Add rendering engine

This commit is contained in:
Guillaume Meunier
2024-01-28 11:33:32 +01:00
parent 814663beae
commit 95d1020559
45 changed files with 4170 additions and 1863 deletions
+2 -2
View File
@@ -116,12 +116,12 @@ endif()
# Common dependencies
FetchContent_Declare(boostpfr URL https://github.com/boostorg/pfr/archive/refs/tags/2.0.3.tar.gz)
# Client dependencies
FetchContent_Declare(fastgltf URL https://github.com/spnda/fastgltf/archive/refs/tags/v0.6.0.tar.gz)
FetchContent_Declare(fastgltf URL https://github.com/spnda/fastgltf/archive/refs/tags/v0.6.1.tar.gz)
FetchContent_Declare(glm URL https://github.com/g-truc/glm/archive/refs/tags/0.9.9.8.tar.gz)
FetchContent_Declare(openxr_loader URL https://github.com/KhronosGroup/OpenXR-SDK/archive/refs/tags/release-1.0.32.tar.gz)
FetchContent_Declare(spdlog URL https://github.com/gabime/spdlog/archive/refs/tags/v1.11.0.tar.gz)
FetchContent_Declare(stb URL https://github.com/nothings/stb/archive/refs/heads/master.zip)
# Server dependencies
FetchContent_Declare(monado
+5 -3
View File
@@ -1,4 +1,4 @@
FetchContent_MakeAvailable(spdlog glm fastgltf imgui)
FetchContent_MakeAvailable(spdlog glm fastgltf imgui stb)
include(FreetypeHarfbuzz)
include(CompileGLSL)
@@ -14,6 +14,9 @@ add_library(imgui OBJECT
target_include_directories(imgui PUBLIC ${imgui_SOURCE_DIR})
add_library(stb INTERFACE)
target_include_directories(stb INTERFACE ${stb_SOURCE_DIR})
if(ANDROID)
add_library(wivrn MODULE)
@@ -62,7 +65,6 @@ if(ANDROID)
target_sources(wivrn PRIVATE ${PLATFORM_SOURCE})
else()
add_executable(wivrn)
target_compile_definitions(wivrn PRIVATE -DXR_USE_PLATFORM_XLIB)
find_package(OpenXR REQUIRED)
target_link_libraries(wivrn OpenXR::openxr_loader OpenXR::headers PkgConfig::LIBAV)
@@ -110,7 +112,7 @@ file(GLOB_RECURSE VULKAN_SHADERS CONFIGURE_DEPENDS "*.glsl")
target_sources(wivrn PRIVATE ${LOCAL_SOURCE} ${VULKAN_SHADERS})
wivrn_compile_glsl(wivrn ${VULKAN_SHADERS})
target_link_libraries(wivrn Vulkan::Vulkan spdlog::spdlog glm::glm fastgltf FreetypeHarfbuzz imgui)
target_link_libraries(wivrn Vulkan::Vulkan spdlog::spdlog glm::glm fastgltf FreetypeHarfbuzz imgui stb fastgltf_simdjson)
target_compile_definitions(wivrn PRIVATE -DXR_USE_GRAPHICS_API_VULKAN)
target_compile_definitions(wivrn PRIVATE -DVMA_STATS_STRING_ENABLED=0)
target_compile_options(wivrn PRIVATE -fdiagnostics-color -Wall -Wextra -pedantic) # -Werror
+60 -33
View File
@@ -25,12 +25,12 @@
#include "spdlog/common.h"
#include "spdlog/spdlog.h"
#include "utils/check.h"
#include "vk/vk.h"
#include "xr/xr.h"
#include <algorithm>
#include "utils/contains.h"
#include <algorithm>
#include <string>
#include <exception>
#include <thread>
#include <vector>
#include <vk_mem_alloc.h>
@@ -45,7 +45,7 @@
#include "utils/backtrace.h"
#endif
#ifdef XR_USE_PLATFORM_ANDROID
#ifdef __ANDROID__
#include <android/native_activity.h>
#include <sys/system_properties.h>
@@ -244,7 +244,7 @@ static XrActionType guess_action_type(const std::string & name)
return XR_ACTION_TYPE_FLOAT_INPUT;
}
#ifndef XR_USE_PLATFORM_ANDROID
#ifndef __ANDROID__
static std::filesystem::path get_config_base_dir()
{
const char * xdg_config_home = std::getenv("XDG_CONFIG_HOME");
@@ -379,7 +379,7 @@ void application::initialize_vulkan()
}
#endif
#ifdef XR_USE_PLATFORM_ANDROID
#ifdef __ANDROID__
device_extensions.push_back(VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME);
device_extensions.push_back(VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME);
device_extensions.push_back(VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME);
@@ -633,7 +633,7 @@ void application::initialize()
extensions.push_back(i.c_str());
}
#ifdef XR_USE_PLATFORM_ANDROID
#ifdef __ANDROID__
xr_instance =
xr::instance(app_info.name, app_info.native_app->activity->vm, app_info.native_app->activity->clazz, extensions);
#else
@@ -675,7 +675,7 @@ void application::initialize()
if (swapchain_format == vk::Format::eUndefined)
throw std::runtime_error("No supported swapchain format");
spdlog::info("Using format {}", string_VkFormat(swapchain_format));
spdlog::info("Using format {}", vk::to_string(swapchain_format));
// XrViewConfigurationProperties view_props = xr_system_id.view_configuration_properties(viewconfig);
@@ -717,32 +717,34 @@ std::pair<XrAction, XrActionType> application::get_action(const std::string & re
application::application(application_info info) :
app_info(std::move(info))
{
#ifdef XR_USE_PLATFORM_ANDROID
#ifdef __ANDROID__
// https://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/types.html
setup_jni();
jni::object<""> act(app_info.native_app->activity->clazz);
auto app = act.call<jni::object<"android/app/Application">>("getApplication");
auto ctx = app.call<jni::object<"android/content/Context">>("getApplicationContext");
// Get the intent, to handle wivrn://uri
auto intent = act.call<jni::object<"android/content/Intent">>("getIntent");
std::string data_string;
if (auto data_string_jni = intent.call<jni::string>("getDataString"))
{
data_string = data_string_jni;
}
jni::object<""> act(app_info.native_app->activity->clazz);
auto app = act.call<jni::object<"android/app/Application">>("getApplication");
auto ctx = app.call<jni::object<"android/content/Context">>("getApplicationContext");
spdlog::info("dataString = {}", data_string);
if (data_string.starts_with("wivrn://"))
{
server_address = data_string.substr(strlen("wivrn://"));
}
// Get the intent, to handle wivrn://uri
auto intent = act.call<jni::object<"android/content/Intent">>("getIntent");
std::string data_string;
if (auto data_string_jni = intent.call<jni::string>("getDataString"))
{
data_string = data_string_jni;
}
auto files_dir = ctx.call<jni::object<"java/io/File">>("getFilesDir");
if (auto files_dir_path = files_dir.call<jni::string>("getAbsolutePath"))
{
config_path = files_dir_path;
spdlog::info("dataString = {}", data_string);
if (data_string.starts_with("wivrn://"))
{
server_address = data_string.substr(strlen("wivrn://"));
}
auto files_dir = ctx.call<jni::object<"java/io/File">>("getFilesDir");
if (auto files_dir_path = files_dir.call<jni::string>("getAbsolutePath"))
{
config_path = files_dir_path;
}
}
app_info.native_app->userData = this;
@@ -786,6 +788,24 @@ application::application(application_info info) :
};
initializeLoader((const XrLoaderInitInfoBaseHeaderKHR *)&loaderInitInfoAndroid);
}
{
spdlog::info("trying stuff");
AAssetDir * dir = AAssetManager_openDir(asset_manager(), "");
const char * filename;
while((filename = AAssetDir_getNextFileName(dir)) != nullptr)
{
spdlog::info("Found asset file: {}", filename);
}
dir = AAssetManager_openDir(asset_manager(), "assets");
while((filename = AAssetDir_getNextFileName(dir)) != nullptr)
{
spdlog::info("Found asset file: assets/{}", filename);
}
};
#else
config_path = get_config_base_dir() / "wivrn";
#endif
@@ -797,14 +817,15 @@ application::application(application_info info) :
{
initialize();
}
catch (...)
catch (std::exception& e)
{
spdlog::error("Error during initialization: {}", e.what());
cleanup();
throw;
}
}
#ifdef XR_USE_PLATFORM_ANDROID
#ifdef __ANDROID__
void application::setup_jni()
{
jni::jni_thread::setup_thread(app_info.native_app->activity->vm);
@@ -848,9 +869,15 @@ void application::set_wifi_locks(bool enabled)
void application::cleanup()
{
// The Vulkan device and instance are destroyed by the OpenXR runtime
if (allocator)
{
// vmaDestroyAllocator(allocator);
// allocator = nullptr;
}
#ifdef __ANDROID__
#ifdef XR_USE_PLATFORM_ANDROID
jni::jni_thread::detach();
#endif
}
@@ -895,7 +922,7 @@ void application::loop()
}
}
#ifdef XR_USE_PLATFORM_ANDROID
#ifdef __ANDROID__
void application::run()
{
std::thread application_thread{[&]() {
@@ -1096,7 +1123,7 @@ void application::session_state_changed(XrSessionState new_state, XrTime timesta
case XR_SESSION_STATE_FOCUSED:
session_visible = true;
session_focused = true;
#ifdef XR_USE_PLATFORM_ANDROID
#ifdef __ANDROID__
set_wifi_locks(true);
#endif
break;
@@ -1106,7 +1133,7 @@ void application::session_state_changed(XrSessionState new_state, XrTime timesta
session_focused = false;
xr_session.end_session();
session_running = false;
#ifdef XR_USE_PLATFORM_ANDROID
#ifdef __ANDROID__
set_wifi_locks(false);
#endif
break;
+24 -10
View File
@@ -19,12 +19,11 @@
#pragma once
#ifdef XR_USE_PLATFORM_ANDROID
#ifdef __ANDROID__
#include <android_native_app_glue.h>
#endif
#include "spdlog/spdlog.h"
#include "vk/vk.h"
#include "xr/xr.h"
#include <array>
#include <filesystem>
@@ -47,7 +46,7 @@ struct application_info
XrViewConfigurationType viewconfig = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO;
XrVersion min_vulkan_version = XR_MAKE_VERSION(1, 1, 0);
#ifdef XR_USE_PLATFORM_ANDROID
#ifdef __ANDROID__
android_app * native_app;
#endif
};
@@ -57,7 +56,7 @@ class application : public singleton<application>
friend class scene;
application_info app_info;
#ifdef XR_USE_PLATFORM_ANDROID
#ifdef __ANDROID__
ANativeWindow * native_window = nullptr;
bool resumed = false;
#endif
@@ -150,10 +149,15 @@ public:
application(const application &) = delete;
~application();
#ifdef XR_USE_PLATFORM_ANDROID
#ifdef __ANDROID__
void setup_jni();
void set_wifi_locks(bool enabled);
static AAssetManager* asset_manager()
{
return instance().app_info.native_app->activity->assetManager;
}
#endif
static bool is_session_running()
@@ -259,12 +263,22 @@ public:
#endif
}
static void set_debug_reports_name(void * object, std::string name)
template<typename T>
static void set_debug_reports_name(const T& object, std::string name)
{
#ifndef NDEBUG
printf("set_debug_reports_name %p, %s\n", object, name.c_str());
instance().debug_report_object_name[(uint64_t)object] = std::move(name);
#endif
// #ifndef NDEBUG
// if (instance().debug_utils_found)
const vk::DebugUtilsObjectNameInfoEXT name_info {
.objectType = T::objectType,
.objectHandle = (uint64_t)(typename T::NativeType)object,
.pObjectName = name.c_str(),
};
instance().vk_device.setDebugUtilsObjectNameEXT(name_info);
// printf("set_debug_reports_name %p, %s\n", object, name.c_str());
// instance().debug_report_object_name[(uint64_t)object] = std::move(name);
// #endif
}
static XrTime now()
+80
View File
@@ -0,0 +1,80 @@
/*
* WiVRn VR streaming
* Copyright (C) 2024 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2024 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 "asset.h"
#include "application.h"
#include <fstream>
#include <spdlog/spdlog.h>
#ifdef __ANDROID__
#include <android/asset_manager.h>
asset::asset(std::filesystem::path path)
{
spdlog::debug("Loading Android asset {}", path.string());
android_asset = AAssetManager_open(application::asset_manager(), path.c_str(), AASSET_MODE_BUFFER);
if (!android_asset)
throw std::runtime_error("Cannot open Android asset " + path.string());
bytes = std::span<const std::byte>{reinterpret_cast<const std::byte *>(AAsset_getBuffer(android_asset)), (size_t)AAsset_getLength64(android_asset)};
}
asset::asset(asset && other) :
android_asset(other.android_asset)
{
other.android_asset = nullptr;
}
asset & asset::operator=(asset && other)
{
std::swap(android_asset, other.android_asset);
return *this;
}
asset::~asset()
{
if (android_asset)
AAsset_close(android_asset);
}
#else
asset::asset(std::filesystem::path path)
{
// TODO mmap
// TODO: load only once if it is already loaded
spdlog::debug("Loading file asset {}", path.string());
if (path.is_relative())
path = "assets" / path;
std::ifstream file(path, std::ios::binary | std::ios::ate);
file.exceptions(std::ios_base::badbit | std::ios_base::failbit);
size_t size = file.tellg();
file.seekg(0);
bytes.resize(size);
file.read(reinterpret_cast<char *>(bytes.data()), size);
}
#endif
+77
View File
@@ -0,0 +1,77 @@
/*
* WiVRn VR streaming
* Copyright (C) 2024 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2024 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 <cstddef>
#include <filesystem>
#include <span>
#include <vector>
#ifdef __ANDROID__
struct AAsset;
#endif
class asset
{
#ifdef __ANDROID__
AAsset * android_asset = nullptr;
std::span<const std::byte> bytes;
#else
std::vector<std::byte> bytes;
#endif
public:
asset() = default;
asset(std::filesystem::path path);
#ifdef __ANDROID__
asset(asset && other);
asset & operator=(asset && other);
~asset();
#else
asset(asset && other) = default;
asset & operator=(asset && other) = default;
#endif
asset(const asset &) = delete;
asset & operator=(const asset &) = delete;
const std::byte * data() const
{
return bytes.data();
}
size_t size() const
{
return bytes.size();
}
operator std::span<const std::byte>() const
{
return bytes;
}
operator std::string() const
{
return std::string(reinterpret_cast<const char*>(data()), size());
}
};
+1 -1
View File
@@ -21,7 +21,7 @@
#include "wivrn_packets.h"
#ifdef XR_USE_PLATFORM_ANDROID
#ifdef __ANDROID__
#include "android/audio.h"
using audio = ::wivrn::android::audio;
#else
+1 -1
View File
@@ -23,7 +23,7 @@
#include <memory>
#include <vulkan/vulkan.hpp>
#ifdef XR_USE_PLATFORM_ANDROID
#ifdef __ANDROID__
#include "decoder/android/android_decoder.h"
using decoder_impl = ::wivrn::android::decoder;
#else
+2 -2
View File
@@ -24,7 +24,7 @@
#include <spdlog/spdlog.h>
#ifdef XR_USE_PLATFORM_ANDROID
#ifdef __ANDROID__
#include "utils/wrap_lambda.h"
#include <sys/system_properties.h>
@@ -44,7 +44,7 @@ static std::string get_property(const char * property)
model guess_model()
{
#ifdef XR_USE_PLATFORM_ANDROID
#ifdef __ANDROID__
const auto device = get_property("ro.product.device");
if (device == "monterey")
return model::oculus_quest;
+5 -5
View File
@@ -27,7 +27,7 @@
#include <sys/socket.h>
#include <netdb.h>
#ifdef XR_USE_PLATFORM_ANDROID
#ifdef __ANDROID__
#include "spdlog/sinks/android_sink.h"
#include <android/native_window.h>
#include <android_native_app_glue.h>
@@ -35,7 +35,7 @@
#include "spdlog/sinks/stdout_color_sinks.h"
#endif
#ifdef XR_USE_PLATFORM_ANDROID
#ifdef __ANDROID__
void real_main(android_app * native_app)
#else
void real_main()
@@ -44,7 +44,7 @@ void real_main()
try
{
application_info info;
#ifdef XR_USE_PLATFORM_ANDROID
#ifdef __ANDROID__
info.native_app = native_app;
#endif
info.name = "WiVRn";
@@ -117,7 +117,7 @@ void real_main()
spdlog::error("Caught unknown exception");
}
#ifdef XR_USE_PLATFORM_ANDROID
#ifdef __ANDROID__
ANativeActivity_finish(native_app->activity);
// Read all pending events.
@@ -136,7 +136,7 @@ void real_main()
#endif
}
#ifdef XR_USE_PLATFORM_ANDROID
#ifdef __ANDROID__
void android_main(android_app * native_app) __attribute__((visibility("default")));
void android_main(android_app * native_app)
{
+136
View File
@@ -0,0 +1,136 @@
/*
* 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/>.
*/
#pragma once
#include <vector>
#include <vulkan/vulkan.hpp>
#include <fastgltf/types.hpp>
#include <fastgltf/tools.hpp>
#include "vk/allocation.h"
class gpu_buffer
{
std::vector<std::byte> bytes;
vk::PhysicalDeviceLimits limits;
fastgltf::Asset & asset;
vk::BufferUsageFlags usage;
size_t add(size_t alignment, const void * data_to_add, size_t size)
{
size_t offset = ((bytes.size() + alignment - 1) / alignment) * alignment;
bytes.resize(offset + size);
memcpy(&bytes[offset], data_to_add, size);
return offset;
}
template <typename T>
requires requires(T t) {
{
t.data()
} -> std::convertible_to<const void *>;
{
t.size()
} -> std::convertible_to<size_t>;
}
size_t add(size_t alignment, const T & data_to_add)
{
return add(alignment, data_to_add.data(), data_to_add.size() * sizeof(data_to_add.data()[0]));
}
public:
gpu_buffer(vk::PhysicalDeviceProperties properties, fastgltf::Asset & asset) :
limits(properties.limits), asset(asset), usage(0) {}
template <typename T>
size_t add_uniform(const T & data_to_add)
{
usage |= vk::BufferUsageFlagBits::eUniformBuffer;
size_t alignment = std::max(limits.minUniformBufferOffsetAlignment, alignof(T));
return add(alignment, &data_to_add, sizeof(data_to_add));
}
template <typename T>
size_t add_vertices(const T & data_to_add)
{
usage |= vk::BufferUsageFlagBits::eVertexBuffer;
size_t alignment = std::max<size_t>(4, alignof(T));
return add(alignment, data_to_add);
}
size_t add_indices(const fastgltf::Accessor & accessor)
{
usage |= vk::BufferUsageFlagBits::eIndexBuffer;
switch (accessor.componentType)
{
case fastgltf::ComponentType::Byte:
case fastgltf::ComponentType::UnsignedByte: {
std::vector<uint8_t> indices(accessor.count);
using index_t = std::remove_cvref_t<decltype(*indices.data())>;
fastgltf::copyFromAccessor<index_t>(asset, accessor, indices.data());
return add(4, indices);
}
case fastgltf::ComponentType::Short:
case fastgltf::ComponentType::UnsignedShort: {
std::vector<uint16_t> indices(accessor.count);
using index_t = std::remove_cvref_t<decltype(*indices.data())>;
fastgltf::copyFromAccessor<index_t>(asset, accessor, indices.data());
return add(4, indices);
}
case fastgltf::ComponentType::Int:
case fastgltf::ComponentType::UnsignedInt: {
std::vector<uint32_t> indices(accessor.count);
using index_t = std::remove_cvref_t<decltype(*indices.data())>;
fastgltf::copyFromAccessor<index_t>(asset, accessor, indices.data());
return add(4, indices);
}
default:
throw std::runtime_error("Invalid index type");
}
}
buffer_allocation copy_to_gpu()
{
buffer_allocation gpu_buffer{
vk::BufferCreateInfo{
.size = bytes.size(),
.usage = usage},
VmaAllocationCreateInfo{
.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT,
.usage = VMA_MEMORY_USAGE_AUTO}};
memcpy(gpu_buffer.map(), bytes.data(), bytes.size());
gpu_buffer.unmap();
return gpu_buffer;
}
size_t size() const
{
return bytes.size();
}
};
@@ -0,0 +1,84 @@
/*
* 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 "growable_descriptor_pool.h"
#include <stdexcept>
growable_descriptor_pool::growable_descriptor_pool(vk::raii::Device & device, sizes size_, int descriptorsets_per_pool) :
device(device), descriptorsets_per_pool(descriptorsets_per_pool)
{
std::vector<vk::DescriptorPoolSize> tmp;
tmp.push_back(vk::DescriptorPoolSize{.type = vk::DescriptorType::eSampler, .descriptorCount = (uint32_t)size_.sampler});
tmp.push_back(vk::DescriptorPoolSize{.type = vk::DescriptorType::eCombinedImageSampler, .descriptorCount = (uint32_t)size_.combined_image_sampler});
tmp.push_back(vk::DescriptorPoolSize{.type = vk::DescriptorType::eSampledImage, .descriptorCount = (uint32_t)size_.sampled_image});
tmp.push_back(vk::DescriptorPoolSize{.type = vk::DescriptorType::eStorageImage, .descriptorCount = (uint32_t)size_.storage_image});
tmp.push_back(vk::DescriptorPoolSize{.type = vk::DescriptorType::eUniformTexelBuffer, .descriptorCount = (uint32_t)size_.uniform_texel_buffer});
tmp.push_back(vk::DescriptorPoolSize{.type = vk::DescriptorType::eStorageTexelBuffer, .descriptorCount = (uint32_t)size_.storage_texel_buffer});
tmp.push_back(vk::DescriptorPoolSize{.type = vk::DescriptorType::eUniformBuffer, .descriptorCount = (uint32_t)size_.uniform_buffer});
tmp.push_back(vk::DescriptorPoolSize{.type = vk::DescriptorType::eStorageBuffer, .descriptorCount = (uint32_t)size_.storage_buffer});
tmp.push_back(vk::DescriptorPoolSize{.type = vk::DescriptorType::eUniformBufferDynamic, .descriptorCount = (uint32_t)size_.uniform_buffer_dynamic});
tmp.push_back(vk::DescriptorPoolSize{.type = vk::DescriptorType::eStorageBufferDynamic, .descriptorCount = (uint32_t)size_.storage_buffer_dynamic});
tmp.push_back(vk::DescriptorPoolSize{.type = vk::DescriptorType::eInputAttachment, .descriptorCount = (uint32_t)size_.input_attachment});
for (auto & i: tmp)
{
// Only use the descriptor types that have a descriptorCount above 0
if (i.descriptorCount > 0)
size.push_back(i);
}
if (size.empty())
throw std::invalid_argument("size");
if (descriptorsets_per_pool <= 0)
throw std::invalid_argument("descriptorsets_per_pool");
}
std::shared_ptr<vk::raii::DescriptorSet> growable_descriptor_pool::allocate(vk::DescriptorSetLayout layout)
{
vk::DescriptorSetAllocateInfo alloc_info{
.descriptorSetCount = 1,
.pSetLayouts = &layout,
};
for (vk::raii::DescriptorPool & i: pools)
{
// TODO: don't use exceptions as control flow
try
{
alloc_info.descriptorPool = *i;
return std::make_shared<vk::raii::DescriptorSet>(std::move(device.allocateDescriptorSets(alloc_info)[0]));
}
catch (vk::OutOfPoolMemoryError &)
{
continue;
}
}
vk::DescriptorPoolCreateInfo pool_info{
.flags = vk::DescriptorPoolCreateFlagBits::eFreeDescriptorSet,
.maxSets = (uint32_t)descriptorsets_per_pool};
pool_info.setPoolSizes(size);
alloc_info.descriptorPool = *pools.emplace_back(device, pool_info);
return std::make_shared<vk::raii::DescriptorSet>(std::move(device.allocateDescriptorSets(alloc_info)[0]));
}
+58
View File
@@ -0,0 +1,58 @@
/*
* 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/>.
*/
#pragma once
#include <vector>
#include <vulkan/vulkan_raii.hpp>
class growable_descriptor_pool
{
public:
struct sizes
{
int sampler = 0;
int combined_image_sampler = 0;
int sampled_image = 0;
int storage_image = 0;
int uniform_texel_buffer = 0;
int storage_texel_buffer = 0;
int uniform_buffer = 0;
int storage_buffer = 0;
int uniform_buffer_dynamic = 0;
int storage_buffer_dynamic = 0;
int input_attachment = 0;
};
private:
vk::raii::Device & device;
std::vector<vk::DescriptorPoolSize> size;
int descriptorsets_per_pool;
std::vector<vk::raii::DescriptorPool> pools;
public:
growable_descriptor_pool(vk::raii::Device & device, sizes size, int descriptorsets_per_pool);
std::shared_ptr<vk::raii::DescriptorSet> allocate(vk::DescriptorSetLayout layout);
std::shared_ptr<vk::raii::DescriptorSet> allocate(vk::raii::DescriptorSetLayout& layout)
{
return allocate(*layout);
}
};
+344
View File
@@ -0,0 +1,344 @@
/*
* 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 "image_loader.h"
#include "vulkan/vulkan_enums.hpp"
#include "vulkan/vulkan_handles.hpp"
#include <cstdint>
#include <memory>
#include <span>
#include <variant>
#include <vulkan/vulkan_raii.hpp>
#define STB_IMAGE_IMPLEMENTATION
#define STBI_ONLY_JPEG
#define STBI_ONLY_PNG
#ifdef __ARM_NEON
#define STBI_NEON
#endif
#include "stb_image.h"
using stbi_ptr = std::unique_ptr<void, decltype([](void * pixels) { stbi_image_free(pixels); })>;
namespace
{
template <typename T>
constexpr vk::Format formats[4] = {vk::Format::eUndefined, vk::Format::eUndefined, vk::Format::eUndefined, vk::Format::eUndefined};
template <>
constexpr vk::Format formats<uint8_t>[] = {
vk::Format::eR8Unorm,
vk::Format::eR8G8Unorm,
vk::Format::eUndefined,
vk::Format::eR8G8B8A8Unorm,
};
template <>
constexpr vk::Format formats<uint16_t>[] = {
vk::Format::eR16Unorm,
vk::Format::eR16G16Unorm,
vk::Format::eUndefined,
vk::Format::eR16G16B16A16Unorm,
};
template <>
constexpr vk::Format formats<float>[] = {
vk::Format::eR32Sfloat,
vk::Format::eR32G32Sfloat,
vk::Format::eUndefined,
vk::Format::eR32G32B32A32Sfloat,
};
template <typename T>
vk::Format get_format(int num_components)
{
assert(num_components > 0 && num_components <= 4);
return formats<T>[num_components - 1];
}
vk::Format get_format_srgb(int num_components)
{
switch (num_components)
{
case 1:
return vk::Format::eR8Srgb;
case 2:
return vk::Format::eR8G8Srgb;
case 3:
return vk::Format::eUndefined;
case 4:
return vk::Format::eR8G8B8A8Srgb;
default:
assert(false);
}
}
int bytes_per_pixel(vk::Format format)
{
switch (format)
{
case vk::Format::eR8Srgb:
case vk::Format::eR8Unorm:
return 1;
case vk::Format::eR8G8Srgb:
case vk::Format::eR8G8Unorm:
return 2;
case vk::Format::eR8G8B8A8Srgb:
case vk::Format::eR8G8B8A8Unorm:
return 4;
case vk::Format::eR16Unorm:
return 2;
case vk::Format::eR16G16Unorm:
return 4;
case vk::Format::eR16G16B16A16Unorm:
return 8;
case vk::Format::eR32Sfloat:
return 4;
case vk::Format::eR32G32Sfloat:
return 8;
case vk::Format::eR32G32B32A32Sfloat:
return 16;
default:
assert(false);
}
}
} // namespace
void image_loader::do_load(vk::raii::Device & device, vk::raii::CommandBuffer & cb, const void * pixels, vk::Extent3D extent, vk::Format format)
{
assert(format != vk::Format::eUndefined);
this->format = format;
this->extent = extent;
if (extent.depth > 1)
{
image_type = vk::ImageType::e3D;
image_view_type = vk::ImageViewType::e3D;
}
else
{
image_type = vk::ImageType::e2D;
image_view_type = vk::ImageViewType::e2D;
}
num_mipmaps = std::floor(std::log2(std::max(extent.width, extent.height))) + 1;
size_t byte_size = extent.width * extent.height * extent.depth * bytes_per_pixel(format);
// Copy to staging buffer
staging_buffer = buffer_allocation{
vk::BufferCreateInfo{
.size = byte_size,
.usage = vk::BufferUsageFlagBits::eTransferSrc},
VmaAllocationCreateInfo{
.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT,
.usage = VMA_MEMORY_USAGE_AUTO,
}};
memcpy(staging_buffer.map(), pixels, byte_size);
staging_buffer.unmap();
// Allocate image
image = image_allocation{
vk::ImageCreateInfo{
.imageType = vk::ImageType::e2D,
.format = format,
.extent = extent,
.mipLevels = num_mipmaps,
.arrayLayers = 1,
.samples = vk::SampleCountFlagBits::e1,
.tiling = vk::ImageTiling::eOptimal,
.usage = vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eTransferSrc | vk::ImageUsageFlagBits::eSampled,
.initialLayout = vk::ImageLayout::eUndefined},
VmaAllocationCreateInfo{
.flags = 0,
.usage = VMA_MEMORY_USAGE_AUTO,
}};
// Transition all mipmap levels layout to eTransferDstOptimal
cb.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer, vk::DependencyFlags{}, {}, {}, vk::ImageMemoryBarrier{
.srcAccessMask = vk::AccessFlagBits::eNone,
.dstAccessMask = vk::AccessFlagBits::eTransferWrite,
.oldLayout = vk::ImageLayout::eUndefined,
.newLayout = vk::ImageLayout::eTransferDstOptimal,
.image = image,
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = num_mipmaps,
.baseArrayLayer = 0,
.layerCount = 1,
},
});
// Copy image data
cb.copyBufferToImage(staging_buffer, image, vk::ImageLayout::eTransferDstOptimal, vk::BufferImageCopy{
.bufferOffset = 0,
.bufferRowLength = 0,
.bufferImageHeight = 0,
.imageSubresource = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.mipLevel = 0,
.baseArrayLayer = 0,
.layerCount = 1,
},
.imageOffset = {0, 0, 0},
.imageExtent = extent,
});
// Create mipmaps
int width = extent.width;
int height = extent.height;
for (uint32_t level = 1; level < num_mipmaps; level++)
{
int next_width = width > 1 ? width / 2 : 1;
int next_height = height > 1 ? height / 2 : 1;
// Transition source image layout to eTransferSrcOptimal
cb.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eFragmentShader, vk::DependencyFlags{}, {}, {}, vk::ImageMemoryBarrier{
.srcAccessMask = vk::AccessFlagBits::eTransferWrite,
.dstAccessMask = vk::AccessFlagBits::eShaderRead,
.oldLayout = vk::ImageLayout::eTransferDstOptimal,
.newLayout = vk::ImageLayout::eTransferSrcOptimal,
.image = image,
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = level - 1,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
});
// Blit level n-1 to level n
cb.blitImage(image, vk::ImageLayout::eTransferSrcOptimal, image, vk::ImageLayout::eTransferDstOptimal, vk::ImageBlit{
.srcSubresource = {.aspectMask = vk::ImageAspectFlagBits::eColor, .mipLevel = level - 1, .baseArrayLayer = 0, .layerCount = 1},
.srcOffsets = std::array{
vk::Offset3D{0, 0, 0},
vk::Offset3D{width, height, 1},
},
.dstSubresource = {.aspectMask = vk::ImageAspectFlagBits::eColor, .mipLevel = level, .baseArrayLayer = 0, .layerCount = 1},
.dstOffsets = std::array{
vk::Offset3D{0, 0, 0},
vk::Offset3D{next_width, next_height, 1},
},
},
vk::Filter::eLinear);
// Transition source image layout to eShaderReadOnlyOptimal
cb.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eFragmentShader, vk::DependencyFlags{}, {}, {}, vk::ImageMemoryBarrier{
.srcAccessMask = vk::AccessFlagBits::eTransferRead,
.dstAccessMask = vk::AccessFlagBits::eShaderRead,
.oldLayout = vk::ImageLayout::eTransferSrcOptimal,
.newLayout = vk::ImageLayout::eShaderReadOnlyOptimal,
.image = image,
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = level - 1,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
});
width = next_width;
height = next_height;
}
// Transition the last level to eShaderReadOnlyOptimal
cb.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eFragmentShader, vk::DependencyFlags{}, {}, {}, vk::ImageMemoryBarrier{
.srcAccessMask = vk::AccessFlagBits::eTransferWrite,
.dstAccessMask = vk::AccessFlagBits::eShaderRead,
.oldLayout = vk::ImageLayout::eTransferDstOptimal,
.newLayout = vk::ImageLayout::eShaderReadOnlyOptimal,
.image = image,
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = num_mipmaps - 1,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
});
// Create the image view
image_view = vk::raii::ImageView{device, vk::ImageViewCreateInfo{
.image = image,
.viewType = image_view_type,
.format = format,
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = num_mipmaps,
.baseArrayLayer = 0,
.layerCount = 1,
},
}};
}
image_loader::image_loader(vk::raii::Device & device, vk::raii::CommandBuffer & cb, const void * pixels, vk::Extent3D extent, vk::Format format)
{
do_load(device, cb, pixels, extent, format);
}
image_loader::image_loader(vk::raii::Device & device, vk::raii::CommandBuffer & cb, std::span<const std::byte> bytes, bool srgb)
{
const stbi_uc * image_data = (const stbi_uc *)bytes.data();
size_t image_size = bytes.size();
int w, h, num_channels, channels_in_file;
stbi_ptr pixels;
if (!stbi_info_from_memory(image_data, image_size, &w, &h, &num_channels))
throw std::runtime_error("Unsupported image format");
assert(num_channels >= 1 && num_channels <= 4);
if (num_channels == 3)
num_channels = 4;
if (stbi_is_hdr_from_memory(image_data, image_size))
{
pixels = stbi_ptr(stbi_loadf_from_memory(image_data, image_size, &w, &h, &channels_in_file, num_channels));
format = get_format<float>(num_channels);
}
else if (stbi_is_16_bit_from_memory(image_data, image_size))
{
pixels = stbi_ptr(stbi_load_16_from_memory(image_data, image_size, &w, &h, &channels_in_file, num_channels));
format = get_format<uint16_t>(num_channels);
}
else
{
pixels = stbi_ptr(stbi_load_from_memory(image_data, image_size, &w, &h, &channels_in_file, num_channels));
format = srgb ? get_format_srgb(num_channels) : get_format<uint8_t>(num_channels);
}
extent.width = w;
extent.height = h;
extent.depth = 1;
do_load(device, cb, pixels.get(), extent, format);
}
+64
View File
@@ -0,0 +1,64 @@
/*
* 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 "vk/allocation.h"
#include <cstddef>
#include <glm/vec2.hpp>
#include <glm/vec3.hpp>
#include <glm/vec4.hpp>
#include <memory>
#include <span>
#include <tuple>
#include <vulkan/vulkan_raii.hpp>
struct image_loader
{
image_allocation image;
vk::raii::ImageView image_view = nullptr;
vk::Format format;
vk::Extent3D extent;
vk::ImageType image_type;
vk::ImageViewType image_view_type;
uint32_t num_mipmaps;
buffer_allocation staging_buffer;
// Load a PNG/JPEG file
image_loader(vk::raii::Device & device, vk::raii::CommandBuffer & cb, std::span<const std::byte> bytes, bool srgb);
// Load raw pixel data
image_loader(vk::raii::Device & device, vk::raii::CommandBuffer & cb, const void * pixels, vk::Extent3D extent, vk::Format format);
template <typename T>
image_loader(vk::raii::Device & device, vk::raii::CommandBuffer & cb, std::span<T> pixels, vk::Extent3D extent, vk::Format format) :
image_loader(device, cb, pixels.data(), extent, format)
{}
template <typename T, size_t N>
image_loader(vk::raii::Device & device, vk::raii::CommandBuffer & cb, const std::array<T, N> & pixels, vk::Extent3D extent, vk::Format format) :
image_loader(device, cb, pixels.data(), extent, format)
{}
private:
void do_load(vk::raii::Device & device, vk::raii::CommandBuffer & cb, const void * pixels, vk::Extent3D extent, vk::Format format);
};
+953
View File
@@ -0,0 +1,953 @@
/*
* 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 <concepts>
#include <fastgltf/base64.hpp>
#include <fastgltf/glm_element_traits.hpp>
#include <fastgltf/parser.hpp>
#include <fastgltf/tools.hpp>
#include <fastgltf/types.hpp>
#include <fastgltf/util.hpp>
#include <fstream>
#include <glm/gtc/type_ptr.hpp>
#include <spdlog/spdlog.h>
#include <stdexcept>
#include <type_traits>
#include <variant>
#include <vk_mem_alloc.h>
#include <vulkan/vulkan_raii.hpp>
#include "application.h"
#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::LoadExternalBuffers |
// fastgltf::Options::LoadExternalImages |
fastgltf::Options::DecomposeNodeMatrices;
fastgltf::Expected<fastgltf::Asset> expected_asset{fastgltf::Error::None};
switch (fastgltf::determineGltfFileType(&buffer))
{
case fastgltf::GltfType::GLB:
expected_asset = parser.loadBinaryGLTF(&buffer, directory, gltf_options);
break;
case fastgltf::GltfType::glTF:
expected_asset = parser.loadGLTF(&buffer, directory, gltf_options);
break;
case fastgltf::GltfType::Invalid:
throw std::runtime_error("Unrecognized file type");
}
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());
}
static fastgltf::MimeType guess_mime_type(std::span<const std::byte> image_data)
{
const uint8_t png_magic[] = {0xFF, 0xD8, 0xFF};
const uint8_t jpeg_magic[] = {0x89, 0x50, 0x4E, 0x47, 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
return fastgltf::MimeType::None;
}
static std::pair<scene_data::image, buffer_allocation> do_load_image(
vk::raii::Device & device,
vk::raii::CommandBuffer & cb,
fastgltf::MimeType image_type,
std::span<const std::byte> image_data,
bool srgb)
{
std::pair<scene_data::image, buffer_allocation> output;
cb.begin(vk::CommandBufferBeginInfo{.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit});
if (image_type == fastgltf::MimeType::GltfBuffer || image_type == fastgltf::MimeType::None)
image_type = guess_mime_type(image_data);
switch (image_type)
{
case fastgltf::MimeType::JPEG:
case fastgltf::MimeType::PNG: {
image_loader loader(device, cb, image_data, srgb);
output.first.image_view = std::move(loader.image_view);
output.first.image_ = std::move(loader.image);
output.second = std::move(loader.staging_buffer);
spdlog::debug("Loaded image {}x{}, format {}, {} mipmaps", loader.extent.width, loader.extent.height, vk::to_string(loader.format), loader.num_mipmaps);
}
break;
case fastgltf::MimeType::KTX2:
// TODO
case fastgltf::MimeType::DDS:
// TODO
default:
throw std::runtime_error("Invalid image MIME type: " + std::to_string((int)image_type));
}
cb.end();
return output;
}
class loader_context
{
std::filesystem::path base_directory;
fastgltf::Asset & gltf;
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::Device & device,
vk::raii::Queue & queue,
vk::raii::CommandPool & cb_pool) :
base_directory(base_directory),
gltf(gltf),
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::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::vector<std::shared_ptr<scene_data::image>> load_all_images()
{
// Determine which image is sRGB
std::vector<bool> srgb;
srgb.resize(gltf.images.size(), false);
for (const fastgltf::Material & gltf_material: gltf.materials)
{
if (gltf_material.pbrData.baseColorTexture)
srgb.at(gltf_material.pbrData.baseColorTexture->textureIndex) = true;
if (gltf_material.emissiveTexture)
srgb.at(gltf_material.emissiveTexture->textureIndex) = true;
}
// Load images
std::vector<std::shared_ptr<scene_data::image>> images;
images.reserve(gltf.images.size());
// Create command buffers and fences
int num_images_in_flight = 3;
std::vector<vk::raii::CommandBuffer> command_buffers = device.allocateCommandBuffers({
.commandPool = *cb_pool,
.level = vk::CommandBufferLevel::ePrimary,
.commandBufferCount = (uint32_t)num_images_in_flight,
});
std::vector<std::pair<vk::raii::Fence, buffer_allocation>> fences;
for (int i = 0; i < num_images_in_flight; ++i)
fences.emplace_back(
device.createFence(vk::FenceCreateInfo{.flags = vk::FenceCreateFlagBits::eSignaled}),
buffer_allocation{});
// TODO: use a single command buffer?
for (const auto [index, gltf_image]: utils::enumerate(gltf.images))
{
auto & cb = command_buffers[index % num_images_in_flight];
auto & fence = fences[index % num_images_in_flight].first;
auto [image_data, mime_type] = visit_source(gltf_image.data);
auto [image, resources] = do_load_image(device, cb, mime_type, image_data, srgb[index]);
// Wait for the previous submit to finish before overwriting fences[...].second
device.waitForFences(*fence, true, 1'000'000'000); // TODO check for timeout
device.resetFences(*fence);
fences[index % num_images_in_flight].second = std::move(resources);
images.emplace_back(std::make_shared<scene_data::image>(std::move(image)));
vk::SubmitInfo info;
info.setCommandBuffers(*cb);
queue.submit(info, *fence);
}
std::vector<vk::Fence> fences2;
for (auto & i: fences)
fences2.push_back(*i.first);
device.waitForFences(fences2, true, 1'000'000'000); // TODO check for timeout
fences.clear();
return images;
}
std::vector<std::shared_ptr<scene_data::texture>> load_all_textures(std::vector<std::shared_ptr<scene_data::image>> & images)
{
std::vector<std::shared_ptr<scene_data::texture>> textures;
textures.reserve(gltf.textures.size());
for (const fastgltf::Texture & gltf_texture: 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.imageIndex)
{
texture_ref.image_ = images.at(*gltf_texture.imageIndex);
}
// else if (gltf_texture.basisuImageIndex)
// {
// // TODO
// }
// else if (gltf_texture.ddsImageIndex)
// {
// // TODO
// }
// else if (gltf_texture.webpImageIndex)
// {
// // TODO
// }
else
{
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
auto & material_ref = *materials.emplace_back(std::make_shared<scene_data::material>(default_material));
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::eClockwise; // 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::scene_object> load_all_objects()
{
std::vector<scene_data::scene_object> unsorted_objects;
unsorted_objects.resize(gltf.nodes.size(), {.parent_id = scene_data::scene_object::root_id });
for (const auto & [index, gltf_node]: utils::enumerate(gltf.nodes))
{
if (gltf_node.meshIndex)
unsorted_objects[index].mesh_id = *gltf_node.meshIndex;
for (size_t child: gltf_node.children)
{
unsorted_objects[child].parent_id = index;
}
auto TRS = std::get<fastgltf::Node::TRS>(gltf_node.transform);
unsorted_objects[index].translation = glm::make_vec3(TRS.translation.data());
unsorted_objects[index].rotation = 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;
}
return unsorted_objects;
}
std::vector<scene_data::scene_object> topological_sort(const std::vector<scene_data::scene_object> & unsorted_objects)
{
std::vector<scene_data::scene_object> sorted_objects;
std::vector<size_t> new_index;
std::vector<bool> already_sorted;
sorted_objects.reserve(unsorted_objects.size());
already_sorted.resize(unsorted_objects.size(), false);
new_index.resize(unsorted_objects.size(), scene_data::scene_object::root_id);
bool loop_detected = true;
while (sorted_objects.size() < unsorted_objects.size())
{
for (size_t i = 0; i < unsorted_objects.size(); i++)
{
if (already_sorted[i])
continue;
if (unsorted_objects[i].parent_id == scene_data::scene_object::root_id)
{
sorted_objects.push_back(unsorted_objects[i]);
already_sorted[i] = true;
new_index[i] = sorted_objects.size() - 1;
loop_detected = false;
}
else if (already_sorted[unsorted_objects[i].parent_id])
{
sorted_objects.emplace_back(unsorted_objects[i]).parent_id = new_index[unsorted_objects[i].parent_id];
already_sorted[i] = true;
new_index[i] = sorted_objects.size() - 1;
loop_detected = false;
}
}
assert(!loop_detected);
}
assert(sorted_objects.size() == unsorted_objects.size());
for(size_t i = 0; i < sorted_objects.size(); i++)
{
assert(sorted_objects[i].parent_id == scene_data::scene_object::root_id || sorted_objects[i].parent_id < i);
}
return sorted_objects;
}
};
} // 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,
.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, 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 images
auto images = ctx.load_all_images();
// Load all textures
auto textures = ctx.load_all_textures(images);
// 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_objects = ctx.topological_sort(ctx.load_all_objects());
// 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, scene_object_handle parent)
{
assert(parent.scene == this || parent.id == scene_object::root_id);
size_t mesh_offset = meshes.size();
size_t scene_objects_offset = scene_objects.size();
for (auto & i: other.meshes)
meshes.push_back(std::move(i));
for (auto i: other.scene_objects)
{
assert(!i.mesh_id || *i.mesh_id < other.meshes.size());
if (i.mesh_id)
*i.mesh_id += mesh_offset;
if (i.parent_id == scene_object::root_id)
{
i.parent_id = parent.id;
}
else
{
assert(i.parent_id < other.scene_objects.size());
i.parent_id += scene_objects_offset;
}
scene_objects.push_back(i);
}
other.meshes.clear();
other.scene_objects.clear();
return *this;
}
scene_data & scene_data::import(scene_data && other)
{
return import(std::move(other), {});
}
scene_object_handle scene_data::new_node()
{
size_t id = scene_objects.size();
scene_objects.push_back(scene_object{
.parent_id = scene_object::root_id,
.translation = {0, 0, 0},
.rotation = {1, 0, 0, 0},
.scale = {1, 1, 1},
.visible = true
});
return {id, this};
}
scene_object_handle scene_data::find_node(std::string_view name)
{
for(auto&& [index, node]: utils::enumerate(scene_objects))
{
if (node.name == name)
{
return {index, this};
}
}
// TODO custom exception
throw std::runtime_error("Node " + std::string(name) + " not found");
}
scene_object_handle scene_data::find_node(scene_object_handle root, std::string_view name)
{
assert(root.id < scene_objects.size());
assert(root.scene == this);
std::vector<bool> flag(scene_objects.size(), false);
flag[root.id] = true;
for(size_t index = root.id; index < scene_objects.size(); index++)
{
size_t parent = scene_objects[index].parent_id;
if (parent == scene_object::root_id)
continue;
if (!flag[parent])
continue;
if (scene_objects[index].name == name)
return {index, this};
flag[index] = true;
}
// TODO custom exception
throw std::runtime_error("Node " + std::string(name) + " not found");
}
+260
View File
@@ -0,0 +1,260 @@
/*
* 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 <string>
#include <utils/magic_hash.h>
#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 scene_object_handle;
struct scene_data
{
struct image
{
image_allocation image_;
vk::raii::ImageView image_view = nullptr;
};
struct texture
{
std::shared_ptr<image> image_{};
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;
// 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;
};
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 scene_object
{
static constexpr size_t root_id = size_t(-1);
size_t parent_id;
std::optional<size_t> mesh_id;
glm::vec3 translation;
glm::quat rotation;
glm::vec3 scale;
std::string name;
bool visible;
// std::vector<glm::mat4> bones_transform; // TODO: bones
};
// TODO: lights
// TODO: skybox
std::vector<scene_data::mesh> meshes;
std::vector<scene_data::scene_object> scene_objects;
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, scene_object_handle parent);
scene_data& import(scene_data && other);
scene_object_handle new_node();
scene_object_handle find_node(std::string_view name);
scene_object_handle find_node(scene_object_handle parent, 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 scene_object_handle
{
friend struct scene_data;
size_t id = scene_data::scene_object::root_id;
scene_data * scene = nullptr;
public:
scene_object_handle() = default;
scene_object_handle(size_t id, scene_data * scene) : id(id), scene(scene) {}
scene_object_handle(const scene_object_handle&) = default;
scene_object_handle& operator=(const scene_object_handle&) = default;
scene_data::scene_object& operator*()
{
assert(scene != nullptr);
assert(id < scene->scene_objects.size());
return scene->scene_objects[id];
}
const scene_data::scene_object& operator*() const
{
assert(scene != nullptr);
assert(id < scene->scene_objects.size());
return scene->scene_objects[id];
}
scene_data::scene_object* operator->()
{
assert(scene != nullptr);
assert(id < scene->scene_objects.size());
return &scene->scene_objects[id];
}
const scene_data::scene_object* operator->() const
{
assert(scene != nullptr);
assert(id < scene->scene_objects.size());
return &scene->scene_objects[id];
}
};
File diff suppressed because it is too large Load Diff
+184 -187
View File
@@ -1,187 +1,184 @@
// #pragma once
//
// #include <memory>
// #include <span>
// #include <vector>
// #include <vulkan/vulkan.h>
//
// #include "glm/vec2.hpp"
// #include "glm/vec3.hpp"
// #include "tiny_gltf.h"
// #include "vk/buffer.h"
// #include "vk/command_pool.h"
// #include "vk/device_memory.h"
// #include "vk/image.h"
// #include "vk/pipeline.h"
// #include "vk/renderpass.h"
//
// class scene_renderer
//
// {
// public:
// class shader
// {
// friend class scene_renderer;
//
// std::vector<VkDescriptorSetLayout> descriptor_set_layouts;
// std::vector<VkDescriptorPool> descriptor_pools;
// VkShaderModule vertex_shader{};
// VkShaderModule fragment_shader{};
// VkPipelineLayout pipeline_layout{};
//
// struct pipeline_info
// {
// VkPrimitiveTopology topology;
// std::vector<VkVertexInputBindingDescription> vertex_bindings;
// std::vector<VkVertexInputAttributeDescription> vertex_attributes;
// };
//
// std::vector<std::pair<pipeline_info, VkPipeline>> pipelines;
//
// shader() = default;
// shader(const shader &) = delete;
// shader(shader &&) = delete;
// };
//
// class image
// {
// friend class scene_renderer;
//
// VkDeviceMemory memory{};
// VkSampler sampler{};
// VkImage vk_image{};
// VkImageView image_view{};
// VkDescriptorSet descriptor_set{};
//
// image() = default;
// image(const image &) = delete;
// image(image &&) = delete;
// };
//
// class buffer
// {
// friend class scene_renderer;
//
// VkDeviceMemory memory{};
// VkBuffer vk_buffer{};
//
// buffer() = default;
// buffer(const buffer &) = delete;
// buffer(buffer &&) = delete;
// };
//
// struct mesh_primitive
// {
// struct vertex
// {
// glm::vec3 position;
// glm::vec3 normal;
// glm::vec2 texcoord;
// };
//
// VkPrimitiveTopology topology;
//
// VkPipeline pipeline;
//
// std::weak_ptr<buffer> indices;
// size_t indices_offset;
// size_t indices_count;
//
// std::weak_ptr<buffer> vertices;
// size_t vertices_offset;
// };
//
// class model
// {
// friend class scene_renderer;
//
// tinygltf::Model gltf_model;
// std::vector<std::weak_ptr<image>> images;
// std::vector<std::weak_ptr<buffer>> buffers;
// };
//
// class model_instance
// {
// friend class scene_renderer;
//
// model * gltf_model;
//
// void * ubo;
// };
//
// private:
// VkDevice device;
// VkPhysicalDevice physical_device;
// VkPhysicalDeviceProperties physical_device_properties;
// VkQueue queue;
// vk::command_pool command_pool;
//
// tinygltf::TinyGLTF gltf_loader;
//
// // Staging buffer
// size_t staging_buffer_size = 0;
// vk::buffer staging_buffer;
// vk::device_memory staging_memory;
// VkFence staging_fence{};
// void reserve(size_t size);
//
// void load_buffer(VkBuffer b, const void * data, size_t size);
//
// template <typename T>
// void load_buffer(VkBuffer b, std::span<T> data)
// {
// load_buffer(b, data.data(), data.size() * sizeof(T));
// }
//
// void load_image(VkImage i, void * data, VkExtent2D size, VkFormat format, uint32_t mipmap_count, VkImageLayout final_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
//
// // Scene data
// std::vector<std::shared_ptr<shader>> shaders;
// std::vector<std::shared_ptr<image>> images;
// std::vector<std::shared_ptr<buffer>> buffers;
// std::vector<std::shared_ptr<mesh_primitive>> primitives;
// std::vector<std::shared_ptr<model>> models;
// std::vector<model_instance> instances;
//
// // Destination images
// std::vector<VkImage> output_images;
// std::vector<VkImageView> output_image_views;
// std::vector<VkFramebuffer> output_framebuffers;
// VkExtent2D output_size{};
// VkFormat output_format{};
//
// // Render pass
// vk::renderpass renderpass;
//
// void cleanup();
// void cleanup_output_images();
// void cleanup_shader(shader *);
// void cleanup_buffer(buffer *);
// void cleanup_image(image *);
//
// public:
// scene_renderer(VkDevice device, VkPhysicalDevice physical_device, VkQueue queue);
// ~scene_renderer();
// scene_renderer(const scene_renderer &) = delete;
// scene_renderer(scene_renderer &&) = delete;
//
// void set_output_images(std::vector<VkImage> output_images, VkExtent2D output_size, VkFormat output_format);
//
// std::weak_ptr<shader> create_shader(std::string name,
// std::vector<std::vector<VkDescriptorSetLayoutBinding>> uniform_bindings);
//
// VkPipeline get_shader_pipeline(std::weak_ptr<shader> shader, VkPrimitiveTopology topology, std::span<VkVertexInputBindingDescription> vertex_bindings, std::span<VkVertexInputAttributeDescription> vertex_attributes);
//
// std::weak_ptr<image> create_image(void * data, VkExtent2D size, VkFormat format);
//
// std::weak_ptr<buffer> create_buffer(const void * data, size_t size, VkBufferUsageFlags usage);
//
// template <typename T>
// // requires(std::contiguous_iterator<typename T::iterator>)
// std::weak_ptr<buffer> create_buffer(const T & data, VkBufferUsageFlags usage)
// {
// return create_buffer(data.data(), data.size() * sizeof(T), usage);
// }
//
// model * load_gltf(const std::string & filename);
// };
/*
* 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/>.
*/
#pragma once
#include <vulkan/vulkan.hpp>
#include <vulkan/vulkan_raii.hpp>
#include <array>
#include <cstdint>
#include <glm/mat4x4.hpp>
#include <glm/vec2.hpp>
#include <glm/vec3.hpp>
#include <glm/vec4.hpp>
#include <span>
#include <unordered_map>
#include <vector>
#include "vk/allocation.h"
#include "render/growable_descriptor_pool.h"
#include "render/scene_data.h"
struct pipeline_info
{
std::string shader_name;
vk::CullModeFlags cull_mode = vk::CullModeFlagBits::eNone;
vk::FrontFace front_face = vk::FrontFace::eClockwise;
vk::PrimitiveTopology topology = vk::PrimitiveTopology::eTriangleList;
bool operator==(const pipeline_info & other) const noexcept = default;
};
namespace std
{
template <>
struct hash<pipeline_info> : utils::magic_hash<pipeline_info>
{};
} // namespace std
class scene_renderer
{
public:
// vk::raii::Instance& instance;
vk::raii::Device & device;
// vk::raii::PhysicalDevice physical_device;
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
{
vk::raii::Framebuffer framebuffer = nullptr;
vk::raii::ImageView image_view = nullptr;
image_allocation depth_buffer;
vk::raii::ImageView depth_view = nullptr;
};
// Initialization functions
output_image create_output_image_data(vk::Image output);
vk::raii::RenderPass create_renderpass();
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::CommandBuffer & cb, std::vector<buffer_allocation>& staging_buffers, std::initializer_list<float> pixel);
std::shared_ptr<scene_data::material> create_default_material(vk::raii::CommandPool & cb_pool);
// Caches
std::unordered_map<VkImage, output_image> output_images;
std::unordered_map<pipeline_info, vk::raii::Pipeline> pipelines;
output_image & get_output_image_data(vk::Image output);
vk::raii::Pipeline & get_pipeline(const pipeline_info & info);
// Descriptor set 0: per-frame/view data (uniform buffer) and per-instance data (dynamic uniform buffer)
growable_descriptor_pool ds_pool_frame;
vk::raii::DescriptorSetLayout descriptor_set_frame = nullptr;
// Descriptor set 1: per-material data (5 combined image samplers and 1 uniform buffer)
growable_descriptor_pool ds_pool_material;
vk::raii::DescriptorSetLayout descriptor_set_material = nullptr;
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;
// Default material and textures
// This material has 1x1 textures with the following values:
// base_color (1.0, 1.0, 1.0, 1.0)
// metallic_roughness (1.0, 1.0)
// occlusion (1.0)
// emissive (0.0, 0.0, 0.0)
// normal (0.5, 0.5, 1.0)
// And:
// base_color_factor (1.0, 1.0, 1.0, 1.0)
// base_emissive_factor (0.0, 0.0, 0.0)
// metallic_factor 1.0
// roughness_factor 1.0
// occlusion_strength 0.0
// normal_scale 0.0
std::shared_ptr<scene_data::material> default_material;
struct frame_gpu_data
{
glm::mat4 view;
glm::mat4 proj;
glm::vec4 light_position;
glm::vec4 ambient_color;
glm::vec4 light_color;
};
struct instance_gpu_data
{
glm::mat4 model;
glm::mat4 modelview;
glm::mat4 modelviewproj;
};
struct per_frame_resources
{
vk::raii::Fence fence = nullptr;
vk::raii::CommandBuffer cb = nullptr;
std::vector<std::shared_ptr<void>> resources;
// Uniform buffer for per-view and per-instance data
// host visible, host coherent
buffer_allocation staging_buffer;
// device local
// buffer_allocation uniform_buffer;
};
std::vector<per_frame_resources> frame_resources;
int current_frame;
per_frame_resources& start_frame();
void update_material_descriptor_set(scene_data::material& material);
public:
scene_renderer(vk::raii::Device & device, 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, int frames_in_flight = 3);
~scene_renderer();
struct frame_info
{
vk::Image destination;
glm::mat4 projection;
glm::mat4 view;
};
void render(scene_data & scene, std::span<frame_info> info);
std::shared_ptr<scene_data::material> get_default_material()
{
return default_material;
}
};
+64 -66
View File
@@ -34,7 +34,7 @@
#include <vulkan/vulkan_handles.hpp>
#include <vulkan/vulkan_raii.hpp>
#ifdef XR_USE_PLATFORM_ANDROID
#ifdef __ANDROID__
#include <android/font.h>
#include <android/font_matcher.h>
#include <android/system_fonts.h>
@@ -74,8 +74,7 @@ std::error_category & freetype_error_category()
// static hb_feature_t CligOn = { CligTag, 1, 0, std::numeric_limits<unsigned int>::max() };
// }
text_rasterizer::text_rasterizer(vk::raii::Device& device, vk::raii::PhysicalDevice& physical_device, vk::raii::CommandPool& command_pool, vk::raii::Queue& queue) :
text_rasterizer::text_rasterizer(vk::raii::Device & device, vk::raii::PhysicalDevice & physical_device, vk::raii::CommandPool & command_pool, vk::raii::Queue & queue) :
device(device),
physical_device(physical_device),
command_pool(command_pool),
@@ -84,7 +83,7 @@ text_rasterizer::text_rasterizer(vk::raii::Device& device, vk::raii::PhysicalDev
{
std::string font_filename;
#ifdef XR_USE_PLATFORM_ANDROID
#ifdef __ANDROID__
{
std::u16string ws = u"hello";
AFontMatcher * font_matcher = AFontMatcher_create();
@@ -142,39 +141,41 @@ text_rasterizer::text_rasterizer(vk::raii::Device& device, vk::raii::PhysicalDev
image_allocation text_rasterizer::create_image(vk::Extent2D size)
{
image_allocation alloc{vk::ImageCreateInfo{
.imageType = vk::ImageType::e2D,
.format = text::format,
.extent = {
.width = size.width,
.height = size.height,
.depth = 1,
},
.mipLevels = 1,
.arrayLayers = 1,
.samples = vk::SampleCountFlagBits::e1,
.tiling = vk::ImageTiling::eOptimal,
.usage = vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferDst,
.sharingMode = vk::SharingMode::eExclusive,
.initialLayout = vk::ImageLayout::eUndefined,
},
VmaAllocationCreateInfo{
.flags = 0,
.usage = VMA_MEMORY_USAGE_AUTO,
}};
.imageType = vk::ImageType::e2D,
.format = text::format,
.extent = {
.width = size.width,
.height = size.height,
.depth = 1,
},
.mipLevels = 1,
.arrayLayers = 1,
.samples = vk::SampleCountFlagBits::e1,
.tiling = vk::ImageTiling::eOptimal,
.usage = vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferDst,
.sharingMode = vk::SharingMode::eExclusive,
.initialLayout = vk::ImageLayout::eUndefined,
},
VmaAllocationCreateInfo{
.flags = 0,
.usage = VMA_MEMORY_USAGE_AUTO,
}};
application::set_debug_reports_name<vk::Image>(alloc, "text_rasterizer image");
return alloc;
}
buffer_allocation text_rasterizer::create_buffer(size_t size)
{
buffer_allocation alloc{vk::BufferCreateInfo{
.size = size,
.usage = vk::BufferUsageFlagBits::eTransferSrc,
},
VmaAllocationCreateInfo {
.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT,
.usage = VMA_MEMORY_USAGE_AUTO,
}};
.size = size,
.usage = vk::BufferUsageFlagBits::eTransferSrc,
},
VmaAllocationCreateInfo{
.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT,
.usage = VMA_MEMORY_USAGE_AUTO,
}};
application::set_debug_reports_name<vk::Buffer>(alloc, "text_rasterizer buffer");
return alloc;
}
@@ -297,53 +298,50 @@ text text_rasterizer::render(std::string_view s)
memcpy(mapped, rendered_text.data(), rendered_text.size());
vk::raii::CommandBuffers cmdbufs(device, {
.commandPool = *command_pool,
.level = vk::CommandBufferLevel::ePrimary,
.commandBufferCount = 1,
});
vk::raii::CommandBuffer& cmdbuf = cmdbufs[0];
application::set_debug_reports_name((VkCommandBuffer)*cmdbuf, "text_rasterizer command buffer");
.commandPool = *command_pool,
.level = vk::CommandBufferLevel::ePrimary,
.commandBufferCount = 1,
});
vk::raii::CommandBuffer & cmdbuf = cmdbufs[0];
application::set_debug_reports_name(*cmdbuf, "text_rasterizer command buffer");
cmdbuf.begin({});
vk::ImageMemoryBarrier barrier{
.srcAccessMask = vk::AccessFlagBits::eNone,
.dstAccessMask = vk::AccessFlagBits::eTransferWrite,
.oldLayout = vk::ImageLayout::eUndefined,
.newLayout = vk::ImageLayout::eTransferDstOptimal,
.image = return_value.image,
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
.srcAccessMask = vk::AccessFlagBits::eNone,
.dstAccessMask = vk::AccessFlagBits::eTransferWrite,
.oldLayout = vk::ImageLayout::eUndefined,
.newLayout = vk::ImageLayout::eTransferDstOptimal,
.image = return_value.image,
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
};
cmdbuf.pipelineBarrier(vk::PipelineStageFlagBits::eTopOfPipe, vk::PipelineStageFlagBits::eTransfer, vk::DependencyFlags{}, {}, {}, barrier);
vk::BufferImageCopy copy_info{
.bufferOffset = 0,
.bufferRowLength = 0,
.bufferImageHeight = 0,
.imageSubresource = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.mipLevel = 0,
.baseArrayLayer = 0,
.layerCount = 1,
},
.imageOffset = {0, 0, 0},
.imageExtent = {
.width = uint32_t(x_max - x_min),
.height = uint32_t(y_max - y_min),
.depth = 1,
},
.bufferOffset = 0,
.bufferRowLength = 0,
.bufferImageHeight = 0,
.imageSubresource = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.mipLevel = 0,
.baseArrayLayer = 0,
.layerCount = 1,
},
.imageOffset = {0, 0, 0},
.imageExtent = {
.width = uint32_t(x_max - x_min),
.height = uint32_t(y_max - y_min),
.depth = 1,
},
};
cmdbuf.copyBufferToImage(staging_buffer, return_value.image, vk::ImageLayout::eTransferDstOptimal, copy_info);
barrier.srcAccessMask = vk::AccessFlagBits::eTransferWrite;
barrier.dstAccessMask = vk::AccessFlagBits::eMemoryRead;
barrier.oldLayout = vk::ImageLayout::eTransferDstOptimal;
+6 -7
View File
@@ -1,7 +1,6 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022-2024 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022-2023 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
@@ -21,12 +20,12 @@
#include <vulkan/vulkan_raii.hpp>
#include "vk/allocation.h"
#include <freetype/freetype.h>
#include <ft2build.h>
#include <hb.h>
#include <string_view>
#include <vector>
#include "vk/allocation.h"
struct text
{
@@ -45,10 +44,10 @@ struct text
class text_rasterizer
{
vk::raii::Device& device;
vk::raii::PhysicalDevice& physical_device;
vk::raii::CommandPool& command_pool;
vk::raii::Queue& queue;
vk::raii::Device & device;
vk::raii::PhysicalDevice & physical_device;
vk::raii::CommandPool & command_pool;
vk::raii::Queue & queue;
vk::raii::Fence fence;
FT_Library freetype{};
@@ -62,7 +61,7 @@ class text_rasterizer
vk::raii::DeviceMemory allocate_memory(vk::Buffer buffer, vk::MemoryPropertyFlags flags);
public:
text_rasterizer(vk::raii::Device& device, vk::raii::PhysicalDevice& physical_device, vk::raii::CommandPool& command_pool, vk::raii::Queue& queue);
text_rasterizer(vk::raii::Device & device, vk::raii::PhysicalDevice & physical_device, vk::raii::CommandPool & command_pool, vk::raii::Queue & queue);
~text_rasterizer();
text render(std::string_view s);
+407
View File
@@ -0,0 +1,407 @@
/*
* 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 "input_profile.h"
#include "application.h"
#include "asset.h"
#include <cstddef>
#include <magic_enum.hpp>
#include <simdjson.h>
#include <spdlog/spdlog.h>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <map>
#include <glm/gtc/quaternion.hpp>
namespace
{
// clang-format off
const std::unordered_map<std::string, std::string> input_mappings = {
{"xr-standard-squeeze" , "/input/squeeze/value" },
{"xr-standard-trigger" , "/input/trigger/value" },
{"xr-standard-touchpad" , "/input/trackpad" },
{"xr-standard-thumbstick", "/input/thumbstick" },
{"a-button" , "/input/a/click" },
{"b-button" , "/input/b/click" },
{"x-button" , "/input/x/click" },
{"y-button" , "/input/y/click" },
{"thumbrest" , "/input/thumbrest/touch" },
};
// clang-format on
enum class component_type
{
trigger,
squeeze,
button,
thumbstick,
touchpad
};
component_type parse_component_type(std::string_view type)
{
if (type == "trigger")
return component_type::trigger;
if (type == "squeeze")
return component_type::squeeze;
if (type == "button")
return component_type::button;
if (type == "thumbstick")
return component_type::thumbstick;
if (type == "touchpad")
return component_type::touchpad;
throw std::runtime_error("Invalid type: " + std::string(type));
}
enum class component_property
{
x_axis,
y_axis,
button,
state, // ???
};
component_property parse_component_property(std::string_view property)
{
if (property == "xAxis")
return component_property::x_axis;
if (property == "yAxis")
return component_property::y_axis;
if (property == "button")
return component_property::button;
if (property == "state")
return component_property::state;
throw std::runtime_error("Invalid property: " + std::string(property));
}
enum class value_node_property
{
transform,
visibility
};
value_node_property parse_value_node_property(std::string_view property)
{
if (property == "transform")
return value_node_property::transform;
if (property == "visibility")
return value_node_property::visibility;
throw std::runtime_error("Invalid property: " + std::string(property));
}
struct json_visual_response
{
// From the WebXR profile
std::string layout;
std::string component_id;
component_type type;
component_property property;
std::string target_node;
input_profile::node_state state;
// OpenXR component path
std::string component_subpath;
};
} // namespace
input_profile::input_profile(const std::filesystem::path & json_profile, scene_loader & loader, scene_data & scene)
{
std::string json = asset(json_profile);
simdjson::dom::parser parser;
simdjson::dom::element root = parser.parse(json);
id = std::string(root["profileId"]);
// Don't load them into the scene right now in case there is an exception
std::vector<std::pair<std::string, scene_data>> models;
std::vector<json_visual_response> json_responses;
for (simdjson::dom::key_value_pair layout: simdjson::dom::object(root["layouts"]))
{
// TODO handle case where i.key is none and there is no left or right
// std::string user_path = "/user/hand/" + std::string(layout.key);
std::filesystem::path asset_path = json_profile.parent_path() / std::string(layout.value["assetPath"]);
scene_data & data = models.emplace_back(layout.key, loader(asset_path)).second;
for (simdjson::dom::key_value_pair component: simdjson::dom::object(layout.value["components"]))
{
auto it = input_mappings.find(std::string(component.key));
if (it == input_mappings.end())
{
spdlog::debug("Unknown component: {}", component.key);
continue;
}
std::string component_subpath = it->second;
component_type type = parse_component_type(component.value["type"]);
for (simdjson::dom::key_value_pair response: simdjson::dom::object(component.value["visualResponses"]))
{
json_visual_response & vr = json_responses.emplace_back();
vr.layout = layout.key;
vr.component_id = component.key;
vr.type = type;
vr.property = parse_component_property(response.value["componentProperty"]);
vr.target_node = std::string(response.value["valueNodeName"]);
vr.component_subpath = component_subpath;
// Check if the node exists
data.find_node(vr.target_node);
auto node_property = parse_value_node_property(response.value["valueNodeProperty"]);
switch (node_property)
{
case value_node_property::transform: {
auto min_node = data.find_node(response.value["minNodeName"]);
auto max_node = data.find_node(response.value["maxNodeName"]);
node_state_transform min{
min_node->translation,
min_node->rotation};
node_state_transform max{
max_node->translation,
max_node->rotation};
vr.state = std::make_pair(min, max);
}
break;
case value_node_property::visibility:
vr.state = node_state_visibility{};
break;
}
}
}
}
for(auto&& [layout, model]: models)
{
scene_object_handle root_node = scene.new_node();
root_node->name = layout;
XrSpace space;
if (layout == "left")
space = application::left_grip();
else if (layout == "right")
space = application::right_grip();
else
continue;
model_handles.emplace_back(space, root_node);
scene.import(std::move(model), root_node);
}
for(auto& json_response: json_responses)
{
std::string action_path = "/user/hand/" + json_response.layout + json_response.component_subpath;
if (json_response.type == component_type::thumbstick && json_response.property == component_property::button)
action_path += "/click";
auto action = application::get_action(action_path);
if (action.first == XR_NULL_PATH)
{
spdlog::debug("No input for {}/{} ({})", json_response.layout, json_response.component_id, action_path);
continue;
}
auto& response = responses.emplace_back();
response.action = action.first;
response.type = action.second;
switch(json_response.property)
{
case component_property::button:
case component_property::state:
response.axis = -1;
response.bias = 0;
response.scale = 1;
break;
case component_property::x_axis:
response.axis = 0;
response.bias = 0.5;
response.scale = 0.5;
break;
case component_property::y_axis:
// Y axis is reversed in WebXR (min up, max down, https://github.com/immersive-web/webxr-input-profiles/blob/main/packages/assets/tutorial/README.md#buttons) and OpenXR (-1 down, +1 up, §6.3.2, Standard components)
response.axis = 1;
response.bias = 0.5;
response.scale = -0.5;
break;
}
scene_object_handle controller_root_node;
for(auto&& [i, j]: model_handles)
{
if (j->name == json_response.layout)
{
controller_root_node = j;
assert(controller_root_node->name == json_response.layout);
break;
}
}
response.target.node = scene.find_node(controller_root_node, json_response.target_node);
response.target.state = json_response.state;
}
}
static std::optional<std::pair<glm::vec3, glm::quat>> locate_controller(XrSpace space, XrSpace reference, XrTime time)
{
XrSpaceLocation location{.type = XR_TYPE_SPACE_LOCATION};
assert(space != XR_NULL_HANDLE);
assert(reference != XR_NULL_HANDLE);
xrLocateSpace(space, reference, time, &location);
auto req_flags = XR_SPACE_LOCATION_ORIENTATION_VALID_BIT | XR_SPACE_LOCATION_POSITION_VALID_BIT;
if ((location.locationFlags & req_flags) != req_flags)
return {};
glm::vec3 position{
location.pose.position.x,
location.pose.position.y,
location.pose.position.z,
};
glm::quat orientation{
location.pose.orientation.w,
location.pose.orientation.x,
location.pose.orientation.y,
location.pose.orientation.z,
};
return std::make_pair(position, orientation);
}
void apply_visual_response(scene_object_handle node, std::pair<input_profile::node_state_transform, input_profile::node_state_transform> transforms, float value)
{
node->translation = glm::mix(transforms.first.position, transforms.second.position, value);
node->rotation = glm::slerp(transforms.first.orientation, transforms.second.orientation, value);
}
void apply_visual_response(scene_object_handle node, input_profile::node_state_visibility, float value)
{
node->visible = value > 0.5;
}
void input_profile::apply(XrSpace world_space, XrTime predicted_display_time)
{
for (auto && [space, node]: model_handles)
{
if (auto location = locate_controller(space, world_space, predicted_display_time); location)
{
node->visible = true;
node->translation = location->first;
node->rotation = location->second;
}
else
{
node->visible = false;
}
}
for (auto & response: responses)
{
assert(response.action);
std::optional<float> value;
switch (response.type)
{
case XR_ACTION_TYPE_BOOLEAN_INPUT: {
auto opt_value = application::read_action_bool(response.action);
if (opt_value)
value = opt_value->second;
break;
}
case XR_ACTION_TYPE_FLOAT_INPUT: {
auto opt_value = application::read_action_float(response.action);
if (opt_value)
value = opt_value->second;
break;
}
case XR_ACTION_TYPE_VECTOR2F_INPUT: {
auto opt_value = application::read_action_vec2(response.action);
if (opt_value)
{
switch (response.axis)
{
case 0:
value = opt_value->second.x;
break;
case 1:
value = opt_value->second.y;
break;
}
}
break;
}
case XR_ACTION_TYPE_POSE_INPUT:
case XR_ACTION_TYPE_VIBRATION_OUTPUT:
case XR_ACTION_TYPE_MAX_ENUM:
assert(false);
break;
}
if (value)
{
float scaled_value = *value * response.scale + response.bias;
if ((scaled_value < 0) || (scaled_value > 1))
{
std::string full_name = response.target.node->name;
for(auto i = response.target.node; i; i = i.parent())
{
full_name = i->name + "/" + full_name;
}
spdlog::warn("Out of range value {} (scaled to {}) for node {}", *value, scaled_value, full_name);
}
std::visit([&](auto& transform)
{
apply_visual_response(response.target.node, transform, scaled_value);
}, response.target.state);
}
}
}
+66
View File
@@ -0,0 +1,66 @@
/*
* 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/>.
*/
#pragma once
#include <filesystem>
#include <render/scene_data.h>
#include <openxr/openxr.h>
#include <glm/glm.hpp>
struct input_profile
{
struct node_state_transform
{
glm::vec3 position;
glm::quat orientation;
};
struct node_state_visibility
{
};
using node_state = std::variant<std::pair<node_state_transform, node_state_transform>, node_state_visibility>;
struct node_target
{
scene_object_handle node;
node_state state;
};
struct visual_response
{
XrAction action;
XrActionType type;
int axis; // Only if type is XR_ACTION_TYPE_VECTOR2F_INPUT
float bias;
float scale;
node_target target;
};
std::string id;
std::vector<visual_response> responses;
std::vector<std::pair<XrSpace, scene_object_handle>> model_handles;
input_profile(const std::filesystem::path& json_profile, scene_loader& loader, scene_data& scene);
// application::poll_actions() must have been called before
void apply(XrSpace world_space, XrTime predicted_display_time);
};
+144 -296
View File
@@ -1,7 +1,7 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
* Copyright (C) 2022-2024 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022-2024 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
@@ -18,19 +18,21 @@
*/
#include "lobby.h"
#include "render/text_rasterizer.h"
#include "stream.h"
#include "../common/version.h"
#include "application.h"
#include "vk/pipeline_layout.h"
#include "vk/shader.h"
#include "vk/pipeline.h"
#include "input_profile.h"
#include "openxr/openxr.h"
#include "render/scene_data.h"
#include "render/text_rasterizer.h"
#include "stream.h"
#include "hardware.h"
#include <cstdint>
#include <glm/gtc/quaternion.hpp>
#include <string>
#include <magic_enum.hpp>
#include <spdlog/spdlog.h>
#include <string>
#include <utils/ranges.h>
#include <vulkan/vulkan_enums.hpp>
#include <vulkan/vulkan_raii.hpp>
@@ -38,187 +40,55 @@ static const std::string discover_service = "_wivrn._tcp.local.";
scenes::lobby::~lobby() {}
static std::string choose_webxr_profile()
{
#ifndef __ANDROID__
const char * controller = std::getenv("WIVRN_CONTROLLER");
if (controller && strcmp(controller, ""))
return controller;
#endif
switch(guess_model())
{
case model::oculus_quest:
return "oculus-touch-v2";
case model::oculus_quest_2:
return "oculus-touch-v3";
case model::meta_quest_pro:
return "meta-quest-touch-pro";
case model::meta_quest_3:
return "meta-quest-touch-plus";
case model::pico_neo_3:
return "pico-neo3";
case model::pico_4:
return "pico-4";
case model::unknown:
return "generic-trigger-squeeze";
}
}
scenes::lobby::lobby() :
status_string_rasterizer(device, physical_device, commandpool, queue)//, renderer(device, physical_device, queue)
status_string_rasterizer(device, physical_device, commandpool, queue)
{
uint32_t width = swapchains[0].width();
uint32_t height = swapchains[0].height();
vk::Extent2D output_size{width, height};
// Create renderpass
vk::RenderPassCreateInfo renderpass_info;
vk::AttachmentDescription attachment_desc{
.format = swapchains[0].format(),
.samples = vk::SampleCountFlagBits::e1,
.loadOp = vk::AttachmentLoadOp::eClear,
.storeOp = vk::AttachmentStoreOp::eStore,
.initialLayout = vk::ImageLayout::eUndefined,
.finalLayout = vk::ImageLayout::eColorAttachmentOptimal,
};
renderpass_info.setAttachments(attachment_desc);
vk::SubpassDescription subpass_desc{
.pipelineBindPoint = vk::PipelineBindPoint::eGraphics,
};
vk::AttachmentReference color_ref{
.attachment = 0,
.layout = vk::ImageLayout::eColorAttachmentOptimal,
};
subpass_desc.setColorAttachments(color_ref);
renderpass_info.setSubpasses(subpass_desc);
renderpass = vk::raii::RenderPass(device, renderpass_info);
vk::SamplerCreateInfo sampler_info{
.magFilter = vk::Filter::eLinear,
.minFilter = vk::Filter::eLinear,
.mipmapMode = vk::SamplerMipmapMode::eNearest,
.addressModeU = vk::SamplerAddressMode::eClampToBorder,
.addressModeV = vk::SamplerAddressMode::eClampToBorder,
.addressModeW = vk::SamplerAddressMode::eClampToBorder,
.mipLodBias = 0.0f,
.anisotropyEnable = VK_FALSE,
.maxAnisotropy = 1,
.compareEnable = VK_FALSE,
.compareOp = vk::CompareOp::eNever,
.minLod = 0.0f,
.maxLod = 0.0f,
.borderColor = vk::BorderColor::eFloatOpaqueBlack,
.unnormalizedCoordinates = VK_FALSE,
std::array depth_formats{
vk::Format::eD16Unorm,
vk::Format::eX8D24UnormPack32,
vk::Format::eD32Sfloat,
};
status_string_sampler = vk::raii::Sampler(device, sampler_info);
renderer.emplace(device, physical_device, queue, commandpool, output_size, swapchains[0].format(), depth_formats);
// Create descriptor set layout
vk::DescriptorSetLayoutBinding layout_binding{
.binding = 0,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.descriptorCount = 1,
.stageFlags = vk::ShaderStageFlagBits::eFragment,
};
scene_loader loader(device, physical_device, queue, application::queue_family_index(), renderer->get_default_material());
vk::DescriptorSetLayoutCreateInfo layout_info;
layout_info.setBindings(layout_binding);
teapot.import(loader("lobby.gltf"));
status_string_image_descriptor_set_layout = vk::raii::DescriptorSetLayout(device, layout_info);
input = input_profile("webxr-profiles/" + choose_webxr_profile() + "/profile.json", loader, teapot);
vk::DescriptorPoolSize status_string_image_descriptor_set_pool_size{
.type = vk::DescriptorType::eCombinedImageSampler,
.descriptorCount = 1,
};
vk::DescriptorPoolCreateInfo pool_info{
.maxSets = 1,
};
pool_info.setPoolSizes(status_string_image_descriptor_set_pool_size);
status_string_descriptor_pool = vk::raii::DescriptorPool(device, pool_info);
vk::DescriptorSetAllocateInfo ds_info{
.descriptorPool = *status_string_descriptor_pool,
.descriptorSetCount = 1,
};
ds_info.setSetLayouts(*status_string_image_descriptor_set_layout);
status_string_image_descriptor_set = device.allocateDescriptorSets(ds_info)[0].release();
vk::PipelineLayoutCreateInfo pipeline_layout_info;
pipeline_layout_info.setSetLayouts(*status_string_image_descriptor_set_layout);
vk::PushConstantRange push_constant_range{
.stageFlags = vk::ShaderStageFlagBits::eVertex,
.offset = 0,
.size = sizeof(glm::mat4),
};
pipeline_layout_info.setPushConstantRanges(push_constant_range);
layout = vk::raii::PipelineLayout(device, pipeline_layout_info);
// Create graphics pipeline
vk::raii::ShaderModule vertex_shader = load_shader(device, "text.vert");
vk::raii::ShaderModule fragment_shader = load_shader(device, "text.frag");
vk::pipeline_builder pipeline_info
{
.flags = {},
.Stages = {{
.stage = vk::ShaderStageFlagBits::eVertex,
.module = *vertex_shader,
.pName = "main",
},{
.stage = vk::ShaderStageFlagBits::eFragment,
.module = *fragment_shader,
.pName = "main",
}},
.VertexInputState = {.flags = {}},
.VertexBindingDescriptions = {},
.VertexAttributeDescriptions = {},
.InputAssemblyState = {{
.topology = vk::PrimitiveTopology::eTriangleList,
}},
.ViewportState = {.flags = {}},
.Viewports = {{
.x = 0,
.y = 0,
.width = (float)width,
.height = (float)height,
.minDepth = 0,
.maxDepth = 1,
}},
.Scissors = {{
.offset = { .x = 0, .y = 0 },
.extent= { .width = width, .height = height },
}},
.RasterizationState = {{
.polygonMode = vk::PolygonMode::eFill,
.lineWidth = 1,
}},
.MultisampleState = {{
.rasterizationSamples = vk::SampleCountFlagBits::e1,
}},
.ColorBlendState = {.flags = {}},
.ColorBlendAttachments = {{
.colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB
}},
.layout = *layout,
.renderPass = *renderpass,
.subpass = 0,
};
pipeline = vk::raii::Pipeline(device, nullptr, pipeline_info);
images_data.resize(swapchains.size());
for (size_t i = 0; i < swapchains.size(); i++)
{
auto & images = swapchains[i].images();
images_data[i].reserve(images.size());
for (size_t j = 0; j < images.size(); j++)
{
vk::FramebufferCreateInfo fb_create_info{
.renderPass = *renderpass,
.attachmentCount = 1,
.pAttachments = &*images[j].view,
.width = swapchains[i].width(),
.height = swapchains[i].height(),
.layers = 1,
};
images_data[i].emplace_back(image_data{
.framebuffer = vk::raii::Framebuffer(device, fb_create_info),
.render_finished = create_semaphore()
});
}
}
vk::CommandBufferAllocateInfo alloc_info;
alloc_info.commandBufferCount = 1;
alloc_info.level = vk::CommandBufferLevel::ePrimary;
alloc_info.commandPool = *commandpool;
command_buffer = std::move(device.allocateCommandBuffers(alloc_info)[0]);
application::set_debug_reports_name((VkCommandBuffer)*command_buffer, "lobby command buffer");
fence = create_fence(false);
spdlog::info("Loaded input profile {}", input->id);
}
void scenes::lobby::rasterize_status_string()
@@ -226,39 +96,39 @@ void scenes::lobby::rasterize_status_string()
status_string_rasterized_text = status_string_rasterizer.render(status_string);
vk::ImageViewCreateInfo iv_info{
.image = status_string_rasterized_text.image,
.viewType = vk::ImageViewType::e2D,
.format = status_string_rasterized_text.format,
.components = {
.r = vk::ComponentSwizzle::eIdentity,
.g = vk::ComponentSwizzle::eIdentity,
.b = vk::ComponentSwizzle::eIdentity,
.a = vk::ComponentSwizzle::eIdentity,
},
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
.image = status_string_rasterized_text.image,
.viewType = vk::ImageViewType::e2D,
.format = status_string_rasterized_text.format,
.components = {
.r = vk::ComponentSwizzle::eIdentity,
.g = vk::ComponentSwizzle::eIdentity,
.b = vk::ComponentSwizzle::eIdentity,
.a = vk::ComponentSwizzle::eIdentity,
},
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
};
status_string_image_view = vk::raii::ImageView(device, iv_info);
vk::DescriptorImageInfo image_info{
.sampler = *status_string_sampler,
.imageView = *status_string_image_view,
.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal,
.sampler = *status_string_sampler,
.imageView = *status_string_image_view,
.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal,
};
vk::WriteDescriptorSet descriptor_write{
.dstSet = status_string_image_descriptor_set,
.dstBinding = 0,
.dstArrayElement = 0,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.pImageInfo = &image_info,
.dstSet = status_string_image_descriptor_set,
.dstBinding = 0,
.dstArrayElement = 0,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.pImageInfo = &image_info,
};
device.updateDescriptorSets(descriptor_write, {});
@@ -266,12 +136,12 @@ void scenes::lobby::rasterize_status_string()
last_status_string = status_string;
}
std::unique_ptr<wivrn_session> connect_to_session(const std::vector<wivrn_discover::service>& services)
std::unique_ptr<wivrn_session> connect_to_session(const std::vector<wivrn_discover::service> & services)
{
char protocol_string[17];
sprintf(protocol_string, "%016lx", xrt::drivers::wivrn::protocol_version);
for(const wivrn_discover::service& service: services)
for (const wivrn_discover::service & service: services)
{
auto protocol = service.txt.find("protocol");
if (protocol == service.txt.end())
@@ -281,15 +151,16 @@ std::unique_ptr<wivrn_session> connect_to_session(const std::vector<wivrn_discov
continue;
int port = service.port;
for(const auto& address: service.addresses)
for (const auto & address: service.addresses)
{
try
{
return std::visit([port](auto& address){
return std::visit([port](auto & address) {
return std::make_unique<wivrn_session>(address, port);
}, address);
},
address);
}
catch(std::exception& e)
catch (std::exception & e)
{
spdlog::warn("Cannot connect to {}: {}", service.hostname, e.what());
}
@@ -299,6 +170,35 @@ std::unique_ptr<wivrn_session> connect_to_session(const std::vector<wivrn_discov
return {};
}
static glm::mat4 projection_matrix(XrFovf fov, float zn = 0.1)
{
float r = tan(fov.angleRight);
float l = tan(fov.angleLeft);
float t = tan(fov.angleUp);
float b = tan(fov.angleDown);
// clang-format off
return glm::mat4{
{ 2/(r-l), 0, 0, 0 },
{ 0, 2/(b-t), 0, 0 },
{ (l+r)/(r-l), (t+b)/(b-t), -1, -1 },
{ 0, 0, -2*zn, 0 }
};
// clang-format on
}
static glm::mat4 view_matrix(XrPosef pose)
{
XrQuaternionf q = pose.orientation;
XrVector3f pos = pose.position;
glm::mat4 inv_view_matrix = glm::mat4_cast(glm::quat(q.w, q.x, q.y, q.z));
inv_view_matrix = glm::translate(glm::mat4(1), glm::vec3(pos.x, pos.y, pos.z)) * inv_view_matrix;
return glm::inverse(inv_view_matrix);
}
void scenes::lobby::render()
{
if (next_scene && !next_scene->alive())
@@ -339,8 +239,8 @@ void scenes::lobby::render()
status_string = "Waiting for connection";
}
if (status_string != last_status_string)
rasterize_status_string();
// if (status_string != last_status_string)
// rasterize_status_string();
XrFrameState framestate = session.wait_frame();
@@ -353,38 +253,47 @@ void scenes::lobby::render()
session.begin_frame();
command_buffer.reset();
command_buffer.begin(vk::CommandBufferBeginInfo{});
auto [flags, views] = session.locate_views(viewconfig, framestate.predictedDisplayTime, world_space);
assert(views.size() == swapchains.size());
std::vector<XrCompositionLayerProjectionView> layer_view(views.size());
for (size_t swapchain_index = 0; swapchain_index < views.size(); swapchain_index++)
application::poll_actions();
input->apply(world_space, framestate.predictedDisplayTime);
std::vector<XrCompositionLayerProjectionView> layer_view;
std::vector<scene_renderer::frame_info> frames;
layer_view.reserve(views.size());
frames.reserve(views.size());
for (auto && [view, swapchain]: utils::zip(views, swapchains))
{
int image_index = swapchains[swapchain_index].acquire();
swapchains[swapchain_index].wait();
int image_index = swapchain.acquire();
swapchain.wait();
render_view(flags, framestate.predictedDisplayTime, views[swapchain_index], swapchain_index, image_index);
frames.push_back({.destination = swapchain.images()[image_index].image,
.projection = projection_matrix(view.fov),
.view = view_matrix(view.pose)});
swapchains[swapchain_index].release();
layer_view[swapchain_index].type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW;
layer_view[swapchain_index].pose = views[swapchain_index].pose;
layer_view[swapchain_index].fov = views[swapchain_index].fov;
layer_view[swapchain_index].subImage.swapchain = swapchains[swapchain_index];
layer_view[swapchain_index].subImage.imageRect.offset = {0, 0};
layer_view[swapchain_index].subImage.imageRect.extent.width = swapchains[swapchain_index].width();
layer_view[swapchain_index].subImage.imageRect.extent.height = swapchains[swapchain_index].height();
layer_view.push_back({
.type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW,
.pose = view.pose,
.fov = view.fov,
.subImage = {
.swapchain = swapchain,
.imageRect = {
.offset = {0, 0},
.extent = swapchain.extent()}},
});
}
command_buffer.end();
assert(renderer);
renderer->render(teapot, frames);
vk::SubmitInfo submit_info;
submit_info.setCommandBuffers(*command_buffer);
queue.submit(submit_info, *fence);
for (auto & swapchain: swapchains)
swapchain.release();
XrCompositionLayerProjection layer{
.type = XR_TYPE_COMPOSITION_LAYER_PROJECTION,
@@ -398,67 +307,6 @@ void scenes::lobby::render()
layers_base.push_back(reinterpret_cast<XrCompositionLayerBaseHeader *>(&layer));
session.end_frame(framestate.predictedDisplayTime, layers_base);
if (device.waitForFences(*fence, VK_TRUE, UINT64_MAX) == vk::Result::eTimeout)
throw std::runtime_error("Vulkan fence timeout");
device.resetFences(*fence);
}
void scenes::lobby::render_view(XrViewStateFlags flags, XrTime display_time, XrView & view, int swapchain_index, int image_index)
{
xr::swapchain & swapchain = swapchains[swapchain_index];
image_data & data = images_data[swapchain_index][image_index];
vk::ClearValue clear_color;
clear_color.color = {0.0f, 0.0f, 0.0f, 1.0f};
vk::RenderPassBeginInfo renderpass_info{
.renderPass = *renderpass,
.framebuffer = *data.framebuffer,
.renderArea = {
.offset = {0, 0},
.extent = {swapchain.width(), swapchain.height()},
}
};
renderpass_info.setClearValues(clear_color);
command_buffer.beginRenderPass(renderpass_info, vk::SubpassContents::eInline);
command_buffer.bindPipeline(vk::PipelineBindPoint::eGraphics, *pipeline);
command_buffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, *layout, 0, status_string_image_descriptor_set, {});
float zn = 0.1;
float r = tan(view.fov.angleRight);
float l = tan(view.fov.angleLeft);
float t = tan(view.fov.angleUp);
float b = tan(view.fov.angleDown);
// clang-format off
glm::mat4 proj{
{ 2/(r-l), 0, 0, 0 },
{ 0, 2/(b-t), 0, 0 },
{ (l+r)/(r-l), (t+b)/(b-t), -1, -1 },
{ 0, 0, -2*zn, 0 }
};
// clang-format on
glm::mat4 view_matrix = glm::mat4_cast(glm::quat(view.pose.orientation.w, view.pose.orientation.x, view.pose.orientation.y, view.pose.orientation.z));
view_matrix = glm::translate(glm::mat4(1),
glm::vec3(view.pose.position.x, view.pose.position.y, view.pose.position.z)) *
view_matrix;
float aspect_ratio = (float)status_string_rasterized_text.size.width / (float)status_string_rasterized_text.size.height;
glm::mat4 model_matrix{
{aspect_ratio, 0, 0, 0},
{0, 1, 0, 0},
{0, 0, 1, 0},
{-0.5 * aspect_ratio, -0.5, -10, 1}};
glm::mat4 mvp = proj * glm::inverse(view_matrix) * model_matrix;
command_buffer.pushConstants<glm::mat4>(*layout, vk::ShaderStageFlagBits::eVertex, 0, mvp);
command_buffer.draw(6, 1, 0, 0);
command_buffer.endRenderPass();
}
void scenes::lobby::on_focused()
+19 -16
View File
@@ -27,6 +27,7 @@
#include "render/scene_renderer.h"
#include "render/text_rasterizer.h"
#include "input_profile.h"
namespace scenes
{
@@ -44,32 +45,34 @@ class lobby : public scene
vk::DescriptorSet status_string_image_descriptor_set;
text_rasterizer status_string_rasterizer;
vk::raii::RenderPass renderpass = nullptr;
vk::raii::PipelineLayout layout = nullptr;
vk::raii::Pipeline pipeline = nullptr;
// vk::raii::RenderPass renderpass = nullptr;
// vk::raii::PipelineLayout layout = nullptr;
// vk::raii::Pipeline pipeline = nullptr;
vk::raii::Fence fence = nullptr;
vk::raii::CommandBuffer command_buffer = nullptr;
// vk::raii::Fence fence = nullptr;
// vk::raii::CommandBuffer command_buffer = nullptr;
struct image_data
{
vk::raii::Framebuffer framebuffer;
vk::raii::Semaphore render_finished;
};
// struct image_data
// {
// vk::raii::Framebuffer framebuffer;
// vk::raii::Semaphore render_finished;
// };
std::vector<std::vector<image_data>> images_data;
// std::vector<std::vector<image_data>> images_data;
std::optional<wivrn_discover> discover;
std::vector<vk::DeviceMemory> model_memory;
std::vector<vk::Buffer> model_buffers;
std::vector<vk::Image> model_images;
// std::vector<vk::DeviceMemory> model_memory;
// std::vector<vk::Buffer> model_buffers;
// std::vector<vk::Image> model_images;
void load_model(const std::string & filename);
// void load_model(const std::string & filename);
std::shared_ptr<stream> next_scene;
// scene_renderer renderer;
std::optional<scene_renderer> renderer;
scene_data teapot;
std::optional<input_profile> input;
void rasterize_status_string();
+5 -4
View File
@@ -459,8 +459,9 @@ void scenes::stream::setup(const to_headset::video_stream_description & descript
.initialLayout = vk::ImageLayout::eUndefined,
};
VmaAllocationCreateInfo alloc_info{};
alloc_info.requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
VmaAllocationCreateInfo alloc_info{
.requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
};
decoder_output[i].image = image_allocation{image_info, alloc_info};
@@ -506,7 +507,7 @@ void scenes::stream::setup(const to_headset::video_stream_description & descript
}
spdlog::info("Initializing reprojector");
vk::Extent2D extent = {swapchains[0].width(), swapchains[0].height()};
vk::Extent2D extent = {(uint32_t)swapchains[0].width(), (uint32_t)swapchains[0].height()};
std::vector<vk::Image> swapchain_images;
for (auto & swapchain: swapchains)
{
@@ -525,7 +526,7 @@ void scenes::stream::setup(const to_headset::video_stream_description & descript
void scenes::stream::video()
{
#ifdef XR_USE_PLATFORM_ANDROID
#ifdef __ANDROID__
application::instance().setup_jni();
#endif
+132
View File
@@ -0,0 +1,132 @@
/*
* 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/>.
*/
#version 450
#define NB_TEXCOORDS 2
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;
} mesh;
#ifdef FRAG_SHADER
layout(set = 1, binding = 0) uniform sampler2D base_color;
layout(set = 1, binding = 1) uniform sampler2D metallic_roughness;
layout(set = 1, binding = 2) uniform sampler2D occlusion;
layout(set = 1, binding = 3) uniform sampler2D emissive;
layout(set = 1, binding = 4) uniform sampler2D normal_map;
layout(set = 1, binding = 5) uniform material_ubo
{
vec4 base_color_factor;
vec4 base_emissive_factor;
float metallic_factor;
float roughness_factor;
float occlusion_strength;
float normal_scale;
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 vec3 in_tangent;
layout(location = 3) in vec2 in_texcoord[NB_TEXCOORDS];
layout(location = 3+NB_TEXCOORDS) in vec4 in_color;
layout(location = 4+NB_TEXCOORDS) in vec4 in_joints;
layout(location = 5+NB_TEXCOORDS) 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 vec2 texcoord[NB_TEXCOORDS];
layout(location = 1+NB_TEXCOORDS) VERT_TO_FRAG vec3 frag_pos;
layout(location = 2+NB_TEXCOORDS) VERT_TO_FRAG vec4 light_pos;
// Fragment output
#ifdef FRAG_SHADER
layout(location = 0) out vec4 out_color;
#endif
// Shader code
#ifdef VERT_SHADER
void main()
{
normal = vec3(mesh.modelview * vec4(in_normal, 0.0));
for(int i = 0; i < 2; i++)
texcoord[i] = in_texcoord[i];
gl_Position = mesh.modelviewproj * vec4(in_position, 1.0);
frag_pos = vec3(mesh.modelview * vec4(in_position, 1.0));
light_pos = mesh.modelview * scene.light_position;
}
#endif
#ifdef FRAG_SHADER
void main()
{
vec3 light_dir = normalize(light_pos.xyz - frag_pos * light_pos.w);
vec3 view_dir = normalize(frag_pos);
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*/;
// out_color = texture(base_color, texcoord[0]) * vec4(light, 1.0);
// out_color = vec4(1.0, 1.0, 1.0, 1.0);
out_color = texture(base_color, texcoord[0]);
}
#endif
@@ -17,4 +17,16 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "pipeline.h"
#pragma once
#include <concepts>
namespace utils
{
template<typename T>
requires std::integral<T>
T align_up(T alignment, T value)
{
return ((value + alignment - 1) / alignment) * alignment;
}
}
+96
View File
@@ -0,0 +1,96 @@
/*
* 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/>.
*/
#pragma once
#include <spdlog/fmt/fmt.h>
#include <glm/fwd.hpp>
// /usr/include/fmt/chrono.h:2017
template<glm::length_t L, typename T, glm::qualifier Q, typename Char>
struct fmt::formatter<glm::vec<L, T, Q>, Char> //: fmt::formatter<T>
{
// auto parse(basic_format_parse_context<Char>& ctx) const -> decltype(ctx.begin())
// {
// auto begin = ctx.begin(), end = ctx.end();
// // if (begin != end && *begin == 'L') {
// // ++begin;
// // localized = true;
// // }
// return begin;
// }
auto parse(basic_format_parse_context<Char>& ctx) const // -> decltype(ctx.begin())
{
return ctx.begin();
}
template <typename FormatContext>
auto format(const glm::vec<L, T, Q>& v, FormatContext& ctx) const -> decltype(ctx.out())
{
if constexpr (L == 1)
{
return fmt::format_to(ctx.out(), "[ {} ]", v.x);
}
if constexpr (L == 2)
{
return fmt::format_to(ctx.out(), "[ {}, {} ]", v.x, v.y);
}
if constexpr (L == 3)
{
return fmt::format_to(ctx.out(), "[ {}, {}, {} ]", v.x, v.y, v.z);
}
if constexpr (L == 4)
{
return fmt::format_to(ctx.out(), "[ {}, {}, {}, {} ]", v.x, v.y, v.z, v.w);
}
// return formatter<std::string_view>(
// auto time = std::tm();
// time.tm_wday = static_cast<int>(wd.c_encoding());
// detail::get_locale loc(localized, ctx.locale());
// auto w = detail::tm_writer<decltype(ctx.out()), Char>(loc, ctx.out(), time);
// w.on_abbr_weekday();
// return w.out();
}
};
/*
template<glm::length_t C, glm::length_t R, typename T, glm::qualifier Q>
struct fmt::formatter<glm::mat<C, R, T, Q>> : fmt::formatter<std::string>
{
};
template<typename T, glm::qualifier Q>
struct fmt::formatter<glm::qua<T, Q>> : fmt::formatter<std::string>
{
};*/
@@ -19,29 +19,45 @@
#pragma once
#include "utils/handle.h"
#include <vector>
#include <vulkan/vulkan.h>
#include <boost/pfr/core.hpp>
#include <type_traits>
#include <vulkan/vulkan.hpp>
namespace vk
namespace utils
{
class pipeline_layout : public utils::handle<VkPipelineLayout>
{
VkDevice device{};
public:
struct info
template<typename T>
struct is_vk_flags : std::false_type {};
template<typename T>
struct is_vk_flags<vk::Flags<T>> : std::true_type {};
template<typename T>
struct magic_hash
{
std::size_t operator()(const T & info) const noexcept
{
std::vector<VkDescriptorSetLayout> descriptor_set_layouts;
std::vector<VkPushConstantRange> push_constant_ranges;
};
size_t h = 0;
~pipeline_layout();
pipeline_layout() = default;
pipeline_layout(VkDevice device, const info & create_info);
pipeline_layout(const pipeline_layout &) = delete;
pipeline_layout(pipeline_layout &&) = default;
pipeline_layout & operator=(const pipeline_layout &) = delete;
pipeline_layout & operator=(pipeline_layout &&) = default;
boost::pfr::for_each_field(info, [&](const auto & member) {
using U = std::remove_cvref_t<decltype(member)>;
if constexpr (is_vk_flags<U>::value)
{
using V = U::MaskType;
std::hash<V> hasher;
h = std::rotl(h, 5) ^ hasher(static_cast<V>(member));
}
else
{
std::hash<U> hasher;
h = std::rotl(h, 5) ^ hasher(member);
}
});
return h;
}
};
} // namespace vk
}
+25 -2
View File
@@ -25,12 +25,34 @@
namespace utils
{
template<typename T>
concept has_const_iterator = requires {
std::declval<typename T::const_iterator>();
};
template<typename T, bool> struct get_const_iterator_aux;
template<typename T> struct get_const_iterator_aux<T, true>
{
using const_iterator = T::const_iterator;
};
template<typename T> struct get_const_iterator_aux<T, false>
{
using const_iterator = T::iterator;
};
template<typename T>
using get_const_iterator = get_const_iterator_aux<T, has_const_iterator<T>>::const_iterator;
template <typename T>
struct enumerate_range
{
struct iterator
{
using underlying_iterator = std::conditional_t<std::is_const_v<T>, typename T::const_iterator, typename T::iterator>;
using underlying_iterator = std::conditional_t<std::is_const_v<T>, get_const_iterator<T>, typename T::iterator>;
using underlying_value_type = std::conditional_t<std::is_const_v<T>, const typename T::value_type, typename T::value_type>;
size_t index;
@@ -38,7 +60,8 @@ struct enumerate_range
std::pair<size_t, underlying_value_type &> operator*() const
{
return {index, *it};
underlying_value_type & x = *it;
return {index, x};
}
iterator & operator++()
+8 -10
View File
@@ -55,7 +55,7 @@ void basic_allocation_traits<VkBuffer>::destroy(
vmaDestroyBuffer(allocator, buffer.release(), allocation);
}
void * basic_allocation_traits<VkBuffer>::map(VmaAllocation allocation)
void * basic_allocation_traits_base::map(VmaAllocation allocation)
{
VmaAllocator allocator = application::get_allocator();
@@ -64,6 +64,13 @@ void * basic_allocation_traits<VkBuffer>::map(VmaAllocation allocation)
return mapped;
}
void basic_allocation_traits_base::unmap(VmaAllocation allocation)
{
VmaAllocator allocator = application::get_allocator();
vmaUnmapMemory(allocator, allocation);
}
std::pair<vk::raii::Image, VmaAllocation> basic_allocation_traits<VkImage>::create(
const CreateInfo& image_info,
const VmaAllocationCreateInfo* alloc_info)
@@ -90,12 +97,3 @@ void basic_allocation_traits<VkImage>::destroy(
vmaDestroyImage(allocator, image.release(), allocation);
}
void * basic_allocation_traits<VkImage>::map(VmaAllocation allocation)
{
VmaAllocator allocator = application::get_allocator();
void * mapped;
CHECK_VK(vmaMapMemory(allocator, allocation, &mapped));
return mapped;
}
+34 -9
View File
@@ -27,8 +27,14 @@ struct basic_allocation_traits
{
};
struct basic_allocation_traits_base
{
static void * map(VmaAllocation allocation);
static void unmap(VmaAllocation allocation);
};
template<>
struct basic_allocation_traits<VkBuffer>
struct basic_allocation_traits<VkBuffer> : basic_allocation_traits_base
{
using CreateInfo = vk::BufferCreateInfo;
using NativeCreateInfo = CreateInfo::NativeType;
@@ -42,12 +48,10 @@ struct basic_allocation_traits<VkBuffer>
RaiiType& buffer,
VmaAllocation allocation,
void * mapped);
static void * map(VmaAllocation allocation);
};
template<>
struct basic_allocation_traits<VkImage>
struct basic_allocation_traits<VkImage> : basic_allocation_traits_base
{
using CreateInfo = vk::ImageCreateInfo;
using NativeCreateInfo = CreateInfo::NativeType;
@@ -61,8 +65,6 @@ struct basic_allocation_traits<VkImage>
RaiiType& image,
VmaAllocation allocation,
void * mapped);
static void * map(VmaAllocation allocation);
};
template<typename T>
@@ -79,6 +81,7 @@ private:
VmaAllocation allocation = nullptr;
RaiiType resource = nullptr;
void * mapped = nullptr;
CreateInfo create_info{};
public:
operator T()
@@ -91,6 +94,11 @@ public:
return *resource;
}
operator bool() const
{
return *resource;
}
operator VmaAllocation() const
{
return allocation;
@@ -107,16 +115,18 @@ public:
}
basic_allocation() = default;
basic_allocation(const CreateInfo& buffer_info, const VmaAllocationCreateInfo& alloc_info)
basic_allocation(const CreateInfo& create_info, const VmaAllocationCreateInfo& alloc_info) :
create_info(create_info)
{
std::tie(resource, allocation) = traits::create(buffer_info, &alloc_info);
std::tie(resource, allocation) = traits::create(create_info, &alloc_info);
}
basic_allocation(const basic_allocation&) = delete;
basic_allocation(basic_allocation&& other) :
allocation(other.allocation),
resource(std::move(other.resource)),
mapped(other.mapped)
mapped(other.mapped),
create_info(other.create_info)
{
other.allocation = nullptr;
other.mapped = nullptr;
@@ -128,6 +138,7 @@ public:
std::swap(allocation, other.allocation);
std::swap(resource, other.resource);
std::swap(mapped, other.mapped);
std::swap(create_info, other.create_info);
return *this;
}
@@ -146,11 +157,25 @@ public:
return mapped;
}
void unmap()
{
if (!mapped)
return;
traits::unmap(allocation);
mapped = nullptr;
}
template<typename U>
U * data()
{
return reinterpret_cast<U*>(map());
}
const CreateInfo& info() const
{
return create_info;
}
};
-126
View File
@@ -1,126 +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 "device_memory.h"
#include "utils/check.h"
uint32_t vk::device_memory::get_memory_type(VkPhysicalDevice physical_device, VkMemoryRequirements requirements, VkMemoryPropertyFlags property_flags)
{
uint32_t types = requirements.memoryTypeBits;
VkPhysicalDeviceMemoryProperties memory_properties{};
vkGetPhysicalDeviceMemoryProperties(physical_device, &memory_properties);
for (uint32_t type = 0; type < memory_properties.memoryTypeCount; ++type)
{
if (not((1 << type) & types))
continue;
const auto & properties = memory_properties.memoryTypes[type];
if ((properties.propertyFlags & property_flags) == property_flags)
return type;
}
throw std::runtime_error{"No Vulkan memory with required flags"};
}
vk::device_memory::device_memory(VkDevice device, const VkMemoryAllocateInfo & allocate_info) :
device(device)
{
CHECK_VK(vkAllocateMemory(device, &allocate_info, nullptr, &id));
}
vk::device_memory::device_memory(VkDevice device, VkPhysicalDevice physical_device, VkImage target_image, VkMemoryPropertyFlags properties) :
device(device)
{
VkMemoryRequirements requirements;
vkGetImageMemoryRequirements(device, target_image, &requirements);
uint32_t memory_type = get_memory_type(physical_device, requirements, properties);
VkMemoryDedicatedAllocateInfoKHR dedicated_allocate_info{};
dedicated_allocate_info.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO;
dedicated_allocate_info.image = target_image;
VkMemoryAllocateInfo memory_allocate_info{};
memory_allocate_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
memory_allocate_info.allocationSize = requirements.size;
memory_allocate_info.memoryTypeIndex = memory_type;
memory_allocate_info.pNext = &dedicated_allocate_info;
CHECK_VK(vkAllocateMemory(device, &memory_allocate_info, nullptr, &id));
try
{
CHECK_VK(vkBindImageMemory(device, target_image, id, 0));
}
catch (...)
{
vkFreeMemory(device, id, nullptr);
throw;
}
}
vk::device_memory::device_memory(VkDevice device, VkPhysicalDevice physical_device, VkBuffer target_buffer, VkMemoryPropertyFlags properties) :
device(device)
{
VkMemoryRequirements requirements;
vkGetBufferMemoryRequirements(device, target_buffer, &requirements);
uint32_t memory_type = get_memory_type(physical_device, requirements, properties);
VkMemoryDedicatedAllocateInfoKHR dedicated_allocate_info{};
dedicated_allocate_info.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO;
dedicated_allocate_info.buffer = target_buffer;
VkMemoryAllocateInfo memory_allocate_info{};
memory_allocate_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
memory_allocate_info.allocationSize = requirements.size;
memory_allocate_info.memoryTypeIndex = memory_type;
memory_allocate_info.pNext = &dedicated_allocate_info;
CHECK_VK(vkAllocateMemory(device, &memory_allocate_info, nullptr, &id));
try
{
CHECK_VK(vkBindBufferMemory(device, target_buffer, id, 0));
}
catch (...)
{
vkFreeMemory(device, id, nullptr);
throw;
}
}
vk::device_memory::~device_memory()
{
if (device)
{
if (id and map)
{
vkUnmapMemory(device, id);
}
vkFreeMemory(device, id, nullptr);
}
}
void vk::device_memory::map_memory()
{
CHECK_VK(vkMapMemory(device, id, 0, VK_WHOLE_SIZE, 0, (void **)&map));
}
-56
View File
@@ -1,56 +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/handle.h"
#include <vulkan/vulkan.h>
static_assert(not std::is_same_v<VkImage, VkBuffer>, "vulkan handles need to be different types");
namespace vk
{
class device_memory : public utils::handle<VkDeviceMemory>
{
VkDevice device{};
void * map = nullptr;
public:
device_memory() = default;
device_memory(VkDevice device, const VkMemoryAllocateInfo & allocate_info);
device_memory(VkDevice device, VkPhysicalDevice physical_device, VkImage target_image, VkMemoryPropertyFlags properties);
device_memory(VkDevice device, VkPhysicalDevice physical_device, VkBuffer target_buffer, VkMemoryPropertyFlags properties);
device_memory(const device_memory &) = delete;
device_memory(device_memory &&) = default;
device_memory & operator=(const device_memory &) = delete;
device_memory & operator=(device_memory &&) = default;
~device_memory();
void * data()
{
return map;
}
void map_memory();
static uint32_t get_memory_type(VkPhysicalDevice physical_device, VkMemoryRequirements requirements, VkMemoryPropertyFlags property_flags);
};
} // namespace vk
+3 -2
View File
@@ -18,8 +18,9 @@
*/
#include "utils/check.h"
#include "vk.h"
#include <system_error>
#include <vulkan/vulkan.hpp>
#include <vulkan/vulkan_to_string.hpp>
namespace
{
@@ -32,7 +33,7 @@ struct : std::error_category
std::string message(int condition) const override
{
return string_VkResult(static_cast<VkResult>(condition));
return vk::to_string(static_cast<vk::Result>(condition));
}
} vulkan_error_category;
} // namespace
+1 -1
View File
@@ -40,7 +40,7 @@ public:
std::optional<vk::PipelineInputAssemblyStateCreateInfo> InputAssemblyState;
std::optional<vk::PipelineTessellationStateCreateInfo> TessellationState;
vk::PipelineViewportStateCreateInfo ViewportState;
vk::PipelineViewportStateCreateInfo ViewportState; // Automatically filled
std::vector<vk::Viewport> Viewports = {};
std::vector<vk::Rect2D> Scissors = {};
-39
View File
@@ -1,39 +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 "pipeline_layout.h"
#include "utils/check.h"
vk::pipeline_layout::pipeline_layout(VkDevice device, const info & create_info) :
device(device)
{
VkPipelineLayoutCreateInfo plci{
.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
.setLayoutCount = (uint32_t)create_info.descriptor_set_layouts.size(),
.pSetLayouts = create_info.descriptor_set_layouts.data(),
.pushConstantRangeCount = (uint32_t)create_info.push_constant_ranges.size(),
.pPushConstantRanges = create_info.push_constant_ranges.data()};
CHECK_VK(vkCreatePipelineLayout(device, &plci, nullptr, &id));
}
vk::pipeline_layout::~pipeline_layout()
{
if (device)
vkDestroyPipelineLayout(device, id, nullptr);
}
-43
View File
@@ -1,43 +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 "renderpass.h"
#include "vk/vk.h"
vk::renderpass::renderpass(VkDevice device, info & create_info) :
device(device)
{
VkRenderPassCreateInfo renderpass_create_info{};
renderpass_create_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
renderpass_create_info.attachmentCount = create_info.attachments.size();
renderpass_create_info.pAttachments = create_info.attachments.data();
renderpass_create_info.subpassCount = create_info.subpasses.size();
renderpass_create_info.pSubpasses = create_info.subpasses.data();
renderpass_create_info.dependencyCount = create_info.dependencies.size();
renderpass_create_info.pDependencies = create_info.dependencies.data();
CHECK_VK(vkCreateRenderPass(device, &renderpass_create_info, nullptr, &id));
}
vk::renderpass::~renderpass()
{
if (device)
vkDestroyRenderPass(device, id, nullptr);
}
-48
View File
@@ -1,48 +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/handle.h"
#include <vector>
#include <vulkan/vulkan.h>
namespace vk
{
class renderpass : public utils::handle<VkRenderPass>
{
VkDevice device{};
public:
struct info
{
std::vector<VkAttachmentDescription> attachments;
std::vector<VkSubpassDescription> subpasses;
std::vector<VkSubpassDependency> dependencies;
};
renderpass() = default;
renderpass(VkDevice device, info & create_info);
renderpass(const renderpass &) = delete;
renderpass(renderpass &&) = default;
renderpass & operator=(const renderpass &) = delete;
renderpass & operator=(renderpass &&) = default;
~renderpass();
};
} // namespace vk
+4 -3
View File
@@ -21,9 +21,10 @@
vk::raii::ShaderModule load_shader(vk::raii::Device& device, const std::vector<uint32_t> & spirv)
{
vk::ShaderModuleCreateInfo create_info{};
create_info.pCode = data(spirv);
create_info.codeSize = spirv.size() * sizeof(uint32_t);
vk::ShaderModuleCreateInfo create_info{
.codeSize = spirv.size() * sizeof(uint32_t),
.pCode = data(spirv),
};
return vk::raii::ShaderModule{device, create_info};
}
-41
View File
@@ -1,41 +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 "magic_enum.hpp"
#include "utils/check.h"
#include <string>
#include <vulkan/vulkan.h>
#define string_VkFormat(x) std::string(magic_enum::enum_name((VkFormat)(x)))
#define string_VkResult(x) std::string(magic_enum::enum_name((VkResult)(x)))
template <>
struct magic_enum::customize::enum_range<VkFormat>
{
static constexpr int min = 0;
static constexpr int max = 200;
};
template <typename... Args>
struct vk_chain
{
std::tuple<Args...> structs;
};
+1 -1
View File
@@ -19,7 +19,7 @@
#pragma once
#ifdef XR_USE_PLATFORM_ANDROID
#ifdef __ANDROID__
#include <jni.h>
#endif
+14 -16
View File
@@ -19,11 +19,9 @@
#include "swapchain.h"
#include "details/enumerate.h"
#include "error.h"
#include "session.h"
#include "xr.h"
xr::swapchain::swapchain(xr::session & s, vk::raii::Device& device, vk::Format format, uint32_t width, uint32_t height, int sample_count)
xr::swapchain::swapchain(xr::session & s, vk::raii::Device& device, vk::Format format, int32_t width, int32_t height, int sample_count)
{
assert(sample_count == 1);
@@ -54,19 +52,19 @@ xr::swapchain::swapchain(xr::session & s, vk::raii::Device& device, vk::Format f
{
images_[i].image = array[i].image;
vk::ImageViewCreateInfo iv_create_info;
iv_create_info.image = array[i].image;
iv_create_info.viewType = vk::ImageViewType::e2D;
iv_create_info.format = format;
iv_create_info.components.r = vk::ComponentSwizzle::eIdentity;
iv_create_info.components.g = vk::ComponentSwizzle::eIdentity;
iv_create_info.components.b = vk::ComponentSwizzle::eIdentity;
iv_create_info.components.a = vk::ComponentSwizzle::eIdentity;
iv_create_info.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor;
iv_create_info.subresourceRange.baseMipLevel = 0;
iv_create_info.subresourceRange.levelCount = 1;
iv_create_info.subresourceRange.baseArrayLayer = 0;
iv_create_info.subresourceRange.layerCount = 1;
vk::ImageViewCreateInfo iv_create_info{
.image = array[i].image,
.viewType = vk::ImageViewType::e2D,
.format = format,
.components = {},
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
}
};
images_[i].view = vk::raii::ImageView(device, iv_create_info);
}
+10 -6
View File
@@ -43,8 +43,8 @@ public:
};
private:
uint32_t width_;
uint32_t height_;
int32_t width_;
int32_t height_;
int sample_count_;
vk::Format format_;
@@ -52,21 +52,25 @@ private:
public:
swapchain() = default;
swapchain(session &, vk::raii::Device& device, vk::Format format, uint32_t width, uint32_t height, int sample_count = 1);
swapchain(session &, vk::raii::Device& device, vk::Format format, int32_t width, int32_t height, int sample_count = 1);
swapchain(swapchain &&) = default;
swapchain(const swapchain &) = delete;
swapchain & operator=(swapchain &&) = default;
swapchain & operator=(const swapchain &) = delete;
~swapchain();
uint32_t width() const
int32_t width() const
{
return width_;
}
uint32_t height() const
int32_t height() const
{
return height_;
}
XrExtent2Di extent() const
{
return { width_, height_ };
}
int sample_count() const
{
return sample_count_;
@@ -74,7 +78,7 @@ public:
const std::vector<image> & images() const
{
return images_;
};
}
std::vector<image> & images()
{
return images_;