Misc renderer improvements:

- Use VK_KHR_multiview
- Compute bounding boxes, use them to sort primitives
- Add shader reflection
- Add debug drawer
This commit is contained in:
Guillaume Meunier committed 2025-10-25 10:25:53 +02:00
1 parent 17ac7ab7d9
commit 7963efc034
23 files changed
+1679 -615

No files matched your search

+2
View File
@@ -253,6 +253,8 @@ FetchContent_Declare(entt EXCLUDE_FROM_ALL SYSTEM URL https://github.co
URL_HASH SHA256=01466fcbf77618a79b62891510c0bbf25ac2804af5751c84982b413852234d66)
FetchContent_Declare(curl EXCLUDE_FROM_ALL SYSTEM URL https://github.com/curl/curl/releases/download/curl-8_15_0/curl-8.15.0.tar.xz
URL_HASH SHA256=6cd0a8a5b126ddfda61c94dc2c3fc53481ba7a35461cf7c5ab66aa9d6775b609)
FetchContent_Declare(spirv-reflect EXCLUDE_FROM_ALL SYSTEM URL https://github.com/KhronosGroup/SPIRV-Reflect/archive/refs/tags/vulkan-sdk-1.4.321.0.tar.gz
URL_HASH SHA256=254ed36128e7abe8fb12ef804319d0790e059093c116e9fe55d4003880515f85)
file(GLOB MONADO_PATCHES CONFIGURE_DEPENDS patches/monado/*)
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS monado-rev)
+6 -1
View File
@@ -7,7 +7,11 @@ set(KTX_FEATURE_LOADTEST_APPS OFF)
set(FASTGLTF_COMPILE_AS_CPP20 ON)
FetchContent_MakeAvailable(simdjson spdlog glm fastgltf imgui stb implot uni-algo entt libktx)
set(SPIRV_REFLECT_EXECUTABLE OFF)
set(SPIRV_REFLECT_STATIC_LIB ON)
set(SPIRV_REFLECT_INSTALL OFF)
FetchContent_MakeAvailable(simdjson spdlog glm fastgltf imgui stb implot uni-algo entt libktx spirv-reflect)
include(FreetypeHarfbuzz)
include(CompileGLSL)
@@ -104,6 +108,7 @@ target_link_libraries(wivrn
ktx_read
simdjson
spdlog::spdlog
spirv-reflect-static
stb
uni-algo
Vulkan::Vulkan
+4
View File
@@ -759,6 +759,7 @@ void application::initialize_vulkan()
vk_device_extensions.push_back(VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME);
vk_device_extensions.push_back(VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME);
vk_device_extensions.push_back(VK_KHR_MULTIVIEW_EXTENSION_NAME);
optional_device_extensions.emplace(VK_IMG_FILTER_CUBIC_EXTENSION_NAME);
optional_device_extensions.emplace(VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME);
optional_device_extensions.emplace(VK_EXT_FRAGMENT_DENSITY_MAP_EXTENSION_NAME);
@@ -885,6 +886,9 @@ void application::initialize_vulkan()
vk::PhysicalDeviceTimelineSemaphoreFeaturesKHR{
.timelineSemaphore = true,
},
vk::PhysicalDeviceMultiviewFeaturesKHR{
.multiview = true,
},
};
if (utils::contains(vk_device_extensions, VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME))
+13 -34
View File
@@ -31,6 +31,7 @@
#include <vulkan/vulkan_raii.hpp>
#include "utils/magic_hash.h"
#include "vertex_layout.h"
#include "vk/allocation.h"
namespace renderer
@@ -61,7 +62,7 @@ struct material
float metallic_factor = 1;
float roughness_factor = 1;
float occlusion_strength = 0;
float normal_scale = 0;
float normal_scale = 1;
float alpha_cutoff = 0.5;
uint32_t base_color_texcoord = 0;
@@ -73,13 +74,6 @@ struct material
// TODO: add fastgltf::TextureTransform?
};
enum class alpha_mode_t
{
opaque,
mask,
blend
};
std::shared_ptr<texture> base_color_texture;
std::shared_ptr<texture> metallic_roughness_texture;
std::shared_ptr<texture> occlusion_texture;
@@ -89,7 +83,9 @@ struct material
// Disable back face culling with this material
bool double_sided = true;
alpha_mode_t alpha_mode;
bool blend_enable = false;
bool depth_test_enable = true;
bool depth_write_enable = true;
gpu_data staging;
@@ -98,7 +94,7 @@ struct material
size_t offset;
std::string name;
std::string shader_name = "lit";
std::string fragment_shader_name = "lit.frag";
};
struct primitive
@@ -108,7 +104,13 @@ struct primitive
uint32_t vertex_count;
vk::IndexType index_type;
vk::DeviceSize index_offset;
vk::DeviceSize vertex_offset;
std::vector<vk::DeviceSize> vertex_offset; // TODO: inplace_vector
vertex_layout layout;
glm::vec3 obb_min;
glm::vec3 obb_max;
std::string vertex_shader;
// See also material::double_sided
vk::CullModeFlagBits cull_mode = vk::CullModeFlagBits::eNone;
@@ -124,29 +126,6 @@ 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::vec4 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
+283 -161
View File
@@ -22,7 +22,12 @@
#include "gpu_buffer.h"
#include "image_loader.h"
#include "render/scene_components.h"
#include "render/vertex_layout.h"
#include "utils/ranges.h"
#include "vk/shader.h"
#include <algorithm>
#include <cctype>
#include <cstdint>
#include <entt/entt.hpp>
#include <fastgltf/base64.hpp>
#include <fastgltf/core.hpp>
@@ -32,67 +37,47 @@
#include <fastgltf/types.hpp>
#include <fastgltf/util.hpp>
#include <glm/ext.hpp>
#include <glm/fwd.hpp>
#include <limits>
#include <ranges>
#include <spdlog/spdlog.h>
#include <string>
#include <vulkan/vulkan_format_traits.hpp>
namespace fastgltf
{
// glm_element_traits.hpp is missing all the glm::vec<1, T> and glm:::vec<n, int32_t> specializations
// clang-format off
template <> struct ElementTraits<glm::u8vec1> : ElementTraitsBase<glm::u8vec1, AccessorType::Scalar, std::uint8_t> {};
template <> struct ElementTraits<glm::i8vec1> : ElementTraitsBase<glm::i8vec1, AccessorType::Scalar, std::int8_t> {};
template <> struct ElementTraits<glm::u16vec1> : ElementTraitsBase<glm::u16vec1, AccessorType::Scalar, std::uint16_t> {};
template <> struct ElementTraits<glm::i16vec1> : ElementTraitsBase<glm::i16vec1, AccessorType::Scalar, std::int16_t> {};
template <> struct ElementTraits<glm::u32vec1> : ElementTraitsBase<glm::u32vec1, AccessorType::Scalar, std::uint32_t> {};
template <> struct ElementTraits<glm::i32vec1> : ElementTraitsBase<glm::i32vec1, AccessorType::Scalar, std::int32_t> {};
template <> struct ElementTraits<glm::i32vec2> : ElementTraitsBase<glm::i32vec2, AccessorType::Vec2, std::int32_t> {};
template <> struct ElementTraits<glm::i32vec3> : ElementTraitsBase<glm::i32vec3, AccessorType::Vec3, std::int32_t> {};
template <> struct ElementTraits<glm::i32vec4> : ElementTraitsBase<glm::i32vec4, AccessorType::Vec4, std::int32_t> {};
template <> struct ElementTraits<glm::fvec1> : ElementTraitsBase<glm::fvec1, AccessorType::Scalar, float> {};
template <> struct ElementTraits<glm::dvec1> : ElementTraitsBase<glm::dvec1, AccessorType::Scalar, float> {};
// clang-format on
} // namespace fastgltf
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:
return {vk::Filter::eNearest, {}};
case fastgltf::Filter::Linear:
return {vk::Filter::eLinear, {}};
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};
@@ -176,21 +161,6 @@ glm::vec3 convert(const fastgltf::math::nvec3 & v)
return {v[0], v[1], v[2]};
}
renderer::material::alpha_mode_t convert(fastgltf::AlphaMode alpha_mode)
{
switch (alpha_mode)
{
case fastgltf::AlphaMode::Opaque:
return renderer::material::alpha_mode_t::opaque;
case fastgltf::AlphaMode::Mask:
return renderer::material::alpha_mode_t::mask;
case fastgltf::AlphaMode::Blend:
return renderer::material::alpha_mode_t::blend;
}
throw std::invalid_argument("alpha_mode");
}
components::animation_track_base::interpolation_t convert(fastgltf::AnimationInterpolation interpolation)
{
switch (interpolation)
@@ -209,57 +179,194 @@ components::animation_track_base::interpolation_t convert(fastgltf::AnimationInt
// 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)
std::vector<glm::dvec4> read_vertex_attribute_aux2(const fastgltf::Asset & asset, const fastgltf::Accessor & accessor)
{
using U = T::value_type;
constexpr size_t N = std::tuple_size_v<T>;
std::vector<glm::dvec4> output;
output.resize(accessor.count);
for (size_t i = 0; i < N; i++)
size_t index = 0;
switch (fastgltf::getNumComponents(accessor.type))
{
auto it = primitive.findAttribute(attribute_name + std::to_string(i));
if (it == primitive.attributes.end())
continue;
const fastgltf::Accessor & accessor = asset.accessors.at(it->accessorIndex);
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;
});
case 1:
fastgltf::iterateAccessorWithIndex<T>(asset, accessor, [&](const T & value, size_t index) {
output[index] = glm::dvec4(value[0], 0, 0, 1);
});
break;
case 2:
fastgltf::iterateAccessorWithIndex<T>(asset, accessor, [&](const T & value, size_t index) {
output[index] = glm::dvec4(value[0], value[1], 0, 1);
});
break;
case 3:
fastgltf::iterateAccessorWithIndex<T>(asset, accessor, [&](const T & value, size_t index) {
output[index] = glm::dvec4(value[0], value[1], value[2], 1);
});
break;
case 4:
fastgltf::iterateAccessorWithIndex<T>(asset, accessor, [&](const T & value, size_t index) {
output[index] = glm::dvec4(value[0], value[1], value[2], value[3]);
});
break;
default:
abort();
}
return output;
}
template <typename T>
requires(!is_array_v<T>)
std::vector<glm::dvec4> read_vertex_attribute_aux(const fastgltf::Asset & asset, const fastgltf::Accessor & accessor)
{
switch (fastgltf::getNumComponents(accessor.type))
{
// clang-format off
case 1: return read_vertex_attribute_aux2<glm::vec<1, T>>(asset, accessor);
case 2: return read_vertex_attribute_aux2<glm::vec<2, T>>(asset, accessor);
case 3: return read_vertex_attribute_aux2<glm::vec<3, T>>(asset, accessor);
case 4: return read_vertex_attribute_aux2<glm::vec<4, T>>(asset, accessor);
//clang-format on
}
return {};
}
std::vector<glm::dvec4> read_vertex_attribute(const fastgltf::Asset & asset, const fastgltf::Accessor & accessor)
{
switch (accessor.componentType)
{
// clang-format off
case fastgltf::ComponentType::Byte: return read_vertex_attribute_aux<int8_t>(asset, accessor);
case fastgltf::ComponentType::UnsignedByte: return read_vertex_attribute_aux<uint8_t>(asset, accessor);
case fastgltf::ComponentType::Short: return read_vertex_attribute_aux<int16_t>(asset, accessor);
case fastgltf::ComponentType::UnsignedShort: return read_vertex_attribute_aux<uint16_t>(asset, accessor);
case fastgltf::ComponentType::Int: return read_vertex_attribute_aux<int32_t>(asset, accessor);
case fastgltf::ComponentType::UnsignedInt: return read_vertex_attribute_aux<uint32_t>(asset, accessor);
case fastgltf::ComponentType::Float: return read_vertex_attribute_aux<float>(asset, accessor);
//clang-format on
case fastgltf::ComponentType::Double: // TODO
abort();
break;
case fastgltf::ComponentType::Invalid:
abort();
break;
}
return {};
}
template <typename T>
void write_vertex_attribute_aux(std::byte * output, size_t stride, int components, const std::vector<glm::dvec4> & input)
{
switch (components)
{
case 1:
for (size_t i = 0, n = input.size(); i < n; i++, output += stride)
*reinterpret_cast<glm::vec<1, T> *>(output) = glm::vec<1, T>(input[i].x);
break;
case 2:
for (size_t i = 0, n = input.size(); i < n; i++, output += stride)
*reinterpret_cast<glm::vec<2, T> *>(output) = glm::vec<2, T>(input[i].x, input[i].y);
break;
case 3:
for (size_t i = 0, n = input.size(); i < n; i++, output += stride)
*reinterpret_cast<glm::vec<3, T> *>(output) = glm::vec<3, T>(input[i].x, input[i].y, input[i].z);
break;
case 4:
for (size_t i = 0, n = input.size(); i < n; i++, output += stride)
*reinterpret_cast<glm::vec<3, T> *>(output) = glm::vec<4, T>(input[i].x, input[i].y, input[i].z, input[i].w);
break;
default:
abort();
}
}
void write_vertex_attribute(std::vector<std::byte> & output, size_t offset, size_t stride, vk::Format format, std::vector<glm::dvec4> input)
{
assert(output.size() >= input.size() * stride);
switch (format)
{
case vk::Format::eR32Sfloat:
case vk::Format::eR32G32Sfloat:
case vk::Format::eR32G32B32Sfloat:
case vk::Format::eR32G32B32A32Sfloat:
write_vertex_attribute_aux<float>(output.data() + offset, stride, vk::componentCount(format), input);
return;
default:
return;
}
}
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)
const fastgltf::Accessor & accessor,
std::vector<std::byte> & buffer,
const vk::VertexInputBindingDescription & binding,
const vk::VertexInputAttributeDescription & attribute)
{
auto it = primitive.findAttribute(attribute_name);
assert(buffer.size() >= accessor.count * binding.stride);
if (it == primitive.attributes.end())
return;
write_vertex_attribute(buffer, attribute.offset, binding.stride, attribute.format, read_vertex_attribute(asset, accessor));
}
const fastgltf::Accessor & accessor = asset.accessors.at(it->accessorIndex);
std::pair<size_t, std::vector<std::vector<std::byte>>> create_vertex_buffers(
const renderer::vertex_layout & layout,
const fastgltf::Asset & asset,
const fastgltf::Primitive & primitive)
{
std::pair<size_t, std::vector<std::vector<std::byte>>> size_buffers;
auto & [vertex_count, buffers] = size_buffers;
if (vertices.size() < accessor.count)
vertices.resize(accessor.count, {});
// Count the vertices
vertex_count = 0;
for (const auto & name: layout.attribute_names)
{
if (auto attribute = primitive.findAttribute(name); attribute != primitive.attributes.cend())
vertex_count = std::max(vertex_count, asset.accessors.at(attribute->accessorIndex).count);
}
fastgltf::iterateAccessorWithIndex<T>(asset, accessor, [&](T value, std::size_t idx) {
vertices[idx].*attribute = value;
});
// Allocate buffers
int max_binding = std::ranges::max(layout.bindings, {}, &vk::VertexInputBindingDescription::binding).binding;
buffers.resize(max_binding + 1);
for (const vk::VertexInputBindingDescription & binding: layout.bindings)
{
switch (binding.inputRate)
{
case vk::VertexInputRate::eVertex:
buffers[binding.binding].resize(binding.stride * vertex_count);
break;
case vk::VertexInputRate::eInstance:
buffers[binding.binding].resize(binding.stride);
break;
}
}
// Copy attributes
for (auto && [name, attribute]: std::views::zip(layout.attribute_names, layout.attributes))
{
auto binding_iter = std::ranges::find(layout.bindings, attribute.binding, &vk::VertexInputBindingDescription::binding);
assert(binding_iter != layout.bindings.end());
const vk::VertexInputBindingDescription & binding = *binding_iter;
std::vector<std::byte> & buffer = buffers.at(binding.binding);
const fastgltf::Attribute * gltf_attribute = primitive.findAttribute(name);
if (gltf_attribute == primitive.attributes.cend())
{
// Also check if it's an array of size 1
gltf_attribute = primitive.findAttribute(name + "_0");
if (gltf_attribute == primitive.attributes.cend())
continue;
}
const fastgltf::Accessor & accessor = asset.accessors.at(gltf_attribute->accessorIndex);
copy_vertex_attributes(asset, accessor, buffer, binding, attribute);
}
return size_buffers;
}
// END
@@ -584,7 +691,24 @@ public:
material.buffer.reset();
material.double_sided = gltf_material.doubleSided;
material.alpha_mode = convert(gltf_material.alphaMode);
switch (gltf_material.alphaMode)
{
case fastgltf::AlphaMode::Opaque:
material.fragment_shader_name = "lit.frag";
material.blend_enable = false;
break;
case fastgltf::AlphaMode::Mask:
material.fragment_shader_name = "lit_mask.frag";
material.blend_enable = false;
break;
case fastgltf::AlphaMode::Blend:
material.fragment_shader_name = "lit.frag";
material.blend_enable = true;
break;
}
renderer::material::gpu_data & material_data = material.staging;
@@ -678,29 +802,73 @@ public:
}
}
else
{
primitive_ref.indexed = false;
renderer::vertex_layout & layout = primitive_ref.layout;
if (gltf_primitive.findAttribute("JOINTS_0") == gltf_primitive.attributes.cend())
primitive_ref.vertex_shader = "lit.vert";
else
primitive_ref.vertex_shader = "lit_skinned.vert";
// For attributes types, see https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes-overview (§ 3.7.2.1)
const std::vector<shader::input> & shader_inputs = load_shader(device, primitive_ref.vertex_shader)->inputs;
for (const auto & input: shader_inputs)
{
std::string semantic = input.name;
std::transform(semantic.begin(), semantic.end(), semantic.begin(), [](auto c) { return std::toupper(c); });
if (semantic.starts_with("IN_"))
semantic = semantic.substr(3);
int binding;
if (semantic == "POSITION" or
semantic == "JOINTS" or
semantic == "WEIGHTS")
binding = 0;
else
binding = 1;
layout.add_vertex_attribute(semantic, input.format, binding, input.location, input.array_size);
}
std::vector<renderer::vertex> vertices;
auto [vertex_count, buffers] = create_vertex_buffers(layout, gltf, gltf_primitive);
primitive_ref.vertex_count = vertex_count;
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);
for (auto & buffer: buffers)
primitive_ref.vertex_offset.push_back(staging_buffer.add_vertices(buffer));
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);
// Compute the OBB
glm::vec3 obb_min{std::numeric_limits<float>::max(), std::numeric_limits<float>::max(), std::numeric_limits<float>::max()};
glm::vec3 obb_max = -obb_min;
fastgltf::iterateAccessor<glm::vec3>(gltf, gltf.accessors.at(gltf_primitive.findAttribute("POSITION")->accessorIndex), [&](glm::vec3 position) {
obb_min.x = std::min(obb_min.x, position.x);
obb_min.y = std::min(obb_min.y, position.y);
obb_min.z = std::min(obb_min.z, position.z);
obb_max.x = std::max(obb_max.x, position.x);
obb_max.y = std::max(obb_max.y, position.y);
obb_max.z = std::max(obb_max.z, position.z);
});
primitive_ref.obb_min = obb_min;
primitive_ref.obb_max = obb_max;
if (gltf_primitive.materialIndex)
primitive_ref.material_ = materials.at(*gltf_primitive.materialIndex);
if (primitive_ref.material_ and primitive_ref.material_->double_sided)
{
primitive_ref.cull_mode = vk::CullModeFlagBits::eFrontAndBack;
primitive_ref.front_face = vk::FrontFace::eCounterClockwise;
}
else
{
primitive_ref.cull_mode = vk::CullModeFlagBits::eBack;
primitive_ref.front_face = vk::FrontFace::eCounterClockwise;
}
primitive_ref.topology = convert(gltf_primitive.type);
}
}
@@ -872,52 +1040,6 @@ public:
} // 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;
}
std::shared_ptr<entt::registry> scene_loader::operator()(std::span<const std::byte> data, const std::string & name, const std::filesystem::path & parent_path)
{
vk::PhysicalDeviceProperties physical_device_properties = physical_device.getProperties();
+512 -164
View File
@@ -21,6 +21,7 @@
#include "application.h"
#include "render/image_loader.h"
#include "render/scene_components.h"
#include "render/vertex_layout.h"
#include "utils/alignment.h"
#include "utils/fmt_glm.h"
#include "utils/ranges.h"
@@ -31,10 +32,12 @@
#include <boost/pfr/core.hpp>
#include <entt/entity/entity.hpp>
#include <entt/entt.hpp>
#include <glm/ext/matrix_transform.hpp>
#include <glm/gtc/matrix_access.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/quaternion.hpp>
#include <memory>
#include <numeric>
#include <ranges>
#include <spdlog/spdlog.h>
#include <vk_mem_alloc.h>
@@ -43,6 +46,38 @@
#include <vulkan/vulkan_handles.hpp>
#include <vulkan/vulkan_structs.hpp>
namespace
{
struct frustum
{
// Only 5 planes because the far plane is infinitely far
std::array<glm::vec4, 5> planes;
frustum() = default;
frustum(const frustum &) = default;
frustum(const glm::mat4 & proj)
{
/* Let [x',y',z',w'] = proj * [x,y,z,1]
* Extract the planes from the projection matrix s.t.
*
* (dot(planes[0], [x,y,z,1]) > 0 <=> x' < w' <=> w' - x' > 0) <=> planes[0] = row3-row0
* (dot(planes[1], [x,y,z,1]) > 0 <=> x' > -w' <=> x' + w' > 0) <=> planes[1] = row0+row3
* (dot(planes[2], [x,y,z,1]) > 0 <=> y' < w' <=> w' - y' > 0) <=> planes[2] = row3-row1
* (dot(planes[3], [x,y,z,1]) > 0 <=> y' > -w' <=> y' + w' > 0) <=> planes[3] = row1+row3
* (dot(planes[4], [x,y,z,1]) > 0 <=> z' < w' <=> w' - z' > 0) <=> planes[4] = row3-row2
*
* See Gribb & Hartmann
*/
planes[0] = glm::row(proj, 3) - glm::row(proj, 0);
planes[1] = glm::row(proj, 0) + glm::row(proj, 3);
planes[2] = glm::row(proj, 3) - glm::row(proj, 1);
planes[3] = glm::row(proj, 1) + glm::row(proj, 3);
planes[4] = glm::row(proj, 3) - glm::row(proj, 2);
}
};
} // namespace
// TODO move in lobby?
vk::Format scene_renderer::find_usable_image_format(
vk::raii::PhysicalDevice physical_device,
@@ -139,6 +174,32 @@ static vk::FrontFace reverse(vk::FrontFace face)
return vk::FrontFace::eCounterClockwise;
}
// Return true if the OBB is outside the frustum
static bool frustum_cull(
const frustum & fru,
const glm::mat4 & model,
const glm::vec3 & obb_min,
const glm::vec3 & obb_max)
{
for (const glm::vec4 & plane: fru.planes)
{
int out = 0;
out += glm::dot(plane, model * glm::vec4(obb_min.x, obb_min.y, obb_min.z, 1)) < 0;
out += glm::dot(plane, model * glm::vec4(obb_min.x, obb_min.y, obb_max.z, 1)) < 0;
out += glm::dot(plane, model * glm::vec4(obb_min.x, obb_max.y, obb_min.z, 1)) < 0;
out += glm::dot(plane, model * glm::vec4(obb_min.x, obb_max.y, obb_max.z, 1)) < 0;
out += glm::dot(plane, model * glm::vec4(obb_max.x, obb_min.y, obb_min.z, 1)) < 0;
out += glm::dot(plane, model * glm::vec4(obb_max.x, obb_min.y, obb_max.z, 1)) < 0;
out += glm::dot(plane, model * glm::vec4(obb_max.x, obb_max.y, obb_min.z, 1)) < 0;
out += glm::dot(plane, model * glm::vec4(obb_max.x, obb_max.y, obb_max.z, 1)) < 0;
if (out == 8)
return true;
}
return false;
}
static std::array layout_bindings_0{
vk::DescriptorSetLayoutBinding{
// scene_ubo: per-frame/view data
@@ -272,7 +333,7 @@ scene_renderer::renderpass & scene_renderer::get_renderpass(const renderpass_inf
scene_renderer::renderpass scene_renderer::create_renderpass(const renderpass_info & info_)
{
vk::StructureChain<vk::RenderPassCreateInfo, vk::RenderPassFragmentDensityMapCreateInfoEXT> info;
vk::StructureChain<vk::RenderPassCreateInfo, vk::RenderPassFragmentDensityMapCreateInfoEXT, vk::RenderPassMultiviewCreateInfo> info;
scene_renderer::renderpass rp;
std::vector<vk::AttachmentDescription> attachments;
@@ -380,6 +441,15 @@ scene_renderer::renderpass scene_renderer::create_renderpass(const renderpass_in
}};
info.get().setDependencies(dependencies);
auto & multiview = info.get<vk::RenderPassMultiviewCreateInfo>();
multiview.subpassCount = 1;
std::array view_mask{uint32_t((1 << info_.multiview_count) - 1)};
multiview.setViewMasks(view_mask);
std::array correlation_mask{uint32_t((1 << info_.multiview_count) - 1)};
multiview.setCorrelationMasks(correlation_mask);
rp.attachment_count = (uint32_t)attachments.size();
rp.renderpass = vk::raii::RenderPass(device, info.get());
return rp;
@@ -402,15 +472,15 @@ scene_renderer::output_image scene_renderer::create_output_image_data(const outp
out.image_view = vk::raii::ImageView(
device, vk::ImageViewCreateInfo{
.image = info.color,
.viewType = vk::ImageViewType::e2D,
.viewType = vk::ImageViewType::e2DArray,
.format = info.renderpass.color_format,
.components{},
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = info.base_array_layer,
.layerCount = 1,
.baseArrayLayer = 0,
.layerCount = info.renderpass.multiview_count,
},
});
@@ -427,7 +497,7 @@ scene_renderer::output_image scene_renderer::create_output_image_data(const outp
.depth = 1,
},
.mipLevels = 1,
.arrayLayers = 1,
.arrayLayers = info.renderpass.multiview_count,
.samples = info.renderpass.msaa_samples,
.tiling = vk::ImageTiling::eOptimal,
.usage = vk::ImageUsageFlagBits::eDepthStencilAttachment | vk::ImageUsageFlagBits::eTransientAttachment,
@@ -442,15 +512,15 @@ scene_renderer::output_image scene_renderer::create_output_image_data(const outp
device,
vk::ImageViewCreateInfo{
.image = info.depth ? info.depth : out.depth_buffer,
.viewType = vk::ImageViewType::e2D,
.viewType = vk::ImageViewType::e2DArray,
.format = info.renderpass.depth_format,
.components{},
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eDepth,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = info.depth ? info.base_array_layer : 0,
.layerCount = 1,
.baseArrayLayer = 0,
.layerCount = info.renderpass.multiview_count,
},
});
@@ -467,7 +537,7 @@ scene_renderer::output_image scene_renderer::create_output_image_data(const outp
.depth = 1,
},
.mipLevels = 1,
.arrayLayers = 1,
.arrayLayers = info.renderpass.multiview_count,
.samples = info.renderpass.msaa_samples,
.tiling = vk::ImageTiling::eOptimal,
.usage = vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransientAttachment,
@@ -483,7 +553,7 @@ scene_renderer::output_image scene_renderer::create_output_image_data(const outp
device,
vk::ImageViewCreateInfo{
.image = out.multisample_image,
.viewType = vk::ImageViewType::e2D,
.viewType = vk::ImageViewType::e2DArray,
.format = info.renderpass.color_format,
.components{},
.subresourceRange = {
@@ -491,7 +561,7 @@ scene_renderer::output_image scene_renderer::create_output_image_data(const outp
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
.layerCount = info.renderpass.multiview_count,
},
});
}
@@ -504,15 +574,15 @@ scene_renderer::output_image scene_renderer::create_output_image_data(const outp
device,
vk::ImageViewCreateInfo{
.image = info.foveation,
.viewType = vk::ImageViewType::e2D,
.viewType = vk::ImageViewType::e2DArray,
.format = vk::Format::eR8G8Unorm,
.components{},
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = info.base_array_layer,
.layerCount = 1,
.baseArrayLayer = 0,
.layerCount = info.renderpass.multiview_count,
},
});
}
@@ -597,12 +667,10 @@ 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 = renderer::vertex::describe();
spdlog::debug("Creating pipeline");
auto vertex_shader = load_shader(device, info.shader_name + ".vert");
auto fragment_shader = load_shader(device, info.shader_name + ".frag");
auto vertex_shader = load_shader(device, info.vertex_shader_name);
auto fragment_shader = load_shader(device, info.fragment_shader_name);
auto specialization = make_specialization_constants(
int32_t(info.nb_texcoords),
@@ -630,8 +698,8 @@ vk::raii::Pipeline scene_renderer::create_pipeline(const pipeline_info & info)
},
},
.VertexBindingDescriptions = {vertex_description.binding},
.VertexAttributeDescriptions = vertex_description.attributes,
.VertexBindingDescriptions = info.vertex_layout.bindings,
.VertexAttributeDescriptions = info.vertex_layout.attributes,
.InputAssemblyState = {{
.topology = info.topology,
.primitiveRestartEnable = false,
@@ -745,6 +813,8 @@ void scene_renderer::start_frame()
},
"scene_renderer::render (UBO)"};
}
f.frame_stats = stats{};
}
void scene_renderer::end_frame()
@@ -835,8 +905,11 @@ void scene_renderer::render(
vk::Image color_buffer,
vk::Image depth_buffer,
vk::Image foveation_image,
std::span<frame_info> frames)
std::span<frame_info> frames,
bool render_debug_draws)
{
assert(frames.size() <= instance_gpu_data{}.modelview.size());
per_frame_resources & resources = current_frame();
size_t buffer_alignment = std::max<size_t>(sizeof(glm::mat4), physical_device_properties.limits.minUniformBufferOffsetAlignment);
@@ -885,159 +958,389 @@ void scene_renderer::render(
.msaa_samples = vk::SampleCountFlagBits::e1,
// .msaa_samples = vk::SampleCountFlagBits::e4, // FIXME: MSAA does not work
.fragment_density_map = foveation_image != vk::Image{},
.multiview_count = (uint32_t)frames.size(),
};
vk::raii::RenderPass & renderpass = get_renderpass(rp_info).renderpass;
for (const auto && [frame_index, frame]: utils::enumerate(frames))
// Get the average view position/direction for sorting:
// The distance from a given view is (view * xform_to_root * vec4(0,0,0,1)).z
// => dot(view * xform_to_root * vec4(0,0,0,1), vec4(0,0,1,0))
// => transpose(vec4(0,0,1,0)) * view * xform_to_root * vec(0,0,0,1)
// => dot(row(view, 2), xform_to_root * vec(0,0,0,1))
auto avg_view = 1.f / frames.size() * std::accumulate(frames.begin(), frames.end(), glm::vec4(0, 0, 0, 0), [](const glm::vec4 sum_view, const frame_info & frame) { return sum_view + glm::row(frame.view, 2); });
// Compute the views frustum
std::vector<frustum> frusta;
for (const auto & frame: frames)
{
scene_renderer::output_image & output = get_output_image_data(output_image_info{
.renderpass = rp_info,
.output_size = output_size,
.color = color_buffer,
.depth = depth_buffer,
.foveation = foveation_image,
.base_array_layer = (uint32_t)frame_index,
});
glm::mat4 viewproj = frame.projection * frame.view;
frusta.push_back(frustum{frame.projection * frame.view});
}
vk::DeviceSize frame_ubo_offset = resources.uniform_buffer_offset;
frame_gpu_data & frame_ubo = *reinterpret_cast<frame_gpu_data *>(ubo + resources.uniform_buffer_offset);
resources.uniform_buffer_offset += utils::align_up(buffer_alignment, sizeof(frame_gpu_data));
// 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 (not node.global_visible or not node.mesh or (node.global_layer_mask & layer_mask) == 0)
continue;
// frame_ubo.ambient_color = glm::vec4(0.5,0.5,0.5,0); // TODO
// frame_ubo.light_color = glm::vec4(0.5,0.5,0.5,0); // TODO
// 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.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;
cb.beginRenderPass(
vk::RenderPassBeginInfo{
.renderPass = *renderpass,
.framebuffer = *output.framebuffer,
.renderArea = {
.offset = {0, 0},
.extent = output_size,
},
.clearValueCount = clear_values.size(),
.pClearValues = clear_values.data(),
},
vk::SubpassContents::eInline);
// 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())
for (renderer::primitive & primitive: node.mesh->primitives)
{
if (not node.global_visible or not node.mesh or (node.global_layer_mask & layer_mask) == 0)
continue;
size_t nb_triangles;
size_t nb_vertices = primitive.indexed ? primitive.index_count : primitive.vertex_count;
switch (primitive.topology)
{
case vk::PrimitiveTopology::eTriangleList:
nb_triangles = nb_vertices / 3;
break;
case vk::PrimitiveTopology::eTriangleFan:
nb_triangles = nb_vertices - 2;
break;
case vk::PrimitiveTopology::eTriangleStrip:
nb_triangles = nb_vertices - 2;
break;
default:
nb_triangles = 0;
break;
}
resources.frame_stats.count_primitives++;
resources.frame_stats.count_triangles += nb_triangles;
// Compute the primitive center
glm::vec3 center = 0.5f * (primitive.obb_min + primitive.obb_max);
// Position relative to the camera
glm::vec4 position = frame.view * node.transform_to_root * glm::vec4(0, 0, 0, 1);
float position = glm::dot(avg_view, node.transform_to_root * glm::vec4(center, 1));
for (renderer::primitive & primitive: node.mesh->primitives)
renderer::material & material = primitive.material_ ? *primitive.material_ : *default_material;
if (node.joints.empty())
{
renderer::material & material = primitive.material_ ? *primitive.material_ : *default_material;
primitives.emplace_back(material.alpha_mode == renderer::material::alpha_mode_t::blend or material.alpha_mode == renderer::material::alpha_mode_t::mask, position.z, &node, &primitive);
bool visible = false;
for (const auto & fru: frusta)
visible = visible or not frustum_cull(fru, node.transform_to_root, primitive.obb_min, primitive.obb_max);
if (visible)
primitives.emplace_back(material.blend_enable, position, &node, &primitive);
else
{
resources.frame_stats.count_culled_primitives++;
resources.frame_stats.count_culled_triangles += nb_triangles;
}
}
else
primitives.emplace_back(material.blend_enable, position, &node, &primitive);
}
}
// Sort by blending / distance
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));
});
scene_renderer::output_image & output = get_output_image_data(output_image_info{
.renderpass = rp_info,
.output_size = output_size,
.color = color_buffer,
.depth = depth_buffer,
.foveation = foveation_image,
});
vk::DeviceSize frame_ubo_offset = resources.uniform_buffer_offset;
frame_gpu_data & frame_ubo = *reinterpret_cast<frame_gpu_data *>(ubo + resources.uniform_buffer_offset);
resources.uniform_buffer_offset += utils::align_up(buffer_alignment, sizeof(frame_gpu_data));
// frame_ubo.ambient_color = glm::vec4(0.5,0.5,0.5,0); // TODO
// frame_ubo.light_color = glm::vec4(0.5,0.5,0.5,0); // TODO
// 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.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
std::array<glm::mat4, 2> viewproj;
for (const auto && [frame_index, frame]: utils::enumerate(frames))
{
viewproj[frame_index] = frame.projection * frame.view;
frame_ubo.view[frame_index] = frame.view;
}
cb.beginRenderPass(vk::RenderPassBeginInfo{
.renderPass = *renderpass,
.framebuffer = *output.framebuffer,
.renderArea = {
.offset = {0, 0},
.extent = output_size,
},
.clearValueCount = clear_values.size(),
.pClearValues = clear_values.data(),
},
vk::SubpassContents::eInline);
// 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));
vk::DeviceSize joints_ubo_offset = 0;
if (!node.joints.empty())
{
joints_ubo_offset = resources.uniform_buffer_offset;
glm::mat4 * joint_matrices = reinterpret_cast<glm::mat4 *>(ubo + resources.uniform_buffer_offset);
resources.uniform_buffer_offset += utils::align_up(buffer_alignment, sizeof(glm::mat4) * 32);
assert(node.joints.size() <= 32);
for (auto && [idx, joint]: utils::enumerate(node.joints))
{
glm::mat4 & joint_transform = scene.get<components::node>(joint.first).transform_to_root;
joint_matrices[idx] = glm::inverse(transform) * joint_transform * joint.second;
}
}
// 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)
object_ubo.model = transform;
for (const auto && [frame_index, frame]: utils::enumerate(frames))
{
components::node & node = *node_ptr;
renderer::primitive & primitive = *primitive_ptr;
object_ubo.modelview[frame_index] = frame.view * transform;
object_ubo.modelviewproj[frame_index] = viewproj[frame_index] * transform;
}
object_ubo.clipping_planes = node.clipping_planes;
glm::mat4 & transform = node.transform_to_root;
// Get the material
std::shared_ptr<renderer::material> material = primitive.material_ ? primitive.material_ : default_material;
// TODO: reuse the UBO if another primitive of the same mesh has already been drawn
// Get the pipeline
pipeline_info info{
.renderpass = rp_info,
.vertex_shader_name = primitive.vertex_shader,
.fragment_shader_name = material->fragment_shader_name,
.vertex_layout = primitive.layout,
.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(),
};
if (material->double_sided)
info.cull_mode = vk::CullModeFlagBits::eNone;
if (node.reverse_side)
info.front_face = reverse(info.front_face);
cb.bindPipeline(vk::PipelineBindPoint::eGraphics, *get_pipeline(info));
cb.setViewport(0, vk::Viewport{
.x = 0,
.y = 0,
.width = (float)output_size.width,
.height = (float)output_size.height,
.minDepth = 0,
.maxDepth = 1,
});
cb.setScissor(0, vk::Rect2D{
.offset = {0, 0},
.extent = output_size,
});
if (primitive.indexed)
cb.bindIndexBuffer(*node.mesh->buffer, primitive.index_offset, primitive.index_type);
std::vector<vk::Buffer> buffers;
buffers.resize(primitive.vertex_offset.size(), (vk::Buffer)*node.mesh->buffer);
cb.bindVertexBuffers(0, buffers, primitive.vertex_offset);
vk::DescriptorBufferInfo buffer_info_1{
.buffer = resources.uniform_buffer,
.offset = frame_ubo_offset,
.range = sizeof(frame_gpu_data),
};
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,
};
vk::DescriptorBufferInfo buffer_info_4{
.buffer = *material->buffer,
.offset = material->offset,
.range = sizeof(renderer::material::gpu_data),
};
auto f = [&](renderer::texture & texture) {
return vk::DescriptorImageInfo{
.sampler = get_sampler(texture.sampler),
.imageView = **(texture.image_view),
.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal,
};
};
std::array write_ds_image{
f(*material->base_color_texture),
f(*material->metallic_roughness_texture),
f(*material->occlusion_texture),
f(*material->emissive_texture),
f(*material->normal_texture),
};
std::array descriptors{
vk::WriteDescriptorSet{
.dstBinding = 0,
.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::WriteDescriptorSet{
.dstBinding = 3,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.pImageInfo = write_ds_image.data(),
},
vk::WriteDescriptorSet{
.dstBinding = 4,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.pImageInfo = write_ds_image.data() + 1,
},
vk::WriteDescriptorSet{
.dstBinding = 5,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.pImageInfo = write_ds_image.data() + 2,
},
vk::WriteDescriptorSet{
.dstBinding = 6,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.pImageInfo = write_ds_image.data() + 3,
},
vk::WriteDescriptorSet{
.dstBinding = 7,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.pImageInfo = write_ds_image.data() + 4,
},
vk::WriteDescriptorSet{
.dstBinding = 8,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eUniformBuffer,
.pBufferInfo = &buffer_info_4,
},
};
cb.pushDescriptorSetKHR(vk::PipelineBindPoint::eGraphics, *pipeline_layout, 0, descriptors);
if (primitive.indexed)
cb.drawIndexed(primitive.index_count, 1, 0, 0, 0);
else
cb.draw(primitive.vertex_count, 1, 0, 0);
}
if (render_debug_draws and not debug_draw_vertices.empty())
{
size_t size_bytes = std::span{debug_draw_vertices}.size_bytes();
if (not resources.debug_draw or resources.debug_draw.info().size < size_bytes)
{
resources.debug_draw = buffer_allocation{
device,
vk::BufferCreateInfo{
.size = size_bytes,
.usage = vk::BufferUsageFlagBits::eVertexBuffer,
},
VmaAllocationCreateInfo{
.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT,
.usage = VMA_MEMORY_USAGE_AUTO_PREFER_HOST,
},
"scene_renderer::render (debug draw)",
};
}
memcpy(resources.debug_draw.map(), debug_draw_vertices.data(), size_bytes);
renderer::vertex_layout vertex_layout;
vertex_layout.add_vertex_attribute("Position", vk::Format::eR32G32B32A32Sfloat, 0, 0);
vertex_layout.add_vertex_attribute("Color", vk::Format::eR32G32B32A32Sfloat, 0, 1);
pipeline_info info{
.renderpass = rp_info,
.vertex_shader_name = "debug_draw.vert",
.fragment_shader_name = "debug_draw.frag",
.vertex_layout = vertex_layout,
.cull_mode = vk::CullModeFlagBits::eFrontAndBack,
.front_face = vk::FrontFace::eClockwise,
.topology = vk::PrimitiveTopology::eLineList,
.blend_enable = true,
.depth_test_enable = false,
.depth_write_enable = false,
};
cb.bindPipeline(vk::PipelineBindPoint::eGraphics, *get_pipeline(info));
cb.setViewport(0, vk::Viewport{
.x = 0,
.y = 0,
.width = (float)output_size.width,
.height = (float)output_size.height,
.minDepth = 0,
.maxDepth = 1,
});
cb.setScissor(0, vk::Rect2D{
.offset = {0, 0},
.extent = output_size,
});
{
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));
vk::DeviceSize joints_ubo_offset = 0;
if (!node.joints.empty())
object_ubo.model = glm::identity<glm::mat4>();
for (const auto && [frame_index, frame]: utils::enumerate(frames))
{
joints_ubo_offset = resources.uniform_buffer_offset;
glm::mat4 * joint_matrices = reinterpret_cast<glm::mat4 *>(ubo + resources.uniform_buffer_offset);
resources.uniform_buffer_offset += utils::align_up(buffer_alignment, sizeof(glm::mat4) * 32);
assert(node.joints.size() <= 32);
for (auto && [idx, joint]: utils::enumerate(node.joints))
{
glm::mat4 & joint_transform = scene.get<components::node>(joint.first).transform_to_root;
joint_matrices[idx] = glm::inverse(transform) * joint_transform * joint.second;
}
object_ubo.modelview[frame_index] = frame.view;
object_ubo.modelviewproj[frame_index] = viewproj[frame_index];
}
object_ubo.model = transform;
object_ubo.modelview = frame.view * transform;
object_ubo.modelviewproj = viewproj * transform;
object_ubo.clipping_planes = node.clipping_planes;
// Get the material
std::shared_ptr<renderer::material> material = primitive.material_ ? primitive.material_ : default_material;
// Get the pipeline
pipeline_info info{
.renderpass = rp_info,
.shader_name = material->shader_name,
.cull_mode = primitive.cull_mode,
.front_face = primitive.front_face,
.topology = primitive.topology,
.blend_enable = material->alpha_mode == renderer::material::alpha_mode_t::blend or material->alpha_mode == renderer::material::alpha_mode_t::mask,
.nb_texcoords = 2, // TODO
.alpha_cutout = material->alpha_mode == renderer::material::alpha_mode_t::mask,
.skinning = !node.joints.empty(),
};
if (material->double_sided)
info.cull_mode = vk::CullModeFlagBits::eNone;
if (node.reverse_side)
info.front_face = reverse(info.front_face);
cb.bindPipeline(vk::PipelineBindPoint::eGraphics, *get_pipeline(info));
cb.setViewport(0, vk::Viewport{
.x = 0,
.y = 0,
.width = (float)output_size.width,
.height = (float)output_size.height,
.minDepth = 0,
.maxDepth = 1,
});
cb.setScissor(0, vk::Rect2D{
.offset = {0, 0},
.extent = output_size,
});
if (primitive.indexed)
cb.bindIndexBuffer(*node.mesh->buffer, primitive.index_offset, primitive.index_type);
cb.bindVertexBuffers(0, (vk::Buffer)*node.mesh->buffer, primitive.vertex_offset);
vk::DescriptorBufferInfo buffer_info_1{
.buffer = resources.uniform_buffer,
.offset = frame_ubo_offset,
@@ -1050,12 +1353,12 @@ void scene_renderer::render(
};
vk::DescriptorBufferInfo buffer_info_3{
.buffer = resources.uniform_buffer,
.offset = joints_ubo_offset,
.offset = 0,
.range = sizeof(glm::mat4) * 32,
};
vk::DescriptorBufferInfo buffer_info_4{
.buffer = *material->buffer,
.offset = material->offset,
.buffer = *default_material->buffer,
.offset = default_material->offset,
.range = sizeof(renderer::material::gpu_data),
};
@@ -1068,11 +1371,11 @@ void scene_renderer::render(
};
std::array write_ds_image{
f(*material->base_color_texture),
f(*material->metallic_roughness_texture),
f(*material->occlusion_texture),
f(*material->emissive_texture),
f(*material->normal_texture),
f(*default_material->base_color_texture),
f(*default_material->metallic_roughness_texture),
f(*default_material->occlusion_texture),
f(*default_material->emissive_texture),
f(*default_material->normal_texture),
};
std::array descriptors{
vk::WriteDescriptorSet{
@@ -1132,12 +1435,57 @@ void scene_renderer::render(
};
cb.pushDescriptorSetKHR(vk::PipelineBindPoint::eGraphics, *pipeline_layout, 0, descriptors);
if (primitive.indexed)
cb.drawIndexed(primitive.index_count, 1, 0, 0, 0);
else
cb.draw(primitive.vertex_count, 1, 0, 0);
}
cb.endRenderPass();
cb.bindVertexBuffers(0, (vk::Buffer)resources.debug_draw, (vk::DeviceSize)0);
cb.draw(debug_draw_vertices.size(), 1, 0, 0);
}
cb.endRenderPass();
}
void scene_renderer::debug_draw_clear()
{
debug_draw_vertices.clear();
}
void scene_renderer::debug_draw_box(const glm::mat4 & model, glm::vec3 min, glm::vec3 max, glm::vec4 color)
{
std::array<glm::vec4, 8> v{
model * glm::vec4{min.x, min.y, min.z, 1}, // 2-------6 ^
model * glm::vec4{min.x, min.y, max.z, 1}, // /| /| | +Y
model * glm::vec4{min.x, max.y, min.z, 1}, // 3-------7 | |
model * glm::vec4{min.x, max.y, max.z, 1}, // | | | | O--> +X
model * glm::vec4{max.x, min.y, min.z, 1}, // | 0-----|-4 /
model * glm::vec4{max.x, min.y, max.z, 1}, // |/ |/ v
model * glm::vec4{max.x, max.y, min.z, 1}, // 1-------5 +Z
model * glm::vec4{max.x, max.y, max.z, 1}, //
};
debug_draw_vertices.emplace_back(v[0], color);
debug_draw_vertices.emplace_back(v[1], color);
debug_draw_vertices.emplace_back(v[1], color);
debug_draw_vertices.emplace_back(v[3], color);
debug_draw_vertices.emplace_back(v[3], color);
debug_draw_vertices.emplace_back(v[2], color);
debug_draw_vertices.emplace_back(v[2], color);
debug_draw_vertices.emplace_back(v[0], color);
debug_draw_vertices.emplace_back(v[4], color);
debug_draw_vertices.emplace_back(v[5], color);
debug_draw_vertices.emplace_back(v[5], color);
debug_draw_vertices.emplace_back(v[7], color);
debug_draw_vertices.emplace_back(v[7], color);
debug_draw_vertices.emplace_back(v[6], color);
debug_draw_vertices.emplace_back(v[6], color);
debug_draw_vertices.emplace_back(v[4], color);
debug_draw_vertices.emplace_back(v[0], color);
debug_draw_vertices.emplace_back(v[4], color);
debug_draw_vertices.emplace_back(v[1], color);
debug_draw_vertices.emplace_back(v[5], color);
debug_draw_vertices.emplace_back(v[2], color);
debug_draw_vertices.emplace_back(v[6], color);
debug_draw_vertices.emplace_back(v[3], color);
debug_draw_vertices.emplace_back(v[7], color);
}
+42 -7
View File
@@ -18,6 +18,7 @@
#pragma once
#include "render/vertex_layout.h"
#include <array>
#include <cstdint>
#include <glm/mat4x4.hpp>
@@ -42,6 +43,7 @@ struct renderpass_info
bool keep_depth_buffer;
vk::SampleCountFlagBits msaa_samples = vk::SampleCountFlagBits::e1;
bool fragment_density_map;
uint32_t multiview_count;
bool operator==(const renderpass_info & other) const noexcept = default;
};
@@ -50,7 +52,9 @@ struct pipeline_info
{
renderpass_info renderpass;
std::string shader_name;
std::string vertex_shader_name;
std::string fragment_shader_name;
renderer::vertex_layout vertex_layout;
vk::CullModeFlags cull_mode = vk::CullModeFlagBits::eNone;
vk::FrontFace front_face = vk::FrontFace::eClockwise;
@@ -76,7 +80,6 @@ struct output_image_info
VkImage color;
VkImage depth;
VkImage foveation;
uint32_t base_array_layer;
bool operator==(const output_image_info & other) const noexcept = default;
};
@@ -178,8 +181,7 @@ class scene_renderer
struct frame_gpu_data
{
glm::mat4 view;
glm::mat4 proj;
std::array<glm::mat4, 2> view;
glm::vec4 light_position;
glm::vec4 ambient_color;
glm::vec4 light_color;
@@ -188,11 +190,29 @@ class scene_renderer
struct instance_gpu_data
{
glm::mat4 model;
glm::mat4 modelview;
glm::mat4 modelviewproj;
std::array<glm::mat4, 2> modelview;
std::array<glm::mat4, 2> modelviewproj;
std::array<glm::vec4, 4> clipping_planes;
};
struct debug_draw_vertex
{
glm::vec4 position;
glm::vec4 colour;
};
std::vector<debug_draw_vertex> debug_draw_vertices;
public:
struct stats
{
size_t count_primitives;
size_t count_culled_primitives;
size_t count_triangles;
size_t count_culled_triangles;
};
private:
struct per_frame_resources
{
vk::raii::Fence fence = nullptr;
@@ -204,6 +224,11 @@ class scene_renderer
// device local, host visible, host coherent
size_t uniform_buffer_offset;
buffer_allocation uniform_buffer;
buffer_allocation debug_draw;
// Statistics
stats frame_stats;
};
std::vector<per_frame_resources> frame_resources;
@@ -249,9 +274,19 @@ public:
vk::Image color_buffer,
vk::Image depth_buffer,
vk::Image foveation_image,
std::span<frame_info> info);
std::span<frame_info> info,
bool render_debug_draws = false);
void end_frame();
void debug_draw_clear();
// void debug_draw(std::span<glm::vec3> line, glm::vec4 color);
void debug_draw_box(const glm::mat4 & model, glm::vec3 min, glm::vec3 max, glm::vec4 color);
const stats & last_frame_stats() const
{
return frame_resources[current_frame_index].frame_stats;
}
double get_gpu_time() const
{
return gpu_time_s;
+95
View File
@@ -0,0 +1,95 @@
/*
* WiVRn VR streaming
* Copyright (C) 2025 Guillaume Meunier <[email protected]>
*
* 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 <cstddef>
#include <glm/vec2.hpp>
#include <glm/vec3.hpp>
#include <glm/vec4.hpp>
#include <string>
#include <vector>
#include <vulkan/vulkan.hpp>
#include <vulkan/vulkan_format_traits.hpp>
namespace renderer
{
struct vertex_layout
{
std::vector<vk::VertexInputBindingDescription> bindings;
std::vector<vk::VertexInputAttributeDescription> attributes;
std::vector<std::string> attribute_names;
void add_attribute(std::string name, vk::Format format, uint32_t binding, uint32_t location, vk::VertexInputRate input_rate, int array_size = 1)
{
size_t texel_size = vk::blockSize(format);
uint32_t offset = 0;
if (auto iter = std::ranges::find(bindings, binding, &vk::VertexInputBindingDescription::binding); iter == bindings.end())
bindings.push_back(vk::VertexInputBindingDescription{
.binding = binding,
.stride = (uint32_t)(texel_size * array_size),
.inputRate = input_rate,
});
else
{
offset = iter->stride;
iter->stride += texel_size * array_size;
}
for (int index = 0; index < array_size; index++)
{
attributes.push_back(vk::VertexInputAttributeDescription{
.location = location + index,
.binding = binding,
.format = format,
.offset = (uint32_t)(offset + index * texel_size),
});
if (array_size == 1)
attribute_names.push_back(name);
else
attribute_names.push_back(name + "_" + std::to_string(index));
}
}
void add_vertex_attribute(std::string name, vk::Format format, uint32_t binding, uint32_t location, int array_size = 1)
{
add_attribute(std::move(name), format, binding, location, vk::VertexInputRate::eVertex, array_size);
}
bool operator==(const vertex_layout & other) const noexcept = default;
};
} // namespace renderer
namespace std
{
template <>
struct hash<renderer::vertex_layout> : utils::magic_hash<renderer::vertex_layout>
{};
template <>
struct hash<vk::VertexInputBindingDescription> : utils::magic_hash<vk::VertexInputBindingDescription>
{};
template <>
struct hash<vk::VertexInputAttributeDescription> : utils::magic_hash<vk::VertexInputAttributeDescription>
{};
} // namespace std
+4 -2
View File
@@ -155,7 +155,8 @@ void scene::render_world(
bool keep_depth_buffer,
uint32_t layer_mask,
XrColor4f clear_color,
const std::optional<xr::foveation_profile> & foveation)
const std::optional<xr::foveation_profile> & foveation,
bool render_debug_draws)
{
std::vector<scene_renderer::frame_info> frames;
frames.reserve(views.size());
@@ -245,7 +246,8 @@ void scene::render_world(
color_image,
depth_image,
foveation_image,
frames);
frames,
render_debug_draws);
add_projection_layer(
XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT,
+2 -1
View File
@@ -193,7 +193,8 @@ protected:
bool keep_depth_buffer,
uint32_t layer_mask,
XrColor4f clear_color,
const std::optional<xr::foveation_profile> & foveation = std::nullopt);
const std::optional<xr::foveation_profile> & foveation = std::nullopt,
bool render_debug_draws = false);
void set_color_scale_bias(XrColor4f scale, XrColor4f bias);
void set_depth_test(bool write, XrCompareOpFB op);
+4 -4
View File
@@ -257,8 +257,8 @@ void blitter::push_image(vk::raii::CommandBuffer & cmd, uint8_t stream, vk::Samp
VkBool32(alpha));
// Create graphics pipeline
vk::raii::ShaderModule vertex_shader = load_shader(device, "stream.vert");
vk::raii::ShaderModule fragment_shader = load_shader(device, "stream.frag");
vk::ShaderModule vertex_shader = *load_shader(device, "stream.vert");
vk::ShaderModule fragment_shader = *load_shader(device, "stream.frag");
p.layout = device.createPipelineLayout(vk::PipelineLayoutCreateInfo{
.setLayoutCount = 1,
@@ -268,13 +268,13 @@ void blitter::push_image(vk::raii::CommandBuffer & cmd, uint8_t stream, vk::Samp
vk::pipeline_builder pipeline_info{
.Stages = {{
.stage = vk::ShaderStageFlagBits::eVertex,
.module = *vertex_shader,
.module = vertex_shader,
.pName = "main",
.pSpecializationInfo = vert_constants,
},
{
.stage = vk::ShaderStageFlagBits::eFragment,
.module = *fragment_shader,
.module = fragment_shader,
.pName = "main",
.pSpecializationInfo = frag_constants,
}},
+4 -4
View File
@@ -120,25 +120,25 @@ stream_defoveator::pipeline_t & stream_defoveator::ensure_pipeline(size_t view,
const auto & vk_device_extensions = application::get_vk_device_extensions();
// Vertex shader
vk::raii::ShaderModule vertex_shader = load_shader(device, "reprojection.vert");
vk::ShaderModule vertex_shader = *load_shader(device, "reprojection.vert");
// Fragment shader
auto specialization = make_specialization_constants(
int32_t(alpha),
VkBool32(need_srgb_conversion(guess_model())));
vk::raii::ShaderModule fragment_shader = load_shader(device, "reprojection.frag");
vk::ShaderModule fragment_shader = *load_shader(device, "reprojection.frag");
vk::pipeline_builder pipeline_info{
.flags = {},
.Stages = {
{
.stage = vk::ShaderStageFlagBits::eVertex,
.module = *vertex_shader,
.module = vertex_shader,
.pName = "main",
},
{
.stage = vk::ShaderStageFlagBits::eFragment,
.module = *fragment_shader,
.module = fragment_shader,
.pName = "main",
.pSpecializationInfo = specialization,
},
+105
View File
@@ -0,0 +1,105 @@
// kate: hl glsl
const int nb_views = 2;
const int nb_clipping = 4;
const int nb_texcoords = 2;
const bool use_pbr = false;
const bool use_normal_maps = false;
layout(set = 0, binding = 0) uniform scene_ubo
{
mat4 view[nb_views];
vec4 light_position;
vec4 ambient_color;
vec4 light_color;
} scene;
layout(set = 0, binding = 1) uniform mesh_ubo
{
mat4 model;
mat4 modelview[nb_views];
mat4 modelviewproj[nb_views];
vec4 clipping_plane[nb_clipping];
} mesh;
layout(set = 0, binding = 2) uniform joints_ubo
{
mat4 joint_matrices[32];
} joints;
layout(set = 0, binding = 3) uniform sampler2D base_color_texture;
layout(set = 0, binding = 4) uniform sampler2D metallic_roughness_texture;
layout(set = 0, binding = 5) uniform sampler2D occlusion_texture;
layout(set = 0, binding = 6) uniform sampler2D emissive_texture;
layout(set = 0, binding = 7) uniform sampler2D normal_map_texture;
layout(set = 0, binding = 8) uniform material_ubo
{
vec4 base_color_factor;
vec4 base_emissive_factor;
float metallic_factor;
float roughness_factor;
float occlusion_strength;
float normal_scale;
float alpha_cutoff;
int base_color_texcoord;
int metallic_roughness_texcoord;
int occlusion_texcoord;
int emissive_texcoord;
int normal_texcoord;
} material;
const float dither_pattern[4][4] = {
{ 0.0f, 0.5f, 0.125f, 0.625f},
{ 0.75f, 0.25f, 0.875f, 0.375f},
{ 0.1875f, 0.6875f, 0.0625f, 0.5625},
{ 0.9375f, 0.4375f, 0.8125f, 0.3125}
};
vec4 one_over_d_linear_to_srgb(vec4 color)
{
/* Linear to sRGB is:
*
* if (x <= 0.0031308)
* return 12.92 * x;
* else
* return 1.055*pow(x, 1.0 / 2.4) - 0.055;
*
* Its derivative is:
* if (x <= 0.0031308)
* return 12.92;
* else
* return (1.055 / 2.4) * pow(x, -1.4 / 2.4);
*
*/
// vec3 tmp1 = vec3(1.0 / 12.92);
// vec3 tmp2 = (2.4 / 1.055) * pow(color.rgb, vec3(1.4 / 2.4));
vec3 tmp1 = vec3(0.0773993808049);
vec3 tmp2 = 2.27488151659 * pow(color.rgb, vec3(0.583333333333));
// Alpha is not converted to sRGB
return vec4(mix(tmp1, tmp2, vec3(greaterThan(color.rgb, vec3(0.0031308, 0.0031308, 0.0031308)))), 1.0);
}
vec4 dither(ivec2 frag_coord, vec4 colour)
{
ivec2 tmp = frag_coord % 4;
float dither_thd = 1.0f - dither_pattern[tmp.x][tmp.y];
return colour + one_over_d_linear_to_srgb(colour) * vec4(dither_thd, dither_thd, dither_thd, 0) / 255.0f;
}
#ifdef FRAG_SHADER
#define VS_TO_FS in
#else
#define VS_TO_FS out
#endif
// Vertex-to-fragment
layout(location = 0) VS_TO_FS vec3 normal;
layout(location = 1) VS_TO_FS vec4 tangent;
layout(location = 2) VS_TO_FS vec4 frag_pos;
layout(location = 3) VS_TO_FS vec4 light_pos;
layout(location = 4) VS_TO_FS vec2 texcoord[nb_texcoords];
+113
View File
@@ -0,0 +1,113 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <[email protected]>
* Copyright (C) 2022 Patrick Nicolas <[email protected]>
*
* 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/>.
*/
#version 450
#extension GL_EXT_multiview : enable
layout (constant_id = 0) const int nb_texcoords = 2;
layout (constant_id = 1) const bool dithering = true;
layout (constant_id = 2) const bool alpha_cutout = false;
layout (constant_id = 3) const bool skinning = false;
const int nb_views = 2;
const int nb_clipping = 4;
layout(set = 0, binding = 0) uniform scene_ubo
{
mat4 view[nb_views];
vec4 light_position;
vec4 ambient_color;
vec4 light_color;
} scene;
layout(set = 0, binding = 1) uniform mesh_ubo
{
mat4 model;
mat4 modelview[nb_views];
mat4 modelviewproj[nb_views];
vec4 clipping_plane[nb_clipping];
} mesh;
layout(set = 0, binding = 2) uniform joints_ubo
{
mat4 joint_matrices[32];
} joints;
#ifdef FRAG_SHADER
layout(set = 0, binding = 3) uniform sampler2D base_color;
layout(set = 0, binding = 4) uniform sampler2D metallic_roughness;
layout(set = 0, binding = 5) uniform sampler2D occlusion;
layout(set = 0, binding = 6) uniform sampler2D emissive;
layout(set = 0, binding = 7) uniform sampler2D normal_map;
layout(set = 0, binding = 8) uniform material_ubo
{
vec4 base_color_factor;
vec4 base_emissive_factor;
float metallic_factor;
float roughness_factor;
float occlusion_strength;
float normal_scale;
float alpha_cutoff;
int base_color_texcoord;
int metallic_roughness_texcoord;
int occlusion_texcoord;
int emissive_texcoord;
int normal_texcoord;
} material;
#endif
// Vertex input
#ifdef VERT_SHADER
layout(location = 0) in vec4 in_position;
layout(location = 1) in vec4 in_color;
#endif
// Vertex-to-fragment
#ifdef VERT_SHADER
#define VERT_TO_FRAG out
#else
#define VERT_TO_FRAG in
#endif
layout(location = 0) VERT_TO_FRAG vec4 color;
// Shader code
#ifdef VERT_SHADER
out gl_PerVertex
{
vec4 gl_Position;
};
void main()
{
gl_Position = mesh.modelviewproj[gl_ViewIndex] * in_position;
color = in_color;
}
#endif
#ifdef FRAG_SHADER
layout(location = 0) out vec4 out_color;
layout(early_fragment_tests) in;
void main()
{
out_color = color;
}
#endif
+79
View File
@@ -0,0 +1,79 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <[email protected]>
* Copyright (C) 2022 Patrick Nicolas <[email protected]>
*
* 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/>.
*/
#version 450
#extension GL_GOOGLE_include_directive : require
#include "common.glsl.inc"
#include "pbr.glsl.inc"
// Fragment output
layout(location = 0) out vec4 out_color;
layout(early_fragment_tests) in;
void main()
{
vec4 albedo = material.base_color_factor * texture(base_color_texture, texcoord[0]);
vec3 emissive_color = (material.base_emissive_factor * texture(emissive_texture, texcoord[0])).rgb;
vec3 normal_unit;
if (use_normal_maps)
{
vec3 sampled_normal = normalize(vec3(material.normal_scale, material.normal_scale, 1) * (texture(normal_map_texture, texcoord[0]).xyz * 2 - 1));
// glTF spec §3.7.2.1
vec3 bitangent = cross(normal, tangent.xyz) * tangent.w;
mat3 TBN = mat3(tangent.xyz, bitangent, normal); // View space to tangent space?
// Normal in view space
normal_unit = TBN * sampled_normal;
}
else
normal_unit = normalize(normal);
vec3 light_dir = normalize(light_pos.xyz - frag_pos.xyz * light_pos.w);
vec3 view_dir = normalize(-frag_pos.xyz);
if (use_pbr)
{
float ao = 1 + material.occlusion_strength * (texture(occlusion_texture, texcoord[0]).r - 1);
vec4 mr = texture(metallic_roughness_texture, texcoord[0]);
vec3 half_vec = normalize(light_dir + view_dir);
float metallic = material.metallic_factor * mr.b;
float roughness = material.roughness_factor * mr.g;
vec3 light_colour = scene.light_color.rgb;
float attenuation = 1;
vec3 radiance =
per_light_radiance(albedo.rgb, metallic, roughness, light_colour, light_dir, normal_unit, view_dir, half_vec, attenuation) +
vec3(scene.ambient_color) * albedo.rgb * ao;
vec3 tmp = radiance + emissive_color;
out_color = vec4(tmp / (tmp + 1), albedo.a);
}
else
{
out_color = vec4(emissive_color + albedo.rgb * (max(0, dot(normal_unit, light_dir)) * scene.light_color.rgb + scene.ambient_color.rgb), albedo.a);
}
}
-229
View File
@@ -1,229 +0,0 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <[email protected]>
* Copyright (C) 2022 Patrick Nicolas <[email protected]>
*
* 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/>.
*/
#version 450
layout (constant_id = 0) const int nb_texcoords = 2;
layout (constant_id = 1) const bool dithering = true;
layout (constant_id = 2) const bool alpha_cutout = false;
layout (constant_id = 3) const bool skinning = false;
const int nb_clipping = 4;
const float fog_min_dist = 20.0;
const float fog_max_dist = 35.0;
const vec4 fog_color = vec4(0.0, 0.25, 0.5, 1.0);
layout(set = 0, binding = 0) uniform scene_ubo
{
mat4 view;
mat4 proj;
vec4 light_position;
vec4 ambient_color;
vec4 light_color;
} scene;
layout(set = 0, binding = 1) uniform mesh_ubo
{
mat4 model;
mat4 modelview;
mat4 modelviewproj;
vec4 clipping_plane[nb_clipping];
} mesh;
layout(set = 0, binding = 2) uniform joints_ubo
{
mat4 joint_matrices[32];
} joints;
#ifdef FRAG_SHADER
layout(set = 0, binding = 3) uniform sampler2D base_color;
layout(set = 0, binding = 4) uniform sampler2D metallic_roughness;
layout(set = 0, binding = 5) uniform sampler2D occlusion;
layout(set = 0, binding = 6) uniform sampler2D emissive;
layout(set = 0, binding = 7) uniform sampler2D normal_map;
layout(set = 0, binding = 8) uniform material_ubo
{
vec4 base_color_factor;
vec4 base_emissive_factor;
float metallic_factor;
float roughness_factor;
float occlusion_strength;
float normal_scale;
float alpha_cutoff;
int base_color_texcoord;
int metallic_roughness_texcoord;
int occlusion_texcoord;
int emissive_texcoord;
int normal_texcoord;
} material;
#endif
// Vertex input
#ifdef VERT_SHADER
layout(location = 0) in vec3 in_position;
layout(location = 1) in vec3 in_normal;
layout(location = 2) in vec4 in_tangent;
layout(location = 3) in vec2 in_texcoord[2];
layout(location = 5) in vec4 in_color;
layout(location = 6) in vec4 in_joints;
layout(location = 7) in vec4 in_weights;
#endif
// Vertex-to-fragment
#ifdef VERT_SHADER
#define VERT_TO_FRAG out
#else
#define VERT_TO_FRAG in
#endif
layout(location = 0) VERT_TO_FRAG vec3 normal;
layout(location = 1) VERT_TO_FRAG vec4 frag_pos;
layout(location = 2) VERT_TO_FRAG vec4 light_pos;
layout(location = 3) VERT_TO_FRAG vec2 texcoord[nb_texcoords];
// Fragment output
#ifdef FRAG_SHADER
layout(location = 0) out vec4 out_color;
#endif
// Shader code
#ifdef VERT_SHADER
out gl_PerVertex
{
vec4 gl_Position;
float gl_ClipDistance[nb_clipping];
};
void main()
{
// TODO: use base_color_texcoord et al instead of always using texcoord 0
for(int i = 0; i < nb_texcoords; i++)
texcoord[i] = in_texcoord[i];
if (skinning)
{
mat4 skinMatrix =
in_weights.x * joints.joint_matrices[int(in_joints.x)] +
in_weights.y * joints.joint_matrices[int(in_joints.y)] +
in_weights.z * joints.joint_matrices[int(in_joints.z)] +
in_weights.w * joints.joint_matrices[int(in_joints.w)];
normal = vec3(mesh.modelview * skinMatrix * vec4(in_normal, 0.0));
gl_Position = mesh.modelviewproj * skinMatrix * vec4(in_position, 1.0);
}
else
{
normal = vec3(mesh.modelview * vec4(in_normal, 0.0));
gl_Position = mesh.modelviewproj * vec4(in_position, 1.0);
}
frag_pos = mesh.modelview * vec4(in_position, 1.0);
light_pos = scene.view * scene.light_position;
for(int i = 0; i < nb_clipping; i++)
{
gl_ClipDistance[i] = dot(mesh.clipping_plane[i], mesh.model * vec4(in_position, 1.0));
}
}
#endif
#ifdef FRAG_SHADER
const float dither_pattern[4][4] = {
{ 0.0f, 0.5f, 0.125f, 0.625f},
{ 0.75f, 0.25f, 0.875f, 0.375f},
{ 0.1875f, 0.6875f, 0.0625f, 0.5625},
{ 0.9375f, 0.4375f, 0.8125f, 0.3125}
};
vec4 one_over_d_linear_to_srgb(vec4 color)
{
/* Linear to sRGB is:
*
* if (x <= 0.00031308)
* return 12.92 * x;
* else
* return 1.055*pow(x, 1.0 / 2.4) - 0.055;
*
* Its derivative is:
* if (x <= 0.00031308)
* return 12.92;
* else
* return (1.055 / 2.4) * pow(x, -1.4 / 2.4);
*
*/
// Alpha is not converted to sRGB
vec3 tmp1 = vec3(1.0 / 12.92, 1.0 / 12.92, 1.0 / 12.92);
vec3 tmp2 = (2.4 / 1.055) * vec3(pow(color.r, 1.4 / 2.4), pow(color.g, 1.4 / 2.4), pow(color.b, 1.4 / 2.4));
return vec4(mix(tmp1, tmp2, vec3(greaterThan(color.rgb, vec3(0.00031308, 0.00031308, 0.00031308)))), 1.0);
}
void main()
{
vec3 light_dir = normalize(light_pos.xyz - frag_pos.xyz * light_pos.w);
vec3 view_dir = normalize(frag_pos.xyz);
vec3 normal_unit = normalize(normal);
vec3 reflect_dir = reflect(-light_dir, normal_unit);
// Ambient lighting
vec3 ambient = vec3(scene.ambient_color);
// Diffuse lighting
vec3 diffuse = max(dot(normal_unit, light_dir), 0.0) * vec3(scene.light_color);
// Specular lighting
// vec3 half_dir = normalize(light_dir + view_dir);
// float spec_angle = max(dot(half_dir, normal_unit), 0.0);
// vec3 specular = pow(spec_angle, instance.specular_power) * instance.specular_strength * instance.light_color;
vec3 light = ambient + diffuse /*+ specular*/;
vec4 bc = material.base_color_factor * texture(base_color, fract(texcoord[0])) * vec4(light, 1.0);
vec4 ec = material.base_emissive_factor * texture(emissive, fract(texcoord[0]));
float fog = clamp((length(frag_pos) - fog_min_dist) / (fog_max_dist - fog_min_dist), 0.0, 1.0);
bc = mix(bc + ec, fog_color, fog);
if (dithering)
{
ivec2 tmp = ivec2(gl_FragCoord.xy) % 4;
float dither_thd = 1.0f - dither_pattern[tmp.x][tmp.y];
out_color = bc + one_over_d_linear_to_srgb(bc) * vec4(dither_thd, dither_thd, dither_thd, 0) / 255.0f;
}
else
out_color = bc;
if (alpha_cutout)
{
if (out_color.a <= material.alpha_cutoff)
out_color.a = 0.0;
else
out_color.a = 1.0;
}
}
#endif
+64
View File
@@ -0,0 +1,64 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <[email protected]>
* Copyright (C) 2022 Patrick Nicolas <[email protected]>
*
* 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/>.
*/
#version 450
#extension GL_EXT_multiview : require
#extension GL_GOOGLE_include_directive : require
#include "common.glsl.inc"
// Vertex input
layout(location = 0) in vec3 in_position;
layout(location = 1) in vec3 in_normal;
layout(location = 2) in vec4 in_tangent;
layout(location = 3) in vec2 in_texcoord[2];
layout(location = 5) in vec4 in_color;
out gl_PerVertex
{
vec4 gl_Position;
// float gl_ClipDistance[nb_clipping];
};
void main()
{
// TODO: use base_color_texcoord et al instead of always using texcoord 0
for (int i = 0; i < nb_texcoords; i++)
texcoord[i] = in_texcoord[i];
// TODO on CPU?
mat3 mv = inverse(transpose(mat3(mesh.modelview[gl_ViewIndex])));
tangent = vec4(normalize(mv * in_tangent.xyz), in_tangent.w);
if (any(isnan(tangent))) // avoid NaNs if no tangent data is provided
tangent = vec4(0, 0, 0, 0);
normal = normalize(mv * in_normal);
gl_Position = mesh.modelviewproj[gl_ViewIndex] * vec4(in_position, 1.0);
frag_pos = mesh.modelview[gl_ViewIndex] * vec4(in_position, 1.0);
light_pos = scene.view[gl_ViewIndex] * scene.light_position;
// for(int i = 0; i < nb_clipping; i++)
// {
// gl_ClipDistance[i] = dot(mesh.clipping_plane[i], mesh.model * vec4(in_position, 1.0));
// }
}
+82
View File
@@ -0,0 +1,82 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <[email protected]>
* Copyright (C) 2022 Patrick Nicolas <[email protected]>
*
* 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/>.
*/
#version 450
#extension GL_GOOGLE_include_directive : require
#include "common.glsl.inc"
#include "pbr.glsl.inc"
// Fragment output
layout(location = 0) out vec4 out_color;
// layout(early_fragment_tests) in;
void main()
{
vec4 albedo = material.base_color_factor * texture(base_color_texture, texcoord[0]);
vec3 emissive_color = (material.base_emissive_factor * texture(emissive_texture, texcoord[0])).rgb;
vec3 normal_unit;
if (use_normal_maps)
{
vec3 sampled_normal = normalize(vec3(material.normal_scale, material.normal_scale, 1) * (texture(normal_map_texture, texcoord[0]).xyz * 2 - 1));
// glTF spec §3.7.2.1
vec3 bitangent = cross(normal, tangent.xyz) * tangent.w;
mat3 TBN = mat3(tangent.xyz, bitangent, normal); // View space to tangent space?
// Normal in view space
normal_unit = TBN * sampled_normal;
}
else
normal_unit = normalize(normal);
vec3 light_dir = normalize(light_pos.xyz - frag_pos.xyz * light_pos.w);
vec3 view_dir = normalize(-frag_pos.xyz);
if (use_pbr)
{
float ao = 1 + material.occlusion_strength * (texture(occlusion_texture, texcoord[0]).r - 1);
vec4 mr = texture(metallic_roughness_texture, texcoord[0]);
vec3 half_vec = normalize(light_dir + view_dir);
float metallic = material.metallic_factor * mr.b;
float roughness = material.roughness_factor * mr.g;
vec3 light_colour = scene.light_color.rgb;
float attenuation = 1;
vec3 radiance =
per_light_radiance(albedo.rgb, metallic, roughness, light_colour, light_dir, normal_unit, view_dir, half_vec, attenuation) +
vec3(scene.ambient_color) * albedo.rgb * ao;
vec3 tmp = radiance + emissive_color;
out_color = vec4(tmp / (tmp + 1), albedo.a);
}
else
{
out_color = vec4(emissive_color + albedo.rgb * (max(0, dot(normal_unit, light_dir)) * scene.light_color.rgb + scene.ambient_color.rgb), albedo.a);
}
if (albedo.a <= material.alpha_cutoff)
discard;
}
+68
View File
@@ -0,0 +1,68 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <[email protected]>
* Copyright (C) 2022 Patrick Nicolas <[email protected]>
*
* 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/>.
*/
#version 450
#extension GL_EXT_multiview : require
#extension GL_GOOGLE_include_directive : require
#include "common.glsl.inc"
// Vertex input
layout(location = 0) in vec3 in_position;
layout(location = 1) in vec3 in_normal;
layout(location = 2) in vec4 in_tangent;
layout(location = 3) in vec2 in_texcoord[2];
layout(location = 5) in vec4 in_color;
layout(location = 6) in vec4 in_joints;
layout(location = 7) in vec4 in_weights;
out gl_PerVertex
{
vec4 gl_Position;
// float gl_ClipDistance[nb_clipping];
};
void main()
{
// TODO: use base_color_texcoord et al instead of always using texcoord 0
for (int i = 0; i < nb_texcoords; i++)
texcoord[i] = in_texcoord[i];
mat4 skinMatrix =
in_weights.x * joints.joint_matrices[int(in_joints.x)] +
in_weights.y * joints.joint_matrices[int(in_joints.y)] +
in_weights.z * joints.joint_matrices[int(in_joints.z)] +
in_weights.w * joints.joint_matrices[int(in_joints.w)];
// TODO on CPU?
mat3 mv = inverse(transpose(mat3(mesh.modelview[gl_ViewIndex])));
tangent = vec4(normalize(mv * in_tangent.xyz), in_tangent.w);
if (any(isnan(tangent))) // avoid NaNs if no tangent data is provided
tangent = vec4(0, 0, 0, 0);
normal = normalize(mv * in_normal);
normal = vec3(mesh.modelview[gl_ViewIndex] * skinMatrix * vec4(in_normal, 0.0));
gl_Position = mesh.modelviewproj[gl_ViewIndex] * skinMatrix * vec4(in_position, 1.0);
frag_pos = mesh.modelview[gl_ViewIndex] * vec4(in_position, 1.0);
light_pos = scene.view[gl_ViewIndex] * scene.light_position;
}
+95
View File
@@ -0,0 +1,95 @@
// kate: hl glsl
// Copied from https://github.com/JoeyDeVries/LearnOpenGL/blob/master/src/6.pbr/1.1.lighting/1.1.pbr.fs
const float PI = 3.14159265359;
float DistributionGGX(vec3 N, vec3 H, float roughness)
{
float a = roughness*roughness;
float a2 = a*a;
float NdotH = max(dot(N, H), 0.0);
float NdotH2 = NdotH*NdotH;
float nom = a2;
float denom = (NdotH2 * (a2 - 1.0) + 1.0);
denom = PI * denom * denom;
return nom / denom;
}
float GeometrySchlickGGX(float NdotV, float roughness)
{
float r = (roughness + 1.0);
float k = (r*r) / 8.0;
float nom = NdotV;
float denom = NdotV * (1.0 - k) + k;
return nom / denom;
}
float GeometrySmith(vec3 N, vec3 V, vec3 L, float roughness)
{
float NdotV = max(dot(N, V), 0.0);
float NdotL = max(dot(N, L), 0.0);
float ggx2 = GeometrySchlickGGX(NdotV, roughness);
float ggx1 = GeometrySchlickGGX(NdotL, roughness);
return ggx1 * ggx2;
}
vec3 fresnelSchlick(float cosTheta, vec3 F0)
{
// return F0 + (1.0 - F0) * pow(clamp(1.0 - cosTheta, 0.0, 1.0), 5.0);
float tmp = 1.0 - max(cosTheta, 0.0);
float tmp2 = tmp * tmp;
float tmp4 = tmp2 * tmp2;
return F0 + (1.0 - F0) * tmp * tmp4;
}
vec3 per_light_radiance(
vec3 albedo,
float metallic,
float roughness,
vec3 light_colour,
vec3 L, // Light direction relative to the current fragment in view space
vec3 N, // Normal
vec3 V, // Camera position relative to the current fragment in view space
vec3 H, // Half vector, normalize(L+V)
float attenuation // Light attenuation: 1/distance^2 for point lights, 1 for directional lights
)
{
// calculate reflectance at normal incidence; if dia-electric (like plastic) use F0
// of 0.04 and if it's a metal, use the albedo color as F0 (metallic workflow)
vec3 F0 = vec3(0.04);
F0 = mix(F0, albedo, metallic);
vec3 radiance = light_colour * attenuation;
// Cook-Torrance BRDF
float NDF = DistributionGGX(N, H, roughness);
float G = GeometrySmith(N, V, L, roughness);
vec3 F = fresnelSchlick(max(dot(H, V), 0.0), F0);
vec3 numerator = NDF * G * F;
float denominator = 4.0 * max(dot(N, V), 0.0) * max(dot(N, L), 0.0) + 0.0001; // + 0.0001 to prevent divide by zero
vec3 specular = numerator / denominator;
// kS is equal to Fresnel
vec3 kS = F;
// for energy conservation, the diffuse and specular light can't
// be above 1.0 (unless the surface emits light); to preserve this
// relationship the diffuse component (kD) should equal 1.0 - kS.
vec3 kD = vec3(1.0) - kS;
// multiply kD by the inverse metalness such that only non-metals
// have diffuse lighting, or a linear blend if partly metal (pure metals
// have no diffuse light).
kD *= 1.0 - metallic;
// scale light by NdotL
float NdotL = max(dot(N, L), 0.0);
// add to outgoing radiance Lo
return (kD * albedo / PI + specular) * radiance * NdotL; // note that we already multiplied the BRDF by the Fresnel (kS) so we won't multiply by kS again
}
+14 -1
View File
@@ -26,7 +26,6 @@
namespace utils
{
template <typename T>
struct is_vk_flags : std::false_type
{};
@@ -35,6 +34,14 @@ template <typename T>
struct is_vk_flags<vk::Flags<T>> : std::true_type
{};
template <typename T>
struct is_std_vector : std::false_type
{};
template <typename T, typename Allocator>
struct is_std_vector<std::vector<T, Allocator>> : std::true_type
{};
template <typename T>
struct magic_hash
{
@@ -51,6 +58,12 @@ struct magic_hash
std::hash<V> hasher;
h = std::rotl(h, 5) ^ hasher(static_cast<V>(member));
}
else if constexpr (is_std_vector<U>::value)
{
std::hash<typename U::value_type> hasher;
for (const auto & i: member)
h = std::rotl(h, 5) ^ hasher(i);
}
else
{
std::hash<U> hasher;
+55 -5
View File
@@ -18,19 +18,69 @@
*/
#include "shader.h"
#include "utils/cache.h"
#include "wivrn_shaders.h"
#include <magic_enum.hpp>
#include <spdlog/spdlog.h>
#include <spirv_reflect.h>
#include <vulkan/vulkan_to_string.hpp>
vk::raii::ShaderModule load_shader(vk::raii::Device & device, const std::vector<uint32_t> & spirv)
template <typename T, typename F>
std::vector<T *> enumerate(F && f, SpvReflectShaderModule & reflected_shader_module)
{
uint32_t count;
[[maybe_unused]] SpvReflectResult result = f(&reflected_shader_module, &count, nullptr);
assert(result == SPV_REFLECT_RESULT_SUCCESS);
std::vector<T *> data(count);
result = f(&reflected_shader_module, &count, data.data());
assert(result == SPV_REFLECT_RESULT_SUCCESS);
return data;
}
std::shared_ptr<shader> load_shader(vk::raii::Device & device, std::span<const uint32_t> spirv)
{
vk::ShaderModuleCreateInfo create_info{
.codeSize = spirv.size() * sizeof(uint32_t),
.codeSize = spirv.size_bytes(),
.pCode = spirv.data(),
};
return vk::raii::ShaderModule{device, create_info};
std::vector<shader::input> inputs;
std::vector<shader::specialization_constant> specialization_constants;
SpvReflectShaderModule reflect;
if (auto result = spvReflectCreateShaderModule2(SPV_REFLECT_MODULE_FLAG_NONE, spirv.size_bytes(), spirv.data(), &reflect); result == SPV_REFLECT_RESULT_SUCCESS)
{
for (SpvReflectInterfaceVariable * variable: enumerate<SpvReflectInterfaceVariable>(spvReflectEnumerateInputVariables, reflect))
{
int array_size = 1;
for (int i = 0; i < variable->array.dims_count; i++)
array_size *= variable->array.dims[i];
if (variable->built_in == -1)
inputs.emplace_back(
variable->location,
variable->name,
(vk::Format)variable->format,
array_size);
}
for (SpvReflectSpecializationConstant * variable: enumerate<SpvReflectSpecializationConstant>(spvReflectEnumerateSpecializationConstants, reflect))
specialization_constants.emplace_back(variable->constant_id, variable->name);
spvReflectDestroyShaderModule(&reflect);
}
else
spdlog::error("Cannot reflect shader: {}", magic_enum::enum_name(result));
return std::make_shared<shader>(vk::raii::ShaderModule{device, create_info}, inputs, specialization_constants);
}
vk::raii::ShaderModule load_shader(vk::raii::Device & device, const std::string & name)
std::shared_ptr<shader> load_shader(vk::raii::Device & device, const std::string & name)
{
return load_shader(device, shaders.at(name));
using loader_type = std::shared_ptr<shader>(vk::raii::Device &, std::span<const uint32_t>);
static utils::cache<std::string, shader, loader_type *> shader_cache{(loader_type *)load_shader};
return shader_cache.load(name, device, shaders.at(name));
}
+33 -2
View File
@@ -23,5 +23,36 @@
#include <vector>
#include <vulkan/vulkan_raii.hpp>
vk::raii::ShaderModule load_shader(vk::raii::Device & device, const std::vector<uint32_t> & spirv);
vk::raii::ShaderModule load_shader(vk::raii::Device & device, const std::string & name);
struct shader
{
struct input
{
int location;
std::string name;
vk::Format format;
int array_size;
};
struct specialization_constant
{
int id;
std::string name;
};
vk::raii::ShaderModule shader_module;
std::vector<input> inputs;
std::vector<specialization_constant> specialization_constants;
vk::ShaderModule operator*() const
{
return *shader_module;
}
operator vk::ShaderModule() const
{
return *shader_module;
}
};
std::shared_ptr<shader> load_shader(vk::raii::Device & device, std::span<const uint32_t> spirv);
std::shared_ptr<shader> load_shader(vk::raii::Device & device, const std::string & name);