Refactor the client GUI
This commit is contained in:
@@ -876,10 +876,20 @@ void imgui_context::new_frame(XrTime display_time)
|
||||
|
||||
image_index = swapchain.acquire();
|
||||
swapchain.wait();
|
||||
|
||||
hovered_item_prev = hovered_item;
|
||||
hovered_item = 0;
|
||||
}
|
||||
|
||||
std::vector<std::pair<int, XrCompositionLayerQuad>> imgui_context::end_frame()
|
||||
{
|
||||
if (hovered_item != hovered_item_prev && hovered_item != 0)
|
||||
{
|
||||
size_t controller = get_focused_controller();
|
||||
if (auto haptic_output = controllers[controller].first.haptic_output; haptic_output != XR_NULL_HANDLE)
|
||||
application::haptic_start(haptic_output, XR_NULL_PATH, 10'000'000, 1000, 1);
|
||||
}
|
||||
|
||||
vk::Image destination = swapchain.images()[image_index].image;
|
||||
|
||||
ImGui::SetCurrentContext(context);
|
||||
@@ -1070,6 +1080,17 @@ std::vector<std::pair<int, XrCompositionLayerQuad>> imgui_context::end_frame()
|
||||
return quads;
|
||||
}
|
||||
|
||||
void imgui_context::vibrate_on_hover()
|
||||
{
|
||||
if (ImGui::IsItemHovered())
|
||||
hovered_item = ImGui::GetItemID();
|
||||
}
|
||||
|
||||
void imgui_context::set_hovered_item()
|
||||
{
|
||||
hovered_item = ImGui::GetItemID();
|
||||
}
|
||||
|
||||
imgui_context::~imgui_context()
|
||||
{
|
||||
ImGui::SetCurrentContext(context);
|
||||
|
||||
@@ -67,6 +67,8 @@ public:
|
||||
XrAction scroll; // XR_ACTION_TYPE_VECTOR2F_INPUT
|
||||
// TODO: thresholds?
|
||||
|
||||
XrAction haptic_output;
|
||||
|
||||
xr::hand_tracker * hand = nullptr;
|
||||
};
|
||||
|
||||
@@ -161,6 +163,9 @@ private:
|
||||
ImVector<ImWchar> glyph_ranges;
|
||||
bool glyph_range_dirty = true;
|
||||
|
||||
ImGuiID hovered_item = 0; // Hovered item in the current frame, reset at the beginning of the frame
|
||||
ImGuiID hovered_item_prev = 0; // Hovered item at the previous frame
|
||||
|
||||
#if WIVRN_SHOW_IMGUI_DEMO_WINDOW
|
||||
bool show_demo_window = true;
|
||||
#endif
|
||||
@@ -211,4 +216,7 @@ public:
|
||||
|
||||
void add_chars(std::string_view sv);
|
||||
bool is_modal_popup_shown() const;
|
||||
|
||||
void vibrate_on_hover();
|
||||
void set_hovered_item();
|
||||
};
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2024 Guillaume Meunier <guillaume.meunier@centraliens.net>
|
||||
*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "scene_components.h"
|
||||
#include <entt/entt.hpp>
|
||||
#include <spdlog/spdlog.h>
|
||||
|
||||
entt::entity find_node_by_name(entt::registry & scene, std::string_view name)
|
||||
{
|
||||
for (auto && [entity, node]: scene.view<components::node>().each())
|
||||
{
|
||||
if (node.name == name)
|
||||
return entity;
|
||||
}
|
||||
|
||||
// TODO custom exception
|
||||
throw std::runtime_error("Node \"" + (std::string)name + "\" not found");
|
||||
}
|
||||
|
||||
entt::entity find_node_by_name(entt::registry & scene, std::string_view name, entt::entity parent)
|
||||
{
|
||||
for (auto && [entity, node]: scene.view<components::node>().each())
|
||||
{
|
||||
if (node.name != name)
|
||||
continue;
|
||||
|
||||
auto current_parent = node.parent;
|
||||
|
||||
do
|
||||
{
|
||||
if (current_parent == parent)
|
||||
return entity;
|
||||
assert(current_parent != scene.get<components::node>(current_parent).parent);
|
||||
current_parent = scene.get<components::node>(current_parent).parent;
|
||||
|
||||
} while (current_parent != entt::null);
|
||||
}
|
||||
|
||||
// TODO custom exception
|
||||
throw std::runtime_error("Node \"" + (std::string)name + "\" not found");
|
||||
}
|
||||
|
||||
std::string get_node_name(const entt::registry & scene, entt::entity entity)
|
||||
{
|
||||
auto name_parent = [&](entt::entity entity) -> std::pair<std::string, entt::entity> {
|
||||
const auto & node = scene.get<components::node>(entity);
|
||||
if (node.name == "")
|
||||
return {std::to_string((int)entity), node.parent};
|
||||
else
|
||||
return {node.name, node.parent};
|
||||
};
|
||||
|
||||
std::string name;
|
||||
std::tie(name, entity) = name_parent(entity);
|
||||
|
||||
while (entity != entt::null)
|
||||
{
|
||||
std::string tmp;
|
||||
std::tie(tmp, entity) = name_parent(entity);
|
||||
name = tmp + "/" + name;
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2025 Guillaume Meunier <guillaume.meunier@centraliens.net>
|
||||
*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
#include <entt/entity/entity.hpp>
|
||||
#include <glm/ext/quaternion_float.hpp>
|
||||
#include <glm/vec3.hpp>
|
||||
#include <vulkan/vulkan_raii.hpp>
|
||||
|
||||
#include "utils/magic_hash.h"
|
||||
#include "vk/allocation.h"
|
||||
|
||||
namespace renderer
|
||||
{
|
||||
struct sampler_info
|
||||
{
|
||||
vk::Filter mag_filter = vk::Filter::eLinear;
|
||||
vk::Filter min_filter = vk::Filter::eLinear;
|
||||
vk::SamplerMipmapMode min_filter_mipmap = vk::SamplerMipmapMode::eLinear;
|
||||
vk::SamplerAddressMode wrapS = vk::SamplerAddressMode::eRepeat;
|
||||
vk::SamplerAddressMode wrapT = vk::SamplerAddressMode::eRepeat;
|
||||
|
||||
bool operator==(const sampler_info & other) const noexcept = default;
|
||||
};
|
||||
|
||||
struct texture
|
||||
{
|
||||
std::shared_ptr<vk::raii::ImageView> image_view;
|
||||
sampler_info sampler;
|
||||
};
|
||||
|
||||
struct material
|
||||
{
|
||||
struct gpu_data
|
||||
{
|
||||
glm::vec4 base_color_factor = glm::vec4(1, 1, 1, 1);
|
||||
glm::vec4 base_emissive_factor = glm::vec4(0, 0, 0, 0);
|
||||
float metallic_factor = 1;
|
||||
float roughness_factor = 1;
|
||||
float occlusion_strength = 0;
|
||||
float normal_scale = 0;
|
||||
|
||||
uint32_t base_color_texcoord = 0;
|
||||
uint32_t metallic_roughness_texcoord = 0;
|
||||
uint32_t occlusion_texcoord = 0;
|
||||
uint32_t emissive_texcoord = 0;
|
||||
uint32_t normal_texcoord = 0;
|
||||
|
||||
// TODO: add fastgltf::TextureTransform?
|
||||
};
|
||||
|
||||
std::shared_ptr<texture> base_color_texture;
|
||||
std::shared_ptr<texture> metallic_roughness_texture;
|
||||
std::shared_ptr<texture> occlusion_texture;
|
||||
std::shared_ptr<texture> emissive_texture;
|
||||
std::shared_ptr<texture> normal_texture;
|
||||
|
||||
// Disable back face culling with this material
|
||||
bool double_sided = true;
|
||||
|
||||
// TODO transparency
|
||||
// fastgltf::AlphaMode alphaMode;
|
||||
// float alpha_cutoff;
|
||||
|
||||
gpu_data staging;
|
||||
|
||||
// Resources used by this material
|
||||
std::shared_ptr<buffer_allocation> 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<vk::raii::DescriptorSet> 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
|
||||
{
|
||||
bool indexed;
|
||||
uint32_t index_count;
|
||||
uint32_t vertex_count;
|
||||
vk::IndexType index_type;
|
||||
vk::DeviceSize index_offset;
|
||||
vk::DeviceSize vertex_offset;
|
||||
|
||||
// See also material::double_sided
|
||||
vk::CullModeFlagBits cull_mode = vk::CullModeFlagBits::eNone;
|
||||
vk::FrontFace front_face = vk::FrontFace::eClockwise;
|
||||
vk::PrimitiveTopology topology = vk::PrimitiveTopology::eTriangleList;
|
||||
|
||||
std::shared_ptr<material> material_;
|
||||
};
|
||||
|
||||
struct mesh
|
||||
{
|
||||
std::vector<primitive> primitives;
|
||||
std::shared_ptr<buffer_allocation> buffer;
|
||||
};
|
||||
|
||||
// TODO move vertex class in .cpp, put vertex description in the primitive
|
||||
struct vertex
|
||||
{
|
||||
glm::vec3 position;
|
||||
glm::vec3 normal;
|
||||
glm::vec3 tangent;
|
||||
std::array<glm::vec2, 2> texcoord;
|
||||
glm::vec4 color;
|
||||
std::array<glm::vec4, 1> joints;
|
||||
std::array<glm::vec4, 1> weights;
|
||||
|
||||
struct description
|
||||
{
|
||||
vk::VertexInputBindingDescription binding;
|
||||
std::vector<vk::VertexInputAttributeDescription> attributes;
|
||||
std::vector<std::string> attribute_names;
|
||||
|
||||
vk::PipelineVertexInputStateCreateFlags flags{};
|
||||
};
|
||||
|
||||
static description describe();
|
||||
};
|
||||
} // namespace renderer
|
||||
|
||||
namespace std
|
||||
{
|
||||
template <>
|
||||
struct hash<renderer::sampler_info> : utils::magic_hash<renderer::sampler_info>
|
||||
{};
|
||||
} // namespace std
|
||||
|
||||
namespace components
|
||||
{
|
||||
struct node
|
||||
{
|
||||
entt::entity parent = entt::null;
|
||||
std::string name;
|
||||
std::shared_ptr<renderer::mesh> mesh;
|
||||
|
||||
glm::vec3 position = {0, 0, 0};
|
||||
glm::quat orientation = {1, 0, 0, 0};
|
||||
glm::vec3 scale = {1, 1, 1};
|
||||
bool visible = true;
|
||||
uint32_t layer_mask = -1;
|
||||
|
||||
std::array<glm::vec4, 4> clipping_planes;
|
||||
|
||||
// TODO: separate component?
|
||||
std::vector<std::pair<entt::entity, glm::mat4>> joints; // Node index, inverse bind matrix of each joint
|
||||
|
||||
// For internal use by the renderer
|
||||
glm::mat4 transform_to_root;
|
||||
bool global_visible;
|
||||
bool reverse_side;
|
||||
uint32_t global_layer_mask;
|
||||
};
|
||||
} // namespace components
|
||||
|
||||
entt::entity find_node_by_name(entt::registry & scene, std::string_view name);
|
||||
entt::entity find_node_by_name(entt::registry & scene, std::string_view name, entt::entity parent);
|
||||
std::string get_node_name(const entt::registry & scene, entt::entity entity);
|
||||
@@ -1,992 +0,0 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
|
||||
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
|
||||
*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "render/scene_data.h"
|
||||
|
||||
#include "image_loader.h"
|
||||
#include "render/gpu_buffer.h"
|
||||
#include "utils/fmt_glm.h"
|
||||
#include "utils/ranges.h"
|
||||
#include <boost/pfr/core.hpp>
|
||||
#include <fastgltf/base64.hpp>
|
||||
#include <fastgltf/core.hpp>
|
||||
#include <fastgltf/glm_element_traits.hpp>
|
||||
#include <fastgltf/tools.hpp>
|
||||
#include <fastgltf/types.hpp>
|
||||
#include <fastgltf/util.hpp>
|
||||
#include <glm/gtc/type_ptr.hpp>
|
||||
#include <ranges>
|
||||
#include <spdlog/spdlog.h>
|
||||
#include <stdexcept>
|
||||
#include <type_traits>
|
||||
#include <variant>
|
||||
#include <vk_mem_alloc.h>
|
||||
#include <vulkan/vulkan_raii.hpp>
|
||||
|
||||
#include "asset.h"
|
||||
|
||||
template <class T>
|
||||
constexpr vk::Format vk_attribute_format = vk::Format::eUndefined;
|
||||
template <>
|
||||
constexpr vk::Format vk_attribute_format<float> = vk::Format::eR32Sfloat;
|
||||
template <>
|
||||
constexpr vk::Format vk_attribute_format<glm::vec2> = vk::Format::eR32G32Sfloat;
|
||||
template <>
|
||||
constexpr vk::Format vk_attribute_format<glm::vec3> = vk::Format::eR32G32B32Sfloat;
|
||||
template <>
|
||||
constexpr vk::Format vk_attribute_format<glm::vec4> = vk::Format::eR32G32B32A32Sfloat;
|
||||
template <typename T, size_t N>
|
||||
constexpr vk::Format vk_attribute_format<std::array<T, N>> = vk_attribute_format<T>;
|
||||
|
||||
template <class T>
|
||||
constexpr size_t nb_attributes = 1;
|
||||
template <typename T, size_t N>
|
||||
constexpr size_t nb_attributes<std::array<T, N>> = N;
|
||||
|
||||
template <class T>
|
||||
struct remove_array
|
||||
{
|
||||
using type = T;
|
||||
};
|
||||
template <class T, size_t N>
|
||||
struct remove_array<std::array<T, N>>
|
||||
{
|
||||
using type = T;
|
||||
};
|
||||
template <class T>
|
||||
using remove_array_t = remove_array<T>::type;
|
||||
|
||||
template <class T>
|
||||
struct is_array : std::false_type
|
||||
{
|
||||
};
|
||||
|
||||
template <class T, size_t N>
|
||||
struct is_array<std::array<T, N>> : std::true_type
|
||||
{
|
||||
};
|
||||
|
||||
template <class T>
|
||||
constexpr bool is_array_v = is_array<T>::value;
|
||||
|
||||
scene_data::vertex::description scene_data::vertex::describe()
|
||||
{
|
||||
scene_data::vertex::description desc;
|
||||
|
||||
desc.binding = vk::VertexInputBindingDescription{
|
||||
.binding = 0,
|
||||
.stride = sizeof(vertex),
|
||||
.inputRate = vk::VertexInputRate::eVertex,
|
||||
};
|
||||
|
||||
vk::VertexInputAttributeDescription attribute{
|
||||
.location = 0,
|
||||
.binding = 0,
|
||||
};
|
||||
|
||||
#define VERTEX_ATTR(member) \
|
||||
attribute.format = vk_attribute_format<decltype(vertex::member)>; \
|
||||
for (size_t i = 0; i < nb_attributes<decltype(vertex::member)>; i++) \
|
||||
{ \
|
||||
attribute.offset = offsetof(vertex, member) + i * sizeof(remove_array_t<decltype(vertex::member)>); \
|
||||
desc.attributes.push_back(attribute); \
|
||||
attribute.location++; \
|
||||
if (is_array_v<decltype(vertex::member)>) \
|
||||
{ \
|
||||
desc.attribute_names.push_back(#member "_" + std::to_string(i)); \
|
||||
} \
|
||||
else \
|
||||
{ \
|
||||
desc.attribute_names.push_back(#member); \
|
||||
} \
|
||||
}
|
||||
|
||||
VERTEX_ATTR(position);
|
||||
VERTEX_ATTR(normal);
|
||||
VERTEX_ATTR(tangent);
|
||||
VERTEX_ATTR(texcoord);
|
||||
VERTEX_ATTR(color);
|
||||
VERTEX_ATTR(joints);
|
||||
VERTEX_ATTR(weights);
|
||||
|
||||
static_assert(vertex{}.joints.size() == vertex{}.weights.size());
|
||||
|
||||
return desc;
|
||||
}
|
||||
|
||||
// Conversion functions gltf -> vulkan
|
||||
namespace
|
||||
{
|
||||
fastgltf::Asset load_gltf_asset(fastgltf::GltfDataBuffer & buffer, const std::filesystem::path & directory)
|
||||
{
|
||||
fastgltf::Parser parser(fastgltf::Extensions::KHR_texture_basisu);
|
||||
|
||||
auto gltf_options =
|
||||
fastgltf::Options::DontRequireValidAssetMember |
|
||||
fastgltf::Options::AllowDouble |
|
||||
fastgltf::Options::LoadGLBBuffers |
|
||||
fastgltf::Options::DecomposeNodeMatrices;
|
||||
|
||||
auto expected_asset = parser.loadGltf(&buffer, directory, gltf_options);
|
||||
|
||||
if (auto error = expected_asset.error(); error != fastgltf::Error::None)
|
||||
throw std::runtime_error(std::string(fastgltf::getErrorMessage(error)));
|
||||
|
||||
return std::move(expected_asset.get());
|
||||
}
|
||||
|
||||
std::pair<vk::Filter, vk::SamplerMipmapMode> convert(fastgltf::Filter filter)
|
||||
{
|
||||
switch (filter)
|
||||
{
|
||||
case fastgltf::Filter::Nearest:
|
||||
case fastgltf::Filter::NearestMipMapNearest:
|
||||
return {vk::Filter::eNearest, vk::SamplerMipmapMode::eNearest};
|
||||
|
||||
case fastgltf::Filter::Linear:
|
||||
case fastgltf::Filter::LinearMipMapNearest:
|
||||
return {vk::Filter::eLinear, vk::SamplerMipmapMode::eNearest};
|
||||
|
||||
case fastgltf::Filter::NearestMipMapLinear:
|
||||
return {vk::Filter::eNearest, vk::SamplerMipmapMode::eLinear};
|
||||
|
||||
case fastgltf::Filter::LinearMipMapLinear:
|
||||
return {vk::Filter::eLinear, vk::SamplerMipmapMode::eLinear};
|
||||
}
|
||||
|
||||
throw std::invalid_argument("filter");
|
||||
}
|
||||
|
||||
vk::SamplerAddressMode convert(fastgltf::Wrap wrap)
|
||||
{
|
||||
switch (wrap)
|
||||
{
|
||||
case fastgltf::Wrap::ClampToEdge:
|
||||
return vk::SamplerAddressMode::eClampToEdge;
|
||||
|
||||
case fastgltf::Wrap::MirroredRepeat:
|
||||
return vk::SamplerAddressMode::eMirroredRepeat;
|
||||
|
||||
case fastgltf::Wrap::Repeat:
|
||||
return vk::SamplerAddressMode::eRepeat;
|
||||
}
|
||||
|
||||
throw std::invalid_argument("wrap");
|
||||
}
|
||||
|
||||
sampler_info convert(fastgltf::Sampler & sampler)
|
||||
{
|
||||
sampler_info info;
|
||||
|
||||
info.mag_filter = convert(sampler.magFilter.value_or(fastgltf::Filter::Linear)).first;
|
||||
|
||||
std::tie(info.min_filter, info.min_filter_mipmap) = convert(sampler.minFilter.value_or(fastgltf::Filter::LinearMipMapLinear));
|
||||
|
||||
info.wrapS = convert(sampler.wrapS);
|
||||
info.wrapT = convert(sampler.wrapT);
|
||||
|
||||
return info;
|
||||
}
|
||||
|
||||
vk::PrimitiveTopology convert(fastgltf::PrimitiveType type)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case fastgltf::PrimitiveType::Points:
|
||||
return vk::PrimitiveTopology::ePointList;
|
||||
|
||||
case fastgltf::PrimitiveType::Lines:
|
||||
return vk::PrimitiveTopology::eLineList;
|
||||
|
||||
case fastgltf::PrimitiveType::LineLoop:
|
||||
throw std::runtime_error("Unimplemented");
|
||||
|
||||
case fastgltf::PrimitiveType::LineStrip:
|
||||
return vk::PrimitiveTopology::eLineStrip;
|
||||
|
||||
case fastgltf::PrimitiveType::Triangles:
|
||||
return vk::PrimitiveTopology::eTriangleList;
|
||||
|
||||
case fastgltf::PrimitiveType::TriangleStrip:
|
||||
return vk::PrimitiveTopology::eTriangleStrip;
|
||||
|
||||
case fastgltf::PrimitiveType::TriangleFan:
|
||||
return vk::PrimitiveTopology::eTriangleFan;
|
||||
}
|
||||
|
||||
throw std::invalid_argument("type");
|
||||
}
|
||||
|
||||
glm::vec4 convert(const std::array<float, 4> & v)
|
||||
{
|
||||
return {v[0], v[1], v[2], v[3]};
|
||||
}
|
||||
|
||||
glm::vec3 convert(const std::array<float, 3> & v)
|
||||
{
|
||||
return {v[0], v[1], v[2]};
|
||||
}
|
||||
} // namespace
|
||||
|
||||
template <typename T>
|
||||
requires is_array_v<T>
|
||||
void copy_vertex_attributes(
|
||||
const fastgltf::Asset & asset,
|
||||
const fastgltf::Primitive & primitive,
|
||||
std::string attribute_name,
|
||||
std::vector<scene_data::vertex> & vertices,
|
||||
T scene_data::vertex::*attribute)
|
||||
{
|
||||
using U = T::value_type;
|
||||
constexpr size_t N = std::tuple_size_v<T>;
|
||||
|
||||
for (size_t i = 0; i < N; i++)
|
||||
{
|
||||
auto it = primitive.findAttribute(attribute_name + std::to_string(i));
|
||||
|
||||
if (it == primitive.attributes.end())
|
||||
continue;
|
||||
|
||||
const fastgltf::Accessor & accessor = asset.accessors.at(it->second);
|
||||
|
||||
if (vertices.size() < accessor.count)
|
||||
vertices.resize(accessor.count, {});
|
||||
|
||||
fastgltf::iterateAccessorWithIndex<U>(asset, accessor, [&](U value, std::size_t idx) {
|
||||
(vertices[idx].*attribute)[i] = value;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
requires(!is_array_v<T>)
|
||||
void copy_vertex_attributes(
|
||||
const fastgltf::Asset & asset,
|
||||
const fastgltf::Primitive & primitive,
|
||||
std::string attribute_name,
|
||||
std::vector<scene_data::vertex> & vertices,
|
||||
T scene_data::vertex::*attribute)
|
||||
{
|
||||
auto it = primitive.findAttribute(attribute_name);
|
||||
|
||||
if (it == primitive.attributes.end())
|
||||
return;
|
||||
|
||||
const fastgltf::Accessor & accessor = asset.accessors.at(it->second);
|
||||
|
||||
if (vertices.size() < accessor.count)
|
||||
vertices.resize(accessor.count, {});
|
||||
|
||||
fastgltf::iterateAccessorWithIndex<T>(asset, accessor, [&](T value, std::size_t idx) {
|
||||
vertices[idx].*attribute = value;
|
||||
});
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
constexpr bool starts_with(std::span<const std::byte> data, std::span<const uint8_t> prefix)
|
||||
{
|
||||
return data.size() >= prefix.size() && !memcmp(data.data(), prefix.data(), prefix.size());
|
||||
}
|
||||
|
||||
fastgltf::MimeType guess_mime_type(std::span<const std::byte> image_data)
|
||||
{
|
||||
const uint8_t jpeg_magic[] = {0xFF, 0xD8, 0xFF};
|
||||
const uint8_t png_magic[] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A};
|
||||
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};
|
||||
|
||||
if (starts_with(image_data, png_magic))
|
||||
return fastgltf::MimeType::PNG;
|
||||
else if (starts_with(image_data, jpeg_magic))
|
||||
return fastgltf::MimeType::JPEG;
|
||||
else if (starts_with(image_data, ktx1_magic))
|
||||
return fastgltf::MimeType::KTX2;
|
||||
else if (starts_with(image_data, ktx2_magic))
|
||||
return fastgltf::MimeType::KTX2;
|
||||
else
|
||||
return fastgltf::MimeType::None;
|
||||
}
|
||||
|
||||
std::shared_ptr<vk::raii::ImageView> do_load_image(
|
||||
vk::raii::PhysicalDevice & physical_device,
|
||||
vk::raii::Device & device,
|
||||
vk::raii::Queue & queue,
|
||||
vk::raii::CommandPool & cb_pool,
|
||||
std::span<const std::byte> image_data,
|
||||
bool srgb)
|
||||
{
|
||||
switch (guess_mime_type(image_data))
|
||||
{
|
||||
case fastgltf::MimeType::JPEG:
|
||||
case fastgltf::MimeType::PNG:
|
||||
case fastgltf::MimeType::KTX2: {
|
||||
try
|
||||
{
|
||||
image_loader loader(physical_device, device, queue, cb_pool);
|
||||
loader.load(image_data, srgb);
|
||||
|
||||
spdlog::debug("Loaded image {}x{}, format {}, {} mipmaps", loader.extent.width, loader.extent.height, vk::to_string(loader.format), loader.num_mipmaps);
|
||||
return loader.image_view;
|
||||
}
|
||||
catch (std::exception & e)
|
||||
{
|
||||
spdlog::info("Cannot load image: {}", e.what());
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
spdlog::error("Unsupported image MIME type");
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
class loader_context
|
||||
{
|
||||
std::filesystem::path base_directory;
|
||||
fastgltf::Asset & gltf;
|
||||
vk::raii::PhysicalDevice physical_device;
|
||||
vk::raii::Device & device;
|
||||
vk::raii::Queue & queue;
|
||||
vk::raii::CommandPool & cb_pool;
|
||||
|
||||
std::vector<asset> loaded_assets;
|
||||
asset & load_from_asset(const std::filesystem::path & path)
|
||||
{
|
||||
return loaded_assets.emplace_back(path);
|
||||
}
|
||||
|
||||
public:
|
||||
loader_context(std::filesystem::path base_directory,
|
||||
fastgltf::Asset & gltf,
|
||||
vk::raii::PhysicalDevice physical_device,
|
||||
vk::raii::Device & device,
|
||||
vk::raii::Queue & queue,
|
||||
vk::raii::CommandPool & cb_pool) :
|
||||
base_directory(base_directory),
|
||||
gltf(gltf),
|
||||
physical_device(physical_device),
|
||||
device(device),
|
||||
queue(queue),
|
||||
cb_pool(cb_pool)
|
||||
{
|
||||
}
|
||||
|
||||
fastgltf::span<const std::byte> load(const fastgltf::URI & uri)
|
||||
{
|
||||
auto path = base_directory.empty() ? std::filesystem::path(uri.path()) : base_directory / std::filesystem::path(uri.path());
|
||||
std::span<const std::byte> bytes;
|
||||
|
||||
bytes = load_from_asset(path);
|
||||
|
||||
return fastgltf::span<const std::byte>(bytes.data(), bytes.size());
|
||||
}
|
||||
|
||||
fastgltf::span<const std::byte> load(const fastgltf::sources::URI & uri)
|
||||
{
|
||||
return load(uri.uri);
|
||||
}
|
||||
|
||||
template <typename T, std::size_t Extent>
|
||||
fastgltf::span<T, fastgltf::dynamic_extent> subspan(fastgltf::span<T, Extent> span, size_t offset, size_t count = fastgltf::dynamic_extent)
|
||||
{
|
||||
assert(offset < span.size());
|
||||
assert(count == fastgltf::dynamic_extent || count <= span.size() - offset);
|
||||
|
||||
if (count == fastgltf::dynamic_extent)
|
||||
count = span.size() - offset;
|
||||
|
||||
return fastgltf::span<T>{span.data() + offset, count};
|
||||
}
|
||||
|
||||
fastgltf::sources::ByteView visit_source(fastgltf::DataSource & source)
|
||||
{
|
||||
using return_type = fastgltf::sources::ByteView;
|
||||
|
||||
return std::visit(fastgltf::visitor{
|
||||
[&](std::monostate) -> return_type {
|
||||
throw std::runtime_error("Invalid source");
|
||||
},
|
||||
[&](fastgltf::sources::Fallback) -> return_type {
|
||||
throw std::runtime_error("Invalid source");
|
||||
},
|
||||
[&](const fastgltf::sources::BufferView & buffer_view) -> return_type {
|
||||
fastgltf::BufferView & view = gltf.bufferViews.at(buffer_view.bufferViewIndex);
|
||||
|
||||
fastgltf::Buffer & buffer = gltf.buffers.at(view.bufferIndex);
|
||||
|
||||
auto buffer2 = visit_source(buffer.data);
|
||||
|
||||
return {subspan(buffer2.bytes, view.byteOffset, view.byteLength), buffer_view.mimeType};
|
||||
},
|
||||
[&](const fastgltf::sources::URI & uri) -> return_type {
|
||||
if (!uri.uri.isLocalPath())
|
||||
throw std::runtime_error("Non local paths are not supported"); // TODO ?
|
||||
|
||||
fastgltf::span<const std::byte> data = load(uri);
|
||||
|
||||
// Don't use the MIME type from fastgltf, it's not initialized for URIs
|
||||
return {subspan(data, uri.fileByteOffset), fastgltf::MimeType::None};
|
||||
},
|
||||
[&](const fastgltf::sources::Vector & vector) -> return_type {
|
||||
fastgltf::span<const std::byte> data{reinterpret_cast<const std::byte *>(vector.bytes.data()), vector.bytes.size()};
|
||||
return {data, vector.mimeType};
|
||||
},
|
||||
[&](const fastgltf::sources::Array & array) -> return_type {
|
||||
fastgltf::span<const std::byte> data{reinterpret_cast<const std::byte *>(array.bytes.data()), array.bytes.size()};
|
||||
return {data, array.mimeType};
|
||||
},
|
||||
[&](const fastgltf::sources::CustomBuffer & custom_buffer) -> return_type {
|
||||
throw std::runtime_error("Unimplemented source CustomBuffer");
|
||||
// TODO ?
|
||||
},
|
||||
[&](fastgltf::sources::ByteView & byte_view) -> return_type {
|
||||
return {byte_view.bytes, byte_view.mimeType};
|
||||
}},
|
||||
source);
|
||||
}
|
||||
|
||||
std::unordered_map<int, std::shared_ptr<vk::raii::ImageView>> images;
|
||||
std::shared_ptr<vk::raii::ImageView> load_image(int index, bool srgb)
|
||||
{
|
||||
auto it = images.find(index);
|
||||
if (it != images.end())
|
||||
return it->second;
|
||||
|
||||
try
|
||||
{
|
||||
auto [image_data, mime_type] = visit_source(gltf.images[index].data);
|
||||
auto image = do_load_image(physical_device, device, queue, cb_pool, image_data, srgb);
|
||||
|
||||
images.emplace(index, image);
|
||||
return image;
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::shared_ptr<scene_data::texture>> load_all_textures()
|
||||
{
|
||||
// Determine which texture is sRGB
|
||||
std::vector<uint8_t> srgb_array;
|
||||
srgb_array.resize(gltf.textures.size(), false);
|
||||
for (const fastgltf::Material & gltf_material: gltf.materials)
|
||||
{
|
||||
if (gltf_material.pbrData.baseColorTexture)
|
||||
srgb_array.at(gltf_material.pbrData.baseColorTexture->textureIndex) = true;
|
||||
|
||||
if (gltf_material.emissiveTexture)
|
||||
srgb_array.at(gltf_material.emissiveTexture->textureIndex) = true;
|
||||
}
|
||||
|
||||
std::vector<std::shared_ptr<scene_data::texture>> textures;
|
||||
textures.reserve(gltf.textures.size());
|
||||
for (auto && [srgb, gltf_texture]: std::views::zip(srgb_array, gltf.textures))
|
||||
{
|
||||
auto & texture_ref = *textures.emplace_back(std::make_shared<scene_data::texture>());
|
||||
|
||||
if (gltf_texture.samplerIndex)
|
||||
{
|
||||
fastgltf::Sampler & sampler = gltf.samplers.at(*gltf_texture.samplerIndex);
|
||||
texture_ref.sampler = convert(sampler);
|
||||
}
|
||||
|
||||
if (gltf_texture.basisuImageIndex)
|
||||
{
|
||||
texture_ref.image_view = load_image(*gltf_texture.basisuImageIndex, srgb);
|
||||
if (texture_ref.image_view)
|
||||
continue;
|
||||
}
|
||||
|
||||
// if (gltf_texture.ddsImageIndex)
|
||||
// {
|
||||
// // TODO
|
||||
// }
|
||||
|
||||
// if (gltf_texture.webpImageIndex)
|
||||
// {
|
||||
// // TODO
|
||||
// }
|
||||
|
||||
if (gltf_texture.imageIndex)
|
||||
{
|
||||
texture_ref.image_view = load_image(*gltf_texture.imageIndex, srgb);
|
||||
if (texture_ref.image_view)
|
||||
continue;
|
||||
}
|
||||
|
||||
throw std::runtime_error("Unsupported image type");
|
||||
}
|
||||
|
||||
return textures;
|
||||
}
|
||||
|
||||
void load_all_buffers()
|
||||
{
|
||||
for (fastgltf::Buffer & buffer: gltf.buffers)
|
||||
{
|
||||
if (std::holds_alternative<fastgltf::sources::URI>(buffer.data))
|
||||
{
|
||||
fastgltf::sources::URI uri = std::get<fastgltf::sources::URI>(buffer.data);
|
||||
|
||||
// Don't use the MIME type from fastgltf, it's not initialized for URIs
|
||||
buffer.data = fastgltf::sources::ByteView(load(uri), fastgltf::MimeType::None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::shared_ptr<scene_data::material>> load_all_materials(std::vector<std::shared_ptr<scene_data::texture>> & textures, gpu_buffer & staging_buffer, const scene_data::material & default_material)
|
||||
{
|
||||
std::vector<std::shared_ptr<scene_data::material>> materials;
|
||||
materials.reserve(gltf.materials.size());
|
||||
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<scene_data::material>(default_material));
|
||||
material_ref.name = gltf_material.name;
|
||||
spdlog::info("Loading material \"{}\"", material_ref.name);
|
||||
material_ref.buffer.reset();
|
||||
material_ref.ds.reset();
|
||||
|
||||
material_ref.double_sided = gltf_material.doubleSided;
|
||||
|
||||
scene_data::material::gpu_data & material_data = material_ref.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;
|
||||
|
||||
if (gltf_material.pbrData.baseColorTexture)
|
||||
{
|
||||
material_ref.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_data.metallic_roughness_texcoord = gltf_material.pbrData.metallicRoughnessTexture->texCoordIndex;
|
||||
}
|
||||
|
||||
if (gltf_material.occlusionTexture)
|
||||
{
|
||||
material_ref.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_data.emissive_texcoord = gltf_material.emissiveTexture->texCoordIndex;
|
||||
}
|
||||
|
||||
if (gltf_material.normalTexture)
|
||||
{
|
||||
material_ref.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);
|
||||
}
|
||||
|
||||
return materials;
|
||||
}
|
||||
|
||||
std::vector<scene_data::mesh> load_all_meshes(std::vector<std::shared_ptr<scene_data::material>> & materials, gpu_buffer & staging_buffer)
|
||||
{
|
||||
std::vector<scene_data::mesh> meshes;
|
||||
meshes.reserve(gltf.meshes.size());
|
||||
for (const fastgltf::Mesh & gltf_mesh: gltf.meshes)
|
||||
{
|
||||
auto & mesh_ref = meshes.emplace_back();
|
||||
|
||||
mesh_ref.primitives.reserve(gltf_mesh.primitives.size());
|
||||
|
||||
for (const fastgltf::Primitive & gltf_primitive: gltf_mesh.primitives)
|
||||
{
|
||||
auto & primitive_ref = mesh_ref.primitives.emplace_back();
|
||||
|
||||
if (gltf_primitive.indicesAccessor)
|
||||
{
|
||||
fastgltf::Accessor & indices_accessor = gltf.accessors.at(*gltf_primitive.indicesAccessor);
|
||||
|
||||
primitive_ref.indexed = true;
|
||||
primitive_ref.index_offset = staging_buffer.add_indices(indices_accessor);
|
||||
primitive_ref.index_count = indices_accessor.count;
|
||||
|
||||
switch (indices_accessor.componentType)
|
||||
{
|
||||
case fastgltf::ComponentType::Byte:
|
||||
case fastgltf::ComponentType::UnsignedByte:
|
||||
primitive_ref.index_type = vk::IndexType::eUint8EXT;
|
||||
break;
|
||||
|
||||
case fastgltf::ComponentType::Short:
|
||||
case fastgltf::ComponentType::UnsignedShort:
|
||||
primitive_ref.index_type = vk::IndexType::eUint16;
|
||||
break;
|
||||
|
||||
case fastgltf::ComponentType::Int:
|
||||
case fastgltf::ComponentType::UnsignedInt:
|
||||
primitive_ref.index_type = vk::IndexType::eUint32;
|
||||
break;
|
||||
|
||||
default:
|
||||
throw std::runtime_error("Invalid index type");
|
||||
break;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
primitive_ref.indexed = false;
|
||||
}
|
||||
|
||||
std::vector<scene_data::vertex> vertices;
|
||||
|
||||
copy_vertex_attributes(gltf, gltf_primitive, "POSITION", vertices, &scene_data::vertex::position);
|
||||
copy_vertex_attributes(gltf, gltf_primitive, "NORMAL", vertices, &scene_data::vertex::normal);
|
||||
copy_vertex_attributes(gltf, gltf_primitive, "TANGENT", vertices, &scene_data::vertex::tangent);
|
||||
copy_vertex_attributes(gltf, gltf_primitive, "TEXCOORD_", vertices, &scene_data::vertex::texcoord);
|
||||
copy_vertex_attributes(gltf, gltf_primitive, "COLOR", vertices, &scene_data::vertex::color);
|
||||
copy_vertex_attributes(gltf, gltf_primitive, "JOINTS_", vertices, &scene_data::vertex::joints);
|
||||
copy_vertex_attributes(gltf, gltf_primitive, "WEIGHTS_", vertices, &scene_data::vertex::weights);
|
||||
|
||||
primitive_ref.vertex_offset = staging_buffer.add_vertices(vertices);
|
||||
primitive_ref.vertex_count = vertices.size();
|
||||
|
||||
primitive_ref.cull_mode = vk::CullModeFlagBits::eBack; // TBC
|
||||
primitive_ref.front_face = vk::FrontFace::eCounterClockwise; // TBC
|
||||
primitive_ref.topology = convert(gltf_primitive.type);
|
||||
|
||||
if (gltf_primitive.materialIndex)
|
||||
primitive_ref.material_ = materials.at(*gltf_primitive.materialIndex);
|
||||
}
|
||||
}
|
||||
|
||||
return meshes;
|
||||
}
|
||||
|
||||
std::vector<scene_data::node> load_all_nodes()
|
||||
{
|
||||
std::vector<scene_data::node> unsorted_objects;
|
||||
unsorted_objects.resize(gltf.nodes.size(), {.parent_id = scene_data::node::root_id});
|
||||
|
||||
for (const auto & [index, gltf_node]: utils::enumerate(gltf.nodes))
|
||||
{
|
||||
if (gltf_node.meshIndex)
|
||||
unsorted_objects[index].mesh_id = *gltf_node.meshIndex;
|
||||
|
||||
if (gltf_node.skinIndex)
|
||||
{
|
||||
auto & skin = gltf.skins.at(*gltf_node.skinIndex);
|
||||
|
||||
unsorted_objects[index].joints.resize(skin.joints.size());
|
||||
|
||||
for (auto [i, joint_index]: utils::enumerate(skin.joints))
|
||||
unsorted_objects[index].joints.at(i).first = joint_index;
|
||||
|
||||
if (skin.inverseBindMatrices)
|
||||
{
|
||||
const fastgltf::Accessor & accessor = gltf.accessors.at(*skin.inverseBindMatrices);
|
||||
|
||||
fastgltf::iterateAccessorWithIndex<glm::mat4>(gltf, accessor, [&](const glm::mat4 & value, std::size_t idx) {
|
||||
unsorted_objects[index].joints.at(idx).second = value;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (size_t child: gltf_node.children)
|
||||
{
|
||||
unsorted_objects[child].parent_id = index;
|
||||
}
|
||||
|
||||
auto TRS = std::get<fastgltf::TRS>(gltf_node.transform);
|
||||
|
||||
unsorted_objects[index].position = glm::make_vec3(TRS.translation.data());
|
||||
unsorted_objects[index].orientation = glm::make_quat(TRS.rotation.data());
|
||||
unsorted_objects[index].scale = glm::make_vec3(TRS.scale.data());
|
||||
unsorted_objects[index].visible = true;
|
||||
unsorted_objects[index].name = gltf_node.name;
|
||||
std::ranges::fill(unsorted_objects[index].clipping_planes, glm::vec4{0, 0, 0, 1});
|
||||
}
|
||||
|
||||
return unsorted_objects;
|
||||
}
|
||||
|
||||
std::vector<scene_data::node> topological_sort(const std::vector<scene_data::node> & unsorted_nodes)
|
||||
{
|
||||
std::vector<scene_data::node> sorted_nodes;
|
||||
std::vector<size_t> new_index;
|
||||
std::vector<bool> already_sorted;
|
||||
|
||||
sorted_nodes.reserve(unsorted_nodes.size());
|
||||
already_sorted.resize(unsorted_nodes.size(), false);
|
||||
new_index.resize(unsorted_nodes.size(), scene_data::node::root_id);
|
||||
|
||||
[[maybe_unused]] bool loop_detected = true;
|
||||
|
||||
while (sorted_nodes.size() < unsorted_nodes.size())
|
||||
{
|
||||
for (size_t i = 0; i < unsorted_nodes.size(); i++)
|
||||
{
|
||||
if (already_sorted[i])
|
||||
continue;
|
||||
|
||||
if (unsorted_nodes[i].parent_id == scene_data::node::root_id)
|
||||
{
|
||||
sorted_nodes.push_back(unsorted_nodes[i]);
|
||||
already_sorted[i] = true;
|
||||
new_index[i] = sorted_nodes.size() - 1;
|
||||
loop_detected = false;
|
||||
}
|
||||
else if (already_sorted[unsorted_nodes[i].parent_id])
|
||||
{
|
||||
sorted_nodes.emplace_back(unsorted_nodes[i]).parent_id = new_index[unsorted_nodes[i].parent_id];
|
||||
already_sorted[i] = true;
|
||||
new_index[i] = sorted_nodes.size() - 1;
|
||||
loop_detected = false;
|
||||
}
|
||||
}
|
||||
|
||||
assert(!loop_detected);
|
||||
}
|
||||
|
||||
// renumber joint indices
|
||||
for (auto & node: sorted_nodes)
|
||||
{
|
||||
for (auto & joint: node.joints)
|
||||
{
|
||||
joint.first = new_index[joint.first];
|
||||
}
|
||||
}
|
||||
|
||||
assert(sorted_nodes.size() == unsorted_nodes.size());
|
||||
for (size_t i = 0; i < sorted_nodes.size(); i++)
|
||||
{
|
||||
assert(sorted_nodes[i].parent_id == scene_data::node::root_id || sorted_nodes[i].parent_id < i);
|
||||
}
|
||||
|
||||
return sorted_nodes;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
scene_data scene_loader::operator()(const std::filesystem::path & gltf_path)
|
||||
{
|
||||
vk::PhysicalDeviceProperties physical_device_properties = physical_device.getProperties();
|
||||
vk::raii::CommandPool cb_pool{device, vk::CommandPoolCreateInfo{
|
||||
.flags = vk::CommandPoolCreateFlagBits::eTransient | vk::CommandPoolCreateFlagBits::eResetCommandBuffer,
|
||||
.queueFamilyIndex = queue_family_index,
|
||||
}};
|
||||
|
||||
scene_data data;
|
||||
|
||||
asset asset_file(gltf_path);
|
||||
fastgltf::GltfDataBuffer data_buffer;
|
||||
data_buffer.copyBytes(reinterpret_cast<const uint8_t *>(asset_file.data()), asset_file.size());
|
||||
|
||||
fastgltf::Asset asset = load_gltf_asset(data_buffer, gltf_path.parent_path());
|
||||
loader_context ctx(gltf_path.parent_path(), asset, physical_device, device, queue, cb_pool);
|
||||
|
||||
#ifndef NDEBUG
|
||||
if (auto error = fastgltf::validate(asset); error != fastgltf::Error::None)
|
||||
throw std::runtime_error(std::string(fastgltf::getErrorMessage(error)));
|
||||
#endif
|
||||
|
||||
// Load all buffers from URIs
|
||||
ctx.load_all_buffers();
|
||||
|
||||
gpu_buffer staging_buffer(physical_device_properties, asset);
|
||||
|
||||
// Load all textures
|
||||
auto textures = ctx.load_all_textures();
|
||||
|
||||
// Load all materials
|
||||
auto materials = ctx.load_all_materials(textures, staging_buffer, *default_material);
|
||||
|
||||
// Load all meshes
|
||||
data.meshes = ctx.load_all_meshes(materials, staging_buffer);
|
||||
|
||||
data.scene_nodes = ctx.topological_sort(ctx.load_all_nodes());
|
||||
|
||||
// Copy the staging buffer to the GPU
|
||||
spdlog::debug("Uploading scene data ({} bytes) to GPU memory", staging_buffer.size());
|
||||
auto buffer = std::make_shared<buffer_allocation>(staging_buffer.copy_to_gpu());
|
||||
|
||||
for (auto & i: materials)
|
||||
i->buffer = buffer;
|
||||
|
||||
for (auto & i: data.meshes)
|
||||
i.buffer = buffer;
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
scene_data & scene_data::import(scene_data && other, node_handle parent)
|
||||
{
|
||||
assert(parent.scene == this || parent.id == node::root_id);
|
||||
|
||||
size_t mesh_offset = meshes.size();
|
||||
size_t nodes_offset = scene_nodes.size();
|
||||
|
||||
for (auto & mesh: other.meshes)
|
||||
meshes.push_back(std::move(mesh));
|
||||
|
||||
for (auto node: other.scene_nodes)
|
||||
{
|
||||
assert(!node.mesh_id || *node.mesh_id < other.meshes.size());
|
||||
|
||||
if (node.mesh_id)
|
||||
*node.mesh_id += mesh_offset;
|
||||
|
||||
for (auto & joint: node.joints)
|
||||
{
|
||||
joint.first += nodes_offset;
|
||||
}
|
||||
|
||||
if (node.parent_id == node::root_id)
|
||||
{
|
||||
node.parent_id = parent.id;
|
||||
}
|
||||
else
|
||||
{
|
||||
assert(node.parent_id < other.scene_nodes.size());
|
||||
node.parent_id += nodes_offset;
|
||||
}
|
||||
|
||||
scene_nodes.push_back(node);
|
||||
}
|
||||
|
||||
other.meshes.clear();
|
||||
other.scene_nodes.clear();
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
scene_data & scene_data::import(scene_data && other)
|
||||
{
|
||||
return import(std::move(other), {});
|
||||
}
|
||||
|
||||
node_handle scene_data::new_node()
|
||||
{
|
||||
size_t id = scene_nodes.size();
|
||||
|
||||
scene_nodes.push_back(node{
|
||||
.parent_id = node::root_id,
|
||||
.position = {0, 0, 0},
|
||||
.orientation = {1, 0, 0, 0},
|
||||
.scale = {1, 1, 1},
|
||||
.visible = true});
|
||||
|
||||
return {id, this};
|
||||
}
|
||||
|
||||
node_handle scene_data::find_node(std::string_view name)
|
||||
{
|
||||
for (auto && [index, node]: utils::enumerate(scene_nodes))
|
||||
{
|
||||
if (node.name == name)
|
||||
{
|
||||
return {index, this};
|
||||
}
|
||||
}
|
||||
|
||||
// TODO custom exception
|
||||
throw std::runtime_error("Node " + std::string(name) + " not found");
|
||||
}
|
||||
|
||||
node_handle scene_data::find_node(node_handle root, std::string_view name)
|
||||
{
|
||||
assert(root.id < scene_nodes.size());
|
||||
assert(root.scene == this);
|
||||
|
||||
std::vector<bool> flag(scene_nodes.size(), false);
|
||||
|
||||
flag[root.id] = true;
|
||||
|
||||
for (size_t index = root.id; index < scene_nodes.size(); index++)
|
||||
{
|
||||
size_t parent = scene_nodes[index].parent_id;
|
||||
|
||||
if (parent == node::root_id)
|
||||
continue;
|
||||
|
||||
if (!flag[parent])
|
||||
continue;
|
||||
|
||||
if (scene_nodes[index].name == name)
|
||||
return {index, this};
|
||||
|
||||
flag[index] = true;
|
||||
}
|
||||
|
||||
// TODO custom exception
|
||||
throw std::runtime_error("Node " + std::string(name) + " not found");
|
||||
}
|
||||
|
||||
std::vector<node_handle> scene_data::find_children(node_handle root)
|
||||
{
|
||||
assert(root.id < scene_nodes.size());
|
||||
assert(root.scene == this);
|
||||
|
||||
std::vector<bool> flag(scene_nodes.size(), false);
|
||||
|
||||
flag[root.id] = true;
|
||||
|
||||
std::vector<node_handle> nodes;
|
||||
|
||||
for (size_t index = root.id; index < scene_nodes.size(); index++)
|
||||
{
|
||||
size_t parent = scene_nodes[index].parent_id;
|
||||
|
||||
if (parent == node::root_id)
|
||||
continue;
|
||||
|
||||
if (!flag[parent])
|
||||
continue;
|
||||
|
||||
nodes.emplace_back(index, this);
|
||||
|
||||
flag[index] = true;
|
||||
}
|
||||
|
||||
return nodes;
|
||||
}
|
||||
|
||||
std::shared_ptr<scene_data::material> scene_data::find_material(std::string_view name)
|
||||
{
|
||||
for (auto & mesh: meshes)
|
||||
{
|
||||
for (auto & primitive: mesh.primitives)
|
||||
{
|
||||
if (primitive.material_ && primitive.material_->name == name)
|
||||
return primitive.material_;
|
||||
}
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
@@ -1,295 +0,0 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
|
||||
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
|
||||
*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "utils/magic_hash.h"
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <glm/ext/quaternion_float.hpp>
|
||||
#include <glm/mat4x4.hpp>
|
||||
#include <glm/vec2.hpp>
|
||||
#include <glm/vec3.hpp>
|
||||
#include <glm/vec4.hpp>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <vk/allocation.h>
|
||||
#include <vulkan/vulkan_raii.hpp>
|
||||
|
||||
struct sampler_info
|
||||
{
|
||||
vk::Filter mag_filter = vk::Filter::eLinear;
|
||||
vk::Filter min_filter = vk::Filter::eLinear;
|
||||
vk::SamplerMipmapMode min_filter_mipmap = vk::SamplerMipmapMode::eLinear;
|
||||
vk::SamplerAddressMode wrapS = vk::SamplerAddressMode::eRepeat;
|
||||
vk::SamplerAddressMode wrapT = vk::SamplerAddressMode::eRepeat;
|
||||
|
||||
bool operator==(const sampler_info & other) const noexcept = default;
|
||||
};
|
||||
|
||||
namespace std
|
||||
{
|
||||
template <>
|
||||
struct hash<sampler_info> : utils::magic_hash<sampler_info>
|
||||
{};
|
||||
} // namespace std
|
||||
|
||||
class node_handle;
|
||||
|
||||
struct scene_data
|
||||
{
|
||||
struct texture
|
||||
{
|
||||
std::shared_ptr<vk::raii::ImageView> image_view;
|
||||
sampler_info sampler;
|
||||
};
|
||||
|
||||
struct material
|
||||
{
|
||||
struct gpu_data
|
||||
{
|
||||
glm::vec4 base_color_factor = glm::vec4(1, 1, 1, 1);
|
||||
glm::vec4 base_emissive_factor = glm::vec4(0, 0, 0, 0);
|
||||
float metallic_factor = 1;
|
||||
float roughness_factor = 1;
|
||||
float occlusion_strength = 0;
|
||||
float normal_scale = 0;
|
||||
|
||||
uint32_t base_color_texcoord = 0;
|
||||
uint32_t metallic_roughness_texcoord = 0;
|
||||
uint32_t occlusion_texcoord = 0;
|
||||
uint32_t emissive_texcoord = 0;
|
||||
uint32_t normal_texcoord = 0;
|
||||
|
||||
// TODO: add fastgltf::TextureTransform?
|
||||
};
|
||||
|
||||
std::shared_ptr<texture> base_color_texture;
|
||||
std::shared_ptr<texture> metallic_roughness_texture;
|
||||
std::shared_ptr<texture> occlusion_texture;
|
||||
std::shared_ptr<texture> emissive_texture;
|
||||
std::shared_ptr<texture> normal_texture;
|
||||
|
||||
// Disable back face culling with this material
|
||||
bool double_sided = true;
|
||||
|
||||
// TODO transparency
|
||||
// fastgltf::AlphaMode alphaMode;
|
||||
// float alpha_cutoff;
|
||||
|
||||
gpu_data staging;
|
||||
|
||||
// Resources used by this material
|
||||
std::shared_ptr<buffer_allocation> 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<vk::raii::DescriptorSet> 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 vertex
|
||||
{
|
||||
glm::vec3 position;
|
||||
glm::vec3 normal;
|
||||
glm::vec3 tangent;
|
||||
std::array<glm::vec2, 2> texcoord;
|
||||
glm::vec4 color;
|
||||
std::array<glm::vec4, 1> joints;
|
||||
std::array<glm::vec4, 1> weights;
|
||||
|
||||
struct description
|
||||
{
|
||||
vk::VertexInputBindingDescription binding;
|
||||
std::vector<vk::VertexInputAttributeDescription> attributes;
|
||||
std::vector<std::string> attribute_names;
|
||||
|
||||
vk::PipelineVertexInputStateCreateFlags flags{};
|
||||
};
|
||||
|
||||
static description describe();
|
||||
};
|
||||
|
||||
struct primitive
|
||||
{
|
||||
bool indexed;
|
||||
uint32_t index_count;
|
||||
uint32_t vertex_count;
|
||||
vk::IndexType index_type;
|
||||
vk::DeviceSize index_offset;
|
||||
vk::DeviceSize vertex_offset;
|
||||
|
||||
// See also material::double_sided
|
||||
vk::CullModeFlagBits cull_mode = vk::CullModeFlagBits::eNone;
|
||||
vk::FrontFace front_face = vk::FrontFace::eClockwise;
|
||||
vk::PrimitiveTopology topology = vk::PrimitiveTopology::eTriangleList;
|
||||
|
||||
std::shared_ptr<material> material_;
|
||||
};
|
||||
|
||||
struct mesh
|
||||
{
|
||||
std::vector<primitive> primitives;
|
||||
std::shared_ptr<buffer_allocation> buffer;
|
||||
};
|
||||
|
||||
struct node
|
||||
{
|
||||
static constexpr size_t root_id = size_t(-1);
|
||||
|
||||
size_t parent_id;
|
||||
std::optional<size_t> mesh_id;
|
||||
|
||||
glm::vec3 position;
|
||||
glm::quat orientation;
|
||||
glm::vec3 scale;
|
||||
|
||||
std::string name;
|
||||
bool visible;
|
||||
|
||||
std::array<glm::vec4, 4> clipping_planes;
|
||||
|
||||
uint32_t layer_mask = 1;
|
||||
|
||||
std::vector<std::pair<size_t, glm::mat4>> joints; // Node index, inverse bind matrix of each joint
|
||||
};
|
||||
|
||||
// TODO: lights
|
||||
// TODO: skybox
|
||||
|
||||
std::vector<scene_data::mesh> meshes;
|
||||
std::vector<scene_data::node> scene_nodes;
|
||||
|
||||
scene_data() = default;
|
||||
scene_data(const scene_data &) = delete;
|
||||
scene_data(scene_data &&) = default;
|
||||
scene_data & operator=(const scene_data &) = delete;
|
||||
scene_data & operator=(scene_data &&) = default;
|
||||
|
||||
scene_data & import(scene_data && other, node_handle parent);
|
||||
scene_data & import(scene_data && other);
|
||||
|
||||
node_handle new_node();
|
||||
node_handle find_node(std::string_view name);
|
||||
node_handle find_node(node_handle parent, std::string_view name);
|
||||
std::vector<node_handle> find_children(node_handle parent);
|
||||
|
||||
std::shared_ptr<material> find_material(std::string_view name);
|
||||
};
|
||||
|
||||
class scene_loader
|
||||
{
|
||||
vk::raii::Device & device;
|
||||
vk::raii::PhysicalDevice physical_device;
|
||||
vk::raii::Queue & queue;
|
||||
uint32_t queue_family_index;
|
||||
std::shared_ptr<scene_data::material> default_material;
|
||||
|
||||
public:
|
||||
scene_loader(vk::raii::Device & device, vk::raii::PhysicalDevice physical_device, vk::raii::Queue & queue, uint32_t queue_family_index, std::shared_ptr<scene_data::material> default_material) :
|
||||
device(device),
|
||||
physical_device(physical_device),
|
||||
queue(queue),
|
||||
queue_family_index(queue_family_index),
|
||||
default_material(default_material)
|
||||
{}
|
||||
|
||||
scene_data operator()(const std::filesystem::path & gltf_path);
|
||||
};
|
||||
|
||||
class node_handle
|
||||
{
|
||||
friend struct scene_data;
|
||||
size_t id = scene_data::node::root_id;
|
||||
scene_data * scene = nullptr;
|
||||
|
||||
public:
|
||||
node_handle() = default;
|
||||
node_handle(size_t id, scene_data * scene) :
|
||||
id(id), scene(scene) {}
|
||||
node_handle(const node_handle &) = default;
|
||||
node_handle & operator=(const node_handle &) = default;
|
||||
|
||||
scene_data::node & operator*()
|
||||
{
|
||||
assert(scene != nullptr);
|
||||
assert(id < scene->scene_nodes.size());
|
||||
return scene->scene_nodes[id];
|
||||
}
|
||||
|
||||
const scene_data::node & operator*() const
|
||||
{
|
||||
assert(scene != nullptr);
|
||||
assert(id < scene->scene_nodes.size());
|
||||
return scene->scene_nodes[id];
|
||||
}
|
||||
|
||||
scene_data::node * operator->()
|
||||
{
|
||||
assert(scene != nullptr);
|
||||
assert(id < scene->scene_nodes.size());
|
||||
return &scene->scene_nodes[id];
|
||||
}
|
||||
|
||||
const scene_data::node * operator->() const
|
||||
{
|
||||
assert(scene != nullptr);
|
||||
assert(id < scene->scene_nodes.size());
|
||||
return &scene->scene_nodes[id];
|
||||
}
|
||||
|
||||
node_handle parent()
|
||||
{
|
||||
assert(scene != nullptr);
|
||||
assert(id < scene->scene_nodes.size());
|
||||
|
||||
return {scene->scene_nodes[id].parent_id, scene};
|
||||
}
|
||||
|
||||
const node_handle parent() const
|
||||
{
|
||||
assert(scene != nullptr);
|
||||
assert(id < scene->scene_nodes.size());
|
||||
|
||||
return {scene->scene_nodes[id].parent_id, scene};
|
||||
}
|
||||
|
||||
std::vector<node_handle> children()
|
||||
{
|
||||
assert(scene != nullptr);
|
||||
|
||||
return scene->find_children(*this);
|
||||
}
|
||||
|
||||
operator bool() const
|
||||
{
|
||||
return id != scene_data::node::root_id;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -0,0 +1,840 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2025 Guillaume Meunier <guillaume.meunier@centraliens.net>
|
||||
*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "scene_loader.h"
|
||||
|
||||
#include "asset.h"
|
||||
#include "gpu_buffer.h"
|
||||
#include "image_loader.h"
|
||||
#include "render/scene_components.h"
|
||||
#include "utils/ranges.h"
|
||||
#include <entt/entt.hpp>
|
||||
#include <fastgltf/base64.hpp>
|
||||
#include <fastgltf/core.hpp>
|
||||
#include <fastgltf/glm_element_traits.hpp>
|
||||
#include <fastgltf/tools.hpp>
|
||||
#include <fastgltf/types.hpp>
|
||||
#include <fastgltf/util.hpp>
|
||||
#include <glm/ext.hpp>
|
||||
#include <ranges>
|
||||
#include <spdlog/spdlog.h>
|
||||
|
||||
namespace
|
||||
{
|
||||
// BEGIN Utility functions
|
||||
template <class T>
|
||||
constexpr vk::Format vk_attribute_format = vk::Format::eUndefined;
|
||||
template <>
|
||||
constexpr vk::Format vk_attribute_format<float> = vk::Format::eR32Sfloat;
|
||||
template <>
|
||||
constexpr vk::Format vk_attribute_format<glm::vec2> = vk::Format::eR32G32Sfloat;
|
||||
template <>
|
||||
constexpr vk::Format vk_attribute_format<glm::vec3> = vk::Format::eR32G32B32Sfloat;
|
||||
template <>
|
||||
constexpr vk::Format vk_attribute_format<glm::vec4> = vk::Format::eR32G32B32A32Sfloat;
|
||||
template <typename T, size_t N>
|
||||
constexpr vk::Format vk_attribute_format<std::array<T, N>> = vk_attribute_format<T>;
|
||||
|
||||
template <class T>
|
||||
constexpr size_t nb_attributes = 1;
|
||||
template <typename T, size_t N>
|
||||
constexpr size_t nb_attributes<std::array<T, N>> = N;
|
||||
|
||||
template <class T>
|
||||
struct remove_array
|
||||
{
|
||||
using type = T;
|
||||
};
|
||||
template <class T, size_t N>
|
||||
struct remove_array<std::array<T, N>>
|
||||
{
|
||||
using type = T;
|
||||
};
|
||||
template <class T>
|
||||
using remove_array_t = remove_array<T>::type;
|
||||
|
||||
template <class T>
|
||||
struct is_array : std::false_type
|
||||
{
|
||||
};
|
||||
|
||||
template <class T, size_t N>
|
||||
struct is_array<std::array<T, N>> : std::true_type
|
||||
{
|
||||
};
|
||||
|
||||
template <class T>
|
||||
constexpr bool is_array_v = is_array<T>::value;
|
||||
// END
|
||||
|
||||
// BEGIN GLTF -> Vulkan conversion functions
|
||||
std::pair<vk::Filter, vk::SamplerMipmapMode> convert(fastgltf::Filter filter)
|
||||
{
|
||||
switch (filter)
|
||||
{
|
||||
case fastgltf::Filter::Nearest:
|
||||
case fastgltf::Filter::NearestMipMapNearest:
|
||||
return {vk::Filter::eNearest, vk::SamplerMipmapMode::eNearest};
|
||||
|
||||
case fastgltf::Filter::Linear:
|
||||
case fastgltf::Filter::LinearMipMapNearest:
|
||||
return {vk::Filter::eLinear, vk::SamplerMipmapMode::eNearest};
|
||||
|
||||
case fastgltf::Filter::NearestMipMapLinear:
|
||||
return {vk::Filter::eNearest, vk::SamplerMipmapMode::eLinear};
|
||||
|
||||
case fastgltf::Filter::LinearMipMapLinear:
|
||||
return {vk::Filter::eLinear, vk::SamplerMipmapMode::eLinear};
|
||||
}
|
||||
|
||||
throw std::invalid_argument("filter");
|
||||
}
|
||||
|
||||
vk::SamplerAddressMode convert(fastgltf::Wrap wrap)
|
||||
{
|
||||
switch (wrap)
|
||||
{
|
||||
case fastgltf::Wrap::ClampToEdge:
|
||||
return vk::SamplerAddressMode::eClampToEdge;
|
||||
|
||||
case fastgltf::Wrap::MirroredRepeat:
|
||||
return vk::SamplerAddressMode::eMirroredRepeat;
|
||||
|
||||
case fastgltf::Wrap::Repeat:
|
||||
return vk::SamplerAddressMode::eRepeat;
|
||||
}
|
||||
|
||||
throw std::invalid_argument("wrap");
|
||||
}
|
||||
|
||||
renderer::sampler_info convert(fastgltf::Sampler & sampler)
|
||||
{
|
||||
renderer::sampler_info info;
|
||||
|
||||
info.mag_filter = convert(sampler.magFilter.value_or(fastgltf::Filter::Linear)).first;
|
||||
|
||||
std::tie(info.min_filter, info.min_filter_mipmap) = convert(sampler.minFilter.value_or(fastgltf::Filter::LinearMipMapLinear));
|
||||
|
||||
info.wrapS = convert(sampler.wrapS);
|
||||
info.wrapT = convert(sampler.wrapT);
|
||||
|
||||
return info;
|
||||
}
|
||||
|
||||
vk::PrimitiveTopology convert(fastgltf::PrimitiveType type)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case fastgltf::PrimitiveType::Points:
|
||||
return vk::PrimitiveTopology::ePointList;
|
||||
|
||||
case fastgltf::PrimitiveType::Lines:
|
||||
return vk::PrimitiveTopology::eLineList;
|
||||
|
||||
case fastgltf::PrimitiveType::LineLoop:
|
||||
throw std::runtime_error("Unimplemented");
|
||||
|
||||
case fastgltf::PrimitiveType::LineStrip:
|
||||
return vk::PrimitiveTopology::eLineStrip;
|
||||
|
||||
case fastgltf::PrimitiveType::Triangles:
|
||||
return vk::PrimitiveTopology::eTriangleList;
|
||||
|
||||
case fastgltf::PrimitiveType::TriangleStrip:
|
||||
return vk::PrimitiveTopology::eTriangleStrip;
|
||||
|
||||
case fastgltf::PrimitiveType::TriangleFan:
|
||||
return vk::PrimitiveTopology::eTriangleFan;
|
||||
}
|
||||
|
||||
throw std::invalid_argument("type");
|
||||
}
|
||||
|
||||
glm::vec4 convert(const std::array<float, 4> & v)
|
||||
{
|
||||
return {v[0], v[1], v[2], v[3]};
|
||||
}
|
||||
|
||||
glm::vec3 convert(const std::array<float, 3> & v)
|
||||
{
|
||||
return {v[0], v[1], v[2]};
|
||||
}
|
||||
// END
|
||||
|
||||
// BEGIN Vertex attributes loading
|
||||
template <typename T>
|
||||
requires is_array_v<T>
|
||||
void copy_vertex_attributes(
|
||||
const fastgltf::Asset & asset,
|
||||
const fastgltf::Primitive & primitive,
|
||||
std::string attribute_name,
|
||||
std::vector<renderer::vertex> & vertices,
|
||||
T renderer::vertex::*attribute)
|
||||
{
|
||||
using U = T::value_type;
|
||||
constexpr size_t N = std::tuple_size_v<T>;
|
||||
|
||||
for (size_t i = 0; i < N; i++)
|
||||
{
|
||||
auto it = primitive.findAttribute(attribute_name + std::to_string(i));
|
||||
|
||||
if (it == primitive.attributes.end())
|
||||
continue;
|
||||
|
||||
const fastgltf::Accessor & accessor = asset.accessors.at(it->second);
|
||||
|
||||
if (vertices.size() < accessor.count)
|
||||
vertices.resize(accessor.count, {});
|
||||
|
||||
fastgltf::iterateAccessorWithIndex<U>(asset, accessor, [&](U value, std::size_t idx) {
|
||||
(vertices[idx].*attribute)[i] = value;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
requires(!is_array_v<T>)
|
||||
void copy_vertex_attributes(
|
||||
const fastgltf::Asset & asset,
|
||||
const fastgltf::Primitive & primitive,
|
||||
std::string attribute_name,
|
||||
std::vector<renderer::vertex> & vertices,
|
||||
T renderer::vertex::*attribute)
|
||||
{
|
||||
auto it = primitive.findAttribute(attribute_name);
|
||||
|
||||
if (it == primitive.attributes.end())
|
||||
return;
|
||||
|
||||
const fastgltf::Accessor & accessor = asset.accessors.at(it->second);
|
||||
|
||||
if (vertices.size() < accessor.count)
|
||||
vertices.resize(accessor.count, {});
|
||||
|
||||
fastgltf::iterateAccessorWithIndex<T>(asset, accessor, [&](T value, std::size_t idx) {
|
||||
vertices[idx].*attribute = value;
|
||||
});
|
||||
}
|
||||
// END
|
||||
|
||||
// BEGIN Image loading
|
||||
constexpr bool starts_with(std::span<const std::byte> data, std::span<const uint8_t> prefix)
|
||||
{
|
||||
return data.size() >= prefix.size() && !memcmp(data.data(), prefix.data(), prefix.size());
|
||||
}
|
||||
|
||||
fastgltf::MimeType guess_mime_type(std::span<const std::byte> image_data)
|
||||
{
|
||||
const uint8_t jpeg_magic[] = {0xFF, 0xD8, 0xFF};
|
||||
const uint8_t png_magic[] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A};
|
||||
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};
|
||||
|
||||
if (starts_with(image_data, png_magic))
|
||||
return fastgltf::MimeType::PNG;
|
||||
else if (starts_with(image_data, jpeg_magic))
|
||||
return fastgltf::MimeType::JPEG;
|
||||
else if (starts_with(image_data, ktx1_magic))
|
||||
return fastgltf::MimeType::KTX2;
|
||||
else if (starts_with(image_data, ktx2_magic))
|
||||
return fastgltf::MimeType::KTX2;
|
||||
else
|
||||
return fastgltf::MimeType::None;
|
||||
}
|
||||
|
||||
std::shared_ptr<vk::raii::ImageView> do_load_image(
|
||||
vk::raii::PhysicalDevice & physical_device,
|
||||
vk::raii::Device & device,
|
||||
vk::raii::Queue & queue,
|
||||
vk::raii::CommandPool & cb_pool,
|
||||
std::span<const std::byte> image_data,
|
||||
bool srgb)
|
||||
{
|
||||
switch (guess_mime_type(image_data))
|
||||
{
|
||||
case fastgltf::MimeType::JPEG:
|
||||
case fastgltf::MimeType::PNG:
|
||||
case fastgltf::MimeType::KTX2: {
|
||||
try
|
||||
{
|
||||
image_loader loader(physical_device, device, queue, cb_pool);
|
||||
loader.load(image_data, srgb);
|
||||
|
||||
spdlog::debug("Loaded image {}x{}, format {}, {} mipmaps", loader.extent.width, loader.extent.height, vk::to_string(loader.format), loader.num_mipmaps);
|
||||
return loader.image_view;
|
||||
}
|
||||
catch (std::exception & e)
|
||||
{
|
||||
spdlog::info("Cannot load image: {}", e.what());
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
spdlog::error("Unsupported image MIME type");
|
||||
return {};
|
||||
}
|
||||
}
|
||||
// END
|
||||
|
||||
fastgltf::Asset load_gltf_asset(fastgltf::GltfDataBuffer & buffer, const std::filesystem::path & directory)
|
||||
{
|
||||
fastgltf::Parser parser(fastgltf::Extensions::KHR_texture_basisu);
|
||||
|
||||
auto gltf_options =
|
||||
fastgltf::Options::DontRequireValidAssetMember |
|
||||
fastgltf::Options::AllowDouble |
|
||||
fastgltf::Options::LoadGLBBuffers |
|
||||
fastgltf::Options::DecomposeNodeMatrices;
|
||||
|
||||
auto expected_asset = parser.loadGltf(&buffer, directory, gltf_options);
|
||||
|
||||
if (auto error = expected_asset.error(); error != fastgltf::Error::None)
|
||||
throw std::runtime_error(std::string(fastgltf::getErrorMessage(error)));
|
||||
|
||||
return std::move(expected_asset.get());
|
||||
}
|
||||
|
||||
class loader_context
|
||||
{
|
||||
std::filesystem::path base_directory;
|
||||
fastgltf::Asset & gltf;
|
||||
vk::raii::PhysicalDevice physical_device;
|
||||
vk::raii::Device & device;
|
||||
vk::raii::Queue & queue;
|
||||
vk::raii::CommandPool & cb_pool;
|
||||
|
||||
std::vector<asset> loaded_assets;
|
||||
asset & load_from_asset(const std::filesystem::path & path)
|
||||
{
|
||||
return loaded_assets.emplace_back(path);
|
||||
}
|
||||
|
||||
public:
|
||||
loader_context(std::filesystem::path base_directory,
|
||||
fastgltf::Asset & gltf,
|
||||
vk::raii::PhysicalDevice physical_device,
|
||||
vk::raii::Device & device,
|
||||
vk::raii::Queue & queue,
|
||||
vk::raii::CommandPool & cb_pool) :
|
||||
base_directory(base_directory),
|
||||
gltf(gltf),
|
||||
physical_device(physical_device),
|
||||
device(device),
|
||||
queue(queue),
|
||||
cb_pool(cb_pool)
|
||||
{
|
||||
}
|
||||
|
||||
fastgltf::span<const std::byte> load(const fastgltf::URI & uri)
|
||||
{
|
||||
auto path = base_directory.empty() ? std::filesystem::path(uri.path()) : base_directory / std::filesystem::path(uri.path());
|
||||
std::span<const std::byte> bytes;
|
||||
|
||||
bytes = load_from_asset(path);
|
||||
|
||||
return fastgltf::span<const std::byte>(bytes.data(), bytes.size());
|
||||
}
|
||||
|
||||
fastgltf::span<const std::byte> load(const fastgltf::sources::URI & uri)
|
||||
{
|
||||
return load(uri.uri);
|
||||
}
|
||||
|
||||
template <typename T, std::size_t Extent>
|
||||
fastgltf::span<T, fastgltf::dynamic_extent> subspan(fastgltf::span<T, Extent> span, size_t offset, size_t count = fastgltf::dynamic_extent)
|
||||
{
|
||||
assert(offset < span.size());
|
||||
assert(count == fastgltf::dynamic_extent || count <= span.size() - offset);
|
||||
|
||||
if (count == fastgltf::dynamic_extent)
|
||||
count = span.size() - offset;
|
||||
|
||||
return fastgltf::span<T>{span.data() + offset, count};
|
||||
}
|
||||
|
||||
fastgltf::sources::ByteView visit_source(fastgltf::DataSource & source)
|
||||
{
|
||||
using return_type = fastgltf::sources::ByteView;
|
||||
|
||||
return std::visit(fastgltf::visitor{
|
||||
[&](std::monostate) -> return_type {
|
||||
throw std::runtime_error("Invalid source");
|
||||
},
|
||||
[&](fastgltf::sources::Fallback) -> return_type {
|
||||
throw std::runtime_error("Invalid source");
|
||||
},
|
||||
[&](const fastgltf::sources::BufferView & buffer_view) -> return_type {
|
||||
fastgltf::BufferView & view = gltf.bufferViews.at(buffer_view.bufferViewIndex);
|
||||
|
||||
fastgltf::Buffer & buffer = gltf.buffers.at(view.bufferIndex);
|
||||
|
||||
auto buffer2 = visit_source(buffer.data);
|
||||
|
||||
return {subspan(buffer2.bytes, view.byteOffset, view.byteLength), buffer_view.mimeType};
|
||||
},
|
||||
[&](const fastgltf::sources::URI & uri) -> return_type {
|
||||
if (!uri.uri.isLocalPath())
|
||||
throw std::runtime_error("Non local paths are not supported"); // TODO ?
|
||||
|
||||
fastgltf::span<const std::byte> data = load(uri);
|
||||
|
||||
// Don't use the MIME type from fastgltf, it's not initialized for URIs
|
||||
return {subspan(data, uri.fileByteOffset), fastgltf::MimeType::None};
|
||||
},
|
||||
[&](const fastgltf::sources::Vector & vector) -> return_type {
|
||||
fastgltf::span<const std::byte> data{reinterpret_cast<const std::byte *>(vector.bytes.data()), vector.bytes.size()};
|
||||
return {data, vector.mimeType};
|
||||
},
|
||||
[&](const fastgltf::sources::Array & array) -> return_type {
|
||||
fastgltf::span<const std::byte> data{reinterpret_cast<const std::byte *>(array.bytes.data()), array.bytes.size()};
|
||||
return {data, array.mimeType};
|
||||
},
|
||||
[&](const fastgltf::sources::CustomBuffer & custom_buffer) -> return_type {
|
||||
throw std::runtime_error("Unimplemented source CustomBuffer");
|
||||
// TODO ?
|
||||
},
|
||||
[&](fastgltf::sources::ByteView & byte_view) -> return_type {
|
||||
return {byte_view.bytes, byte_view.mimeType};
|
||||
}},
|
||||
source);
|
||||
}
|
||||
|
||||
std::unordered_map<int, std::shared_ptr<vk::raii::ImageView>> images;
|
||||
std::shared_ptr<vk::raii::ImageView> load_image(int index, bool srgb)
|
||||
{
|
||||
auto it = images.find(index);
|
||||
if (it != images.end())
|
||||
return it->second;
|
||||
|
||||
try
|
||||
{
|
||||
auto [image_data, mime_type] = visit_source(gltf.images[index].data);
|
||||
auto image = do_load_image(physical_device, device, queue, cb_pool, image_data, srgb);
|
||||
|
||||
images.emplace(index, image);
|
||||
return image;
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::shared_ptr<renderer::texture>> load_all_textures()
|
||||
{
|
||||
// Determine which texture is sRGB
|
||||
std::vector<uint8_t> srgb_array;
|
||||
srgb_array.resize(gltf.textures.size(), false);
|
||||
for (const fastgltf::Material & gltf_material: gltf.materials)
|
||||
{
|
||||
if (gltf_material.pbrData.baseColorTexture)
|
||||
srgb_array.at(gltf_material.pbrData.baseColorTexture->textureIndex) = true;
|
||||
|
||||
if (gltf_material.emissiveTexture)
|
||||
srgb_array.at(gltf_material.emissiveTexture->textureIndex) = true;
|
||||
}
|
||||
|
||||
std::vector<std::shared_ptr<renderer::texture>> textures;
|
||||
textures.reserve(gltf.textures.size());
|
||||
for (auto && [srgb, gltf_texture]: std::views::zip(srgb_array, gltf.textures))
|
||||
{
|
||||
auto & texture_ref = *textures.emplace_back(std::make_shared<renderer::texture>());
|
||||
|
||||
if (gltf_texture.samplerIndex)
|
||||
{
|
||||
fastgltf::Sampler & sampler = gltf.samplers.at(*gltf_texture.samplerIndex);
|
||||
texture_ref.sampler = convert(sampler);
|
||||
}
|
||||
|
||||
if (gltf_texture.basisuImageIndex)
|
||||
{
|
||||
texture_ref.image_view = load_image(*gltf_texture.basisuImageIndex, srgb);
|
||||
if (texture_ref.image_view)
|
||||
continue;
|
||||
}
|
||||
|
||||
// if (gltf_texture.ddsImageIndex)
|
||||
// {
|
||||
// // TODO
|
||||
// }
|
||||
|
||||
// if (gltf_texture.webpImageIndex)
|
||||
// {
|
||||
// // TODO
|
||||
// }
|
||||
|
||||
if (gltf_texture.imageIndex)
|
||||
{
|
||||
texture_ref.image_view = load_image(*gltf_texture.imageIndex, srgb);
|
||||
if (texture_ref.image_view)
|
||||
continue;
|
||||
}
|
||||
|
||||
throw std::runtime_error("Unsupported image type");
|
||||
}
|
||||
|
||||
return textures;
|
||||
}
|
||||
|
||||
void load_all_buffers()
|
||||
{
|
||||
for (fastgltf::Buffer & buffer: gltf.buffers)
|
||||
{
|
||||
if (std::holds_alternative<fastgltf::sources::URI>(buffer.data))
|
||||
{
|
||||
fastgltf::sources::URI uri = std::get<fastgltf::sources::URI>(buffer.data);
|
||||
|
||||
// Don't use the MIME type from fastgltf, it's not initialized for URIs
|
||||
buffer.data = fastgltf::sources::ByteView(load(uri), fastgltf::MimeType::None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::shared_ptr<renderer::material>> load_all_materials(std::vector<std::shared_ptr<renderer::texture>> & textures, gpu_buffer & staging_buffer, const renderer::material & default_material)
|
||||
{
|
||||
std::vector<std::shared_ptr<renderer::material>> materials;
|
||||
materials.reserve(gltf.materials.size());
|
||||
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<renderer::material>(default_material));
|
||||
material_ref.name = gltf_material.name;
|
||||
spdlog::info("Loading material \"{}\"", material_ref.name);
|
||||
material_ref.buffer.reset();
|
||||
material_ref.ds.reset();
|
||||
|
||||
material_ref.double_sided = gltf_material.doubleSided;
|
||||
material_ref.blend_enable = gltf_material.alphaMode == fastgltf::AlphaMode::Blend; // TODO handle alpha cut off mode
|
||||
|
||||
renderer::material::gpu_data & material_data = material_ref.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;
|
||||
|
||||
if (gltf_material.pbrData.baseColorTexture)
|
||||
{
|
||||
material_ref.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_data.metallic_roughness_texcoord = gltf_material.pbrData.metallicRoughnessTexture->texCoordIndex;
|
||||
}
|
||||
|
||||
if (gltf_material.occlusionTexture)
|
||||
{
|
||||
material_ref.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_data.emissive_texcoord = gltf_material.emissiveTexture->texCoordIndex;
|
||||
}
|
||||
|
||||
if (gltf_material.normalTexture)
|
||||
{
|
||||
material_ref.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);
|
||||
}
|
||||
|
||||
return materials;
|
||||
}
|
||||
|
||||
std::vector<std::shared_ptr<renderer::mesh>> load_all_meshes(std::vector<std::shared_ptr<renderer::material>> & materials, gpu_buffer & staging_buffer)
|
||||
{
|
||||
std::vector<std::shared_ptr<renderer::mesh>> meshes;
|
||||
meshes.reserve(gltf.meshes.size());
|
||||
for (const fastgltf::Mesh & gltf_mesh: gltf.meshes)
|
||||
{
|
||||
std::shared_ptr<renderer::mesh> & mesh_ref = meshes.emplace_back();
|
||||
mesh_ref = std::make_shared<renderer::mesh>();
|
||||
|
||||
mesh_ref->primitives.reserve(gltf_mesh.primitives.size());
|
||||
|
||||
for (const fastgltf::Primitive & gltf_primitive: gltf_mesh.primitives)
|
||||
{
|
||||
auto & primitive_ref = mesh_ref->primitives.emplace_back();
|
||||
|
||||
if (gltf_primitive.indicesAccessor)
|
||||
{
|
||||
fastgltf::Accessor & indices_accessor = gltf.accessors.at(*gltf_primitive.indicesAccessor);
|
||||
|
||||
primitive_ref.indexed = true;
|
||||
primitive_ref.index_offset = staging_buffer.add_indices(indices_accessor);
|
||||
primitive_ref.index_count = indices_accessor.count;
|
||||
|
||||
switch (indices_accessor.componentType)
|
||||
{
|
||||
case fastgltf::ComponentType::Byte:
|
||||
case fastgltf::ComponentType::UnsignedByte:
|
||||
primitive_ref.index_type = vk::IndexType::eUint8EXT;
|
||||
break;
|
||||
|
||||
case fastgltf::ComponentType::Short:
|
||||
case fastgltf::ComponentType::UnsignedShort:
|
||||
primitive_ref.index_type = vk::IndexType::eUint16;
|
||||
break;
|
||||
|
||||
case fastgltf::ComponentType::Int:
|
||||
case fastgltf::ComponentType::UnsignedInt:
|
||||
primitive_ref.index_type = vk::IndexType::eUint32;
|
||||
break;
|
||||
|
||||
default:
|
||||
throw std::runtime_error("Invalid index type");
|
||||
break;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
primitive_ref.indexed = false;
|
||||
}
|
||||
|
||||
std::vector<renderer::vertex> vertices;
|
||||
|
||||
copy_vertex_attributes(gltf, gltf_primitive, "POSITION", vertices, &renderer::vertex::position);
|
||||
copy_vertex_attributes(gltf, gltf_primitive, "NORMAL", vertices, &renderer::vertex::normal);
|
||||
copy_vertex_attributes(gltf, gltf_primitive, "TANGENT", vertices, &renderer::vertex::tangent);
|
||||
copy_vertex_attributes(gltf, gltf_primitive, "TEXCOORD_", vertices, &renderer::vertex::texcoord);
|
||||
copy_vertex_attributes(gltf, gltf_primitive, "COLOR", vertices, &renderer::vertex::color);
|
||||
copy_vertex_attributes(gltf, gltf_primitive, "JOINTS_", vertices, &renderer::vertex::joints);
|
||||
copy_vertex_attributes(gltf, gltf_primitive, "WEIGHTS_", vertices, &renderer::vertex::weights);
|
||||
|
||||
primitive_ref.vertex_offset = staging_buffer.add_vertices(vertices);
|
||||
primitive_ref.vertex_count = vertices.size();
|
||||
|
||||
primitive_ref.cull_mode = vk::CullModeFlagBits::eBack; // TBC
|
||||
primitive_ref.front_face = vk::FrontFace::eCounterClockwise; // TBC
|
||||
primitive_ref.topology = convert(gltf_primitive.type);
|
||||
|
||||
if (gltf_primitive.materialIndex)
|
||||
primitive_ref.material_ = materials.at(*gltf_primitive.materialIndex);
|
||||
}
|
||||
}
|
||||
|
||||
return meshes;
|
||||
}
|
||||
|
||||
entt::registry load_all_nodes(const std::vector<std::shared_ptr<renderer::mesh>> & meshes)
|
||||
{
|
||||
entt::registry registry;
|
||||
|
||||
std::vector<entt::entity> entities{gltf.nodes.size()};
|
||||
registry.create(entities.begin(), entities.end());
|
||||
|
||||
// Create all node components first
|
||||
registry.insert<components::node>(entities.begin(), entities.end());
|
||||
|
||||
for (const auto & [entity, gltf_node]: std::ranges::zip_view(entities, gltf.nodes))
|
||||
{
|
||||
components::node & node = registry.get<components::node>(entity);
|
||||
node.name = gltf_node.name;
|
||||
|
||||
if (gltf_node.meshIndex)
|
||||
node.mesh = meshes[*gltf_node.meshIndex];
|
||||
|
||||
if (gltf_node.skinIndex)
|
||||
{
|
||||
auto & skin = gltf.skins.at(*gltf_node.skinIndex);
|
||||
|
||||
node.joints.resize(skin.joints.size());
|
||||
|
||||
for (auto [i, joint_index]: utils::enumerate(skin.joints))
|
||||
node.joints.at(i).first = entities[joint_index];
|
||||
|
||||
if (skin.inverseBindMatrices)
|
||||
{
|
||||
const fastgltf::Accessor & accessor = gltf.accessors.at(*skin.inverseBindMatrices);
|
||||
|
||||
fastgltf::iterateAccessorWithIndex<glm::mat4>(gltf, accessor, [&](const glm::mat4 & value, std::size_t idx) {
|
||||
node.joints.at(idx).second = value;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (size_t child: gltf_node.children)
|
||||
{
|
||||
registry.get<components::node>(entities[child]).parent = entity;
|
||||
}
|
||||
|
||||
auto TRS = std::get<fastgltf::TRS>(gltf_node.transform);
|
||||
|
||||
node.position = glm::make_vec3(TRS.translation.data());
|
||||
node.orientation = glm::make_quat(TRS.rotation.data());
|
||||
node.scale = glm::make_vec3(TRS.scale.data());
|
||||
node.visible = true;
|
||||
std::ranges::fill(node.clipping_planes, glm::vec4{0, 0, 0, 1});
|
||||
}
|
||||
|
||||
return registry;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
renderer::vertex::description renderer::vertex::describe()
|
||||
{
|
||||
renderer::vertex::description desc;
|
||||
|
||||
desc.binding = vk::VertexInputBindingDescription{
|
||||
.binding = 0,
|
||||
.stride = sizeof(vertex),
|
||||
.inputRate = vk::VertexInputRate::eVertex,
|
||||
};
|
||||
|
||||
vk::VertexInputAttributeDescription attribute{
|
||||
.location = 0,
|
||||
.binding = 0,
|
||||
};
|
||||
|
||||
#define VERTEX_ATTR(member) \
|
||||
attribute.format = vk_attribute_format<decltype(vertex::member)>; \
|
||||
for (size_t i = 0; i < nb_attributes<decltype(vertex::member)>; i++) \
|
||||
{ \
|
||||
attribute.offset = offsetof(vertex, member) + i * sizeof(remove_array_t<decltype(vertex::member)>); \
|
||||
desc.attributes.push_back(attribute); \
|
||||
attribute.location++; \
|
||||
if (is_array_v<decltype(vertex::member)>) \
|
||||
{ \
|
||||
desc.attribute_names.push_back(#member "_" + std::to_string(i)); \
|
||||
} \
|
||||
else \
|
||||
{ \
|
||||
desc.attribute_names.push_back(#member); \
|
||||
} \
|
||||
}
|
||||
|
||||
VERTEX_ATTR(position);
|
||||
VERTEX_ATTR(normal);
|
||||
VERTEX_ATTR(tangent);
|
||||
VERTEX_ATTR(texcoord);
|
||||
VERTEX_ATTR(color);
|
||||
VERTEX_ATTR(joints);
|
||||
VERTEX_ATTR(weights);
|
||||
|
||||
static_assert(vertex{}.joints.size() == vertex{}.weights.size());
|
||||
|
||||
return desc;
|
||||
}
|
||||
|
||||
entt::registry scene_loader::operator()(const std::filesystem::path & gltf_path)
|
||||
{
|
||||
vk::PhysicalDeviceProperties physical_device_properties = physical_device.getProperties();
|
||||
vk::raii::CommandPool cb_pool{device, vk::CommandPoolCreateInfo{
|
||||
.flags = vk::CommandPoolCreateFlagBits::eTransient | vk::CommandPoolCreateFlagBits::eResetCommandBuffer,
|
||||
.queueFamilyIndex = queue_family_index,
|
||||
}};
|
||||
|
||||
spdlog::debug("Loading {}", gltf_path.native());
|
||||
|
||||
asset asset_file(gltf_path);
|
||||
fastgltf::GltfDataBuffer data_buffer;
|
||||
data_buffer.copyBytes(reinterpret_cast<const uint8_t *>(asset_file.data()), asset_file.size());
|
||||
|
||||
fastgltf::Asset asset = load_gltf_asset(data_buffer, gltf_path.parent_path());
|
||||
loader_context ctx(gltf_path.parent_path(), asset, physical_device, device, queue, cb_pool);
|
||||
|
||||
#ifndef NDEBUG
|
||||
if (auto error = fastgltf::validate(asset); error != fastgltf::Error::None)
|
||||
throw std::runtime_error(std::string(fastgltf::getErrorMessage(error)));
|
||||
#endif
|
||||
|
||||
// Load all buffers from URIs
|
||||
ctx.load_all_buffers();
|
||||
|
||||
gpu_buffer staging_buffer(physical_device_properties, asset);
|
||||
|
||||
// Load all textures
|
||||
auto textures = ctx.load_all_textures();
|
||||
|
||||
// Load all materials
|
||||
auto materials = ctx.load_all_materials(textures, staging_buffer, *default_material);
|
||||
|
||||
// Load all meshes
|
||||
auto meshes = ctx.load_all_meshes(materials, staging_buffer);
|
||||
|
||||
// Load all nodes
|
||||
entt::registry loaded_scene = ctx.load_all_nodes(meshes);
|
||||
|
||||
// Copy the staging buffer to the GPU
|
||||
spdlog::debug("Uploading scene data ({} bytes) to GPU memory", staging_buffer.size());
|
||||
auto buffer = std::make_shared<buffer_allocation>(staging_buffer.copy_to_gpu());
|
||||
|
||||
for (auto & i: materials)
|
||||
i->buffer = buffer;
|
||||
|
||||
for (auto & i: meshes)
|
||||
i->buffer = buffer;
|
||||
|
||||
return loaded_scene;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void copy_components(entt::registry & scene, const entt::registry & prefab, const std::unordered_map<entt::entity, entt::entity> & entity_map)
|
||||
{
|
||||
for (const auto & [entity, component]: prefab.view<T>().each())
|
||||
{
|
||||
scene.emplace<T>(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<entt::entity>();
|
||||
|
||||
std::vector<entt::entity> scene_entities{prefab_entities.size()};
|
||||
scene.create(scene_entities.begin(), scene_entities.end());
|
||||
|
||||
std::unordered_map<entt::entity, entt::entity> 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<components::node>(scene, prefab, entity_map);
|
||||
|
||||
// update links
|
||||
for (auto [prefab_entity, scene_entity]: entity_map)
|
||||
{
|
||||
if (prefab_entity == entt::null)
|
||||
continue;
|
||||
|
||||
auto & node = scene.get<components::node>(scene_entity);
|
||||
|
||||
node.parent = entity_map.at(node.parent);
|
||||
|
||||
for (auto & joint: node.joints)
|
||||
{
|
||||
joint.first = entity_map.at(joint.first);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* WiVRn VR streaming
|
||||
* Copyright (C) 2025 Guillaume Meunier <guillaume.meunier@centraliens.net>
|
||||
*
|
||||
* 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <filesystem>
|
||||
#include <vulkan/vulkan_raii.hpp>
|
||||
|
||||
#include "scene_components.h"
|
||||
|
||||
class scene_loader
|
||||
{
|
||||
vk::raii::Device & device;
|
||||
vk::raii::PhysicalDevice physical_device;
|
||||
vk::raii::Queue & queue;
|
||||
uint32_t queue_family_index;
|
||||
std::shared_ptr<renderer::material> default_material;
|
||||
|
||||
public:
|
||||
scene_loader(vk::raii::Device & device, vk::raii::PhysicalDevice physical_device, vk::raii::Queue & queue, uint32_t queue_family_index, std::shared_ptr<renderer::material> default_material) :
|
||||
device(device),
|
||||
physical_device(physical_device),
|
||||
queue(queue),
|
||||
queue_family_index(queue_family_index),
|
||||
default_material(default_material)
|
||||
{}
|
||||
|
||||
entt::registry operator()(const std::filesystem::path & gltf_path);
|
||||
|
||||
void add_prefab(entt::registry & scene, const entt::registry & prefab, entt::entity root = entt::null);
|
||||
};
|
||||
+354
-242
@@ -21,7 +21,7 @@
|
||||
#include "application.h"
|
||||
#include "render/growable_descriptor_pool.h"
|
||||
#include "render/image_loader.h"
|
||||
#include "render/scene_data.h"
|
||||
#include "render/scene_components.h"
|
||||
#include "utils/alignment.h"
|
||||
#include "utils/fmt_glm.h"
|
||||
#include "utils/ranges.h"
|
||||
@@ -29,6 +29,8 @@
|
||||
#include "vk/pipeline.h"
|
||||
#include "vk/shader.h"
|
||||
#include <boost/pfr/core.hpp>
|
||||
#include <entt/entity/entity.hpp>
|
||||
#include <entt/entt.hpp>
|
||||
#include <glm/gtc/matrix_access.hpp>
|
||||
#include <glm/gtc/type_ptr.hpp>
|
||||
#include <glm/gtx/quaternion.hpp>
|
||||
@@ -37,6 +39,8 @@
|
||||
#include <ranges>
|
||||
#include <spdlog/spdlog.h>
|
||||
#include <vk_mem_alloc.h>
|
||||
#include <vulkan/vulkan_enums.hpp>
|
||||
#include <vulkan/vulkan_structs.hpp>
|
||||
|
||||
extern const std::map<std::string, std::vector<uint32_t>> shaders;
|
||||
|
||||
@@ -74,7 +78,7 @@ vk::Format scene_renderer::find_usable_image_format(
|
||||
return vk::Format::eUndefined;
|
||||
}
|
||||
|
||||
std::shared_ptr<scene_data::texture> scene_renderer::create_default_texture(vk::raii::CommandPool & cb_pool, std::vector<uint8_t> pixel)
|
||||
std::shared_ptr<renderer::texture> scene_renderer::create_default_texture(vk::raii::CommandPool & cb_pool, std::vector<uint8_t> pixel)
|
||||
{
|
||||
vk::Format format;
|
||||
|
||||
@@ -99,12 +103,12 @@ std::shared_ptr<scene_data::texture> scene_renderer::create_default_texture(vk::
|
||||
|
||||
std::shared_ptr<vk::raii::ImageView> image_view = loader.image_view;
|
||||
|
||||
return std::make_shared<scene_data::texture>(image_view, sampler_info{});
|
||||
return std::make_shared<renderer::texture>(image_view, renderer::sampler_info{});
|
||||
}
|
||||
|
||||
std::shared_ptr<scene_data::material> scene_renderer::create_default_material(vk::raii::CommandPool & cb_pool)
|
||||
std::shared_ptr<renderer::material> scene_renderer::create_default_material(vk::raii::CommandPool & cb_pool)
|
||||
{
|
||||
auto default_material = std::make_shared<scene_data::material>();
|
||||
auto default_material = std::make_shared<renderer::material>();
|
||||
default_material->name = "default";
|
||||
|
||||
default_material->base_color_texture = create_default_texture(cb_pool, {255, 255, 255, 255});
|
||||
@@ -200,23 +204,14 @@ scene_renderer::scene_renderer(
|
||||
vk::raii::PhysicalDevice physical_device,
|
||||
vk::raii::Queue & queue,
|
||||
vk::raii::CommandPool & cb_pool,
|
||||
vk::Extent2D output_size,
|
||||
vk::Format output_format,
|
||||
// std::span<vk::Format> depth_formats,
|
||||
vk::Format depth_format,
|
||||
int frames_in_flight,
|
||||
bool keep_depth_buffer) :
|
||||
int frames_in_flight) :
|
||||
physical_device(physical_device),
|
||||
device(device),
|
||||
physical_device_properties(physical_device.getProperties()),
|
||||
queue(queue),
|
||||
output_size(output_size),
|
||||
output_format(output_format),
|
||||
depth_format(depth_format),
|
||||
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
|
||||
keep_depth_buffer(keep_depth_buffer)
|
||||
ds_pool_material(device, layout_1, layout_bindings_1, 100) // TODO tunable
|
||||
{
|
||||
// Create the default material
|
||||
default_material = create_default_material(cb_pool);
|
||||
@@ -243,8 +238,6 @@ scene_renderer::scene_renderer(
|
||||
.queryCount = uint32_t(2 * frames_in_flight),
|
||||
});
|
||||
|
||||
renderpass = create_renderpass();
|
||||
|
||||
std::array layouts{*layout_0, *layout_1};
|
||||
pipeline_layout = create_pipeline_layout(layouts);
|
||||
}
|
||||
@@ -264,40 +257,40 @@ void scene_renderer::wait_idle()
|
||||
throw std::runtime_error("vkWaitForfences: " + vk::to_string(result));
|
||||
}
|
||||
|
||||
// #define MSAA_4x
|
||||
vk::raii::RenderPass & scene_renderer::get_renderpass(const renderpass_info & info)
|
||||
{
|
||||
auto it = renderpasses.find(info);
|
||||
if (it != renderpasses.end())
|
||||
return it->second;
|
||||
|
||||
#ifdef MSAA_4x
|
||||
#define MSAA_SAMPLES vk::SampleCountFlagBits::e4
|
||||
#else
|
||||
#define MSAA_SAMPLES vk::SampleCountFlagBits::e1
|
||||
#endif
|
||||
return renderpasses.emplace(info, create_renderpass(info)).first->second;
|
||||
}
|
||||
|
||||
vk::raii::RenderPass scene_renderer::create_renderpass()
|
||||
vk::raii::RenderPass scene_renderer::create_renderpass(const renderpass_info & info_)
|
||||
{
|
||||
vk::RenderPassCreateInfo info;
|
||||
|
||||
std::array attachments = {
|
||||
vk::AttachmentDescription{
|
||||
.format = output_format,
|
||||
.samples = MSAA_SAMPLES,
|
||||
.format = info_.color_format,
|
||||
.samples = info_.msaa_samples,
|
||||
.loadOp = vk::AttachmentLoadOp::eClear,
|
||||
.storeOp = vk::AttachmentStoreOp::eStore,
|
||||
.initialLayout = vk::ImageLayout::eUndefined,
|
||||
.finalLayout = vk::ImageLayout::eColorAttachmentOptimal,
|
||||
},
|
||||
vk::AttachmentDescription{
|
||||
.format = depth_format,
|
||||
.samples = MSAA_SAMPLES,
|
||||
.format = info_.depth_format,
|
||||
.samples = info_.msaa_samples,
|
||||
.loadOp = vk::AttachmentLoadOp::eClear,
|
||||
.storeOp = keep_depth_buffer ? vk::AttachmentStoreOp::eStore : vk::AttachmentStoreOp::eDontCare,
|
||||
.storeOp = info_.keep_depth_buffer ? vk::AttachmentStoreOp::eStore : vk::AttachmentStoreOp::eDontCare,
|
||||
.stencilLoadOp = vk::AttachmentLoadOp::eClear,
|
||||
.stencilStoreOp = vk::AttachmentStoreOp::eDontCare,
|
||||
.initialLayout = vk::ImageLayout::eUndefined,
|
||||
.finalLayout = vk::ImageLayout::eDepthStencilAttachmentOptimal,
|
||||
},
|
||||
#ifdef MSAA_4x
|
||||
vk::AttachmentDescription{
|
||||
.format = output_format,
|
||||
.format = info_.color_format,
|
||||
.samples = vk::SampleCountFlagBits::e1,
|
||||
.loadOp = vk::AttachmentLoadOp::eDontCare,
|
||||
.storeOp = vk::AttachmentStoreOp::eStore,
|
||||
@@ -306,10 +299,17 @@ vk::raii::RenderPass scene_renderer::create_renderpass()
|
||||
.initialLayout = vk::ImageLayout::eUndefined,
|
||||
.finalLayout = vk::ImageLayout::eColorAttachmentOptimal,
|
||||
|
||||
}
|
||||
#endif
|
||||
};
|
||||
info.setAttachments(attachments);
|
||||
}};
|
||||
|
||||
if (info_.msaa_samples != vk::SampleCountFlagBits::e1)
|
||||
{
|
||||
info.setAttachments(attachments);
|
||||
}
|
||||
else
|
||||
{
|
||||
info.setPAttachments(attachments.data());
|
||||
info.setAttachmentCount(2);
|
||||
}
|
||||
|
||||
vk::AttachmentReference color_attachment{
|
||||
.attachment = 0,
|
||||
@@ -321,22 +321,22 @@ vk::raii::RenderPass scene_renderer::create_renderpass()
|
||||
.layout = vk::ImageLayout::eDepthStencilAttachmentOptimal,
|
||||
};
|
||||
|
||||
#ifdef MSAA_4x
|
||||
// Only used if MSAA is enabled
|
||||
vk::AttachmentReference resolve_attachment{
|
||||
.attachment = 2,
|
||||
.layout = vk::ImageLayout::eColorAttachmentOptimal,
|
||||
};
|
||||
#endif
|
||||
|
||||
vk::SubpassDescription subpasses{
|
||||
.pipelineBindPoint = vk::PipelineBindPoint::eGraphics,
|
||||
.colorAttachmentCount = 1,
|
||||
.pColorAttachments = &color_attachment,
|
||||
#ifdef MSAA_4x
|
||||
.pResolveAttachments = &resolve_attachment,
|
||||
#endif
|
||||
.pDepthStencilAttachment = &depth_attachment,
|
||||
};
|
||||
|
||||
if (info_.msaa_samples != vk::SampleCountFlagBits::e1)
|
||||
subpasses.pResolveAttachments = &resolve_attachment;
|
||||
|
||||
info.setSubpasses(subpasses);
|
||||
|
||||
std::array dependencies{
|
||||
@@ -361,53 +361,53 @@ vk::raii::RenderPass scene_renderer::create_renderpass()
|
||||
return vk::raii::RenderPass(device, info);
|
||||
}
|
||||
|
||||
scene_renderer::output_image & scene_renderer::get_output_image_data(vk::Image output_color, vk::Image output_depth)
|
||||
scene_renderer::output_image & scene_renderer::get_output_image_data(const output_image_info & info)
|
||||
{
|
||||
std::pair images{output_color, output_depth};
|
||||
auto it = output_images.find(images);
|
||||
auto it = output_images.find(info);
|
||||
if (it != output_images.end())
|
||||
return it->second;
|
||||
|
||||
return output_images.emplace(images, create_output_image_data(output_color, output_depth)).first->second;
|
||||
return output_images.emplace(info, create_output_image_data(info)).first->second;
|
||||
}
|
||||
|
||||
scene_renderer::output_image scene_renderer::create_output_image_data(vk::Image output_color, vk::Image output_depth)
|
||||
scene_renderer::output_image scene_renderer::create_output_image_data(const output_image_info & info)
|
||||
{
|
||||
output_image out;
|
||||
|
||||
// TODO: use image view from xr::swapchain
|
||||
out.image_view = vk::raii::ImageView(
|
||||
device, vk::ImageViewCreateInfo{
|
||||
.image = output_color,
|
||||
.image = info.color,
|
||||
.viewType = vk::ImageViewType::e2D,
|
||||
.format = output_format,
|
||||
.format = info.renderpass.color_format,
|
||||
.components{},
|
||||
.subresourceRange = {
|
||||
.aspectMask = vk::ImageAspectFlagBits::eColor,
|
||||
.baseMipLevel = 0,
|
||||
.levelCount = 1,
|
||||
.baseArrayLayer = 0,
|
||||
.baseArrayLayer = info.base_array_layer,
|
||||
.layerCount = 1,
|
||||
},
|
||||
});
|
||||
|
||||
// TODO: check requiredFlags
|
||||
if (not output_depth)
|
||||
if (not info.depth)
|
||||
out.depth_buffer = image_allocation{
|
||||
device,
|
||||
vk::ImageCreateInfo{
|
||||
.imageType = vk::ImageType::e2D,
|
||||
.format = depth_format,
|
||||
.format = info.renderpass.depth_format,
|
||||
.extent = {
|
||||
.width = output_size.width,
|
||||
.height = output_size.height,
|
||||
.width = info.output_size.width,
|
||||
.height = info.output_size.height,
|
||||
.depth = 1,
|
||||
},
|
||||
.mipLevels = 1,
|
||||
.arrayLayers = 1,
|
||||
.samples = MSAA_SAMPLES,
|
||||
.samples = info.renderpass.msaa_samples,
|
||||
.tiling = vk::ImageTiling::eOptimal,
|
||||
.usage = vk::ImageUsageFlagBits::eDepthStencilAttachment | vk::ImageUsageFlagBits::eTransientAttachment},
|
||||
.usage = vk::ImageUsageFlagBits::eDepthStencilAttachment | vk::ImageUsageFlagBits::eTransientAttachment,
|
||||
},
|
||||
VmaAllocationCreateInfo{
|
||||
.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT,
|
||||
.usage = VMA_MEMORY_USAGE_AUTO,
|
||||
@@ -417,77 +417,87 @@ scene_renderer::output_image scene_renderer::create_output_image_data(vk::Image
|
||||
out.depth_view = vk::raii::ImageView(
|
||||
device,
|
||||
vk::ImageViewCreateInfo{
|
||||
.image = output_depth ? output_depth : out.depth_buffer,
|
||||
.image = info.depth ? info.depth : out.depth_buffer,
|
||||
.viewType = vk::ImageViewType::e2D,
|
||||
.format = depth_format,
|
||||
.format = info.renderpass.depth_format,
|
||||
.components{},
|
||||
.subresourceRange = {
|
||||
.aspectMask = vk::ImageAspectFlagBits::eDepth,
|
||||
.baseMipLevel = 0,
|
||||
.levelCount = 1,
|
||||
.baseArrayLayer = 0,
|
||||
.baseArrayLayer = info.depth ? info.base_array_layer : 0,
|
||||
.layerCount = 1,
|
||||
},
|
||||
});
|
||||
|
||||
#ifdef MSAA_4x
|
||||
out.multisample_image = image_allocation{vk::ImageCreateInfo{
|
||||
.imageType = vk::ImageType::e2D,
|
||||
.format = output_format,
|
||||
.extent = {
|
||||
.width = output_size.width,
|
||||
.height = output_size.height,
|
||||
.depth = 1,
|
||||
},
|
||||
.mipLevels = 1,
|
||||
.arrayLayers = 1,
|
||||
.samples = MSAA_SAMPLES,
|
||||
.tiling = vk::ImageTiling::eOptimal,
|
||||
.usage = vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransientAttachment,
|
||||
},
|
||||
VmaAllocationCreateInfo{
|
||||
.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT,
|
||||
.usage = VMA_MEMORY_USAGE_AUTO,
|
||||
.requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, // TODO: check
|
||||
.preferredFlags = VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT,
|
||||
}};
|
||||
if (info.renderpass.msaa_samples != vk::SampleCountFlagBits::e1)
|
||||
{
|
||||
out.multisample_image = image_allocation{
|
||||
device,
|
||||
vk::ImageCreateInfo{
|
||||
.imageType = vk::ImageType::e2D,
|
||||
.format = info.renderpass.color_format,
|
||||
.extent = {
|
||||
.width = info.output_size.width,
|
||||
.height = info.output_size.height,
|
||||
.depth = 1,
|
||||
},
|
||||
.mipLevels = 1,
|
||||
.arrayLayers = 1,
|
||||
.samples = info.renderpass.msaa_samples,
|
||||
.tiling = vk::ImageTiling::eOptimal,
|
||||
.usage = vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransientAttachment,
|
||||
},
|
||||
VmaAllocationCreateInfo{
|
||||
.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT,
|
||||
.usage = VMA_MEMORY_USAGE_AUTO,
|
||||
.requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, // TODO: check
|
||||
.preferredFlags = VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT,
|
||||
}};
|
||||
|
||||
out.multisample_view = vk::raii::ImageView(device, vk::ImageViewCreateInfo{
|
||||
.image = out.multisample_image,
|
||||
.viewType = vk::ImageViewType::e2D,
|
||||
.format = output_format,
|
||||
.components{},
|
||||
.subresourceRange = {
|
||||
.aspectMask = vk::ImageAspectFlagBits::eColor,
|
||||
.baseMipLevel = 0,
|
||||
.levelCount = 1,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = 1,
|
||||
},
|
||||
});
|
||||
#endif
|
||||
out.multisample_view = vk::raii::ImageView(
|
||||
device,
|
||||
vk::ImageViewCreateInfo{
|
||||
.image = out.multisample_image,
|
||||
.viewType = vk::ImageViewType::e2D,
|
||||
.format = info.renderpass.color_format,
|
||||
.components{},
|
||||
.subresourceRange = {
|
||||
.aspectMask = vk::ImageAspectFlagBits::eColor,
|
||||
.baseMipLevel = 0,
|
||||
.levelCount = 1,
|
||||
.baseArrayLayer = 0,
|
||||
.layerCount = 1,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
vk::FramebufferCreateInfo fb_info{
|
||||
.renderPass = *renderpass,
|
||||
.width = output_size.width,
|
||||
.height = output_size.height,
|
||||
.renderPass = *get_renderpass(info.renderpass),
|
||||
.width = info.output_size.width,
|
||||
.height = info.output_size.height,
|
||||
.layers = 1,
|
||||
};
|
||||
|
||||
#ifdef MSAA_4x
|
||||
std::array attachments{
|
||||
vk::ImageView{*out.multisample_view},
|
||||
vk::ImageView{*out.depth_view},
|
||||
vk::ImageView{*out.image_view},
|
||||
};
|
||||
#else
|
||||
std::array attachments{
|
||||
vk::ImageView{*out.image_view},
|
||||
vk::ImageView{*out.depth_view},
|
||||
};
|
||||
#endif
|
||||
fb_info.setAttachments(attachments);
|
||||
out.framebuffer = vk::raii::Framebuffer(device, fb_info);
|
||||
if (info.renderpass.msaa_samples != vk::SampleCountFlagBits::e1)
|
||||
{
|
||||
std::array attachments{
|
||||
vk::ImageView{*out.multisample_view},
|
||||
vk::ImageView{*out.depth_view},
|
||||
vk::ImageView{*out.image_view},
|
||||
};
|
||||
fb_info.setAttachments(attachments);
|
||||
out.framebuffer = vk::raii::Framebuffer(device, fb_info);
|
||||
}
|
||||
else
|
||||
{
|
||||
std::array attachments{
|
||||
vk::ImageView{*out.image_view},
|
||||
vk::ImageView{*out.depth_view},
|
||||
};
|
||||
fb_info.setAttachments(attachments);
|
||||
out.framebuffer = vk::raii::Framebuffer(device, fb_info);
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
@@ -518,7 +528,7 @@ vk::raii::PipelineLayout scene_renderer::create_pipeline_layout(std::span<vk::De
|
||||
|
||||
vk::raii::Pipeline scene_renderer::create_pipeline(const pipeline_info & info)
|
||||
{
|
||||
auto vertex_description = scene_data::vertex::describe();
|
||||
auto vertex_description = renderer::vertex::describe();
|
||||
|
||||
spdlog::debug("Creating pipeline");
|
||||
|
||||
@@ -580,18 +590,8 @@ vk::raii::Pipeline scene_renderer::create_pipeline(const pipeline_info & info)
|
||||
.topology = info.topology,
|
||||
.primitiveRestartEnable = false,
|
||||
}},
|
||||
.Viewports = {vk::Viewport{
|
||||
.x = 0,
|
||||
.y = 0,
|
||||
.width = (float)output_size.width,
|
||||
.height = (float)output_size.height,
|
||||
.minDepth = 0,
|
||||
.maxDepth = 1,
|
||||
}},
|
||||
.Scissors = {vk::Rect2D{
|
||||
.offset = {0, 0},
|
||||
.extent = output_size,
|
||||
}},
|
||||
.Viewports = {vk::Viewport{}}, // Dynamic scissor / viewport but the count must be set
|
||||
.Scissors = {vk::Rect2D{}},
|
||||
.RasterizationState = {vk::PipelineRasterizationStateCreateInfo{
|
||||
.polygonMode = vk::PolygonMode::eFill,
|
||||
.cullMode = info.cull_mode,
|
||||
@@ -599,7 +599,7 @@ vk::raii::Pipeline scene_renderer::create_pipeline(const pipeline_info & info)
|
||||
.lineWidth = 1.0,
|
||||
}},
|
||||
.MultisampleState = {vk::PipelineMultisampleStateCreateInfo{
|
||||
.rasterizationSamples = MSAA_SAMPLES,
|
||||
.rasterizationSamples = info.renderpass.msaa_samples,
|
||||
}},
|
||||
.DepthStencilState = {vk::PipelineDepthStencilStateCreateInfo{
|
||||
.depthTestEnable = info.depth_test_enable,
|
||||
@@ -619,13 +619,17 @@ vk::raii::Pipeline scene_renderer::create_pipeline(const pipeline_info & info)
|
||||
.dstAlphaBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha,
|
||||
.alphaBlendOp = vk::BlendOp::eAdd,
|
||||
.colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA}},
|
||||
.DynamicStates = {
|
||||
vk::DynamicState::eViewport,
|
||||
vk::DynamicState::eScissor,
|
||||
},
|
||||
.layout = *pipeline_layout,
|
||||
.renderPass = *renderpass,
|
||||
.renderPass = *get_renderpass(info.renderpass),
|
||||
.subpass = 0,
|
||||
}};
|
||||
}
|
||||
|
||||
vk::Sampler scene_renderer::get_sampler(const sampler_info & info)
|
||||
vk::Sampler scene_renderer::get_sampler(const renderer::sampler_info & info)
|
||||
{
|
||||
auto it = samplers.find(info);
|
||||
if (it != samplers.end())
|
||||
@@ -715,14 +719,14 @@ scene_renderer::per_frame_resources & scene_renderer::current_frame()
|
||||
return frame_resources[current_frame_index];
|
||||
}
|
||||
|
||||
void scene_renderer::update_material_descriptor_set(scene_data::material & material)
|
||||
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<scene_data::texture> & texture) {
|
||||
auto f = [&](std::shared_ptr<renderer::texture> & texture) {
|
||||
return vk::DescriptorImageInfo{
|
||||
.sampler = get_sampler(texture->sampler),
|
||||
.imageView = **texture->image_view,
|
||||
@@ -741,7 +745,7 @@ void scene_renderer::update_material_descriptor_set(scene_data::material & mater
|
||||
vk::DescriptorBufferInfo write_ds_buffer{
|
||||
.buffer = *material.buffer,
|
||||
.offset = material.offset,
|
||||
.range = sizeof(scene_data::material::gpu_data),
|
||||
.range = sizeof(renderer::material::gpu_data),
|
||||
};
|
||||
|
||||
// Write each descriptor separately because the HTC XR Elite needs it for some reason
|
||||
@@ -793,24 +797,74 @@ void scene_renderer::update_material_descriptor_set(scene_data::material & mater
|
||||
device.updateDescriptorSets(write_ds, {});
|
||||
}
|
||||
|
||||
// static void print_scene_hierarchy(const scene_data& scene, std::span<glm::mat4> model_matrices, size_t root = scene_data::node::root_id, int level = 0)
|
||||
static void print_scene_hierarchy(const entt::registry & scene, entt::entity root = entt::null, int level = 0)
|
||||
{
|
||||
if (level == 0)
|
||||
spdlog::info("Node hierarchy:");
|
||||
|
||||
for (auto && [entity, node]: scene.view<components::node>().each())
|
||||
{
|
||||
if (node.parent != root)
|
||||
continue;
|
||||
|
||||
// glm::mat4 M = model_matrices[index];
|
||||
// glm::vec4 pos = glm::column(M, 3);
|
||||
// spdlog::info("{:{}} {} pos={}, rot={}, pos to root={}", "", level * 2, node.name, node.translation, node.rotation, glm::vec3(pos));
|
||||
|
||||
spdlog::info("{:{}} {} ({}, visible: {}, {})", "", level * 2, node.name, (int)entity, node.visible, node.global_visible);
|
||||
|
||||
print_scene_hierarchy(scene, entity, level + 1);
|
||||
}
|
||||
if (level == 0)
|
||||
spdlog::info("---------------");
|
||||
}
|
||||
|
||||
// Topological sort of all nodes
|
||||
// static std::vector<entt::entity> sort_nodes(entt::registry & scene)
|
||||
// {
|
||||
// for(const auto&& [index, node]: utils::enumerate(scene.scene_nodes))
|
||||
// std::vector<std::pair<entt::entity, entt::entity>> unsorted; // first: child, second: parent
|
||||
// std::unordered_set<entt::entity> processed;
|
||||
// std::vector<entt::entity> sorted;
|
||||
//
|
||||
// for(auto && [entity, node]: scene.view<components::node>().each())
|
||||
// {
|
||||
// if (node.parent_id != root)
|
||||
// continue;
|
||||
//
|
||||
// // glm::mat4 M = model_matrices[index];
|
||||
// // glm::vec4 pos = glm::column(M, 3);
|
||||
// // spdlog::info("{:{}} {} pos={}, rot={}, pos to root={}", "", level * 2, node.name, node.translation, node.rotation, glm::vec3(pos));
|
||||
//
|
||||
// spdlog::info("{:{}} {}", "", level * 2, node.name);
|
||||
//
|
||||
// print_scene_hierarchy(scene, model_matrices, index, level + 1);
|
||||
// if (scene.valid(node.parent))
|
||||
// unsorted.push_back({entity, node.parent});
|
||||
// else
|
||||
// {
|
||||
// processed.emplace(entity);
|
||||
// sorted.push_back(entity);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// while(not unsorted.empty())
|
||||
// {
|
||||
// for(auto it = unsorted.begin(); it != unsorted.end(); )
|
||||
// {
|
||||
// if (processed.contains(it->second))
|
||||
// {
|
||||
// processed.emplace(it->first);
|
||||
// sorted.push_back(it->first);
|
||||
// it = unsorted.erase(it);
|
||||
// }
|
||||
// else
|
||||
// ++it;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// return sorted;
|
||||
// }
|
||||
|
||||
void scene_renderer::render(scene_data & scene, const std::array<float, 4> & clear_color, std::span<frame_info> frames)
|
||||
void scene_renderer::render(
|
||||
entt::registry & scene,
|
||||
const std::array<float, 4> & clear_color,
|
||||
uint32_t layer_mask,
|
||||
vk::Extent2D output_size,
|
||||
vk::Format color_format,
|
||||
vk::Format depth_format,
|
||||
vk::Image color_buffer,
|
||||
vk::Image depth_buffer,
|
||||
std::span<frame_info> frames)
|
||||
{
|
||||
per_frame_resources & resources = current_frame();
|
||||
|
||||
@@ -826,41 +880,48 @@ void scene_renderer::render(scene_data & scene, const std::array<float, 4> & cle
|
||||
vk::ClearDepthStencilValue{0.0, 0},
|
||||
};
|
||||
|
||||
auto vertex_layout = scene_data::vertex::describe();
|
||||
|
||||
std::vector<glm::mat4> transform_to_root(scene.scene_nodes.size());
|
||||
std::vector<bool> reverse_side(scene.scene_nodes.size());
|
||||
std::vector<bool> visible(scene.scene_nodes.size());
|
||||
|
||||
for (const auto & [index, object]: utils::enumerate(scene.scene_nodes))
|
||||
// TODO once per frame, even if render is called several times
|
||||
for (auto && [entity, node]: scene.view<components::node>().each())
|
||||
{
|
||||
glm::mat4 transform_to_parent = glm::translate(glm::mat4(1), object.position) * (glm::mat4)object.orientation * glm::scale(glm::mat4(1), object.scale);
|
||||
float det = object.scale.x * object.scale.y * object.scale.z;
|
||||
glm::mat4 transform_to_root{1.0}; // Identity
|
||||
bool visible = true;
|
||||
bool reverse_side = false;
|
||||
uint32_t layers = -1;
|
||||
|
||||
if (object.parent_id == scene_data::node::root_id)
|
||||
for (auto i = &node; i != nullptr and visible; i = scene.try_get<components::node>(i->parent))
|
||||
{
|
||||
transform_to_root[index] = transform_to_parent;
|
||||
reverse_side[index] = det < 0;
|
||||
visible[index] = object.visible;
|
||||
float det = i->scale.x * i->scale.y * i->scale.z;
|
||||
glm::mat4 transform_to_parent = glm::translate(glm::mat4(1), i->position) * (glm::mat4)i->orientation * glm::scale(glm::mat4(1), i->scale);
|
||||
|
||||
transform_to_root = transform_to_parent * transform_to_root;
|
||||
reverse_side = reverse_side ^ (det < 0);
|
||||
visible = visible and i->visible;
|
||||
layers = layers bitand i->layer_mask;
|
||||
}
|
||||
else
|
||||
{
|
||||
size_t parent = object.parent_id;
|
||||
assert(parent < index);
|
||||
|
||||
transform_to_root[index] = transform_to_root.at(parent) * transform_to_parent;
|
||||
|
||||
reverse_side[index] = reverse_side[parent] ^ (det < 0);
|
||||
|
||||
visible[index] = visible[parent] && object.visible;
|
||||
}
|
||||
node.transform_to_root = transform_to_root;
|
||||
node.global_visible = visible;
|
||||
node.reverse_side = reverse_side;
|
||||
node.global_layer_mask = layers;
|
||||
}
|
||||
|
||||
// print_scene_hierarchy(scene, transform_to_root);
|
||||
// print_scene_hierarchy(scene);
|
||||
|
||||
for (const auto && [frame_index, frame]: utils::enumerate(frames))
|
||||
{
|
||||
scene_renderer::output_image & output = get_output_image_data(frame.destination, frame.depth_buffer);
|
||||
scene_renderer::output_image & output = get_output_image_data(output_image_info{
|
||||
.renderpass = {
|
||||
.color_format = color_format,
|
||||
.depth_format = depth_format,
|
||||
.keep_depth_buffer = depth_buffer != vk::Image{},
|
||||
.msaa_samples = vk::SampleCountFlagBits::e1,
|
||||
// .msaa_samples = vk::SampleCountFlagBits::e4, // FIXME: MSAA does not work
|
||||
},
|
||||
.output_size = output_size,
|
||||
.color = color_buffer,
|
||||
.depth = depth_buffer,
|
||||
.base_array_layer = (uint32_t)frame_index,
|
||||
});
|
||||
glm::mat4 viewproj = frame.projection * frame.view;
|
||||
|
||||
vk::DeviceSize frame_ubo_offset = resources.uniform_buffer_offset;
|
||||
@@ -873,13 +934,19 @@ void scene_renderer::render(scene_data & scene, const std::array<float, 4> & cle
|
||||
// frame_ubo.ambient_color = glm::vec4(0.2,0.2,0.2,0); // TODO
|
||||
// frame_ubo.light_color = glm::vec4(0.8,0.8,0.8,0); // TODO
|
||||
|
||||
frame_ubo.ambient_color = glm::vec4(0, 0, 0, 0); // TODO
|
||||
frame_ubo.light_color = glm::vec4(0.8, 0.8, 0.8, 0); // TODO
|
||||
frame_ubo.ambient_color = glm::vec4(0.1, 0.1, 0.1, 0); // TODO
|
||||
frame_ubo.light_color = glm::vec4(0.8, 0.8, 0.8, 0); // TODO
|
||||
|
||||
frame_ubo.light_position = glm::vec4(1, 1, 1, 0); // TODO
|
||||
frame_ubo.proj = frame.projection;
|
||||
frame_ubo.view = frame.view;
|
||||
|
||||
vk::raii::RenderPass & renderpass = get_renderpass(renderpass_info{
|
||||
.color_format = color_format,
|
||||
.depth_format = depth_format,
|
||||
.keep_depth_buffer = depth_buffer != vk::Image{},
|
||||
});
|
||||
|
||||
cb.beginRenderPass(
|
||||
vk::RenderPassBeginInfo{
|
||||
.renderPass = *renderpass,
|
||||
@@ -893,17 +960,46 @@ void scene_renderer::render(scene_data & scene, const std::array<float, 4> & cle
|
||||
},
|
||||
vk::SubpassContents::eInline);
|
||||
|
||||
for (const auto & [index, node]: utils::enumerate(scene.scene_nodes))
|
||||
// Accumulate all visible primitives
|
||||
std::vector<std::tuple<bool, float, components::node *, renderer::primitive *>> primitives; // TODO keep it between frames
|
||||
for (auto && [entity, node]: scene.view<components::node>().each())
|
||||
{
|
||||
if (!node.mesh_id)
|
||||
if (not node.global_visible or not node.mesh or (node.global_layer_mask & layer_mask) == 0)
|
||||
continue;
|
||||
|
||||
if (!visible[index])
|
||||
continue;
|
||||
// Position relative to the camera
|
||||
glm::vec4 position = frame.view * node.transform_to_root * glm::vec4(0, 0, 0, 1);
|
||||
|
||||
scene_data::mesh & mesh = scene.meshes.at(*node.mesh_id);
|
||||
glm::mat4 & transform = transform_to_root[index];
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by blending / distance
|
||||
// TODO add frustum culling
|
||||
std::ranges::stable_sort(primitives, [](const auto & a, const auto & b) -> bool {
|
||||
// Put the opaque objects first
|
||||
if (std::get<0>(a) < std::get<0>(b))
|
||||
return true;
|
||||
if (std::get<0>(a) > std::get<0>(b))
|
||||
return false;
|
||||
|
||||
// If blending is disabled (std::get<0> == false), put the closest objects first
|
||||
// If blending is enabled (std::get<0> == true), put the farthest objeccts first
|
||||
return std::get<0>(a) ^ (std::get<1>(a) > std::get<1>(b));
|
||||
});
|
||||
|
||||
// TODO try to add a depth pre-pass
|
||||
for (auto & [blend_enable, distance, node_ptr, primitive_ptr]: primitives)
|
||||
{
|
||||
components::node & node = *node_ptr;
|
||||
renderer::primitive & primitive = *primitive_ptr;
|
||||
|
||||
glm::mat4 & transform = node.transform_to_root;
|
||||
|
||||
// TODO: reuse the UBO if another primitive of the same mesh has already been drawn
|
||||
vk::DeviceSize instance_ubo_offset = resources.uniform_buffer_offset;
|
||||
instance_gpu_data & object_ubo = *reinterpret_cast<instance_gpu_data *>(ubo + resources.uniform_buffer_offset);
|
||||
resources.uniform_buffer_offset += utils::align_up(buffer_alignment, sizeof(instance_gpu_data));
|
||||
@@ -918,7 +1014,8 @@ void scene_renderer::render(scene_data & scene, const std::array<float, 4> & cle
|
||||
|
||||
for (auto && [idx, joint]: utils::enumerate(node.joints))
|
||||
{
|
||||
joint_matrices[idx] = glm::inverse(transform) * transform_to_root[joint.first] * joint.second;
|
||||
glm::mat4 & joint_transform = scene.get<components::node>(joint.first).transform_to_root;
|
||||
joint_matrices[idx] = glm::inverse(transform) * joint_transform * joint.second;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -927,87 +1024,102 @@ void scene_renderer::render(scene_data & scene, const std::array<float, 4> & cle
|
||||
object_ubo.modelviewproj = viewproj * transform;
|
||||
object_ubo.clipping_planes = node.clipping_planes;
|
||||
|
||||
for (scene_data::primitive & primitive: mesh.primitives)
|
||||
{
|
||||
// Get the material
|
||||
std::shared_ptr<scene_data::material> material = primitive.material_ ? primitive.material_ : default_material;
|
||||
// Get the material
|
||||
std::shared_ptr<renderer::material> material = primitive.material_ ? primitive.material_ : default_material;
|
||||
|
||||
if (material->ds_dirty || !material->ds)
|
||||
update_material_descriptor_set(*material);
|
||||
if (material->ds_dirty || !material->ds)
|
||||
update_material_descriptor_set(*material);
|
||||
|
||||
// Get the pipeline
|
||||
pipeline_info info{
|
||||
.shader_name = material->shader_name,
|
||||
.cull_mode = primitive.cull_mode,
|
||||
.front_face = primitive.front_face,
|
||||
.topology = primitive.topology,
|
||||
.blend_enable = material->blend_enable,
|
||||
// Get the pipeline
|
||||
pipeline_info info{
|
||||
.renderpass = {
|
||||
.color_format = color_format,
|
||||
.depth_format = depth_format,
|
||||
.keep_depth_buffer = depth_buffer != vk::Image{}},
|
||||
.shader_name = material->shader_name,
|
||||
.cull_mode = primitive.cull_mode,
|
||||
.front_face = primitive.front_face,
|
||||
.topology = primitive.topology,
|
||||
.blend_enable = material->blend_enable,
|
||||
|
||||
.nb_texcoords = 2, // TODO
|
||||
.skinning = !node.joints.empty(),
|
||||
};
|
||||
.nb_texcoords = 2, // TODO
|
||||
.skinning = !node.joints.empty(),
|
||||
};
|
||||
|
||||
if (material->double_sided)
|
||||
info.cull_mode = vk::CullModeFlagBits::eNone;
|
||||
if (material->double_sided)
|
||||
info.cull_mode = vk::CullModeFlagBits::eNone;
|
||||
|
||||
if (reverse_side[index])
|
||||
info.front_face = reverse(info.front_face);
|
||||
if (node.reverse_side)
|
||||
info.front_face = reverse(info.front_face);
|
||||
|
||||
cb.bindPipeline(vk::PipelineBindPoint::eGraphics, *get_pipeline(info));
|
||||
cb.bindPipeline(vk::PipelineBindPoint::eGraphics, *get_pipeline(info));
|
||||
|
||||
if (primitive.indexed)
|
||||
cb.bindIndexBuffer(*mesh.buffer, primitive.index_offset, primitive.index_type);
|
||||
cb.setViewport(0, vk::Viewport{
|
||||
.x = 0,
|
||||
.y = 0,
|
||||
.width = (float)output_size.width,
|
||||
.height = (float)output_size.height,
|
||||
.minDepth = 0,
|
||||
.maxDepth = 1,
|
||||
});
|
||||
|
||||
cb.bindVertexBuffers(0, (vk::Buffer)*mesh.buffer, primitive.vertex_offset);
|
||||
cb.setScissor(0, vk::Rect2D{
|
||||
.offset = {0, 0},
|
||||
.extent = output_size,
|
||||
});
|
||||
|
||||
vk::DescriptorBufferInfo buffer_info_1{
|
||||
.buffer = resources.uniform_buffer,
|
||||
.offset = frame_ubo_offset,
|
||||
.range = sizeof(frame_gpu_data)
|
||||
if (primitive.indexed)
|
||||
cb.bindIndexBuffer(*node.mesh->buffer, primitive.index_offset, primitive.index_type);
|
||||
|
||||
};
|
||||
vk::DescriptorBufferInfo buffer_info_2{
|
||||
.buffer = resources.uniform_buffer,
|
||||
.offset = instance_ubo_offset,
|
||||
.range = sizeof(instance_gpu_data)};
|
||||
vk::DescriptorBufferInfo buffer_info_3{
|
||||
.buffer = resources.uniform_buffer,
|
||||
.offset = joints_ubo_offset,
|
||||
.range = sizeof(glm::mat4) * 32};
|
||||
cb.bindVertexBuffers(0, (vk::Buffer)*node.mesh->buffer, primitive.vertex_offset);
|
||||
|
||||
std::array descriptors{
|
||||
vk::WriteDescriptorSet{
|
||||
.dstBinding = 0,
|
||||
.descriptorCount = 1,
|
||||
.descriptorType = vk::DescriptorType::eUniformBuffer,
|
||||
.pBufferInfo = &buffer_info_1,
|
||||
},
|
||||
vk::WriteDescriptorSet{
|
||||
.dstBinding = 1,
|
||||
.descriptorCount = 1,
|
||||
.descriptorType = vk::DescriptorType::eUniformBuffer,
|
||||
.pBufferInfo = &buffer_info_2,
|
||||
},
|
||||
vk::WriteDescriptorSet{
|
||||
.dstBinding = 2,
|
||||
.descriptorCount = 1,
|
||||
.descriptorType = vk::DescriptorType::eUniformBuffer,
|
||||
.pBufferInfo = &buffer_info_3,
|
||||
},
|
||||
};
|
||||
vk::DescriptorBufferInfo buffer_info_1{
|
||||
.buffer = resources.uniform_buffer,
|
||||
.offset = frame_ubo_offset,
|
||||
.range = sizeof(frame_gpu_data)
|
||||
|
||||
cb.pushDescriptorSetKHR(vk::PipelineBindPoint::eGraphics, *pipeline_layout, 0, descriptors);
|
||||
};
|
||||
vk::DescriptorBufferInfo buffer_info_2{
|
||||
.buffer = resources.uniform_buffer,
|
||||
.offset = instance_ubo_offset,
|
||||
.range = sizeof(instance_gpu_data)};
|
||||
vk::DescriptorBufferInfo buffer_info_3{
|
||||
.buffer = resources.uniform_buffer,
|
||||
.offset = joints_ubo_offset,
|
||||
.range = sizeof(glm::mat4) * 32};
|
||||
|
||||
// Set 1: material
|
||||
cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, *pipeline_layout, 1, **material->ds, {});
|
||||
std::array descriptors{
|
||||
vk::WriteDescriptorSet{
|
||||
.dstBinding = 0,
|
||||
.descriptorCount = 1,
|
||||
.descriptorType = vk::DescriptorType::eUniformBuffer,
|
||||
.pBufferInfo = &buffer_info_1,
|
||||
},
|
||||
vk::WriteDescriptorSet{
|
||||
.dstBinding = 1,
|
||||
.descriptorCount = 1,
|
||||
.descriptorType = vk::DescriptorType::eUniformBuffer,
|
||||
.pBufferInfo = &buffer_info_2,
|
||||
},
|
||||
vk::WriteDescriptorSet{
|
||||
.dstBinding = 2,
|
||||
.descriptorCount = 1,
|
||||
.descriptorType = vk::DescriptorType::eUniformBuffer,
|
||||
.pBufferInfo = &buffer_info_3,
|
||||
},
|
||||
};
|
||||
|
||||
if (primitive.indexed)
|
||||
cb.drawIndexed(primitive.index_count, 1, 0, 0, 0);
|
||||
else
|
||||
cb.draw(primitive.vertex_count, 1, 0, 0);
|
||||
cb.pushDescriptorSetKHR(vk::PipelineBindPoint::eGraphics, *pipeline_layout, 0, descriptors);
|
||||
|
||||
resources.resources.push_back(material->ds);
|
||||
}
|
||||
// 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();
|
||||
}
|
||||
|
||||
@@ -24,7 +24,6 @@
|
||||
#include <glm/vec2.hpp>
|
||||
#include <glm/vec3.hpp>
|
||||
#include <glm/vec4.hpp>
|
||||
#include <map>
|
||||
#include <span>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
@@ -34,10 +33,22 @@
|
||||
#include "vk/allocation.h"
|
||||
|
||||
#include "render/growable_descriptor_pool.h"
|
||||
#include "render/scene_data.h"
|
||||
#include "render/scene_components.h"
|
||||
|
||||
struct renderpass_info
|
||||
{
|
||||
vk::Format color_format;
|
||||
vk::Format depth_format;
|
||||
bool keep_depth_buffer;
|
||||
vk::SampleCountFlagBits msaa_samples = vk::SampleCountFlagBits::e1;
|
||||
|
||||
bool operator==(const renderpass_info & other) const noexcept = default;
|
||||
};
|
||||
|
||||
struct pipeline_info
|
||||
{
|
||||
renderpass_info renderpass;
|
||||
|
||||
std::string shader_name;
|
||||
|
||||
vk::CullModeFlags cull_mode = vk::CullModeFlagBits::eNone;
|
||||
@@ -56,11 +67,35 @@ struct pipeline_info
|
||||
bool operator==(const pipeline_info & other) const noexcept = default;
|
||||
};
|
||||
|
||||
struct output_image_info
|
||||
{
|
||||
renderpass_info renderpass;
|
||||
|
||||
vk::Extent2D output_size;
|
||||
VkImage color;
|
||||
VkImage depth;
|
||||
uint32_t base_array_layer;
|
||||
|
||||
bool operator==(const output_image_info & other) const noexcept = default;
|
||||
};
|
||||
|
||||
namespace std
|
||||
{
|
||||
template <>
|
||||
struct hash<renderpass_info> : utils::magic_hash<renderpass_info>
|
||||
{};
|
||||
|
||||
template <>
|
||||
struct hash<pipeline_info> : utils::magic_hash<pipeline_info>
|
||||
{};
|
||||
|
||||
template <>
|
||||
struct hash<vk::Extent2D> : utils::magic_hash<vk::Extent2D>
|
||||
{};
|
||||
|
||||
template <>
|
||||
struct hash<output_image_info> : utils::magic_hash<output_image_info>
|
||||
{};
|
||||
} // namespace std
|
||||
|
||||
class scene_renderer
|
||||
@@ -70,11 +105,6 @@ class scene_renderer
|
||||
vk::PhysicalDeviceProperties physical_device_properties;
|
||||
vk::raii::Queue & queue;
|
||||
|
||||
// Scene format
|
||||
const vk::Extent2D output_size;
|
||||
const vk::Format output_format;
|
||||
const vk::Format depth_format;
|
||||
|
||||
// Destination images
|
||||
struct output_image
|
||||
{
|
||||
@@ -84,26 +114,28 @@ class scene_renderer
|
||||
image_allocation depth_buffer;
|
||||
vk::raii::ImageView depth_view = nullptr;
|
||||
|
||||
// image_allocation multisample_image;
|
||||
// vk::raii::ImageView multisample_view = nullptr;
|
||||
image_allocation multisample_image;
|
||||
vk::raii::ImageView multisample_view = nullptr;
|
||||
};
|
||||
|
||||
// Initialization functions
|
||||
output_image create_output_image_data(vk::Image output_color, vk::Image output_depth);
|
||||
vk::raii::RenderPass create_renderpass();
|
||||
output_image create_output_image_data(const output_image_info & info);
|
||||
vk::raii::RenderPass create_renderpass(const renderpass_info & info);
|
||||
vk::raii::PipelineLayout create_pipeline_layout(std::span<vk::DescriptorSetLayout> layouts);
|
||||
vk::raii::Pipeline create_pipeline(const pipeline_info & info);
|
||||
|
||||
std::shared_ptr<scene_data::texture> create_default_texture(vk::raii::CommandPool & cb_pool, std::vector<uint8_t> pixel);
|
||||
std::shared_ptr<scene_data::material> create_default_material(vk::raii::CommandPool & cb_pool);
|
||||
std::shared_ptr<renderer::texture> create_default_texture(vk::raii::CommandPool & cb_pool, std::vector<uint8_t> pixel);
|
||||
std::shared_ptr<renderer::material> create_default_material(vk::raii::CommandPool & cb_pool);
|
||||
vk::raii::DescriptorSetLayout create_descriptor_set_layout(std::span<vk::DescriptorSetLayoutBinding> bindings, vk::DescriptorSetLayoutCreateFlags flags = {});
|
||||
|
||||
// Caches
|
||||
std::/*unordered_*/ map<std::pair<VkImage, VkImage>, output_image> output_images; // TODO: use an unordered_map, create a hash for std::pair
|
||||
std::unordered_map<renderpass_info, vk::raii::RenderPass> renderpasses;
|
||||
std::unordered_map<output_image_info, output_image> output_images;
|
||||
std::unordered_map<pipeline_info, vk::raii::Pipeline> pipelines;
|
||||
|
||||
output_image & get_output_image_data(vk::Image output_color, vk::Image output_depth);
|
||||
output_image & get_output_image_data(const output_image_info & info);
|
||||
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)
|
||||
@@ -114,11 +146,8 @@ class scene_renderer
|
||||
vk::raii::PipelineLayout pipeline_layout = nullptr;
|
||||
|
||||
// Texture samplers
|
||||
std::unordered_map<sampler_info, std::shared_ptr<vk::raii::Sampler>> samplers;
|
||||
vk::Sampler get_sampler(const sampler_info & info);
|
||||
|
||||
// Render pass
|
||||
vk::raii::RenderPass renderpass = nullptr;
|
||||
std::unordered_map<renderer::sampler_info, std::shared_ptr<vk::raii::Sampler>> samplers;
|
||||
vk::Sampler get_sampler(const renderer::sampler_info & info);
|
||||
|
||||
// Default material and textures
|
||||
// This material has 1x1 textures with the following values:
|
||||
@@ -134,7 +163,7 @@ class scene_renderer
|
||||
// roughness_factor 1.0
|
||||
// occlusion_strength 0.0
|
||||
// normal_scale 0.0
|
||||
std::shared_ptr<scene_data::material> default_material;
|
||||
std::shared_ptr<renderer::material> default_material;
|
||||
|
||||
struct frame_gpu_data
|
||||
{
|
||||
@@ -170,11 +199,10 @@ class scene_renderer
|
||||
int current_frame_index;
|
||||
vk::raii::QueryPool query_pool = nullptr;
|
||||
double gpu_time_s = 0;
|
||||
bool keep_depth_buffer = false;
|
||||
|
||||
per_frame_resources & current_frame();
|
||||
|
||||
void update_material_descriptor_set(scene_data::material & material);
|
||||
void update_material_descriptor_set(renderer::material & material);
|
||||
|
||||
public:
|
||||
static vk::Format find_usable_image_format(
|
||||
@@ -191,24 +219,27 @@ public:
|
||||
vk::raii::PhysicalDevice physical_device,
|
||||
vk::raii::Queue & queue,
|
||||
vk::raii::CommandPool & cb_pool,
|
||||
vk::Extent2D output_size,
|
||||
vk::Format output_format,
|
||||
vk::Format depth_format,
|
||||
int frames_in_flight = 2,
|
||||
bool keep_depth_buffer = false);
|
||||
int frames_in_flight = 2);
|
||||
|
||||
~scene_renderer();
|
||||
|
||||
struct frame_info
|
||||
{
|
||||
vk::Image destination;
|
||||
vk::Image depth_buffer;
|
||||
glm::mat4 projection;
|
||||
glm::mat4 view;
|
||||
};
|
||||
|
||||
void start_frame();
|
||||
void render(scene_data & scene, const std::array<float, 4> & clear_color, std::span<frame_info> info);
|
||||
void render(
|
||||
entt::registry & scene,
|
||||
const std::array<float, 4> & clear_color,
|
||||
uint32_t layer_mask,
|
||||
vk::Extent2D output_size,
|
||||
vk::Format output_format,
|
||||
vk::Format depth_format,
|
||||
vk::Image color_buffer,
|
||||
vk::Image depth_buffer,
|
||||
std::span<frame_info> info);
|
||||
void end_frame();
|
||||
|
||||
double get_gpu_time() const
|
||||
@@ -216,7 +247,7 @@ public:
|
||||
return gpu_time_s;
|
||||
}
|
||||
|
||||
std::shared_ptr<scene_data::material> get_default_material()
|
||||
std::shared_ptr<renderer::material> get_default_material()
|
||||
{
|
||||
return default_material;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user