diff --git a/CMakeLists.txt b/CMakeLists.txt index c0060b9..a53b0d4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required(VERSION 3.26) -# TODO: cmake configuration time weird increased last time - investigate it +# TODO: cmake configuration time weirdly increased last time - investigate it project(ts VERSION 0.0.1 LANGUAGES CXX) set(GAME_NAME "Awesome Game" CACHE STRING "Game name") diff --git a/assets/shaders/common.h b/assets/shaders/common.h index 1cad248..bd8e8b9 100644 --- a/assets/shaders/common.h +++ b/assets/shaders/common.h @@ -1,3 +1,4 @@ #pragma once #define PI 3.14159265359 +#define LIGHTS_N 2 \ No newline at end of file diff --git a/assets/shaders/pbr.frag b/assets/shaders/pbr.frag index 16f209b..bd6af5b 100644 --- a/assets/shaders/pbr.frag +++ b/assets/shaders/pbr.frag @@ -3,6 +3,7 @@ #extension GL_GOOGLE_include_directive : enable #extension GL_EXT_multiview : enable #extension GL_EXT_debug_printf : enable +#extension GL_EXT_nonuniform_qualifier : enable #include "assets/shaders/common.h" @@ -17,7 +18,7 @@ layout (binding = 1) uniform CommonUbo { } commonUbo; layout (binding = 2) uniform LightsUbo { - vec3 lights[2]; + vec3 positions[LIGHTS_N]; } lightsUbo; layout(push_constant) uniform Material { @@ -38,7 +39,8 @@ float D_GGX(float dotNH, float roughness) float alpha = roughness * roughness; float alpha2 = alpha * alpha; float denom = dotNH * dotNH * (alpha2 - 1.0) + 1.0; - return (alpha2)/(PI * denom*denom); + + return alpha2 / (PI * denom*denom); } float G_SchlicksmithGGX(float dotNL, float dotNV, float roughness) @@ -47,6 +49,7 @@ float G_SchlicksmithGGX(float dotNL, float dotNV, float roughness) float k = (r*r) / 8.0; float GL = dotNL / (dotNL * (1.0 - k) + k); float GV = dotNV / (dotNV * (1.0 - k) + k); + return GL * GV; } @@ -54,6 +57,7 @@ vec3 F_Schlick(float cosTheta, float metallic) { vec3 F0 = mix(vec3(0.04), materialcolor(), metallic); vec3 F = F0 + (1.0 - F0) * pow(1.0 - cosTheta, 5.0); + return F; } @@ -88,9 +92,6 @@ void main() { vec3 N = normalize(inNormal); - // vec3 var = vec4(inverse(commonUbo.viewMats[gl_ViewIndex]) * vec4(-commonUbo.camPos - inWorldPos, 1.0)).xyz; - // vec3 V = normalize(vec3(var.x, var.y + 1.0, var.z)); - vec3 temp = vec3(commonUbo.viewMats[gl_ViewIndex][3]); vec3 v1 = vec3( commonUbo.camPos.x + temp.x, @@ -100,9 +101,9 @@ void main() vec3 V = normalize(-v1 - inWorldPos); vec3 Lo = vec3(0.0); - for (int i = 0; i < lightsUbo.lights.length(); i++) + for (int i = 0; i < lightsUbo.positions.length(); i++) { - vec3 L = normalize(lightsUbo.lights[i] - inWorldPos); + vec3 L = normalize(lightsUbo.positions[i] - inWorldPos); Lo += BRDF(L, V, N, material.metallic, material.roughness); }; diff --git a/engine/CMakeLists.txt b/engine/CMakeLists.txt index f5357f9..9ed0e14 100644 --- a/engine/CMakeLists.txt +++ b/engine/CMakeLists.txt @@ -149,6 +149,8 @@ if(MSVC) $<$: /O2 /MD> /W3 /WX /wd4710 ) +else() + message(FATAL_ERROR "not implemented") endif() if(ENABLE_TESTS) diff --git a/engine/include/tsengine/asset_store.h b/engine/include/tsengine/asset_store.h index 125073f..95f8244 100644 --- a/engine/include/tsengine/asset_store.h +++ b/engine/include/tsengine/asset_store.h @@ -2,7 +2,7 @@ #include "utils.hpp" -#include "tsengine/ecs/ecs.hpp" +#include "tsengine/ecs/ecs.h" #include "tsengine/ecs/components/mesh_component.hpp" namespace ts diff --git a/engine/include/tsengine/core.h b/engine/include/tsengine/core.h index a603430..3bd5790 100644 --- a/engine/include/tsengine/core.h +++ b/engine/include/tsengine/core.h @@ -12,10 +12,10 @@ class Engine Engine(const Engine&&) = delete; Engine& operator=(Engine&&) = delete; - virtual bool init(const char*& gameName, unsigned& width, unsigned& height) = 0; - virtual void loadLvL() {}; + virtual bool init(const char*& gameName, unsigned& width, unsigned& height); + virtual void loadLvL() = 0; virtual bool tick() = 0; - virtual void close() = 0; + virtual void close(); }; int run(Engine* const engine); diff --git a/engine/include/tsengine/ecs/components/asset_component.h b/engine/include/tsengine/ecs/components/asset_component.h index ae6e87f..b2f40e0 100644 --- a/engine/include/tsengine/ecs/components/asset_component.h +++ b/engine/include/tsengine/ecs/components/asset_component.h @@ -1,5 +1,7 @@ #pragma once +#include "tsengine/utils.hpp" + namespace ts { class AssetStore; @@ -8,11 +10,12 @@ struct AssetComponent : public Component { using Base = AssetComponent; - AssetComponent(const std::string_view assetName_ = "") : assetName{assetName_} + AssetComponent(const std::string_view assetName_ = "") : assetName{assetName_}, assetNameId{std::hash{}(assetName_)} {} protected: friend AssetStore; std::string assetName; + size_t assetNameId; }; } \ No newline at end of file diff --git a/engine/include/tsengine/ecs/components/renderer_component.hpp b/engine/include/tsengine/ecs/components/renderer_component.hpp index c84b1b4..5260966 100644 --- a/engine/include/tsengine/ecs/components/renderer_component.hpp +++ b/engine/include/tsengine/ecs/components/renderer_component.hpp @@ -4,6 +4,8 @@ namespace ts { +class Renderer; + // TODO: enum reflection // TODO: implement color @@ -27,23 +29,31 @@ enum class PipelineType struct RendererComponentBase : public Component { using Base = RendererComponentBase; + using ZIdxT = int32_t; + + RendererComponentBase(const ZIdxT z_ = {}) : z{z_} {} + + ZIdxT z; }; template struct RendererComponent : public RendererComponentBase { PipelineType pipeline{pipeType}; + + RendererComponent(const ZIdxT z_ = {}) : RendererComponentBase{z_} + {} }; template<> struct RendererComponent : public RendererComponentBase { #define TS_MATERIALS_LIST \ - MATERIAL(WHITE, .color = { 1.0f, 1.0f, 1.0f}, .roughness = 0.5f, .metallic = 1.0f) \ - MATERIAL(RED, .color = { 1.0f, 0.0f, 0.0f}, .roughness = 0.5f, .metallic = 1.0f) \ - MATERIAL(BLUE, .color = { 0.0f, 0.0f, 1.0f}, .roughness = 0.5f, .metallic = 1.0f) \ - MATERIAL(BLACK, .color = { 0.0f, 0.0f, 0.0f}, .roughness = 0.5f, .metallic = 1.0f) \ - MATERIAL(GOLD, .color = { 1.0f, 0.765557f, 0.336057f}, .roughness = 0.5f, .metallic = 1.0f) \ + MATERIAL(WHITE, .color = {1.0f , 1.0f ,1.0f }, .roughness = 0.5f, .metallic = 1.0f) \ + MATERIAL(RED, .color = {1.0f , 0.0f ,0.0f }, .roughness = 0.5f, .metallic = 1.0f) \ + MATERIAL(BLUE, .color = {0.0f , 0.0f ,1.0f }, .roughness = 0.5f, .metallic = 1.0f) \ + MATERIAL(BLACK, .color = {0.0f , 0.0f ,0.0f }, .roughness = 0.5f, .metallic = 1.0f) \ + MATERIAL(GOLD, .color = {1.0f , 0.765557f, 0.336057f}, .roughness = 0.5f, .metallic = 1.0f) \ MATERIAL(COPPER, .color = {0.955008f, 0.637427f, 0.538163f}, .roughness = 0.5f, .metallic = 1.0f) \ MATERIAL(CHROMIUM, .color = {0.549585f, 0.556114f, 0.554256f}, .roughness = 0.5f, .metallic = 1.0f) \ MATERIAL(NICKEL, .color = {0.659777f, 0.608679f, 0.525649f}, .roughness = 0.5f, .metallic = 1.0f) \ @@ -66,9 +76,10 @@ struct RendererComponent : public RendererComponentBase { switch (type) { -#define MATERIAL(type, ...) \ - case Material::Type::type: \ +#define MATERIAL(type, ...) \ + case Material::Type::type: \ return Material{__VA_ARGS__}; + TS_MATERIALS_LIST #undef MATERIAL default: throw Exception{"Invalid material type"}; @@ -82,6 +93,10 @@ struct RendererComponent : public RendererComponentBase float metallic; }; - Material material{Material::create(Material::Type::RED)}; + Material material; + + RendererComponent(const Material material_ = Material::create(Material::Type::RED), const ZIdxT z_ = {}) + : RendererComponentBase{z_}, material{material_} + {} }; } diff --git a/engine/include/tsengine/ecs/components/transform_component.hpp b/engine/include/tsengine/ecs/components/transform_component.hpp index f846481..6810bd9 100644 --- a/engine/include/tsengine/ecs/components/transform_component.hpp +++ b/engine/include/tsengine/ecs/components/transform_component.hpp @@ -9,7 +9,7 @@ struct TransformComponent : public Component math::Vec3 pos; math::Mat4 modelMat{1.f}; - TransformComponent(const math::Vec3 pos_ = math::Vec3{1.f}) : pos{pos_} + TransformComponent(const math::Vec3 pos_ = math::Vec3{0.f}) : pos{pos_} {} }; } diff --git a/engine/include/tsengine/ecs/ecs.hpp b/engine/include/tsengine/ecs/ecs.h similarity index 97% rename from engine/include/tsengine/ecs/ecs.hpp rename to engine/include/tsengine/ecs/ecs.h index 63ea895..e46c991 100644 --- a/engine/include/tsengine/ecs/ecs.hpp +++ b/engine/include/tsengine/ecs/ecs.h @@ -127,7 +127,7 @@ class Pool : public IPool const T& operator [](const Id index) const { return data.at(index); } }; -inline class Registry +class Registry { std::unordered_map> systems; std::unordered_map entityPerTag; @@ -176,7 +176,9 @@ inline class Registry void addEntityToSystems(const Entity entity); void removeEntityFromSystems(const Entity entity); -} gRegistry; +}; + +Registry& getMainReg(); // Entity @@ -367,7 +369,7 @@ inline Entity Registry::createEntity() const auto [entity, isQueued] = entitiesToBeAdded.emplace(entityId, this); - TS_ASSERT(isQueued, "Entity couldn't be added to the queue of entities to be added."); + TS_ASSERT_MSG(isQueued, "Entity couldn't be added to the queue of entities to be added."); return *entity; } @@ -380,8 +382,6 @@ inline void Registry::tagEntity(const Entity entity, const std::string& tag) inline bool Registry::entityHasTag(const Entity entity, const std::string& tag) const { - TS_ASSERT(tagPerEntity.find(entity.getId()) != tagPerEntity.end(), "Entity doesn't have tag"); - return entityPerTag.find(tag)->second == entity; } @@ -447,7 +447,7 @@ void Registry::addSystem(TArgs&& ...args) { const auto index = std::type_index(typeid(TSystem)); - TS_ASSERT(systems.find(index) == systems.end(), "System is already added"); + TS_ASSERT_MSG(systems.find(index) == systems.end(), "System is already added"); const auto newSystem = std::make_shared(std::forward(args)...); systems.insert(std::make_pair(std::type_index(typeid(TSystem)), newSystem)); @@ -479,7 +479,7 @@ void Registry::addComponent(const Entity entity, TArgs&& ...args) { if constexpr (!is_component_of_v) { - _addComponent(entity, std::forward(args)...); + _addComponent(entity); } _addComponent(entity, std::forward(args)...); diff --git a/engine/include/tsengine/logger.h b/engine/include/tsengine/logger.h index b580094..2705a0a 100644 --- a/engine/include/tsengine/logger.h +++ b/engine/include/tsengine/logger.h @@ -8,20 +8,26 @@ #define NOT_PRINT_LINE_NUMBER -1 -#define TS_LOG(message) ts::logger::log(message, __FILE__, FUNCTION_SIGNATURE, __LINE__) -#define TS_WARN(message) ts::logger::warning(message, __FILE__, FUNCTION_SIGNATURE, __LINE__) -#define TS_ERR(message) ts::logger::error(message, __FILE__, FUNCTION_SIGNATURE, __LINE__) +#define TS_LOG(msg) ts::logger::log(msg, __FILE__, FUNCTION_SIGNATURE, __LINE__) +#define TS_WARN(msg) ts::logger::warning(msg, __FILE__, FUNCTION_SIGNATURE, __LINE__) +#define TS_ERR(msg) ts::logger::error(msg, __FILE__, FUNCTION_SIGNATURE, __LINE__) -// TODO: default message #ifndef NDEBUG -#define TS_ASSERT(condition, ...) \ - if (!(condition)) \ - { \ - ts::logger::warning(__VA_ARGS__, __FILE__, FUNCTION_SIGNATURE, __LINE__, true); \ +#define TS_ASSERT(condition) \ + if (!(condition)) \ + { \ + ts::logger::warning("Assertion Failed: " #condition, __FILE__, FUNCTION_SIGNATURE, __LINE__, true); \ + } + +#define TS_ASSERT_MSG(condition, msg) \ + if (!(condition)) \ + { \ + ts::logger::warning(msg, __FILE__, FUNCTION_SIGNATURE, __LINE__, true); \ } #else -#define TS_ASSERT(condition, ...) +#define TS_ASSERT(condition) +#define TS_ASSERT_MSG(condition, msg) #endif namespace ts diff --git a/engine/include/tsengine/utils.hpp b/engine/include/tsengine/utils.hpp index dff5b11..1616e85 100644 --- a/engine/include/tsengine/utils.hpp +++ b/engine/include/tsengine/utils.hpp @@ -2,25 +2,25 @@ // TODO: Remove the need of providing class name - reflection -#define NOT_COPYABLE(ClassName) \ +#define TS_NOT_COPYABLE(ClassName) \ ClassName(const ClassName&) = delete; \ ClassName& operator=(const ClassName&) = delete; -#define NOT_MOVEABLE(ClassName) \ +#define TS_NOT_MOVEABLE(ClassName) \ ClassName(ClassName&&) = delete; \ ClassName& operator=(ClassName&&) = delete; -#define NOT_COPYABLE_AND_MOVEABLE(ClassName) \ - NOT_COPYABLE(ClassName); \ - NOT_MOVEABLE(ClassName); +#define TS_NOT_COPYABLE_AND_MOVEABLE(ClassName) \ + TS_NOT_COPYABLE(ClassName); \ + TS_NOT_MOVEABLE(ClassName); -#define SINGLETON_BODY(ClassName) \ - NOT_COPYABLE_AND_MOVEABLE(ClassName); \ - private: ClassName() = default; \ +#define TS_SINGLETON_BODY(ClassName) \ + TS_NOT_COPYABLE_AND_MOVEABLE(ClassName); \ + private: ClassName() = default; \ friend Singleton; -#define STR(x) XSTR(x) -#define XSTR(x) #x +#define TS_STR(x) XSTR(x) +#define TS_XSTR(x) #x template<> struct std::hash final @@ -44,8 +44,8 @@ enum { TS_SUCCESS, TS_FAILURE, - STL_FAILURE, - UNKNOWN_FAILURE + TS_STL_FAILURE, + TS_UNKNOWN_FAILURE }; class Exception : public std::exception @@ -63,7 +63,7 @@ class Exception : public std::exception template class Singleton { - NOT_COPYABLE_AND_MOVEABLE(Singleton); + TS_NOT_COPYABLE_AND_MOVEABLE(Singleton); public: static auto& getInstance() diff --git a/engine/src/core/asset_store.cpp b/engine/src/core/asset_store.cpp index b004b71..cfb53f2 100644 --- a/engine/src/core/asset_store.cpp +++ b/engine/src/core/asset_store.cpp @@ -1,8 +1,9 @@ #include "tsengine/asset_store.h" +#include "globals.hpp" #include "tsengine/logger.h" -#include "tsengine/ecs/ecs.hpp" +#include "tsengine/ecs/ecs.h" #include "tsengine/ecs/components/mesh_component.hpp" #include "tsengine/ecs/components/transform_component.hpp" @@ -19,7 +20,7 @@ namespace // TODO: avoid the same files void AssetStore::Models::load() { - for (const auto entity : gRegistry.getSystem().getSystemEntities()) + for (const auto entity : gReg.getSystem().getSystemEntities()) { auto& meshComponent = entity.getComponent(); const auto& fileName = meshComponent.assetName; diff --git a/engine/src/core/context.cpp b/engine/src/core/context.cpp index a35cdfb..fa73c4b 100644 --- a/engine/src/core/context.cpp +++ b/engine/src/core/context.cpp @@ -37,7 +37,7 @@ Context& Context::createOpenXrContext() void Context::createVulkanContext() { - TS_ASSERT(mIsXrContextCreated, "XrContext should be firstly created"); + TS_ASSERT_MSG(mIsXrContextCreated, "XrContext should be firstly created"); vulkanloader::connectWithLoader(); vulkanloader::loadExportFunction(); @@ -109,7 +109,7 @@ void Context::createXrDebugMessenger() .userCallback = reinterpret_cast(khronos_utils::xrCallback) }; - LOGGER_XR(xrCreateDebugUtilsMessengerEXT, + TS_XR_CHECK(xrCreateDebugUtilsMessengerEXT, mXrInstance, &ci, &mXrDebugMessenger); @@ -124,39 +124,39 @@ void Context::createVkDebugMessenger() .pfnUserCallback = &khronos_utils::vkCallback }; - LOGGER_VK(vkCreateDebugUtilsMessengerEXT, mVkInstance, &ci, nullptr, &mVkDebugMessenger); + TS_VK_CHECK(vkCreateDebugUtilsMessengerEXT, mVkInstance, &ci, nullptr, &mVkDebugMessenger); } #endif // DEBUG void Context::loadXrExtensions() { - LOGGER_XR(xrGetInstanceProcAddr, + TS_XR_CHECK(xrGetInstanceProcAddr, mXrInstance, "xrGetVulkanInstanceExtensionsKHR", reinterpret_cast(&xrGetVulkanInstanceExtensionsKHR)); - LOGGER_XR(xrGetInstanceProcAddr, + TS_XR_CHECK(xrGetInstanceProcAddr, mXrInstance, "xrGetVulkanGraphicsDeviceKHR", reinterpret_cast(&xrGetVulkanGraphicsDeviceKHR)); - LOGGER_XR(xrGetInstanceProcAddr, + TS_XR_CHECK(xrGetInstanceProcAddr, mXrInstance, "xrGetVulkanDeviceExtensionsKHR", reinterpret_cast(&xrGetVulkanDeviceExtensionsKHR)); - LOGGER_XR(xrGetInstanceProcAddr, + TS_XR_CHECK(xrGetInstanceProcAddr, mXrInstance, "xrGetVulkanGraphicsRequirementsKHR", reinterpret_cast(&xrGetVulkanGraphicsRequirementsKHR)); #ifndef NDEBUG - LOGGER_XR(xrGetInstanceProcAddr, + TS_XR_CHECK(xrGetInstanceProcAddr, mXrInstance, "xrCreateDebugUtilsMessengerEXT", reinterpret_cast(&xrCreateDebugUtilsMessengerEXT)); - LOGGER_XR(xrGetInstanceProcAddr, + TS_XR_CHECK(xrGetInstanceProcAddr, mXrInstance, "xrDestroyDebugUtilsMessengerEXT", reinterpret_cast(&xrDestroyDebugUtilsMessengerEXT)); @@ -189,19 +189,14 @@ void Context::initXrSystemId() .formFactor = XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY }; - auto result = xrGetSystem(mXrInstance, &xrSystemInfo, &mXrSystemId); - - if (XR_FAILED(result)) - { - TS_ERR("No headset detected"); - } + TS_XR_CHECK_MSG("No headset detected", xrGetSystem, mXrInstance, &xrSystemInfo, &mXrSystemId); } void Context::initXrSystemInfo() { XrSystemProperties xrSystemProperties{XR_TYPE_SYSTEM_PROPERTIES}; - LOGGER_XR(xrGetSystemProperties, mXrInstance, mXrSystemId, &xrSystemProperties); + TS_XR_CHECK(xrGetSystemProperties, mXrInstance, mXrSystemId, &xrSystemProperties); // TODO: print xr device info // TODO: costum xr loader @@ -210,7 +205,7 @@ void Context::initXrSystemInfo() void Context::isXrBlendModeAvailable() { uint32_t environmentBlendModeCount; - LOGGER_XR(xrEnumerateEnvironmentBlendModes, + TS_XR_CHECK(xrEnumerateEnvironmentBlendModes, mXrInstance, mXrSystemId, xrViewType, @@ -218,7 +213,7 @@ void Context::isXrBlendModeAvailable() &environmentBlendModeCount, nullptr); std::vector supportedEnvironmentBlendModes(environmentBlendModeCount); - LOGGER_XR(xrEnumerateEnvironmentBlendModes, + TS_XR_CHECK(xrEnumerateEnvironmentBlendModes, mXrInstance, mXrSystemId, xrViewType, @@ -245,7 +240,7 @@ void Context::isXrBlendModeAvailable() void Context::getRequiredVulkanInstanceExtensions(std::vector& vulkanInstanceExtensions) { uint32_t count; - LOGGER_XR(xrGetVulkanInstanceExtensionsKHR, + TS_XR_CHECK(xrGetVulkanInstanceExtensionsKHR, mXrInstance, mXrSystemId, 0, @@ -253,7 +248,7 @@ void Context::getRequiredVulkanInstanceExtensions(std::vector& vulk nullptr); std::string xrVulkanExtensionsStr(count, ' '); - LOGGER_XR(xrGetVulkanInstanceExtensionsKHR, + TS_XR_CHECK(xrGetVulkanInstanceExtensionsKHR, mXrInstance, mXrSystemId, count, @@ -301,13 +296,13 @@ void Context::isVulkanInstanceExtensionsAvailable(const std::vector void Context::getSupportedVulkanInstanceExtensions(std::vector& supportedVulkanInstanceExtensions) { uint32_t instanceExtensionCount; - LOGGER_VK(vkEnumerateInstanceExtensionProperties, + TS_VK_CHECK(vkEnumerateInstanceExtensionProperties, nullptr, &instanceExtensionCount, nullptr); supportedVulkanInstanceExtensions.resize(instanceExtensionCount); - LOGGER_VK(vkEnumerateInstanceExtensionProperties, + TS_VK_CHECK(vkEnumerateInstanceExtensionProperties, nullptr, &instanceExtensionCount, supportedVulkanInstanceExtensions.data()); @@ -340,10 +335,10 @@ void Context::createVulkanInstance(const std::vector& vulkanInstanc #ifndef NDEBUG std::vector supportedInstanceLayers; uint32_t instanceLayerCount; - LOGGER_VK(vkEnumerateInstanceLayerProperties, &instanceLayerCount, nullptr); + TS_VK_CHECK(vkEnumerateInstanceLayerProperties, &instanceLayerCount, nullptr); supportedInstanceLayers.resize(instanceLayerCount); - LOGGER_VK(vkEnumerateInstanceLayerProperties, &instanceLayerCount, supportedInstanceLayers.data()); + TS_VK_CHECK(vkEnumerateInstanceLayerProperties, &instanceLayerCount, supportedInstanceLayers.data()); for (const auto layer : vkLayers) { @@ -367,12 +362,12 @@ void Context::createVulkanInstance(const std::vector& vulkanInstanc ci.ppEnabledLayerNames = vkLayers.data(); #endif // DEBUG - LOGGER_VK(vkCreateInstance, &ci, nullptr, &mVkInstance); + TS_VK_CHECK(vkCreateInstance, &ci, nullptr, &mVkInstance); } void Context::createPhysicalDevice() { - LOGGER_XR(xrGetVulkanGraphicsDeviceKHR, mXrInstance, mXrSystemId, mVkInstance, &mPhysicalDevice); + TS_XR_CHECK(xrGetVulkanGraphicsDeviceKHR, mXrInstance, mXrSystemId, mVkInstance, &mPhysicalDevice); } void Context::getGraphicsQueue() @@ -431,7 +426,7 @@ void Context::getPresentQueue(const VkSurfaceKHR mirrorSurface) } VkBool32 presentSupport{}; - LOGGER_VK(vkGetPhysicalDeviceSurfaceSupportKHR, + TS_VK_CHECK(vkGetPhysicalDeviceSurfaceSupportKHR, mPhysicalDevice, static_cast(queueFamilyIndexCandidate), mirrorSurface, &presentSupport); @@ -509,14 +504,14 @@ void Context::isVulkanDeviceExtensionsAvailable( void Context::getSupportedVulkanDeviceExtensions(std::vector& vulkanDeviceExtensions) { uint32_t deviceExtensionCount; - LOGGER_VK(vkEnumerateDeviceExtensionProperties, + TS_VK_CHECK(vkEnumerateDeviceExtensionProperties, mPhysicalDevice, nullptr, &deviceExtensionCount, nullptr); vulkanDeviceExtensions.resize(deviceExtensionCount); - LOGGER_VK(vkEnumerateDeviceExtensionProperties, + TS_VK_CHECK(vkEnumerateDeviceExtensionProperties, mPhysicalDevice, nullptr, &deviceExtensionCount, @@ -526,11 +521,11 @@ void Context::getSupportedVulkanDeviceExtensions(std::vector& requiredVulkanDeviceExtensions) { uint32_t count; - LOGGER_XR(xrGetVulkanDeviceExtensionsKHR, mXrInstance, mXrSystemId, 0, &count, nullptr); + TS_XR_CHECK(xrGetVulkanDeviceExtensionsKHR, mXrInstance, mXrSystemId, 0, &count, nullptr); std::string buffer; buffer.resize(count); - LOGGER_XR(xrGetVulkanDeviceExtensionsKHR, mXrInstance, mXrSystemId, count, &count, buffer.data()); + TS_XR_CHECK(xrGetVulkanDeviceExtensionsKHR, mXrInstance, mXrSystemId, count, &count, buffer.data()); khronos_utils::unpackXrExtensionString(buffer, requiredVulkanDeviceExtensions); @@ -560,10 +555,10 @@ void Context::createLogicalDevice( .pEnabledFeatures = &physicalDeviceFeatures, }; - LOGGER_VK(vkCreateDevice, mPhysicalDevice, &deviceCi, nullptr, &mVkDevice); + TS_VK_CHECK(vkCreateDevice, mPhysicalDevice, &deviceCi, nullptr, &mVkDevice); XrGraphicsRequirementsVulkanKHR graphicsRequirements{XR_TYPE_GRAPHICS_REQUIREMENTS_VULKAN_KHR}; - LOGGER_XR(xrGetVulkanGraphicsRequirementsKHR, mXrInstance, mXrSystemId, &graphicsRequirements); + TS_XR_CHECK(xrGetVulkanGraphicsRequirementsKHR, mXrInstance, mXrSystemId, &graphicsRequirements); } void Context::createQueues(std::vector& deviceQueueCis) @@ -620,8 +615,8 @@ Context::~Context() void Context::createXrInstance() { - TS_ASSERT(mGameName.size() > 0, "setGameName() should be firstly called"); - TS_ASSERT(mGameName.size() > 0, "setGameName() should be firstly called"); + TS_ASSERT_MSG(mGameName.size() > 0, "setGameName() should be firstly called"); + TS_ASSERT_MSG(mGameName.size() > 0, "setGameName() should be firstly called"); XrApplicationInfo appInfo{ .applicationVersion = static_cast(XR_MAKE_VERSION(0, 1, 0)), @@ -642,7 +637,7 @@ void Context::createXrInstance() std::vector supportedXrInstanceExtensions; uint32_t instanceExtensionCount; - LOGGER_XR(xrEnumerateInstanceExtensionProperties, nullptr, 0, &instanceExtensionCount, nullptr) + TS_XR_CHECK(xrEnumerateInstanceExtensionProperties, nullptr, 0, &instanceExtensionCount, nullptr) supportedXrInstanceExtensions.resize(instanceExtensionCount); for (auto& extensionProperty : supportedXrInstanceExtensions) @@ -650,7 +645,7 @@ void Context::createXrInstance() extensionProperty.type = XR_TYPE_EXTENSION_PROPERTIES; } - LOGGER_XR(xrEnumerateInstanceExtensionProperties, + TS_XR_CHECK(xrEnumerateInstanceExtensionProperties, nullptr, instanceExtensionCount, &instanceExtensionCount, @@ -685,6 +680,6 @@ void Context::createXrInstance() .enabledExtensionNames = extensions.data(), }; - LOGGER_XR(xrCreateInstance, &instanceCi, &mXrInstance); + TS_XR_CHECK(xrCreateInstance, &instanceCi, &mXrInstance); } } // namespace ts \ No newline at end of file diff --git a/engine/src/core/context.h b/engine/src/core/context.h index 28570d7..99b1794 100644 --- a/engine/src/core/context.h +++ b/engine/src/core/context.h @@ -9,7 +9,7 @@ namespace ts { class Context final { - NOT_COPYABLE_AND_MOVEABLE(Context); + TS_NOT_COPYABLE_AND_MOVEABLE(Context); static constexpr XrEnvironmentBlendMode xrEnvironmentBlendMode{XR_ENVIRONMENT_BLEND_MODE_OPAQUE}; diff --git a/engine/src/core/controllers.cpp b/engine/src/core/controllers.cpp index 53e3e84..a13b0b1 100644 --- a/engine/src/core/controllers.cpp +++ b/engine/src/core/controllers.cpp @@ -6,7 +6,7 @@ namespace XrPath stringToXrPath(XrInstance instance, std::string_view str) { XrPath path; - LOGGER_XR(xrStringToPath, instance, str.data(), &path); + TS_XR_CHECK(xrStringToPath, instance, str.data(), &path); return path; } @@ -44,7 +44,7 @@ void Controllers::setupControllers() strcpy(actionSetCreateInfo.actionSetName, actionSetName.data()); strcpy(actionSetCreateInfo.localizedActionSetName, localizedActionSetName.data()); - LOGGER_XR(xrCreateActionSet, mInstance, &actionSetCreateInfo, &mActionSet); + TS_XR_CHECK(xrCreateActionSet, mInstance, &actionSetCreateInfo, &mActionSet); mPaths.at(0) = stringToXrPath(mInstance, "/user/hand/left"); mPaths.at(1) = stringToXrPath(mInstance, "/user/hand/right"); @@ -62,7 +62,7 @@ void Controllers::setupControllers() .poseInActionSpace = khronos_utils::makeXrIdentity() }; - LOGGER_XR(xrCreateActionSpace, mSession, &actionSpaceCreateInfo, &mSpaces.at(controllerIndex)); + TS_XR_CHECK(xrCreateActionSpace, mSession, &actionSpaceCreateInfo, &mSpaces.at(controllerIndex)); } const std::array bindings{ @@ -79,7 +79,7 @@ void Controllers::setupControllers() .suggestedBindings = bindings.data(), }; - LOGGER_XR(xrSuggestInteractionProfileBindings, mInstance, &interactionProfileSuggestedBinding); + TS_XR_CHECK(xrSuggestInteractionProfileBindings, mInstance, &interactionProfileSuggestedBinding); XrSessionActionSetsAttachInfo sessionActionSetsAttachInfo{ .type = XR_TYPE_SESSION_ACTION_SETS_ATTACH_INFO, @@ -87,7 +87,7 @@ void Controllers::setupControllers() .actionSets = &mActionSet }; - LOGGER_XR(xrAttachSessionActionSets, mSession, &sessionActionSetsAttachInfo); + TS_XR_CHECK(xrAttachSessionActionSets, mSession, &sessionActionSetsAttachInfo); } void Controllers::sync(const XrSpace space, const XrTime time) @@ -118,7 +118,7 @@ void Controllers::sync(const XrSpace space, const XrTime time) if (poseState.isActive) { XrSpaceLocation spaceLocation{ XR_TYPE_SPACE_LOCATION }; - LOGGER_XR(xrLocateSpace, mSpaces.at(controllerIndex), space, time, &spaceLocation); + TS_XR_CHECK(xrLocateSpace, mSpaces.at(controllerIndex), space, time, &spaceLocation); constexpr XrSpaceLocationFlags checkFlags{ XR_SPACE_LOCATION_POSITION_VALID_BIT | XR_SPACE_LOCATION_POSITION_TRACKED_BIT | @@ -148,7 +148,7 @@ void Controllers::updateActionStatePose(const XrSession session, const XrAction .subactionPath = path }; - LOGGER_XR(xrGetActionStatePose, session, &actionStateGetInfo, &state); + TS_XR_CHECK(xrGetActionStatePose, session, &actionStateGetInfo, &state); } void Controllers::updateActionStateFloat(const XrSession session, const XrAction action, const XrPath path, XrActionStateFloat& state) @@ -159,7 +159,7 @@ void Controllers::updateActionStateFloat(const XrSession session, const XrAction .subactionPath = path }; - LOGGER_XR(xrGetActionStateFloat, session, &actionStateGetInfo, &state); + TS_XR_CHECK(xrGetActionStateFloat, session, &actionStateGetInfo, &state); } void Controllers::createAction(const std::string& actionName, const std::string& localizedActionName, const XrActionType type, XrAction& action) @@ -174,6 +174,6 @@ void Controllers::createAction(const std::string& actionName, const std::string& strcpy(const_cast(actionCreateInfo.actionName), actionName.data()); strcpy(const_cast(actionCreateInfo.localizedActionName), localizedActionName.data()); - LOGGER_XR(xrCreateAction, mActionSet, &actionCreateInfo, &action); + TS_XR_CHECK(xrCreateAction, mActionSet, &actionCreateInfo, &action); } } \ No newline at end of file diff --git a/engine/src/core/controllers.h b/engine/src/core/controllers.h index b42134d..544979e 100644 --- a/engine/src/core/controllers.h +++ b/engine/src/core/controllers.h @@ -9,7 +9,7 @@ namespace ts { class Controllers final { - NOT_COPYABLE_AND_MOVEABLE(Controllers); + TS_NOT_COPYABLE_AND_MOVEABLE(Controllers); static constexpr std::string_view actionSetName{"actionset"}; static constexpr std::string_view localizedActionSetName{"Actions"}; diff --git a/engine/src/core/core.cpp b/engine/src/core/core.cpp index 3ee9037..689d5c6 100644 --- a/engine/src/core/core.cpp +++ b/engine/src/core/core.cpp @@ -1,5 +1,7 @@ #include "tsengine/core.h" +#include "globals.hpp" + #include "tsengine/asset_store.h" #include "context.h" #include "window.h" @@ -11,16 +13,20 @@ #include "renderer.h" #include "tests_core_adapter.h" -#include "tsengine/ecs/ecs.hpp" -#include "ecs/movement_system.hpp" -#include "ecs/render_system.hpp" - -#ifdef CYBSDK_FOUND - #include "CVirt.h" -#endif +#include "tsengine/ecs/ecs.h" +#include "ecs/systems/movement_system.hpp" +#include "ecs/systems/render_system.hpp" namespace ts { +bool Engine::init(const char*& gameName, unsigned& width, unsigned& height) +{ + return true; +} + +void Engine::close() +{} + namespace { std::mutex engineInit; @@ -74,12 +80,12 @@ int run(Engine* const game) try compileShaders("assets/shaders"); - auto player = ts::gRegistry.createEntity(); + auto player = gReg.createEntity(); player.setTag("player"); player.addComponent(); - player.addComponent(2.f); + player.addComponent(7.f); - auto grid = ts::gRegistry.createEntity(); + auto grid = gReg.createEntity(); grid.setTag("grid"); grid.addComponent>(); @@ -89,11 +95,11 @@ int run(Engine* const game) try Context ctx{gameName}; ctx.createOpenXrContext().createVulkanContext(); - gRegistry.addSystem(); - gRegistry.addSystem(); - gRegistry.addSystem(ctx.getUniformBufferOffsetAlignment()); + gReg.addSystem(); + gReg.addSystem(); + gReg.addSystem(ctx.getUniformBufferOffsetAlignment()); - gRegistry.update(); + gReg.update(); AssetStore::Models::load(); @@ -113,38 +119,13 @@ int run(Engine* const game) try TS_LOG("tsengine initialization completed successfully"); window->show(); - math::Vec3 cameraPosition{1.f}; auto loop = true; auto previousTime = std::chrono::high_resolution_clock::now(); auto startTime = std::chrono::steady_clock::now(); // TODO: firstly render to the window then copy to the headset - -#ifdef CYBSDK_FOUND - const auto device = CybSDK::Virt::FindDevice(); - if (device == nullptr) - { - LOGGER_ERR("Cyberith Virtualizer device not found"); - } - - const auto info = device->GetDeviceInfo(); - - const auto virtName = info.ProductName; - const auto virtNameLen = wcslen(virtName); - std::vector virtBuf(virtNameLen); - wcstombs(virtBuf.data(), virtName, virtNameLen); - std::string virtConvertedName(virtBuf.begin(), virtBuf.end()); - LOGGER_LOG(std::format("Device found {} Firmware Version: {}.{}", virtConvertedName, static_cast(info.MajorVersion), static_cast(info.MinorVersion)).c_str()); - - - if (!device->Open()) - { - LOGGER_ERR("Unable to connect to Cyberith Virtualizer"); - } -#endif - while (loop) { -#ifdef TESTER_ADAPTER +#ifdef TESTER_ADAPTER if ((testerAdapter != nullptr) && isRenderingStarted) { if (std::chrono::steady_clock::now() >= (startTime + testerAdapter->renderingDuration)) @@ -174,12 +155,10 @@ int run(Engine* const game) try const long long elapsedNanoseconds = std::chrono::duration_cast(nowTime - previousTime).count(); static constexpr auto nanosecondsPerSecond = 1e9f; - const auto deltaTime = static_cast(elapsedNanoseconds) / nanosecondsPerSecond; + const auto dt = static_cast(elapsedNanoseconds) / nanosecondsPerSecond; previousTime = nowTime; - gRegistry.update(); - - gRegistry.getSystem().update(deltaTime); + gReg.update(); uint32_t swapchainImageIndex; const auto frameResult = headset.beginFrame(swapchainImageIndex); @@ -192,50 +171,10 @@ int run(Engine* const game) try } #endif -#ifdef CYBSDK_FOUND - const auto ringHeight = device->GetPlayerHeight(); - auto ringAngle = device->GetPlayerOrientation(); - const auto movementDirection = device->GetMovementDirection(); - const auto movementSpeed = device->GetMovementSpeed(); - - if (movementSpeed > 0.f) - { - ringAngle *= 2 * std::numbers::pi_v; - auto offsetX = std::sin(ringAngle) * movementSpeed * flySpeedMultiplier * deltaTime; - auto offsetZ = -(std::cos(ringAngle) * movementSpeed * flySpeedMultiplier * deltaTime); - - if (movementDirection == -1.f) - { - offsetX *= -1; - offsetZ *= -1; - } - cameraPosition.x += offsetX; - cameraPosition.z += offsetZ; - } -#else controllers.sync(headset.getXrSpace(), headset.getXrFrameState().predictedDisplayTime); + gReg.getSystem().update(dt, controllers); - for (size_t controllerIndex{}; controllerIndex < controllers.controllerCount; ++controllerIndex) - { - const auto flyState = controllers.getFlyState(controllerIndex); - if (flyState) - { - const auto controllerPose = controllers.getPose(controllerIndex)[2]; - - if ((!controllerPose.isNan()) || (controllerPose == math::Vec3{0.f})) - { - const math::Vec3 forward{controllers.getPose(controllerIndex)[2]}; - cameraPosition += forward * player.getComponent().velocity * deltaTime; - } - else - { - TS_WARN(std::format("Controller no. {} can not be located.", controllerIndex).c_str()); - } - } - } -#endif - - renderer.render(cameraPosition, swapchainImageIndex); + renderer.render(swapchainImageIndex); const auto mirrorResult = mirrorView.render(swapchainImageIndex); const auto isMirrorViewVisible = (mirrorResult == MirrorView::RenderResult::VISIBLE); diff --git a/engine/src/core/data_buffer.cpp b/engine/src/core/data_buffer.cpp index 8503a7e..85d71a1 100644 --- a/engine/src/core/data_buffer.cpp +++ b/engine/src/core/data_buffer.cpp @@ -38,7 +38,7 @@ void DataBuffer::createDataBuffer(const VkBufferUsageFlags bufferUsageFlags, con .usage = bufferUsageFlags, .sharingMode = VK_SHARING_MODE_EXCLUSIVE }; - LOGGER_VK(vkCreateBuffer, device, &bufferCreateInfo, nullptr, &mBuffer); + TS_VK_CHECK(vkCreateBuffer, device, &bufferCreateInfo, nullptr, &mBuffer); VkMemoryRequirements memoryRequirements; vkGetBufferMemoryRequirements(device, mBuffer, &memoryRequirements); @@ -55,9 +55,9 @@ void DataBuffer::createDataBuffer(const VkBufferUsageFlags bufferUsageFlags, con .allocationSize = memoryRequirements.size, .memoryTypeIndex = suitableMemoryTypeIndex }; - LOGGER_VK(vkAllocateMemory, device, &memoryAllocateInfo, nullptr, &mDeviceMemory); + TS_VK_CHECK(vkAllocateMemory, device, &memoryAllocateInfo, nullptr, &mDeviceMemory); - LOGGER_VK(vkBindBufferMemory, device, mBuffer, mDeviceMemory, 0); + TS_VK_CHECK(vkBindBufferMemory, device, mBuffer, mDeviceMemory, 0); } void DataBuffer::copyTo(const DataBuffer& target, VkCommandBuffer commandBuffer, VkQueue queue) const @@ -66,29 +66,29 @@ void DataBuffer::copyTo(const DataBuffer& target, VkCommandBuffer commandBuffer, .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT }; - LOGGER_VK(vkBeginCommandBuffer, commandBuffer, &beginInfo); + TS_VK_CHECK(vkBeginCommandBuffer, commandBuffer, &beginInfo); VkBufferCopy copyRegion{ .size = mSize }; vkCmdCopyBuffer(commandBuffer, mBuffer, target.getBuffer(), 1, ©Region); - LOGGER_VK(vkEndCommandBuffer, commandBuffer); + TS_VK_CHECK(vkEndCommandBuffer, commandBuffer); VkSubmitInfo submitInfo{ .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .commandBufferCount = 1, .pCommandBuffers = &commandBuffer }; - LOGGER_VK(vkQueueSubmit, queue, 1, &submitInfo, VK_NULL_HANDLE); + TS_VK_CHECK(vkQueueSubmit, queue, 1, &submitInfo, VK_NULL_HANDLE); - LOGGER_VK(vkQueueWaitIdle, queue); + TS_VK_CHECK(vkQueueWaitIdle, queue); } void* DataBuffer::map() const { void* data; - LOGGER_VK(vkMapMemory, mCtx.getVkDevice(), mDeviceMemory, 0, mSize, 0, &data); + TS_VK_CHECK(vkMapMemory, mCtx.getVkDevice(), mDeviceMemory, 0, mSize, 0, &data); return data; } diff --git a/engine/src/core/data_buffer.h b/engine/src/core/data_buffer.h index 11f6774..89c99ea 100644 --- a/engine/src/core/data_buffer.h +++ b/engine/src/core/data_buffer.h @@ -10,7 +10,7 @@ class Context; class DataBuffer final { - NOT_COPYABLE_AND_MOVEABLE(DataBuffer); + TS_NOT_COPYABLE_AND_MOVEABLE(DataBuffer); public: DataBuffer(const Context& ctx); diff --git a/engine/src/core/headset.cpp b/engine/src/core/headset.cpp index f5507c6..c9a3013 100644 --- a/engine/src/core/headset.cpp +++ b/engine/src/core/headset.cpp @@ -95,10 +95,10 @@ Headset::BeginFrameResult Headset::beginFrame(uint32_t& swapchainImageIndex) mXrFrameState.type = XR_TYPE_FRAME_STATE; XrFrameWaitInfo frameWaitInfo{XR_TYPE_FRAME_WAIT_INFO}; - LOGGER_XR(xrWaitFrame, mXrSession, &frameWaitInfo, &mXrFrameState); + TS_XR_CHECK(xrWaitFrame, mXrSession, &frameWaitInfo, &mXrFrameState); XrFrameBeginInfo frameBeginInfo{XR_TYPE_FRAME_BEGIN_INFO}; - LOGGER_XR(xrBeginFrame, mXrSession, &frameBeginInfo); + TS_XR_CHECK(xrBeginFrame, mXrSession, &frameBeginInfo); if (!mXrFrameState.shouldRender) { @@ -113,7 +113,7 @@ Headset::BeginFrameResult Headset::beginFrame(uint32_t& swapchainImageIndex) .space = mXrSpace }; uint32_t viewCount; - LOGGER_XR(xrLocateViews, + TS_XR_CHECK(xrLocateViews, mXrSession, &viewLocateInfo, &mXrViewState, @@ -139,13 +139,13 @@ Headset::BeginFrameResult Headset::beginFrame(uint32_t& swapchainImageIndex) } XrSwapchainImageAcquireInfo swapchainImageAcquireInfo{ XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO }; - LOGGER_XR(xrAcquireSwapchainImage, mXrSwapchain, &swapchainImageAcquireInfo, &swapchainImageIndex); + TS_XR_CHECK(xrAcquireSwapchainImage, mXrSwapchain, &swapchainImageAcquireInfo, &swapchainImageIndex); XrSwapchainImageWaitInfo swapchainImageWaitInfo{ .type = XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO, .timeout = XR_INFINITE_DURATION, }; - LOGGER_XR(xrWaitSwapchainImage, mXrSwapchain, &swapchainImageWaitInfo); + TS_XR_CHECK(xrWaitSwapchainImage, mXrSwapchain, &swapchainImageWaitInfo); return BeginFrameResult::RENDER_FULLY; } @@ -236,7 +236,7 @@ void Headset::createVkRenderPass() }; const auto vkDevice = mCtx.getVkDevice(); - LOGGER_VK(vkCreateRenderPass, vkDevice, &renderPassCreateInfo, nullptr, &mVkRenderPass); + TS_VK_CHECK(vkCreateRenderPass, vkDevice, &renderPassCreateInfo, nullptr, &mVkRenderPass); } void Headset::createXrSession() @@ -257,7 +257,7 @@ void Headset::createXrSession() }; const auto pXrInstance{mCtx.getXrInstance()}; - LOGGER_XR(xrCreateSession, pXrInstance, &sessionCreateInfo, &mXrSession); + TS_XR_CHECK(xrCreateSession, pXrInstance, &sessionCreateInfo, &mXrSession); } void Headset::createXrSpace() @@ -269,12 +269,12 @@ void Headset::createXrSpace() .poseInReferenceSpace = identity }; - LOGGER_XR(xrCreateReferenceSpace, mXrSession, &referenceSpaceCreateInfo, &mXrSpace); + TS_XR_CHECK(xrCreateReferenceSpace, mXrSession, &referenceSpaceCreateInfo, &mXrSpace); } void Headset::createViews() { - LOGGER_XR(xrEnumerateViewConfigurationViews, + TS_XR_CHECK(xrEnumerateViewConfigurationViews, mCtx.getXrInstance(), mCtx.getXrSystemId(), mCtx.xrViewType, @@ -288,7 +288,7 @@ void Headset::createViews() eyeInfo.next = nullptr; } - LOGGER_XR(xrEnumerateViewConfigurationViews, + TS_XR_CHECK(xrEnumerateViewConfigurationViews, mCtx.getXrInstance(), mCtx.getXrSystemId(), mCtx.xrViewType, @@ -308,10 +308,10 @@ void Headset::createXrSwapchain() createViews(); uint32_t formatCount{}; - LOGGER_XR(xrEnumerateSwapchainFormats, mXrSession, 0, &formatCount, nullptr); + TS_XR_CHECK(xrEnumerateSwapchainFormats, mXrSession, 0, &formatCount, nullptr); std::vector formats(formatCount); - LOGGER_XR(xrEnumerateSwapchainFormats, mXrSession, formatCount, &formatCount, formats.data()); + TS_XR_CHECK(xrEnumerateSwapchainFormats, mXrSession, formatCount, &formatCount, formats.data()); bool isFormatFound{}; for (const auto& format : formats) @@ -361,10 +361,10 @@ void Headset::createXrSwapchain() .mipCount = 1 }; - LOGGER_XR(xrCreateSwapchain, mXrSession, &swapchainCreateInfo, &mXrSwapchain); + TS_XR_CHECK(xrCreateSwapchain, mXrSession, &swapchainCreateInfo, &mXrSwapchain); uint32_t swapchainImageCount; - LOGGER_XR(xrEnumerateSwapchainImages, mXrSwapchain, 0, &swapchainImageCount, nullptr); + TS_XR_CHECK(xrEnumerateSwapchainImages, mXrSwapchain, 0, &swapchainImageCount, nullptr); std::vector swapchainImages; swapchainImages.resize(swapchainImageCount); @@ -374,7 +374,7 @@ void Headset::createXrSwapchain() } auto pXrSwapchainImageBaseHeader{reinterpret_cast(swapchainImages.data())}; - LOGGER_XR(xrEnumerateSwapchainImages, + TS_XR_CHECK(xrEnumerateSwapchainImages, mXrSwapchain, static_cast(swapchainImages.size()), &swapchainImageCount, @@ -421,7 +421,7 @@ void Headset::endFrame(bool skipReleaseSwapchainImage) const if (!skipReleaseSwapchainImage) { XrSwapchainImageReleaseInfo swapchainImageReleaseInfo{ XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO }; - LOGGER_XR(xrReleaseSwapchainImage, mXrSwapchain, &swapchainImageReleaseInfo); + TS_XR_CHECK(xrReleaseSwapchainImage, mXrSwapchain, &swapchainImageReleaseInfo); } XrCompositionLayerProjection compositionLayerProjection{ @@ -447,7 +447,7 @@ void Headset::endFrame(bool skipReleaseSwapchainImage) const .layerCount = static_cast(layers.size()), .layers = layers.data(), }; - LOGGER_XR(xrEndFrame, mXrSession, &frameEndInfo); + TS_XR_CHECK(xrEndFrame, mXrSession, &frameEndInfo); } [[nodiscard]] VkExtent2D Headset::getEyeResolution(int32_t eyeIndex) const @@ -462,12 +462,12 @@ void Headset::beginSession() const .type = XR_TYPE_SESSION_BEGIN_INFO, .primaryViewConfigurationType = mCtx.xrViewType }; - LOGGER_XR(xrBeginSession, mXrSession, &sessionBeginInfo); + TS_XR_CHECK(xrBeginSession, mXrSession, &sessionBeginInfo); } void Headset::endSession() const { - LOGGER_XR(xrEndSession, mXrSession); + TS_XR_CHECK(xrEndSession, mXrSession); } } // namespace ts diff --git a/engine/src/core/headset.h b/engine/src/core/headset.h index d967e9f..3d1af53 100644 --- a/engine/src/core/headset.h +++ b/engine/src/core/headset.h @@ -14,7 +14,7 @@ class RenderTarget; class Headset final { - NOT_COPYABLE_AND_MOVEABLE(Headset); + TS_NOT_COPYABLE_AND_MOVEABLE(Headset); static constexpr XrReferenceSpaceType spaceType{XR_REFERENCE_SPACE_TYPE_STAGE}; static constexpr VkFormat colorFormat{VK_FORMAT_R8G8B8A8_SRGB}; diff --git a/engine/src/core/image_buffer.cpp b/engine/src/core/image_buffer.cpp index 6f52100..945b1ee 100644 --- a/engine/src/core/image_buffer.cpp +++ b/engine/src/core/image_buffer.cpp @@ -54,7 +54,7 @@ void ImageBuffer::createImage( const auto device = mCtx.getVkDevice(); - LOGGER_VK(vkCreateImage, device, &imageCreateInfo, nullptr, &mImage); + TS_VK_CHECK(vkCreateImage, device, &imageCreateInfo, nullptr, &mImage); VkMemoryRequirements memoryRequirements; vkGetImageMemoryRequirements(device, mImage, &memoryRequirements); @@ -74,8 +74,8 @@ void ImageBuffer::createImage( .allocationSize = memoryRequirements.size, .memoryTypeIndex = suitableMemoryTypeIndex }; - LOGGER_VK(vkAllocateMemory, device, &memoryAllocateInfo, nullptr, &mDeviceMemory); - LOGGER_VK(vkBindImageMemory, device, mImage, mDeviceMemory, 0); + TS_VK_CHECK(vkAllocateMemory, device, &memoryAllocateInfo, nullptr, &mDeviceMemory); + TS_VK_CHECK(vkBindImageMemory, device, mImage, mDeviceMemory, 0); VkImageViewCreateInfo imageViewCreateInfo{ .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, @@ -97,6 +97,6 @@ void ImageBuffer::createImage( } }; - LOGGER_VK(vkCreateImageView, device, &imageViewCreateInfo, nullptr, &mImageView); + TS_VK_CHECK(vkCreateImageView, device, &imageViewCreateInfo, nullptr, &mImageView); } } diff --git a/engine/src/core/image_buffer.h b/engine/src/core/image_buffer.h index 7511e89..503f5f8 100644 --- a/engine/src/core/image_buffer.h +++ b/engine/src/core/image_buffer.h @@ -10,7 +10,7 @@ class Context; class ImageBuffer final { - NOT_COPYABLE_AND_MOVEABLE(ImageBuffer); + TS_NOT_COPYABLE_AND_MOVEABLE(ImageBuffer); public: ImageBuffer(const Context& ctx) : mCtx{ctx} diff --git a/engine/src/core/mirror_view.cpp b/engine/src/core/mirror_view.cpp index a15484a..68179fe 100644 --- a/engine/src/core/mirror_view.cpp +++ b/engine/src/core/mirror_view.cpp @@ -285,7 +285,7 @@ void MirrorView::createSurface() .hwnd = winWindow->getHwnd() }; - LOGGER_VK(vkCreateWin32SurfaceKHR, mCtx.getVkInstance(), &ci, nullptr, &mSurface); + TS_VK_CHECK(vkCreateWin32SurfaceKHR, mCtx.getVkInstance(), &ci, nullptr, &mSurface); #else #error not implemented #endif @@ -320,7 +320,7 @@ void MirrorView::getSurfaceCapabilitiesAndExtent() { const auto physicalDevice = mCtx.getVkPhysicalDevice(); - LOGGER_VK(vkGetPhysicalDeviceSurfaceCapabilitiesKHR, physicalDevice, mSurface, &mSurfaceCapabilities); + TS_VK_CHECK(vkGetPhysicalDeviceSurfaceCapabilitiesKHR, physicalDevice, mSurface, &mSurfaceCapabilities); if (!(mSurfaceCapabilities.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_DST_BIT)) { @@ -355,10 +355,10 @@ void MirrorView::pickSurfaceFormat() const auto physicalDevice = mCtx.getVkPhysicalDevice(); uint32_t surfaceFormatCount{}; - LOGGER_VK(vkGetPhysicalDeviceSurfaceFormatsKHR, physicalDevice, mSurface, &surfaceFormatCount, nullptr); + TS_VK_CHECK(vkGetPhysicalDeviceSurfaceFormatsKHR, physicalDevice, mSurface, &surfaceFormatCount, nullptr); std::vector surfaceFormats(surfaceFormatCount); - LOGGER_VK(vkGetPhysicalDeviceSurfaceFormatsKHR, physicalDevice, mSurface, &surfaceFormatCount, surfaceFormats.data()); + TS_VK_CHECK(vkGetPhysicalDeviceSurfaceFormatsKHR, physicalDevice, mSurface, &surfaceFormatCount, surfaceFormats.data()); bool surfaceFormatFound{}; for (const VkSurfaceFormatKHR& surfaceFormatCandidate : surfaceFormats) @@ -401,12 +401,12 @@ void MirrorView::createSwapchain() .presentMode = presentMode, .clipped = VK_TRUE, }; - LOGGER_VK(vkCreateSwapchainKHR, device, &swapchainCreateInfo, nullptr, &mSwapchain); + TS_VK_CHECK(vkCreateSwapchainKHR, device, &swapchainCreateInfo, nullptr, &mSwapchain); uint32_t swapchainImageCount{}; - LOGGER_VK(vkGetSwapchainImagesKHR, device, mSwapchain, &swapchainImageCount, nullptr); + TS_VK_CHECK(vkGetSwapchainImagesKHR, device, mSwapchain, &swapchainImageCount, nullptr); mSwapchainImages.resize(swapchainImageCount); - LOGGER_VK(vkGetSwapchainImagesKHR, device, mSwapchain, &swapchainImageCount, mSwapchainImages.data()); + TS_VK_CHECK(vkGetSwapchainImagesKHR, device, mSwapchain, &swapchainImageCount, mSwapchainImages.data()); } } diff --git a/engine/src/core/mirror_view.h b/engine/src/core/mirror_view.h index 801b4bf..c5e363e 100644 --- a/engine/src/core/mirror_view.h +++ b/engine/src/core/mirror_view.h @@ -13,7 +13,7 @@ class Renderer; class MirrorView final { - NOT_COPYABLE_AND_MOVEABLE(MirrorView); + TS_NOT_COPYABLE_AND_MOVEABLE(MirrorView); static constexpr VkFormat colorFormat{VK_FORMAT_B8G8R8A8_SRGB}; static constexpr VkPresentModeKHR presentMode{VK_PRESENT_MODE_FIFO_KHR}; diff --git a/engine/src/core/pipeline.cpp b/engine/src/core/pipeline.cpp index 377cd36..02804d3 100644 --- a/engine/src/core/pipeline.cpp +++ b/engine/src/core/pipeline.cpp @@ -26,7 +26,7 @@ void loadShaderFromFile(const VkDevice device, const std::string& fileName, VkSh .pCode = reinterpret_cast(code.data()) }; - LOGGER_VK(vkCreateShaderModule, device, &shaderModuleCreateInfo, nullptr, &shaderModule); + TS_VK_CHECK(vkCreateShaderModule, device, &shaderModuleCreateInfo, nullptr, &shaderModule); } } @@ -162,7 +162,7 @@ void Pipeline::createPipeline( .layout = pipelinelineLayout, .renderPass = renderPass, }; - LOGGER_VK(vkCreateGraphicsPipelines, device, nullptr, 1, &graphicsPipelineCreateInfo, nullptr, &mPipeline); + TS_VK_CHECK(vkCreateGraphicsPipelines, device, nullptr, 1, &graphicsPipelineCreateInfo, nullptr, &mPipeline); vkDestroyShaderModule(device, vertexShaderModule, nullptr); vkDestroyShaderModule(device, fragmentShaderModule, nullptr); diff --git a/engine/src/core/pipeline.h b/engine/src/core/pipeline.h index 8f9156e..659ee48 100644 --- a/engine/src/core/pipeline.h +++ b/engine/src/core/pipeline.h @@ -9,7 +9,7 @@ class Context; class Pipeline final { - NOT_COPYABLE_AND_MOVEABLE(Pipeline); + TS_NOT_COPYABLE_AND_MOVEABLE(Pipeline); public: Pipeline(const Context& ctx); diff --git a/engine/src/core/render_target.cpp b/engine/src/core/render_target.cpp index fbe71ac..848d957 100644 --- a/engine/src/core/render_target.cpp +++ b/engine/src/core/render_target.cpp @@ -43,7 +43,7 @@ void RenderTarget::createRenderTarget( } }; - LOGGER_VK(vkCreateImageView, mDevice, &imageViewCreateInfo, nullptr, &mImageView); + TS_VK_CHECK(vkCreateImageView, mDevice, &imageViewCreateInfo, nullptr, &mImageView); const std::array attachments{colorImageView, depthImageView, mImageView}; @@ -57,6 +57,6 @@ void RenderTarget::createRenderTarget( .layers = 1 }; - LOGGER_VK(vkCreateFramebuffer, mDevice, &framebufferCreateInfo, nullptr, &mFramebuffer); + TS_VK_CHECK(vkCreateFramebuffer, mDevice, &framebufferCreateInfo, nullptr, &mFramebuffer); } } \ No newline at end of file diff --git a/engine/src/core/render_target.h b/engine/src/core/render_target.h index 761df29..a4e5341 100644 --- a/engine/src/core/render_target.h +++ b/engine/src/core/render_target.h @@ -7,7 +7,7 @@ namespace ts { class RenderTarget final { - NOT_COPYABLE_AND_MOVEABLE(RenderTarget); + TS_NOT_COPYABLE_AND_MOVEABLE(RenderTarget); public: RenderTarget(VkDevice device, VkImage image) : mDevice(device), mImage(image) diff --git a/engine/src/core/renderer.cpp b/engine/src/core/renderer.cpp index 0145e5e..045af54 100644 --- a/engine/src/core/renderer.cpp +++ b/engine/src/core/renderer.cpp @@ -1,5 +1,6 @@ #include "renderer.h" +#include "globals.hpp" #include "tsengine/math.hpp" #include "context.h" @@ -15,7 +16,7 @@ #include "tsengine/ecs/components/renderer_component.hpp" #include "tsengine/ecs/components/mesh_component.hpp" -#include "ecs/render_system.hpp" +#include "ecs/systems/render_system.hpp" namespace ts { @@ -68,7 +69,7 @@ void Renderer::createRenderer() .flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, .queueFamilyIndex = mCtx.getVkGraphicsQueueFamilyIndex() }; - LOGGER_VK(vkCreateCommandPool, device, &commandPoolCreateInfo, nullptr, &mCommandPool); + TS_VK_CHECK(vkCreateCommandPool, device, &commandPoolCreateInfo, nullptr, &mCommandPool); const std::array descriptorPoolSizes{ VkDescriptorPoolSize{ @@ -87,7 +88,7 @@ void Renderer::createRenderer() .poolSizeCount = static_cast(descriptorPoolSizes.size()), .pPoolSizes = descriptorPoolSizes.data(), }; - LOGGER_VK(vkCreateDescriptorPool, device, &descriptorPoolCreateInfo, nullptr, &mDescriptorPool); + TS_VK_CHECK(vkCreateDescriptorPool, device, &descriptorPoolCreateInfo, nullptr, &mDescriptorPool); const std::array descriptorSetLayoutBindings{ VkDescriptorSetLayoutBinding{ @@ -127,7 +128,7 @@ void Renderer::createRenderer() .bindingCount = static_cast(descriptorSetLayoutBindings.size()), .pBindings = descriptorSetLayoutBindings.data() }; - LOGGER_VK(vkCreateDescriptorSetLayout, device, &descriptorSetLayoutCreateInfo, nullptr, &mDescriptorSetLayout); + TS_VK_CHECK(vkCreateDescriptorSetLayout, device, &descriptorSetLayoutCreateInfo, nullptr, &mDescriptorSetLayout); const VkPipelineLayoutCreateInfo pipelinelineLayoutCreateInfo{ .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, @@ -136,12 +137,17 @@ void Renderer::createRenderer() .pushConstantRangeCount = static_cast(pushConstantRanges.size()), .pPushConstantRanges = pushConstantRanges.data(), }; - LOGGER_VK(vkCreatePipelineLayout, device, &pipelinelineLayoutCreateInfo, nullptr, &mPipelineLayout); + TS_VK_CHECK(vkCreatePipelineLayout, device, &pipelinelineLayoutCreateInfo, nullptr, &mPipelineLayout); for (auto& renderProcess : mRenderProcesses) { renderProcess = std::make_unique(mCtx, mHeadset); - renderProcess->createRendererProcess(mCommandPool, mDescriptorPool, mDescriptorSetLayout, gRegistry.getSystem().getSystemEntities().size()); + renderProcess->createRendererProcess( + mCommandPool, + mDescriptorPool, + mDescriptorSetLayout, + gReg.getSystem().getSystemEntities().size(), + gReg.getSystem().getSystemEntities().size()); } mGridPipeline = std::make_shared(mCtx); @@ -210,20 +216,20 @@ void Renderer::createRenderer() initRendererFrontend(); } -void Renderer::render(const math::Vec3& cameraPosition, const size_t swapchainImageIndex) +void Renderer::render(const size_t swapchainImageIndex) { mCurrentRenderProcessIndex = (mCurrentRenderProcessIndex + 1) % mRenderProcesses.size(); auto& renderProcess = mRenderProcesses.at(mCurrentRenderProcessIndex); const auto busyFence = renderProcess->getFence(); - LOGGER_VK(vkWaitForFences, mCtx.getVkDevice(), 1, &busyFence, true, std::numeric_limits::max()); - LOGGER_VK(vkResetFences, mCtx.getVkDevice(), 1, &busyFence); + TS_VK_CHECK(vkWaitForFences, mCtx.getVkDevice(), 1, &busyFence, true, std::numeric_limits::max()); + TS_VK_CHECK(vkResetFences, mCtx.getVkDevice(), 1, &busyFence); const auto commandBuffer = renderProcess->getCommandBuffer(); const VkCommandBufferBeginInfo commandBufferBeginInfo{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; - LOGGER_VK(vkBeginCommandBuffer, commandBuffer, &commandBufferBeginInfo); + TS_VK_CHECK(vkBeginCommandBuffer, commandBuffer, &commandBufferBeginInfo); - updateUniformData(cameraPosition, renderProcess); + updateUniformData(renderProcess); const std::array clearValues{ VkClearValue{.color = {0.01f, 0.01f, 0.01f, 1.f}}, @@ -267,7 +273,7 @@ void Renderer::render(const math::Vec3& cameraPosition, const size_t swapchainIm const auto descriptorSet = renderProcess->getDescriptorSet(); - gRegistry.getSystem().update(commandBuffer, descriptorSet); + gReg.getSystem().update(commandBuffer, descriptorSet); vkCmdEndRenderPass(commandBuffer); } @@ -276,7 +282,7 @@ void Renderer::submit(const bool useSemaphores) const { const auto& renderProcess = mRenderProcesses.at(mCurrentRenderProcessIndex); const auto commandBuffer = renderProcess->getCommandBuffer(); - LOGGER_VK(vkEndCommandBuffer, commandBuffer); + TS_VK_CHECK(vkEndCommandBuffer, commandBuffer); constexpr VkPipelineStageFlags waitStages{VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT}; const auto drawableSemaphore = renderProcess->getDrawableSemaphore(); @@ -293,7 +299,7 @@ void Renderer::submit(const bool useSemaphores) const .pSignalSemaphores = useSemaphores ? &presentableSemaphore : nullptr }; - LOGGER_VK(vkQueueSubmit, mCtx.getVkGraphicsQueue(), 1, &submitInfo, renderProcess->getFence()); + TS_VK_CHECK(vkQueueSubmit, mCtx.getVkGraphicsQueue(), 1, &submitInfo, renderProcess->getFence()); } VkSemaphore Renderer::getCurrentDrawableSemaphore() const @@ -347,15 +353,22 @@ void Renderer::createVertexIndexBuffer() stagingBuffer.reset(); } -void Renderer::updateUniformData(const math::Vec3& cameraPosition, const std::unique_ptr& renderProcess) +void Renderer::updateUniformData(const std::unique_ptr& renderProcess) { - const auto entities = gRegistry.getSystem().getSystemEntities(); - for (size_t modelIndex{}; modelIndex < entities.size(); ++modelIndex) + const auto assets = gReg.getSystem().getSystemEntities(); + for (size_t modelIdx{}; modelIdx < assets.size(); ++modelIdx) { - renderProcess->mIndividualUniformData.at(modelIndex).model = entities.at(modelIndex).getComponent().modelMat; + renderProcess->mIndividualUniformData.at(modelIdx).model = assets.at(modelIdx).getComponent().modelMat; } - renderProcess->mCommonUniformData.cameraPosition = cameraPosition; + const auto lights = gReg.getSystem().getSystemEntities(); + for (size_t lightIdx{}; lightIdx < lights.size(); ++lightIdx) + { + renderProcess->mLightsUniformData.positions.at(lightIdx) = lights.at(lightIdx).getComponent().pos; + } + + const auto cameraPos = gReg.getEntityByTag("player").getComponent().pos; + renderProcess->mCommonUniformData.cameraPosition = cameraPos; for (size_t eyeIndex{}; eyeIndex < mHeadset.getEyeCount(); ++eyeIndex) { renderProcess->mCommonUniformData.viewMats.at(eyeIndex) = mHeadset.getEyeViewMatrix(eyeIndex); @@ -366,7 +379,7 @@ void Renderer::updateUniformData(const math::Vec3& cameraPosition, const std::un } void Renderer::initRendererFrontend() { - auto& renderSystem = gRegistry.getSystem(); + auto& renderSystem = gReg.getSystem(); renderSystem.mpGridPipeline = mGridPipeline; renderSystem.mpNormalLightingPipeline = mNormalLightingPipeline; renderSystem.mpPbrPipeline = mPbrPipeline; diff --git a/engine/src/core/renderer.h b/engine/src/core/renderer.h index 9db774b..df7a403 100644 --- a/engine/src/core/renderer.h +++ b/engine/src/core/renderer.h @@ -17,7 +17,7 @@ class DataBuffer; class Renderer { - NOT_COPYABLE_AND_MOVEABLE(Renderer); + TS_NOT_COPYABLE_AND_MOVEABLE(Renderer); static constexpr size_t framesInFlightCount{2}; @@ -27,7 +27,7 @@ class Renderer virtual ~Renderer(); void createRenderer(); - void render(const math::Vec3& cameraPosition, const size_t swapchainImageIndex); + void render(const size_t swapchainImageIndex); void submit(const bool useSemaphores) const; [[nodiscard]] VkSemaphore getCurrentDrawableSemaphore() const; @@ -36,7 +36,7 @@ class Renderer private: void createVertexIndexBuffer(); - void updateUniformData(const math::Vec3& cameraMatrix, const std::unique_ptr& renderProcess); + void updateUniformData(const std::unique_ptr& renderProcess); void initRendererFrontend(); const Context& mCtx; diff --git a/engine/src/core/renderer_process.cpp b/engine/src/core/renderer_process.cpp index 9fa971f..0b34e7c 100644 --- a/engine/src/core/renderer_process.cpp +++ b/engine/src/core/renderer_process.cpp @@ -1,5 +1,7 @@ #include "renderer_process.h" +#include "globals.hpp" + #include "context.h" #include "vulkan_tools/vulkan_functions.h" #include "tsengine/logger.h" @@ -7,9 +9,9 @@ #include "data_buffer.h" #include "headset.h" -#include "tsengine/ecs/ecs.hpp" +#include "tsengine/ecs/ecs.h" #include "tsengine/ecs/components/renderer_component.hpp" -#include "ecs/render_system.hpp" +#include "ecs/systems/render_system.hpp" namespace ts { @@ -45,12 +47,13 @@ RenderProcess::~RenderProcess() } void RenderProcess::createRendererProcess( - VkCommandPool commandPool, - VkDescriptorPool descriptorPool, - VkDescriptorSetLayout descriptorSetLayout, - size_t modelCount) + const VkCommandPool commandPool, + const VkDescriptorPool descriptorPool, + const VkDescriptorSetLayout descriptorSetLayout, + const size_t modelsNum, + const size_t lightsNum) { - mIndividualUniformData.resize(modelCount); + mIndividualUniformData.resize(modelsNum); const auto device = mCtx.getVkDevice(); @@ -60,18 +63,18 @@ void RenderProcess::createRendererProcess( .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY, .commandBufferCount = 1, }; - LOGGER_VK(vkAllocateCommandBuffers, device, &commandBufferAllocateInfo, &mCommandBuffer); + TS_VK_CHECK(vkAllocateCommandBuffers, device, &commandBufferAllocateInfo, &mCommandBuffer); const VkSemaphoreCreateInfo semaphoreCreateInfo{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO}; - LOGGER_VK(vkCreateSemaphore, device, &semaphoreCreateInfo, nullptr, &mDrawableSemaphore); + TS_VK_CHECK(vkCreateSemaphore, device, &semaphoreCreateInfo, nullptr, &mDrawableSemaphore); - LOGGER_VK(vkCreateSemaphore, device, &semaphoreCreateInfo, nullptr, &mPresentableSemaphore); + TS_VK_CHECK(vkCreateSemaphore, device, &semaphoreCreateInfo, nullptr, &mPresentableSemaphore); const VkFenceCreateInfo fenceCreateInfo{ .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, .flags = VK_FENCE_CREATE_SIGNALED_BIT, }; - LOGGER_VK(vkCreateFence, device, &fenceCreateInfo, nullptr, &mFence); + TS_VK_CHECK(vkCreateFence, device, &fenceCreateInfo, nullptr, &mFence); const auto uniformBufferOffsetAlignment = mCtx.getUniformBufferOffsetAlignment(); @@ -82,13 +85,17 @@ void RenderProcess::createRendererProcess( }); descriptorBufferInfos.emplace_back(VkDescriptorBufferInfo{ - .offset = descriptorBufferInfos.at(0).offset + khronos_utils::align(descriptorBufferInfos.at(0).range, uniformBufferOffsetAlignment) * static_cast(modelCount), + .offset = descriptorBufferInfos.at(0).offset + + khronos_utils::align(descriptorBufferInfos.at(0).range, uniformBufferOffsetAlignment) * + static_cast(modelsNum), .range = sizeof(mCommonUniformData), }); descriptorBufferInfos.emplace_back(VkDescriptorBufferInfo{ - .offset = descriptorBufferInfos.at(1).offset + khronos_utils::align(descriptorBufferInfos.at(1).range, uniformBufferOffsetAlignment), - .range = sizeof(math::Vec3) * gRegistry.getSystem().getSystemEntities().size() + .offset = descriptorBufferInfos.at(1).offset + + khronos_utils::align(descriptorBufferInfos.at(1).range, uniformBufferOffsetAlignment) * + static_cast(lightsNum), + .range = sizeof(decltype(mLightsUniformData.positions)) * mLightsUniformData.positions.size() }); if (descriptorBufferInfos.empty()) @@ -115,7 +122,7 @@ void RenderProcess::createRendererProcess( .descriptorSetCount = 1, .pSetLayouts = &descriptorSetLayout }; - LOGGER_VK(vkAllocateDescriptorSets, device, &descriptorSetAllocateInfo, &mDescriptorSet); + TS_VK_CHECK(vkAllocateDescriptorSets, device, &descriptorSetAllocateInfo, &mDescriptorSet); for (auto& descriptorBufferInfo : descriptorBufferInfos) { @@ -147,7 +154,7 @@ void RenderProcess::createRendererProcess( .dstBinding = 2, .dstArrayElement = 0, .descriptorCount = 1, - .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // TODO: SBBO + .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, .pBufferInfo = &descriptorBufferInfos.at(2), }, }; @@ -169,10 +176,10 @@ void RenderProcess::updateUniformBufferData() const auto uniformBufferOffsetAlignment = mCtx.getUniformBufferOffsetAlignment(); - auto offset = static_cast(mUniformBufferMemory); + auto offset = static_cast(mUniformBufferMemory); { - constexpr VkDeviceSize length{sizeof(decltype(mIndividualUniformData)::value_type)}; + constexpr auto length = sizeof(decltype(mIndividualUniformData)::value_type); for (const auto& individualData : mIndividualUniformData) { memcpy(offset, &individualData, length); @@ -181,15 +188,18 @@ void RenderProcess::updateUniformBufferData() } { - constexpr VkDeviceSize length = sizeof(decltype(mCommonUniformData)); + constexpr auto length = sizeof(decltype(mCommonUniformData)); memcpy(offset, &mCommonUniformData, length); offset += khronos_utils::align(length, uniformBufferOffsetAlignment); } - //{ - // constexpr VkDeviceSize length = sizeof(lightUniformData); - // memcpy(offset, &lightUniformData, length); - // offset += khronos_utils::align(length, uniformBufferOffsetAlignment); - //} + { + constexpr auto length = sizeof(decltype(mLightsUniformData.positions)); + for (const auto& lightData : mLightsUniformData.positions) + { + memcpy(offset, &lightData, length); + offset += khronos_utils::align(length, uniformBufferOffsetAlignment); + } + } } } diff --git a/engine/src/core/renderer_process.h b/engine/src/core/renderer_process.h index 3208807..9810548 100644 --- a/engine/src/core/renderer_process.h +++ b/engine/src/core/renderer_process.h @@ -2,6 +2,7 @@ #include "tsengine/math.hpp" #include "internal_utils.h" +#include "shaders/common.h" #include "vulkan/vulkan.h" @@ -13,23 +14,29 @@ class Headset; class RenderProcess final { - NOT_COPYABLE_AND_MOVEABLE(RenderProcess); + TS_NOT_COPYABLE_AND_MOVEABLE(RenderProcess); public: RenderProcess(const Context& ctx, const Headset& headset); ~RenderProcess(); void createRendererProcess( - VkCommandPool commandPool, - VkDescriptorPool descriptorPool, - VkDescriptorSetLayout descriptorSetLayout, - size_t modelCount); + const VkCommandPool commandPool, + const VkDescriptorPool descriptorPool, + const VkDescriptorSetLayout descriptorSetLayout, + const size_t modelsNum, + const size_t lightsNum); struct IndivialData final { math::Mat4 model; }; - std::vector mIndividualUniformData; + std::vector mIndividualUniformData{}; + + struct LightData final + { + std::array positions; + } mLightsUniformData{}; struct CommonUniformData final { diff --git a/engine/src/core/window.h b/engine/src/core/window.h index 2f30be5..7b6e1e8 100644 --- a/engine/src/core/window.h +++ b/engine/src/core/window.h @@ -10,7 +10,7 @@ namespace ts { class Window { - NOT_COPYABLE_AND_MOVEABLE(Window); + TS_NOT_COPYABLE_AND_MOVEABLE(Window); public: Window(const std::string_view windowName, const size_t width, const size_t height) : diff --git a/engine/src/ecs/ecs.cpp b/engine/src/ecs/ecs.cpp new file mode 100644 index 0000000..7266a3b --- /dev/null +++ b/engine/src/ecs/ecs.cpp @@ -0,0 +1,9 @@ +#include "globals.hpp" + +namespace ts +{ +Registry& getMainReg() +{ + return gReg; +} +} \ No newline at end of file diff --git a/engine/src/ecs/movement_system.hpp b/engine/src/ecs/movement_system.hpp deleted file mode 100644 index 7795504..0000000 --- a/engine/src/ecs/movement_system.hpp +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once - -#include "tsengine/ecs/ecs.hpp" - -#include "tsengine/ecs/components/transform_component.hpp" -#include "tsengine/ecs/components/rigid_body_component.hpp" - -namespace ts -{ -class MovementSystem : public ts::System -{ -public: - MovementSystem() - { - requireComponent(); - requireComponent(); - } - - void update(const float deltaTime) - {} -}; -} diff --git a/engine/src/ecs/systems/movement_system.hpp b/engine/src/ecs/systems/movement_system.hpp new file mode 100644 index 0000000..95c829b --- /dev/null +++ b/engine/src/ecs/systems/movement_system.hpp @@ -0,0 +1,107 @@ +#pragma once + +#include "tsengine/logger.h" + +#include "tsengine/ecs/ecs.h" + +#include "tsengine/ecs/components/transform_component.hpp" +#include "tsengine/ecs/components/rigid_body_component.hpp" + +#ifdef CYBSDK_FOUND + #include "CVirt.h" +#endif + +// TODO: create cyberith decorator +namespace ts +{ +class MovementSystem : public ts::System +{ +public: + MovementSystem() + { + requireComponent(); + requireComponent(); + +#ifdef CYBSDK_FOUND + mpCyberithDevice = CybSDK::Virt::FindDevice(); + if (mpCyberithDevice == nullptr) + { + TS_ERR("Cyberith Virtualizer device not found"); + } + + const auto info = mpCyberithDevice->GetDeviceInfo(); + + const auto virtName = info.ProductName; + const auto virtNameLen = wcslen(virtName); + std::vector virtBuf(virtNameLen); + wcstombs(virtBuf.data(), virtName, virtNameLen); + std::string virtConvertedName(virtBuf.begin(), virtBuf.end()); + TS_LOG(std::format("Device found {} Firmware Version: {}.{}", + virtConvertedName, + static_cast(info.MajorVersion), + static_cast(info.MinorVersion)).c_str()); + + + if (!mpCyberithDevice->Open()) + { + TS_ERR("Unable to connect to Cyberith Virtualizer"); + } +#endif + } + + void update(const float dt, const Controllers& controllers) + { + const auto player = gReg.getEntityByTag("player"); + +#ifdef CYBSDK_FOUND + const auto ringHeight = mpCyberithDevice->GetPlayerHeight(); + auto ringAngle = mpCyberithDevice->GetPlayerOrientation(); + const auto movementDirection = mpCyberithDevice->GetMovementDirection(); + const auto movementSpeed = mpCyberithDevice->GetMovementSpeed(); + + if (movementSpeed > 0.f) + { + const auto flySpeedMultiplier = player.getComponent().velocity; + ringAngle *= 2 * std::numbers::pi_v; + auto offsetX = std::sin(ringAngle) * movementSpeed * flySpeedMultiplier * dt; + auto offsetZ = -(std::cos(ringAngle) * movementSpeed * flySpeedMultiplier * dt); + + if (movementDirection == -1.f) + { + offsetX *= -1; + offsetZ *= -1; + } + + auto& playerPosition = player.getComponent().pos; + playerPosition.x += offsetX; + playerPosition.z += offsetZ; + } +#else + for (size_t controllerIndex{}; controllerIndex < controllers.controllerCount; ++controllerIndex) + { + const auto flyState = controllers.getFlyState(controllerIndex); + if (flyState) + { + const auto controllerPose = controllers.getPose(controllerIndex)[2]; + + // TODO: something is wrong with this code, investigate it + if ((!controllerPose.isNan()) || (controllerPose == math::Vec3{0.f})) + { + const math::Vec3 forward{controllers.getPose(controllerIndex)[2]}; + player.getComponent().pos += forward * player.getComponent().velocity * dt; + } + else + { + TS_WARN(std::format("Controller no. {} can not be located.", controllerIndex).c_str()); + } + } + } +#endif + } + +private: +#ifdef CYBSDK_FOUND + CybSDK::VirtDevice* mpCyberithDevice; +#endif +}; +} diff --git a/engine/src/ecs/render_system.hpp b/engine/src/ecs/systems/render_system.hpp similarity index 81% rename from engine/src/ecs/render_system.hpp rename to engine/src/ecs/systems/render_system.hpp index db53f53..aca5db2 100644 --- a/engine/src/ecs/render_system.hpp +++ b/engine/src/ecs/systems/render_system.hpp @@ -1,6 +1,6 @@ #pragma once -#include "tsengine/ecs/ecs.hpp" +#include "tsengine/ecs/ecs.h" #include "tsengine/ecs/components/mesh_component.hpp" #include "tsengine/ecs/components/transform_component.hpp" @@ -12,6 +12,7 @@ #include "shaders/light_cube.h" #include "shaders/grid.h" +#include "shaders/common.h" #include "vulkan_tools/vulkan_functions.h" @@ -27,20 +28,23 @@ class RenderSystem : public System { requireComponent(); - gRegistry.addSystem(); + gReg.addSystem(); + gReg.addSystem(); } - // TODO: sort by z void update(const VkCommandBuffer cmdBuf, const VkDescriptorSet descriptorSet) { - for (const auto entity : getSystemEntities()) - { - auto v = entity.getTag(); + auto entities = getSystemEntities(); + + std::ranges::sort(entities, std::less{}, [](const auto entity) { + return entity.getComponent().z; + }); + for (const auto entity : entities) + { size_t entityIndexforUniformBufferOffset{}; - const auto uniformBufferOffset = static_cast( - khronos_utils::align( - static_cast(sizeof(decltype(RenderProcess::mIndividualUniformData)::value_type)), + uint32_t uniformBufferOffsets = + static_cast(khronos_utils::align(static_cast(sizeof(decltype(RenderProcess::mIndividualUniformData)::value_type)), mVkUniformBufferOffsetAlignment) * static_cast(entityIndexforUniformBufferOffset)); vkCmdBindDescriptorSets( @@ -51,7 +55,7 @@ class RenderSystem : public System 1, &descriptorSet, 1, - &uniformBufferOffset); + &uniformBufferOffsets); auto& pos = entity.getComponent().pos; if (entity.hasComponent()) @@ -66,7 +70,7 @@ class RenderSystem : public System if (entity.hasComponent()) { - TS_ASSERT(!entity.hasComponent>(), "Not implemented yet"); + TS_ASSERT_MSG(!entity.hasComponent>(), "Not implemented yet"); const auto& mesh = entity.getComponent(); @@ -150,6 +154,10 @@ class RenderSystem : public System requireComponent>(); } + void update() + { + TS_ASSERT_MSG(getSystemEntities().size() == LIGHTS_N, "TODO: lights pipeline is prepared for 2 light sources"); + } }; private: @@ -157,5 +165,14 @@ class RenderSystem : public System const VkDeviceSize& mVkUniformBufferOffsetAlignment; std::weak_ptr mpGridPipeline, mpNormalLightingPipeline, mpPbrPipeline, mpLightCubePipeline; VkPipelineLayout mpPipelineLayout{}; + + class Meshes : public System + { + public: + Meshes() + { + requireComponent(); + } + }; }; } \ No newline at end of file diff --git a/engine/src/globals.hpp b/engine/src/globals.hpp index 1d46613..1fd6b6b 100644 --- a/engine/src/globals.hpp +++ b/engine/src/globals.hpp @@ -1,9 +1,13 @@ #pragma once +#include "tsengine/ecs/ecs.h" + namespace ts { +inline Registry gReg; + namespace khronos_utils { -inline auto gThrowExceptions{true}; +inline auto gThrowExceptions = true; } } \ No newline at end of file diff --git a/engine/src/internal_utils.h b/engine/src/internal_utils.h index caed7c5..3abedf0 100644 --- a/engine/src/internal_utils.h +++ b/engine/src/internal_utils.h @@ -31,12 +31,12 @@ \ cleanerFunction(); \ \ - return STL_FAILURE; \ + return TS_STL_FAILURE; \ } \ catch (...) \ { \ cleanerFunction(); \ \ - return UNKNOWN_FAILURE; \ + return TS_UNKNOWN_FAILURE; \ } diff --git a/engine/src/khronos_utils.h b/engine/src/khronos_utils.h index ca55b5f..8087a1e 100644 --- a/engine/src/khronos_utils.h +++ b/engine/src/khronos_utils.h @@ -7,7 +7,7 @@ #include "openxr/openxr.h" #include "vulkan/vulkan.h" -#define LOGGER_VK(function, ...) \ +#define TS_VK_CHECK(function, ...) \ { \ VkResult result{function(__VA_ARGS__)}; \ if (result != VK_SUCCESS) \ @@ -20,7 +20,7 @@ } \ } -#define LOGGER_XR(function, ...) \ +#define TS_XR_CHECK(function, ...) \ { \ XrResult result{function(__VA_ARGS__)}; \ if (result != XR_SUCCESS) \ @@ -33,6 +33,32 @@ } \ } +#define TS_VK_CHECK_MSG(msg, function, ...) \ + { \ + VkResult result{function(__VA_ARGS__)}; \ + if (result != VK_SUCCESS) \ + { \ + ts::logger::error( \ + msg, \ + __FILE__, \ + FUNCTION_SIGNATURE, \ + __LINE__); \ + } \ + } + +#define TS_XR_CHECK_MSG(msg, function, ...) \ + { \ + XrResult result{function(__VA_ARGS__)}; \ + if (result != XR_SUCCESS) \ + { \ + ts::logger::error( \ + msg, \ + __FILE__, \ + FUNCTION_SIGNATURE, \ + __LINE__); \ + } \ + } + namespace ts::khronos_utils { diff --git a/engine/src/tests_core_adapter.h b/engine/src/tests_core_adapter.h index ac1a7fe..d346eb4 100644 --- a/engine/src/tests_core_adapter.h +++ b/engine/src/tests_core_adapter.h @@ -18,12 +18,9 @@ struct TesterEngine : public Engine TesterEngine(const TesterEngine&&) = delete; TesterEngine& operator=(TesterEngine&&) = delete; - virtual bool init(const char*& gameName, unsigned& width, unsigned& height) override { return true; } - - virtual void close() override - {} - virtual bool tick() override { return true; } + virtual void loadLvL() override + {} std::chrono::steady_clock::duration renderingDuration; }; diff --git a/engine/tests/tester.cpp b/engine/tests/tester.cpp index 7e36e2d..8093ea4 100644 --- a/engine/tests/tester.cpp +++ b/engine/tests/tester.cpp @@ -132,9 +132,9 @@ TEST(MathTests, mat4InversionTest) TEST(MathTests, mat4rotationTest) { - const ts::math::Mat4 matrix = ts::math::Mat4(1.f); + const auto matrix = ts::math::Mat4(1.f); - const ts::math::Vec3 axis { 0.f, 1.f, 0.f }; + const ts::math::Vec3 axis{0.f, 1.f, 0.f}; const auto result = ts::math::rotate(matrix, axis, ts::math::radians(180.f)); const ts::math::Mat4 expected @@ -154,13 +154,6 @@ class TestGame final : public ts::TesterEngine public: TestGame() : TesterEngine{renderingDuration} {} - - bool init(const char*& gameName, unsigned& width, unsigned& height) override { return true; } - - bool tick() override { return true; } - - void close() override - {} }; TEST(GameTests, RunReturnsZero) diff --git a/game/game.cpp b/game/game.cpp index 7f635b7..e23314a 100644 --- a/game/game.cpp +++ b/game/game.cpp @@ -3,7 +3,7 @@ #include "tsengine/math.hpp" #include "tsengine/logger.h" -#include "tsengine/ecs/ecs.hpp" +#include "tsengine/ecs/ecs.h" #include "tsengine/ecs/components/transform_component.hpp" #include "tsengine/ecs/components/rigid_body_component.hpp" #include "tsengine/ecs/components/renderer_component.hpp" @@ -18,13 +18,13 @@ bool Game::init(const char*& gameName, unsigned&, unsigned&) void Game::loadLvL() { - ts::Entity village = ts::gRegistry.createEntity(); + auto village = ts::getMainReg().createEntity(); village.setTag("village"); village.addComponent(); village.addComponent>(); village.addComponent("assets/models/village.obj"); - ts::Entity polonez = ts::gRegistry.createEntity(); + auto polonez = ts::getMainReg().createEntity(); polonez.setTag("polonez"); polonez.addComponent(ts::math::Vec3{0.f, 0.f, -10.f}); polonez.addComponent>(); @@ -34,19 +34,23 @@ void Game::loadLvL() for (size_t i{}; i < spheresNumber; ++i) { - ts::Entity sphere = ts::gRegistry.createEntity(); + auto sphere = ts::getMainReg().createEntity(); sphere.setTag("sphere" + std::to_string(i)); sphere.addComponent(ts::math::Vec3{spheresNumber / 3 * -5.f + 5.f * i, 2.f, -5.f}); - sphere.addComponent>(); + + const auto material = ts::RendererComponent::Material::create( + ts::RendererComponent::Material::Type::GOLD); + + sphere.addComponent>(material); sphere.addComponent("assets/models/sphere.obj"); } - ts::Entity light1 = ts::gRegistry.createEntity(); + auto light1 = ts::getMainReg().createEntity(); light1.setTag("light1"); light1.addComponent(ts::math::Vec3{0.f, 5.f, -7.f}); light1.addComponent>(); - ts::Entity light2 = ts::gRegistry.createEntity(); + auto light2 = ts::getMainReg().createEntity(); light2.setTag("light2"); light2.addComponent(ts::math::Vec3{0.f, 5.f, 0.f}); light2.addComponent>(); @@ -59,7 +63,7 @@ bool Game::tick() void Game::close() { - + TS_LOG("Thanks for playing!"); } TS_MAIN() \ No newline at end of file diff --git a/game/game.h b/game/game.h index 4f57f3d..4361698 100644 --- a/game/game.h +++ b/game/game.h @@ -2,7 +2,7 @@ #include "tsengine/asset_store.h" #include "tsengine/core.h" -#include "tsengine/ecs/ecs.hpp" +#include "tsengine/ecs/ecs.h" #include "tsengine/event_bus.hpp" #include