Cleanup with namespaces.

This commit is contained in:
Anish Bhobe 2025-06-01 21:40:34 +02:00
parent 299665a0fd
commit 84f38e18ed
62 changed files with 487 additions and 809 deletions

View File

@ -7,6 +7,6 @@ add_subdirectory("systems")
add_subdirectory("util") add_subdirectory("util")
target_sources(aster_core target_sources(aster_core
PUBLIC "aster.h") PUBLIC "aster.h" "import_types.h")
target_precompile_headers(aster_core PUBLIC "aster.h") target_precompile_headers(aster_core PUBLIC "aster.h")

View File

@ -5,4 +5,11 @@
#pragma once #pragma once
#include "core/global.h" #include "aster/core/global.h"
#include "aster/core/window.h"
#include "aster/systems/commit_manager.h"
#include "aster/systems/context.h"
#include "aster/systems/rendering_device.h"
#include "aster/systems/resource.h"

View File

@ -7,6 +7,8 @@
#include "global.h" #include "global.h"
namespace aster
{
struct Device; struct Device;
/// A Vulkan buffer wrapper. /// A Vulkan buffer wrapper.
@ -116,3 +118,4 @@ template <typename T, typename TTo>
concept BufferRefTo = Deref<T> and BufferInto<DerefType<T>, TTo>; concept BufferRefTo = Deref<T> and BufferInto<DerefType<T>, TTo>;
} // namespace concepts } // namespace concepts
} // namespace aster

View File

@ -15,6 +15,8 @@
#include <atomic> #include <atomic>
namespace aster::types
{
using c8 = char; using c8 = char;
using u8 = uint8_t; using u8 = uint8_t;
using u16 = uint16_t; using u16 = uint16_t;
@ -34,19 +36,6 @@ using isize = intptr_t;
using uptr = uintptr_t; using uptr = uintptr_t;
using cstr = char const *; using cstr = char const *;
namespace ansi_color
{
constexpr auto Black = "\u001b[30m";
constexpr auto Red = "\u001b[31m";
constexpr auto Green = "\u001b[32m";
constexpr auto Yellow = "\u001b[33m";
constexpr auto Blue = "\u001b[34m";
constexpr auto Magenta = "\u001b[35m";
constexpr auto Cyan = "\u001b[36m";
constexpr auto White = "\u001b[37m";
constexpr auto Reset = "\u001b[0m";
} // namespace ansi_color
constexpr f32 constexpr f32
operator""_deg(long double degrees) operator""_deg(long double degrees)
{ {
@ -83,57 +72,6 @@ using glm::mat2;
using glm::mat3; using glm::mat3;
using glm::mat4; using glm::mat4;
constexpr auto *PROJECT_NAME = "Aster";
struct Version
{
u8 m_Major;
u8 m_Minor;
u8 m_Patch;
[[nodiscard]] u32
GetVkVersion() const
{
return VK_MAKE_API_VERSION(0, m_Major, m_Minor, m_Patch);
}
};
constexpr Version VERSION = {
.m_Major = 0,
.m_Minor = 1,
.m_Patch = 0,
};
constexpr u32
Kilobyte(u32 const in)
{
return in * 1024;
}
constexpr usize
Kilobyte(usize const in)
{
return in * 1024;
}
constexpr u32
Megabyte(u32 const in)
{
return in * 1024 * 1024;
}
constexpr usize
Megabyte(usize const in)
{
return in * 1024 * 1024;
}
constexpr usize
Gigabyte(usize const in)
{
return in * 1024 * 1024 * 1024;
}
template <typename T> template <typename T>
constexpr T MaxValue = std::numeric_limits<T>::max(); constexpr T MaxValue = std::numeric_limits<T>::max();
@ -157,3 +95,22 @@ constexpr T Qnan = std::numeric_limits<T>::quiet_NaN();
template <typename T> template <typename T>
constexpr T Snan = std::numeric_limits<T>::signalling_NaN(); constexpr T Snan = std::numeric_limits<T>::signalling_NaN();
} // namespace aster::types
namespace aster
{
using namespace types;
namespace ansi_color
{
constexpr auto Black = "\u001b[30m";
constexpr auto Red = "\u001b[31m";
constexpr auto Green = "\u001b[32m";
constexpr auto Yellow = "\u001b[33m";
constexpr auto Blue = "\u001b[34m";
constexpr auto Magenta = "\u001b[35m";
constexpr auto Cyan = "\u001b[36m";
constexpr auto White = "\u001b[37m";
constexpr auto Reset = "\u001b[0m";
} // namespace ansi_color
} // namespace aster

View File

@ -10,6 +10,8 @@
#include <EASTL/span.h> #include <EASTL/span.h>
#include <EASTL/vector.h> #include <EASTL/vector.h>
namespace aster
{
struct QueueAllocation; struct QueueAllocation;
struct Instance; struct Instance;
struct PhysicalDevice; struct PhysicalDevice;
@ -82,3 +84,4 @@ Device::SetName(T const &object, cstr name) const
WARN_IF(Failed(result), "Could not name {:x}: {} as {}. Cause: {}", handle, to_string(object.objectType), name, WARN_IF(Failed(result), "Could not name {:x}: {} as {}. Cause: {}", handle, to_string(object.objectType), name,
result); result);
} }
} // namespace aster

View File

@ -39,8 +39,6 @@
#include <vulkan/vulkan.hpp> #include <vulkan/vulkan.hpp>
constexpr u32 ASTER_API_VERSION = VK_API_VERSION_1_3;
#define CODE_LOC " @ " __FILE__ ":" VULKAN_HPP_STRINGIFY(__LINE__) #define CODE_LOC " @ " __FILE__ ":" VULKAN_HPP_STRINGIFY(__LINE__)
#define DISALLOW_COPY_AND_ASSIGN(CLASS_NAME) \ #define DISALLOW_COPY_AND_ASSIGN(CLASS_NAME) \
@ -89,24 +87,67 @@ Failed(vk::Result const result)
return result != vk::Result::eSuccess; return result != vk::Result::eSuccess;
} }
namespace concepts namespace aster::concepts
{ {
template <typename T> template <typename T>
concept VkHandle = vk::isVulkanHandleType<T>::value; concept VkHandle = vk::isVulkanHandleType<T>::value;
} }
namespace aster
{
constexpr u32 ASTER_API_VERSION = VK_API_VERSION_1_3;
using NameString = eastl::fixed_string<char, 32, false>; using NameString = eastl::fixed_string<char, 32, false>;
template <typename TFlagBits> struct Version
struct eastl::hash<vk::Flags<TFlagBits>> // NOLINT(*-dcl58-cpp)
{ {
[[nodiscard]] usize u8 m_Major;
operator()(vk::Flags<TFlagBits> const &val) u8 m_Minor;
u8 m_Patch;
[[nodiscard]] u32
GetVkVersion() const
{ {
return std::hash<u32>()(static_cast<u32>(val)); return VK_MAKE_API_VERSION(0, m_Major, m_Minor, m_Patch);
} }
}; };
constexpr Version VERSION = {
.m_Major = 0,
.m_Minor = 1,
.m_Patch = 0,
};
constexpr u32
Kilobyte(u32 const in)
{
return in * 1024;
}
constexpr usize
Kilobyte(usize const in)
{
return in * 1024;
}
constexpr u32
Megabyte(u32 const in)
{
return in * 1024 * 1024;
}
constexpr usize
Megabyte(usize const in)
{
return in * 1024 * 1024;
}
constexpr usize
Gigabyte(usize const in)
{
return in * 1024 * 1024 * 1024;
}
template <typename T> template <typename T>
[[nodiscard]] usize [[nodiscard]] usize
HashAny(T const &val) HashAny(T const &val)
@ -231,7 +272,14 @@ concept VkToString = requires(T a) {
{ vk::to_string(a) } -> std::convertible_to<std::string>; { vk::to_string(a) } -> std::convertible_to<std::string>;
}; };
template <VkToString T> template <typename T>
using Ref = eastl::shared_ptr<T>;
template <typename T>
using WeakRef = eastl::weak_ptr<T>;
} // namespace aster
template <aster::VkToString T>
struct fmt::formatter<T> : nested_formatter<std::string> struct fmt::formatter<T> : nested_formatter<std::string>
{ {
auto auto
@ -243,8 +291,8 @@ struct fmt::formatter<T> : nested_formatter<std::string>
} }
}; };
template <typename TType, usize TCount, bool TOverflow> template <typename TType, aster::usize TCount, bool TOverflow>
struct fmt::formatter<eastl::fixed_string<TType, TCount, TOverflow>> : nested_formatter<cstr> struct fmt::formatter<eastl::fixed_string<TType, TCount, TOverflow>> : nested_formatter<aster::cstr>
{ {
auto auto
// ReSharper disable once CppInconsistentNaming // ReSharper disable once CppInconsistentNaming
@ -254,8 +302,12 @@ struct fmt::formatter<eastl::fixed_string<TType, TCount, TOverflow>> : nested_fo
} }
}; };
template <typename T> template <typename TFlagBits>
using Ref = eastl::shared_ptr<T>; struct eastl::hash<vk::Flags<TFlagBits>> // NOLINT(*-dcl58-cpp)
{
template <typename T> [[nodiscard]] aster::usize
using WeakRef = eastl::weak_ptr<T>; operator()(vk::Flags<TFlagBits> const &val)
{
return std::hash<aster::u32>()(static_cast<aster::u32>(val));
}
};

View File

@ -7,6 +7,8 @@
#include "global.h" #include "global.h"
namespace aster
{
struct StorageTexture; struct StorageTexture;
struct Device; struct Device;
@ -130,3 +132,4 @@ template <typename T, typename TTo>
concept ImageRefTo = Deref<T> and ImageInto<DerefType<T>, TTo>; concept ImageRefTo = Deref<T> and ImageInto<DerefType<T>, TTo>;
} // namespace concepts } // namespace concepts
} // namespace aster

View File

@ -8,6 +8,8 @@
#include "global.h" #include "global.h"
#include "image.h" #include "image.h"
namespace aster
{
template <concepts::AnyImage TImage> template <concepts::AnyImage TImage>
struct View struct View
{ {
@ -106,3 +108,4 @@ template <typename T, typename TTo>
concept ViewRefTo = ViewRef<T> and ImageInto<typename DerefType<T>::ImageType, TTo>; concept ViewRefTo = ViewRef<T> and ImageInto<typename DerefType<T>::ImageType, TTo>;
} // namespace concepts } // namespace concepts
} // namespace aster

View File

@ -7,6 +7,8 @@
#include "global.h" #include "global.h"
namespace aster
{
/** /**
* @class Instance * @class Instance
* *
@ -37,3 +39,4 @@ struct Instance final
DISALLOW_COPY_AND_ASSIGN(Instance); DISALLOW_COPY_AND_ASSIGN(Instance);
}; };
} // namespace aster

View File

@ -12,6 +12,8 @@
#include <EASTL/fixed_vector.h> #include <EASTL/fixed_vector.h>
namespace aster
{
struct Window; struct Window;
struct Instance; struct Instance;
@ -90,3 +92,4 @@ class PhysicalDevices : public eastl::fixed_vector<PhysicalDevice, 4>
public: public:
PhysicalDevices(Surface const &surface, Instance const &context); PhysicalDevices(Surface const &surface, Instance const &context);
}; };
} // namespace aster

View File

@ -9,6 +9,8 @@
#include <EASTL/vector.h> #include <EASTL/vector.h>
namespace aster
{
struct Device; struct Device;
struct Pipeline struct Pipeline
@ -55,3 +57,4 @@ struct Pipeline
return *this; return *this;
} }
}; };
} // namespace aster

View File

@ -7,8 +7,11 @@
#include "global.h" #include "global.h"
namespace aster
{
struct QueueAllocation struct QueueAllocation
{ {
u32 m_Family; u32 m_Family;
u32 m_Count; u32 m_Count;
}; };
} // namespace aster

View File

@ -7,6 +7,8 @@
#include "global.h" #include "global.h"
namespace aster
{
struct Device; struct Device;
struct Sampler final struct Sampler final
@ -30,3 +32,4 @@ struct Sampler final
DISALLOW_COPY_AND_ASSIGN(Sampler); DISALLOW_COPY_AND_ASSIGN(Sampler);
}; };
} // namespace aster

View File

@ -7,6 +7,8 @@
#include "global.h" #include "global.h"
namespace aster
{
struct Size2D struct Size2D
{ {
u32 m_Width = 0; u32 m_Width = 0;
@ -41,3 +43,4 @@ struct Size2D
return {m_Width, m_Height}; return {m_Width, m_Height};
} }
}; };
} // namespace aster

View File

@ -7,6 +7,8 @@
#include "global.h" #include "global.h"
namespace aster
{
struct Instance; struct Instance;
struct Window; struct Window;
@ -27,3 +29,4 @@ struct Surface
DISALLOW_COPY_AND_ASSIGN(Surface); DISALLOW_COPY_AND_ASSIGN(Surface);
}; };
} // namespace aster

View File

@ -11,6 +11,8 @@
#include <EASTL/fixed_vector.h> #include <EASTL/fixed_vector.h>
namespace aster
{
struct PhysicalDevice; struct PhysicalDevice;
struct Surface; struct Surface;
struct Device; struct Device;
@ -42,6 +44,7 @@ struct Swapchain final
DISALLOW_COPY_AND_ASSIGN(Swapchain); DISALLOW_COPY_AND_ASSIGN(Swapchain);
private: private:
void Cleanup(); void Cleanup();
}; };
} // namespace aster

View File

@ -7,6 +7,8 @@
#include "constants.h" #include "constants.h"
namespace aster
{
struct Device; struct Device;
struct Image; struct Image;
@ -26,3 +28,4 @@ template <Deref T>
using DerefType = std::remove_cvref_t<decltype(*std::declval<T>())>; using DerefType = std::remove_cvref_t<decltype(*std::declval<T>())>;
} // namespace concepts } // namespace concepts
} // namespace aster

View File

@ -12,6 +12,8 @@
#include <EASTL/fixed_string.h> #include <EASTL/fixed_string.h>
#include <atomic> #include <atomic>
namespace aster
{
struct Window final struct Window final
{ {
// fields // fields
@ -47,3 +49,4 @@ struct Window final
DISALLOW_COPY_AND_ASSIGN(Window); DISALLOW_COPY_AND_ASSIGN(Window);
}; };
} // namespace aster

View File

@ -0,0 +1,10 @@
// =============================================
// Aster: import_types.h
// Copyright (c) 2020-2024 Anish Bhobe
// =============================================
#pragma once
#include "aster/aster.h"
using namespace aster::types;

View File

@ -18,7 +18,7 @@
#include "aster/core/sampler.h" #include "aster/core/sampler.h"
#include "resource.h" #include "resource.h"
namespace systems namespace aster
{ {
class RenderingDevice; class RenderingDevice;

View File

@ -23,7 +23,7 @@
#include <foonathan/memory/memory_pool.hpp> #include <foonathan/memory/memory_pool.hpp>
#include <foonathan/memory/namespace_alias.hpp> #include <foonathan/memory/namespace_alias.hpp>
namespace systems namespace aster
{ {
class RenderingDevice; class RenderingDevice;

View File

@ -11,7 +11,7 @@
#include <slang.h> #include <slang.h>
#include <variant> #include <variant>
namespace systems namespace aster
{ {
class RenderingDevice; class RenderingDevice;
@ -29,10 +29,10 @@ struct PipelineCreationError
PipelineCreationError(); PipelineCreationError();
}; };
vk::ShaderStageFlagBits SlangToVulkanShaderStage(SlangStage stage);
namespace _internal namespace _internal
{ {
vk::ShaderStageFlagBits SlangToVulkanShaderStage(SlangStage const stage);
struct PipelineLayoutBuilder struct PipelineLayoutBuilder
{ {
RenderingDevice *m_Device; RenderingDevice *m_Device;
@ -72,4 +72,4 @@ struct DescriptorLayoutBuilder
void Build(); void Build();
}; };
} // namespace _internal } // namespace _internal
} // namespace systems } // namespace aster

View File

@ -28,42 +28,45 @@
#include <slang-com-ptr.h> #include <slang-com-ptr.h>
#include <slang.h> #include <slang.h>
namespace aster
{
constexpr static u32 MAX_FRAMES_IN_FLIGHT = 3; constexpr static u32 MAX_FRAMES_IN_FLIGHT = 3;
struct Window; struct Window;
} // namespace aster
template <> template <>
struct eastl::hash<vk::SamplerCreateInfo> struct eastl::hash<vk::SamplerCreateInfo>
{ {
usize aster::usize
operator()(vk::SamplerCreateInfo const &createInfo) const noexcept operator()(vk::SamplerCreateInfo const &createInfo) const noexcept
{ {
usize hash = HashAny(createInfo.flags); aster::usize hash = aster::HashAny(createInfo.flags);
hash = HashCombine(hash, HashAny(createInfo.magFilter)); hash = aster::HashCombine(hash, aster::HashAny(createInfo.magFilter));
hash = HashCombine(hash, HashAny(createInfo.minFilter)); hash = aster::HashCombine(hash, aster::HashAny(createInfo.minFilter));
hash = HashCombine(hash, HashAny(createInfo.mipmapMode)); hash = aster::HashCombine(hash, aster::HashAny(createInfo.mipmapMode));
hash = HashCombine(hash, HashAny(createInfo.addressModeU)); hash = aster::HashCombine(hash, aster::HashAny(createInfo.addressModeU));
hash = HashCombine(hash, HashAny(createInfo.addressModeV)); hash = aster::HashCombine(hash, aster::HashAny(createInfo.addressModeV));
hash = HashCombine(hash, HashAny(createInfo.addressModeW)); hash = aster::HashCombine(hash, aster::HashAny(createInfo.addressModeW));
hash = HashCombine(hash, HashAny(static_cast<usize>(createInfo.mipLodBias * 1000))); // Resolution of 10^-3 hash = aster::HashCombine(hash, aster::HashAny(static_cast<aster::usize>(createInfo.mipLodBias * 1000))); // Resolution of 10^-3
hash = HashCombine(hash, HashAny(createInfo.anisotropyEnable)); hash = aster::HashCombine(hash, aster::HashAny(createInfo.anisotropyEnable));
hash = HashCombine( hash = aster::HashCombine(
hash, hash,
HashAny(static_cast<usize>(createInfo.maxAnisotropy * 0x20))); // 32:1 Anisotropy is enough resolution aster::HashAny(static_cast<aster::usize>(createInfo.maxAnisotropy * 0x20))); // 32:1 Anisotropy is enough resolution
hash = HashCombine(hash, HashAny(createInfo.compareEnable)); hash = aster::HashCombine(hash, aster::HashAny(createInfo.compareEnable));
hash = HashCombine(hash, HashAny(createInfo.compareOp)); hash = aster::HashCombine(hash, aster::HashAny(createInfo.compareOp));
hash = HashCombine(hash, HashAny(static_cast<usize>(createInfo.minLod * 1000))); // 0.001 resolution is enough. hash = aster::HashCombine(hash, aster::HashAny(static_cast<aster::usize>(createInfo.minLod * 1000))); // 0.001 resolution is enough.
hash = HashCombine( hash = aster::HashCombine(
hash, hash,
HashAny(static_cast<usize>(createInfo.maxLod * 1000))); // 0.001 resolution is enough. (1 == NO Clamp) aster::HashAny(static_cast<aster::usize>(createInfo.maxLod * 1000))); // 0.001 resolution is enough. (1 == NO Clamp)
hash = HashCombine(hash, HashAny(createInfo.borderColor)); hash = aster::HashCombine(hash, aster::HashAny(createInfo.borderColor));
hash = HashCombine(hash, HashAny(createInfo.unnormalizedCoordinates)); hash = aster::HashCombine(hash, aster::HashAny(createInfo.unnormalizedCoordinates));
return hash; return hash;
} }
}; };
namespace systems namespace aster
{ {
// ==================================================================================================== // ====================================================================================================

View File

@ -11,7 +11,7 @@
#include <EASTL/intrusive_ptr.h> #include <EASTL/intrusive_ptr.h>
namespace systems namespace aster
{ {
// ==================================================================================================== // ====================================================================================================

View File

@ -9,13 +9,13 @@
#include <EASTL/deque.h> #include <EASTL/deque.h>
#include <EASTL/intrusive_list.h> #include <EASTL/intrusive_list.h>
namespace systems namespace aster
{ {
class Receipt; class Receipt;
class RenderingDevice; class RenderingDevice;
} // namespace systems } // namespace systems
namespace systems::_internal namespace aster::_internal
{ {
struct TimelinePoint struct TimelinePoint
{ {

View File

@ -10,6 +10,9 @@
#include <EASTL/span.h> #include <EASTL/span.h>
#include <EASTL/vector.h> #include <EASTL/vector.h>
namespace aster
{
eastl::vector<u32> ReadFile(std::string_view fileName); eastl::vector<u32> ReadFile(std::string_view fileName);
eastl::vector<u8> ReadFileBytes(std::string_view fileName, bool errorOnFail = true); eastl::vector<u8> ReadFileBytes(std::string_view fileName, bool errorOnFail = true);
bool WriteFileBytes(std::string_view fileName, eastl::span<u8> data); bool WriteFileBytes(std::string_view fileName, eastl::span<u8> data);
} // namespace aster

View File

@ -9,6 +9,8 @@
#include <debugbreak.h> #include <debugbreak.h>
#include <fmt/core.h> #include <fmt/core.h>
namespace aster
{
struct Logger struct Logger
{ {
enum class LogType : u32 enum class LogType : u32
@ -94,60 +96,61 @@ struct Logger
#endif #endif
} }
}; };
}
extern Logger g_Logger; extern aster::Logger g_Logger;
#define MIN_LOG_LEVEL(LOG_LVL) g_Logger.SetMinimumLoggingLevel(LOG_LVL) #define MIN_LOG_LEVEL(LOG_LVL) g_Logger.SetMinimumLoggingLevel(LOG_LVL)
#define ERROR(...) g_Logger.Log<Logger::LogType::eError>(fmt::format(__VA_ARGS__), __FILE__, __LINE__) #define ERROR(...) g_Logger.Log<aster::Logger::LogType::eError>(fmt::format(__VA_ARGS__), __FILE__, __LINE__)
#define WARN(...) g_Logger.Log<Logger::LogType::eWarning>(fmt::format(__VA_ARGS__), __FILE__, __LINE__) #define WARN(...) g_Logger.Log<aster::Logger::LogType::eWarning>(fmt::format(__VA_ARGS__), __FILE__, __LINE__)
#define INFO(...) g_Logger.Log<Logger::LogType::eInfo>(fmt::format(__VA_ARGS__), __FILE__, __LINE__) #define INFO(...) g_Logger.Log<aster::Logger::LogType::eInfo>(fmt::format(__VA_ARGS__), __FILE__, __LINE__)
#define ERROR_IF(expr, ...) \ #define ERROR_IF(expr, ...) \
if (static_cast<bool>(expr)) [[unlikely]] \ if (static_cast<bool>(expr)) [[unlikely]] \
g_Logger.LogCond<Logger::LogType::eError>(#expr, fmt::format(__VA_ARGS__), __FILE__, __LINE__) g_Logger.LogCond<aster::Logger::LogType::eError>(#expr, fmt::format(__VA_ARGS__), __FILE__, __LINE__)
#define WARN_IF(expr, ...) \ #define WARN_IF(expr, ...) \
if (static_cast<bool>(expr)) [[unlikely]] \ if (static_cast<bool>(expr)) [[unlikely]] \
g_Logger.LogCond<Logger::LogType::eWarning>(#expr, fmt::format(__VA_ARGS__), __FILE__, __LINE__) g_Logger.LogCond<aster::Logger::LogType::eWarning>(#expr, fmt::format(__VA_ARGS__), __FILE__, __LINE__)
#define INFO_IF(expr, ...) \ #define INFO_IF(expr, ...) \
if (static_cast<bool>(expr)) \ if (static_cast<bool>(expr)) \
g_Logger.LogCond<Logger::LogType::eInfo>(#expr, fmt::format(__VA_ARGS__), __FILE__, __LINE__) g_Logger.LogCond<aster::Logger::LogType::eInfo>(#expr, fmt::format(__VA_ARGS__), __FILE__, __LINE__)
#define ELSE_IF_ERROR(expr, ...) \ #define ELSE_IF_ERROR(expr, ...) \
; \ ; \
else if (static_cast<bool>(expr)) \ else if (static_cast<bool>(expr)) \
[[unlikely]] g_Logger.LogCond<Logger::LogType::eError>(#expr, fmt::format(__VA_ARGS__), __FILE__, __LINE__) [[unlikely]] g_Logger.LogCond<aster::Logger::LogType::eError>(#expr, fmt::format(__VA_ARGS__), __FILE__, __LINE__)
#define ELSE_IF_WARN(expr, ...) \ #define ELSE_IF_WARN(expr, ...) \
; \ ; \
else if (static_cast<bool>(expr)) \ else if (static_cast<bool>(expr)) \
[[unlikely]] g_Logger.LogCond<Logger::LogType::eWarning>(#expr, fmt::format(__VA_ARGS__), __FILE__, __LINE__) [[unlikely]] g_Logger.LogCond<aster::Logger::LogType::eWarning>(#expr, fmt::format(__VA_ARGS__), __FILE__, __LINE__)
#define ELSE_IF_INFO(expr, ...) \ #define ELSE_IF_INFO(expr, ...) \
; \ ; \
else if (static_cast<bool>(expr)) \ else if (static_cast<bool>(expr)) \
g_Logger.LogCond<Logger::LogType::eInfo>(#expr, fmt::format(__VA_ARGS__), __FILE__, __LINE__) g_Logger.LogCond<aster::Logger::LogType::eInfo>(#expr, fmt::format(__VA_ARGS__), __FILE__, __LINE__)
#define ELSE_ERROR(...) \ #define ELSE_ERROR(...) \
; \ ; \
else [[unlikely]] g_Logger.Log<Logger::LogType::eError>(fmt::format(__VA_ARGS__), __FILE__, __LINE__) else [[unlikely]] g_Logger.Log<aster::Logger::LogType::eError>(fmt::format(__VA_ARGS__), __FILE__, __LINE__)
#define ELSE_WARN(...) \ #define ELSE_WARN(...) \
; \ ; \
else [[unlikely]] g_Logger.Log<Logger::LogType::eWarning>(fmt::format(__VA_ARGS__), __FILE__, __LINE__) else [[unlikely]] g_Logger.Log<aster::Logger::LogType::eWarning>(fmt::format(__VA_ARGS__), __FILE__, __LINE__)
#define ELSE_INFO(...) \ #define ELSE_INFO(...) \
; \ ; \
else g_Logger.Log<Logger::LogType::eInfo>(fmt::format(__VA_ARGS__), __FILE__, __LINE__) else g_Logger.Log<aster::Logger::LogType::eInfo>(fmt::format(__VA_ARGS__), __FILE__, __LINE__)
#if !defined(DEBUG_LOG_DISABLED) && !defined(ASTER_NDEBUG) #if !defined(DEBUG_LOG_DISABLED) && !defined(ASTER_NDEBUG)
#define DEBUG(...) g_Logger.Log<Logger::LogType::eDebug>(fmt::format(__VA_ARGS__), __FILE__, __LINE__) #define DEBUG(...) g_Logger.Log<aster::Logger::LogType::eDebug>(fmt::format(__VA_ARGS__), __FILE__, __LINE__)
#define DEBUG_IF(expr, ...) \ #define DEBUG_IF(expr, ...) \
if (static_cast<bool>(expr)) \ if (static_cast<bool>(expr)) \
g_Logger.LogCond<Logger::LogType::eDebug>(#expr, fmt::format(__VA_ARGS__), __FILE__, __LINE__) g_Logger.LogCond<aster::Logger::LogType::eDebug>(#expr, fmt::format(__VA_ARGS__), __FILE__, __LINE__)
#define ELSE_IF_DEBUG(expr, ...) \ #define ELSE_IF_DEBUG(expr, ...) \
; \ ; \
else if (static_cast<bool>(expr)) \ else if (static_cast<bool>(expr)) \
g_Logger.LogCond<Logger::LogType::eDebug>(#expr, fmt::format(__VA_ARGS__), __FILE__, __LINE__) g_Logger.LogCond<aster::Logger::LogType::eDebug>(#expr, fmt::format(__VA_ARGS__), __FILE__, __LINE__)
#define ELSE_DEBUG(...) \ #define ELSE_DEBUG(...) \
; \ ; \
else g_Logger.Log<Logger::LogType::eDebug>(fmt::format(__VA_ARGS__), __FILE__, __LINE__) else g_Logger.Log<aster::Logger::LogType::eDebug>(fmt::format(__VA_ARGS__), __FILE__, __LINE__)
#else // !defined(DEBUG_LOG_DISABLED) #else // !defined(DEBUG_LOG_DISABLED)
@ -172,17 +175,17 @@ extern Logger g_Logger;
#if !defined(VERBOSE_LOG_DISABLED) && !defined(ASTER_NDEBUG) #if !defined(VERBOSE_LOG_DISABLED) && !defined(ASTER_NDEBUG)
#define VERBOSE(...) g_Logger.Log<Logger::LogType::eVerbose>(fmt::format(__VA_ARGS__), __FILE__, __LINE__) #define VERBOSE(...) g_Logger.Log<aster::Logger::LogType::eVerbose>(fmt::format(__VA_ARGS__), __FILE__, __LINE__)
#define VERBOSE_IF(expr, ...) \ #define VERBOSE_IF(expr, ...) \
if (static_cast<bool>(expr)) \ if (static_cast<bool>(expr)) \
g_Logger.LogCond<Logger::LogType::eVerbose>(#expr, fmt::format(__VA_ARGS__), __FILE__, __LINE__) g_Logger.LogCond<aster::Logger::LogType::eVerbose>(#expr, fmt::format(__VA_ARGS__), __FILE__, __LINE__)
#define ELSE_IF_VERBOSE(expr, ...) \ #define ELSE_IF_VERBOSE(expr, ...) \
; \ ; \
else if (static_cast<bool>(expr)) \ else if (static_cast<bool>(expr)) \
g_Logger.LogCond<Logger::LogType::eVerbose>(#expr, fmt::format(__VA_ARGS__), __FILE__, __LINE__) g_Logger.LogCond<aster::Logger::LogType::eVerbose>(#expr, fmt::format(__VA_ARGS__), __FILE__, __LINE__)
#define ELSE_VERBOSE(...) \ #define ELSE_VERBOSE(...) \
; \ ; \
else g_Logger.Log<Logger::LogType::eVerbose>(fmt::format(__VA_ARGS__), __FILE__, __LINE__) else g_Logger.Log<aster::Logger::LogType::eVerbose>(fmt::format(__VA_ARGS__), __FILE__, __LINE__)
#else // !defined(DEBUG_LOG_DISABLED) #else // !defined(DEBUG_LOG_DISABLED)
@ -207,5 +210,5 @@ extern Logger g_Logger;
#endif // !defined(VERBOSE_LOG_DISABLED) #endif // !defined(VERBOSE_LOG_DISABLED)
#define DO(code) , code #define DO(code) , code
#define ABORT(code) exit(static_cast<i32>(code)) #define ABORT(code) exit(static_cast<int>(code))
#define THEN_ABORT(code) , ABORT(code) #define THEN_ABORT(code) , ABORT(code)

View File

@ -7,6 +7,8 @@
#include "aster/core/device.h" #include "aster/core/device.h"
using namespace aster;
Buffer::Buffer(Device const *device, usize const size, vk::BufferUsageFlags const bufferUsage, Buffer::Buffer(Device const *device, usize const size, vk::BufferUsageFlags const bufferUsage,
VmaAllocationCreateFlags const allocationFlags, VmaMemoryUsage const memoryUsage, cstr const name) VmaAllocationCreateFlags const allocationFlags, VmaMemoryUsage const memoryUsage, cstr const name)
{ {

View File

@ -12,6 +12,8 @@
#include <EASTL/array.h> #include <EASTL/array.h>
#include <EASTL/fixed_vector.h> #include <EASTL/fixed_vector.h>
using namespace aster;
// TODO: This will need to be flexible for devices that don't support some of the extensions. // TODO: This will need to be flexible for devices that don't support some of the extensions.
constexpr eastl::array DEVICE_EXTENSIONS = { constexpr eastl::array DEVICE_EXTENSIONS = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME, VK_KHR_SWAPCHAIN_EXTENSION_NAME,

View File

@ -14,6 +14,8 @@
// NOTE: Vulkan Dispatch Loader Storage - Should only appear once. // NOTE: Vulkan Dispatch Loader Storage - Should only appear once.
VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE
using namespace aster;
struct MemorySize struct MemorySize
{ {
u16 m_Gigabytes; u16 m_Gigabytes;

View File

@ -7,6 +7,8 @@
#include "aster/core/device.h" #include "aster/core/device.h"
using namespace aster;
Image & Image &
Image::operator=(Image &&other) noexcept Image::operator=(Image &&other) noexcept
{ {

View File

@ -10,6 +10,8 @@
#include <EASTL/array.h> #include <EASTL/array.h>
#include <EASTL/fixed_vector.h> #include <EASTL/fixed_vector.h>
using namespace aster;
VKAPI_ATTR b32 VKAPI_CALL VKAPI_ATTR b32 VKAPI_CALL
DebugCallback(vk::DebugUtilsMessageSeverityFlagBitsEXT const messageSeverity, DebugCallback(vk::DebugUtilsMessageSeverityFlagBitsEXT const messageSeverity,
vk::DebugUtilsMessageTypeFlagsEXT const messageType, vk::DebugUtilsMessageTypeFlagsEXT const messageType,
@ -43,7 +45,7 @@ Instance::Instance(cstr const appName, Version const version, bool enableValidat
vk::ApplicationInfo const appInfo = { vk::ApplicationInfo const appInfo = {
.pApplicationName = appName, .pApplicationName = appName,
.applicationVersion = version.GetVkVersion(), .applicationVersion = version.GetVkVersion(),
.pEngineName = PROJECT_NAME, .pEngineName = "aster",
.engineVersion = version.GetVkVersion(), .engineVersion = version.GetVkVersion(),
.apiVersion = ASTER_API_VERSION, .apiVersion = ASTER_API_VERSION,
}; };

View File

@ -8,8 +8,10 @@
#include "aster/core/instance.h" #include "aster/core/instance.h"
#include "aster/core/surface.h" #include "aster/core/surface.h"
using namespace aster;
[[nodiscard]] vk::SurfaceCapabilitiesKHR [[nodiscard]] vk::SurfaceCapabilitiesKHR
GetSurfaceCapabilities(vk::PhysicalDevice const physicalDevice, vk::SurfaceKHR const surface) aster::GetSurfaceCapabilities(vk::PhysicalDevice const physicalDevice, vk::SurfaceKHR const surface)
{ {
vk::SurfaceCapabilitiesKHR surfaceCapabilities; vk::SurfaceCapabilitiesKHR surfaceCapabilities;
@ -21,7 +23,7 @@ GetSurfaceCapabilities(vk::PhysicalDevice const physicalDevice, vk::SurfaceKHR c
} }
[[nodiscard]] eastl::vector<vk::SurfaceFormatKHR> [[nodiscard]] eastl::vector<vk::SurfaceFormatKHR>
GetSurfaceFormats(vk::PhysicalDevice const physicalDevice, vk::SurfaceKHR const surface) aster::GetSurfaceFormats(vk::PhysicalDevice const physicalDevice, vk::SurfaceKHR const surface)
{ {
// vk::Result::eIncomplete should not occur in this function. The rest are errors. Thus, abort is allowed. // vk::Result::eIncomplete should not occur in this function. The rest are errors. Thus, abort is allowed.
u32 count = 0; u32 count = 0;
@ -38,7 +40,7 @@ GetSurfaceFormats(vk::PhysicalDevice const physicalDevice, vk::SurfaceKHR const
} }
[[nodiscard]] eastl::vector<vk::PresentModeKHR> [[nodiscard]] eastl::vector<vk::PresentModeKHR>
GetSurfacePresentModes(vk::PhysicalDevice const physicalDevice, vk::SurfaceKHR const surface) aster::GetSurfacePresentModes(vk::PhysicalDevice const physicalDevice, vk::SurfaceKHR const surface)
{ {
// vk::Result::eIncomplete should not occur in this function. The rest are errors. Thus, abort is allowed. // vk::Result::eIncomplete should not occur in this function. The rest are errors. Thus, abort is allowed.
u32 count = 0; u32 count = 0;

View File

@ -7,6 +7,8 @@
#include "aster/core/device.h" #include "aster/core/device.h"
using namespace aster;
Pipeline::Pipeline(Device const *device, vk::PipelineLayout const layout, vk::Pipeline const pipeline, Pipeline::Pipeline(Device const *device, vk::PipelineLayout const layout, vk::Pipeline const pipeline,
eastl::vector<vk::DescriptorSetLayout> &&setLayouts, Kind const kind) eastl::vector<vk::DescriptorSetLayout> &&setLayouts, Kind const kind)
: m_Device{device} : m_Device{device}

View File

@ -7,6 +7,8 @@
#include "aster/core/device.h" #include "aster/core/device.h"
using namespace aster;
Sampler::~Sampler() Sampler::~Sampler()
{ {
if (!IsValid()) if (!IsValid())

View File

@ -8,6 +8,8 @@
#include "aster/core/instance.h" #include "aster/core/instance.h"
#include "aster/core/window.h" #include "aster/core/window.h"
using namespace aster;
Surface::Surface(Instance &context, Window const &window) Surface::Surface(Instance &context, Window const &window)
: m_Context(&context) : m_Context(&context)
{ {

View File

@ -9,6 +9,8 @@
#include "aster/core/physical_device.h" #include "aster/core/physical_device.h"
#include "aster/core/surface.h" #include "aster/core/surface.h"
using namespace aster;
[[nodiscard]] vk::Extent2D GetExtent(Size2D size, vk::SurfaceCapabilitiesKHR *surfaceCapabilities); [[nodiscard]] vk::Extent2D GetExtent(Size2D size, vk::SurfaceCapabilitiesKHR *surfaceCapabilities);
Swapchain::Swapchain(Surface const &surface, Device const &device, Size2D size) Swapchain::Swapchain(Surface const &surface, Device const &device, Size2D size)

View File

@ -8,6 +8,8 @@
#include "aster/core/instance.h" #include "aster/core/instance.h"
#include "aster/util/logger.h" #include "aster/util/logger.h"
using namespace aster;
std::atomic_uint64_t Window::m_WindowCount = 0; std::atomic_uint64_t Window::m_WindowCount = 0;
std::atomic_bool Window::m_IsGlfwInit = false; std::atomic_bool Window::m_IsGlfwInit = false;

View File

@ -10,7 +10,7 @@
#include "aster/core/image_view.h" #include "aster/core/image_view.h"
#include "aster/systems/rendering_device.h" #include "aster/systems/rendering_device.h"
using namespace systems; using namespace aster;
CommitManager *CommitManager::m_Instance = nullptr; CommitManager *CommitManager::m_Instance = nullptr;

View File

@ -8,6 +8,8 @@
#include "aster/systems/commit_manager.h" #include "aster/systems/commit_manager.h"
#include "aster/systems/rendering_device.h" #include "aster/systems/rendering_device.h"
using namespace aster;
constexpr static u32 constexpr static u32
GetFormatSize(vk::Format const format) GetFormatSize(vk::Format const format)
{ {
@ -129,34 +131,34 @@ GetFormatSize(vk::Format const format)
} }
void void
systems::Context::KeepAlive(Ref<Buffer> const &buffer) Context::KeepAlive(Ref<Buffer> const &buffer)
{ {
assert(m_Pool); assert(m_Pool);
m_Pool->KeepAlive(buffer); m_Pool->KeepAlive(buffer);
} }
void void
systems::Context::KeepAlive(Ref<Image> const &image) Context::KeepAlive(Ref<Image> const &image)
{ {
assert(m_Pool); assert(m_Pool);
m_Pool->KeepAlive(image); m_Pool->KeepAlive(image);
} }
void void
systems::Context::KeepAlive(Ref<ImageView> const &view) Context::KeepAlive(Ref<ImageView> const &view)
{ {
assert(m_Pool); assert(m_Pool);
m_Pool->KeepAlive(view); m_Pool->KeepAlive(view);
} }
void void
systems::Context::Dependency(vk::DependencyInfo const &dependencyInfo) Context::Dependency(vk::DependencyInfo const &dependencyInfo)
{ {
m_Cmd.pipelineBarrier2(&dependencyInfo); m_Cmd.pipelineBarrier2(&dependencyInfo);
} }
void void
systems::Context::Begin() Context::Begin()
{ {
vk::CommandBufferBeginInfo commandBufferBeginInfo = { vk::CommandBufferBeginInfo commandBufferBeginInfo = {
.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit, .flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit,
@ -169,7 +171,7 @@ systems::Context::Begin()
// Release versions inline 'no-op'. // Release versions inline 'no-op'.
#if !defined(ASTER_NDEBUG) #if !defined(ASTER_NDEBUG)
void void
systems::Context::BeginDebugRegion(cstr const name, vec4 const color) Context::BeginDebugRegion(cstr const name, vec4 const color)
{ {
vk::DebugUtilsLabelEXT const label = { vk::DebugUtilsLabelEXT const label = {
.pLabelName = name, .pLabelName = name,
@ -179,21 +181,21 @@ systems::Context::BeginDebugRegion(cstr const name, vec4 const color)
} }
void void
systems::Context::EndDebugRegion() Context::EndDebugRegion()
{ {
m_Cmd.endDebugUtilsLabelEXT(); m_Cmd.endDebugUtilsLabelEXT();
} }
#endif #endif
void void
systems::Context::End() Context::End()
{ {
auto result = m_Cmd.end(); auto result = m_Cmd.end();
ERROR_IF(Failed(result), "Could not end context") THEN_ABORT(result); ERROR_IF(Failed(result), "Could not end context") THEN_ABORT(result);
} }
void void
systems::ComputeContext::Dispatch(Pipeline const &pipeline, u32 x, u32 y, u32 z, usize size, void *data) ComputeContext::Dispatch(Pipeline const &pipeline, u32 x, u32 y, u32 z, usize size, void *data)
{ {
BindPipeline(pipeline); BindPipeline(pipeline);
PushConstantBlock(0, size, data); PushConstantBlock(0, size, data);
@ -202,7 +204,7 @@ systems::ComputeContext::Dispatch(Pipeline const &pipeline, u32 x, u32 y, u32 z,
} }
void void
systems::ComputeContext::BindPipeline(Pipeline const &pipeline) ComputeContext::BindPipeline(Pipeline const &pipeline)
{ {
auto bindPoint = vk::PipelineBindPoint::eGraphics; auto bindPoint = vk::PipelineBindPoint::eGraphics;
switch (pipeline.m_Kind) switch (pipeline.m_Kind)
@ -229,57 +231,57 @@ systems::ComputeContext::BindPipeline(Pipeline const &pipeline)
} }
void void
systems::GraphicsContext::SetViewport(vk::Viewport const &viewport) GraphicsContext::SetViewport(vk::Viewport const &viewport)
{ {
m_Cmd.setViewport(0, 1, &viewport); m_Cmd.setViewport(0, 1, &viewport);
} }
void void
systems::GraphicsContext::BindVertexBuffer(Ref<VertexBuffer> const &vertexBuffer) GraphicsContext::BindVertexBuffer(Ref<VertexBuffer> const &vertexBuffer)
{ {
constexpr vk::DeviceSize offset = 0; constexpr vk::DeviceSize offset = 0;
m_Cmd.bindVertexBuffers(0, 1, &vertexBuffer->m_Buffer, &offset); m_Cmd.bindVertexBuffers(0, 1, &vertexBuffer->m_Buffer, &offset);
} }
void void
systems::GraphicsContext::BindIndexBuffer(Ref<IndexBuffer> const &indexBuffer) GraphicsContext::BindIndexBuffer(Ref<IndexBuffer> const &indexBuffer)
{ {
m_Cmd.bindIndexBuffer(indexBuffer->m_Buffer, 0, vk::IndexType::eUint32); m_Cmd.bindIndexBuffer(indexBuffer->m_Buffer, 0, vk::IndexType::eUint32);
} }
void void
systems::GraphicsContext::Draw(usize const vertexCount) GraphicsContext::Draw(usize const vertexCount)
{ {
m_Cmd.draw(static_cast<u32>(vertexCount), 1, 0, 0); m_Cmd.draw(static_cast<u32>(vertexCount), 1, 0, 0);
} }
void void
systems::GraphicsContext::DrawIndexed(usize indexCount) GraphicsContext::DrawIndexed(usize indexCount)
{ {
m_Cmd.drawIndexed(static_cast<u32>(indexCount), 1, 0, 0, 0); m_Cmd.drawIndexed(static_cast<u32>(indexCount), 1, 0, 0, 0);
} }
void void
systems::GraphicsContext::DrawIndexed(usize const indexCount, usize const firstIndex, usize const firstVertex) GraphicsContext::DrawIndexed(usize const indexCount, usize const firstIndex, usize const firstVertex)
{ {
m_Cmd.drawIndexed(static_cast<u32>(indexCount), 1, static_cast<u32>(firstIndex), static_cast<i32>(firstVertex), 0); m_Cmd.drawIndexed(static_cast<u32>(indexCount), 1, static_cast<u32>(firstIndex), static_cast<i32>(firstVertex), 0);
} }
void void
systems::GraphicsContext::BeginRendering(vk::RenderingInfo const &renderingInfo) GraphicsContext::BeginRendering(vk::RenderingInfo const &renderingInfo)
{ {
m_Cmd.beginRendering(&renderingInfo); m_Cmd.beginRendering(&renderingInfo);
m_Cmd.setScissor(0, 1, &renderingInfo.renderArea); m_Cmd.setScissor(0, 1, &renderingInfo.renderArea);
} }
void void
systems::GraphicsContext::EndRendering() GraphicsContext::EndRendering()
{ {
m_Cmd.endRendering(); m_Cmd.endRendering();
} }
void void
systems::TransferContext::UploadTexture(Ref<Image> const &image, eastl::span<u8> const &data) TransferContext::UploadTexture(Ref<Image> const &image, eastl::span<u8> const &data)
{ {
ERROR_IF(not(image and image->IsValid()), "Invalid image"); ERROR_IF(not(image and image->IsValid()), "Invalid image");
@ -314,7 +316,7 @@ systems::TransferContext::UploadTexture(Ref<Image> const &image, eastl::span<u8>
} }
void void
systems::TransferContext::UploadBuffer(Ref<Buffer> const &buffer, usize size, void const *data) TransferContext::UploadBuffer(Ref<Buffer> const &buffer, usize size, void const *data)
{ {
ERROR_IF(not(buffer and buffer->IsValid()), "Invalid buffer"); ERROR_IF(not(buffer and buffer->IsValid()), "Invalid buffer");
@ -333,18 +335,18 @@ systems::TransferContext::UploadBuffer(Ref<Buffer> const &buffer, usize size, vo
} }
void void
systems::TransferContext::Blit(vk::BlitImageInfo2 const &mipBlitInfo) TransferContext::Blit(vk::BlitImageInfo2 const &mipBlitInfo)
{ {
m_Cmd.blitImage2(&mipBlitInfo); m_Cmd.blitImage2(&mipBlitInfo);
} }
systems::TransferContext::TransferContext(TransferContext &&other) noexcept TransferContext::TransferContext(TransferContext &&other) noexcept
: Context{std::move(other)} : Context{std::move(other)}
{ {
} }
systems::TransferContext & TransferContext &
systems::TransferContext::operator=(TransferContext &&other) noexcept TransferContext::operator=(TransferContext &&other) noexcept
{ {
if (this == &other) if (this == &other)
return *this; return *this;
@ -353,7 +355,7 @@ systems::TransferContext::operator=(TransferContext &&other) noexcept
} }
void void
systems::ComputeContext::PushConstantBlock(usize const offset, usize const size, void const *data) ComputeContext::PushConstantBlock(usize const offset, usize const size, void const *data)
{ {
assert(m_PipelineInUse); assert(m_PipelineInUse);
@ -371,7 +373,7 @@ systems::ComputeContext::PushConstantBlock(usize const offset, usize const size,
m_Cmd.pushConstants(m_PipelineInUse->m_Layout, stage, static_cast<u32>(offset), static_cast<u32>(size), data); m_Cmd.pushConstants(m_PipelineInUse->m_Layout, stage, static_cast<u32>(offset), static_cast<u32>(size), data);
} }
using namespace systems::_internal; using namespace _internal;
ContextPool::ContextPool(RenderingDevice &device, u32 const queueFamilyIndex, ManagedBy const managedBy) ContextPool::ContextPool(RenderingDevice &device, u32 const queueFamilyIndex, ManagedBy const managedBy)
: m_Device{&device} : m_Device{&device}
@ -468,7 +470,7 @@ ContextPool::AllocateCommandBuffer()
return cmd; return cmd;
} }
systems::Context Context
ContextPool::CreateContext() ContextPool::CreateContext()
{ {
return Context{*this, AllocateCommandBuffer()}; return Context{*this, AllocateCommandBuffer()};
@ -487,19 +489,19 @@ ContextPool::Reset()
m_OwnedImageViews.clear(); m_OwnedImageViews.clear();
} }
systems::TransferContext TransferContext
TransferContextPool::CreateTransferContext() TransferContextPool::CreateTransferContext()
{ {
return TransferContext{*this, AllocateCommandBuffer()}; return TransferContext{*this, AllocateCommandBuffer()};
} }
systems::ComputeContext ComputeContext
ComputeContextPool::CreateComputeContext() ComputeContextPool::CreateComputeContext()
{ {
return ComputeContext{*this, AllocateCommandBuffer()}; return ComputeContext{*this, AllocateCommandBuffer()};
} }
systems::GraphicsContext GraphicsContext
GraphicsContextPool::CreateGraphicsContext() GraphicsContextPool::CreateGraphicsContext()
{ {
return GraphicsContext{*this, AllocateCommandBuffer()}; return GraphicsContext{*this, AllocateCommandBuffer()};

View File

@ -7,7 +7,8 @@
#include <aster/systems/pipeline_helpers.h> #include <aster/systems/pipeline_helpers.h>
using namespace systems::_internal; using namespace aster;
using namespace aster::_internal;
struct WhatVisitor struct WhatVisitor
{ {
@ -48,39 +49,39 @@ struct ValueVisitor
}; };
i32 i32
systems::PipelineCreationError::Value() PipelineCreationError::Value()
{ {
return std::visit(ValueVisitor{}, m_Data); return std::visit(ValueVisitor{}, m_Data);
} }
systems::PipelineCreationError::PipelineCreationError(vk::Result res) PipelineCreationError::PipelineCreationError(vk::Result res)
: m_Data{res} : m_Data{res}
{ {
} }
systems::PipelineCreationError::PipelineCreationError(SlangResult res) PipelineCreationError::PipelineCreationError(SlangResult res)
: m_Data{res} : m_Data{res}
{ {
} }
systems::PipelineCreationError::PipelineCreationError() PipelineCreationError::PipelineCreationError()
: m_Data{std::monostate{}} : m_Data{std::monostate{}}
{ {
} }
systems::PipelineCreationError::operator bool() const PipelineCreationError::operator bool() const
{ {
return not std::holds_alternative<std::monostate>(m_Data); return not std::holds_alternative<std::monostate>(m_Data);
} }
std::string std::string
systems::PipelineCreationError::What() PipelineCreationError::What()
{ {
return std::visit(WhatVisitor{}, m_Data); return std::visit(WhatVisitor{}, m_Data);
} }
vk::ShaderStageFlagBits vk::ShaderStageFlagBits
systems::SlangToVulkanShaderStage(SlangStage const stage) _internal::SlangToVulkanShaderStage(SlangStage const stage)
{ {
switch (stage) switch (stage)
{ {

View File

@ -21,37 +21,39 @@
#undef DOMAIN #undef DOMAIN
#endif #endif
using namespace aster;
static constexpr QueueSupportFlags REQUIRED_QUEUE_SUPPORT = static constexpr QueueSupportFlags REQUIRED_QUEUE_SUPPORT =
QueueSupportFlags{} | QueueSupportFlagBits::eGraphics | QueueSupportFlagBits::eCompute | QueueSupportFlags{} | QueueSupportFlagBits::eGraphics | QueueSupportFlagBits::eCompute |
QueueSupportFlagBits::ePresent | QueueSupportFlagBits::eTransfer; QueueSupportFlagBits::ePresent | QueueSupportFlagBits::eTransfer;
vk::CompareOp vk::CompareOp
DepthOpToVulkan(systems::GraphicsPipelineCreateInfo::CompareOp depthOp) DepthOpToVulkan(GraphicsPipelineCreateInfo::CompareOp depthOp)
{ {
switch (depthOp) switch (depthOp)
{ {
case systems::GraphicsPipelineCreateInfo::CompareOp::eNever: case GraphicsPipelineCreateInfo::CompareOp::eNever:
return vk::CompareOp::eNever; return vk::CompareOp::eNever;
case systems::GraphicsPipelineCreateInfo::CompareOp::eLessThan: case GraphicsPipelineCreateInfo::CompareOp::eLessThan:
return vk::CompareOp::eLess; return vk::CompareOp::eLess;
case systems::GraphicsPipelineCreateInfo::CompareOp::eEqualTo: case GraphicsPipelineCreateInfo::CompareOp::eEqualTo:
return vk::CompareOp::eEqual; return vk::CompareOp::eEqual;
case systems::GraphicsPipelineCreateInfo::CompareOp::eGreaterThan: case GraphicsPipelineCreateInfo::CompareOp::eGreaterThan:
return vk::CompareOp::eGreater; return vk::CompareOp::eGreater;
case systems::GraphicsPipelineCreateInfo::CompareOp::eLessThanOrEqualTo: case GraphicsPipelineCreateInfo::CompareOp::eLessThanOrEqualTo:
return vk::CompareOp::eLessOrEqual; return vk::CompareOp::eLessOrEqual;
case systems::GraphicsPipelineCreateInfo::CompareOp::eGreaterThanOrEqualTo: case GraphicsPipelineCreateInfo::CompareOp::eGreaterThanOrEqualTo:
return vk::CompareOp::eGreaterOrEqual; return vk::CompareOp::eGreaterOrEqual;
case systems::GraphicsPipelineCreateInfo::CompareOp::eNotEqualTo: case GraphicsPipelineCreateInfo::CompareOp::eNotEqualTo:
return vk::CompareOp::eNotEqual; return vk::CompareOp::eNotEqual;
case systems::GraphicsPipelineCreateInfo::CompareOp::eAlways: case GraphicsPipelineCreateInfo::CompareOp::eAlways:
return vk::CompareOp::eAlways; return vk::CompareOp::eAlways;
} }
return vk::CompareOp::eAlways; return vk::CompareOp::eAlways;
} }
vk::PipelineDepthStencilStateCreateInfo vk::PipelineDepthStencilStateCreateInfo
systems::GraphicsPipelineCreateInfo::GetDepthStencilStateCreateInfo() const GraphicsPipelineCreateInfo::GetDepthStencilStateCreateInfo() const
{ {
bool depthEnabled = false; bool depthEnabled = false;
bool depthWriteEnabled = false; bool depthWriteEnabled = false;
@ -77,7 +79,7 @@ systems::GraphicsPipelineCreateInfo::GetDepthStencilStateCreateInfo() const
} }
PhysicalDevice PhysicalDevice
systems::DefaultPhysicalDeviceSelector(PhysicalDevices const &physicalDevices) aster::DefaultPhysicalDeviceSelector(PhysicalDevices const &physicalDevices)
{ {
for (auto &physicalDevice : physicalDevices) for (auto &physicalDevice : physicalDevices)
{ {
@ -107,7 +109,7 @@ systems::DefaultPhysicalDeviceSelector(PhysicalDevices const &physicalDevices)
// ==================================================================================================== // ====================================================================================================
Ref<StorageBuffer> Ref<StorageBuffer>
systems::RenderingDevice::CreateStorageBuffer(usize const size, cstr const name) RenderingDevice::CreateStorageBuffer(usize const size, cstr const name)
{ {
// TODO: Storage and Index buffer are set. // TODO: Storage and Index buffer are set.
// This is hacky and should be improved. // This is hacky and should be improved.
@ -122,7 +124,7 @@ systems::RenderingDevice::CreateStorageBuffer(usize const size, cstr const name)
} }
Ref<IndexBuffer> Ref<IndexBuffer>
systems::RenderingDevice::CreateIndexBuffer(usize size, cstr name) RenderingDevice::CreateIndexBuffer(usize size, cstr name)
{ {
// TODO: Storage and Index buffer are set. // TODO: Storage and Index buffer are set.
// This is hacky and should be improved. // This is hacky and should be improved.
@ -137,7 +139,7 @@ systems::RenderingDevice::CreateIndexBuffer(usize size, cstr name)
} }
Ref<UniformBuffer> Ref<UniformBuffer>
systems::RenderingDevice::CreateUniformBuffer(usize const size, cstr const name) RenderingDevice::CreateUniformBuffer(usize const size, cstr const name)
{ {
constexpr vk::BufferUsageFlags usage = vk::BufferUsageFlagBits::eUniformBuffer; constexpr vk::BufferUsageFlags usage = vk::BufferUsageFlagBits::eUniformBuffer;
constexpr VmaAllocationCreateFlags createFlags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | constexpr VmaAllocationCreateFlags createFlags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT |
@ -148,7 +150,7 @@ systems::RenderingDevice::CreateUniformBuffer(usize const size, cstr const name)
} }
Ref<StagingBuffer> Ref<StagingBuffer>
systems::RenderingDevice::CreateStagingBuffer(usize const size, cstr const name) RenderingDevice::CreateStagingBuffer(usize const size, cstr const name)
{ {
constexpr vk::BufferUsageFlags usage = vk::BufferUsageFlagBits::eTransferSrc; constexpr vk::BufferUsageFlags usage = vk::BufferUsageFlagBits::eTransferSrc;
constexpr VmaAllocationCreateFlags createFlags = constexpr VmaAllocationCreateFlags createFlags =
@ -158,7 +160,7 @@ systems::RenderingDevice::CreateStagingBuffer(usize const size, cstr const name)
} }
Ref<VertexBuffer> Ref<VertexBuffer>
systems::RenderingDevice::CreateVertexBuffer(usize const size, cstr const name) RenderingDevice::CreateVertexBuffer(usize const size, cstr const name)
{ {
constexpr vk::BufferUsageFlags usage = vk::BufferUsageFlagBits::eVertexBuffer; constexpr vk::BufferUsageFlags usage = vk::BufferUsageFlagBits::eVertexBuffer;
constexpr VmaAllocationCreateFlags createFlags = constexpr VmaAllocationCreateFlags createFlags =
@ -172,10 +174,10 @@ systems::RenderingDevice::CreateVertexBuffer(usize const size, cstr const name)
#pragma region Image Management #pragma region Image Management
// ==================================================================================================== // ====================================================================================================
vk::ImageCreateInfo ToImageCreateInfo(systems::Texture2DCreateInfo const &createInfo); vk::ImageCreateInfo ToImageCreateInfo(Texture2DCreateInfo const &createInfo);
vk::ImageCreateInfo ToImageCreateInfo(systems::TextureCubeCreateInfo const &createInfo); vk::ImageCreateInfo ToImageCreateInfo(TextureCubeCreateInfo const &createInfo);
vk::ImageCreateInfo ToImageCreateInfo(systems::AttachmentCreateInfo const &createInfo); vk::ImageCreateInfo ToImageCreateInfo(AttachmentCreateInfo const &createInfo);
vk::ImageCreateInfo ToImageCreateInfo(systems::DepthStencilImageCreateInfo const &createInfo); vk::ImageCreateInfo ToImageCreateInfo(DepthStencilImageCreateInfo const &createInfo);
namespace usage_flags namespace usage_flags
{ {
@ -189,7 +191,7 @@ constexpr vk::ImageUsageFlags DEPTH_STENCIL_ATTACHMENT = vk::ImageUsageFlagBits:
} // namespace usage_flags } // namespace usage_flags
Ref<Image> Ref<Image>
systems::RenderingDevice::CreateTexture2D(Texture2DCreateInfo const &createInfo) RenderingDevice::CreateTexture2D(Texture2DCreateInfo const &createInfo)
{ {
constexpr VmaAllocationCreateInfo allocationCreateInfo = { constexpr VmaAllocationCreateInfo allocationCreateInfo = {
.flags = {}, .flags = {},
@ -221,7 +223,7 @@ systems::RenderingDevice::CreateTexture2D(Texture2DCreateInfo const &createInfo)
} }
Ref<ImageCube> Ref<ImageCube>
systems::RenderingDevice::CreateTextureCube(TextureCubeCreateInfo const &createInfo) RenderingDevice::CreateTextureCube(TextureCubeCreateInfo const &createInfo)
{ {
constexpr VmaAllocationCreateInfo allocationCreateInfo = { constexpr VmaAllocationCreateInfo allocationCreateInfo = {
.flags = {}, .flags = {},
@ -253,7 +255,7 @@ systems::RenderingDevice::CreateTextureCube(TextureCubeCreateInfo const &createI
} }
Ref<Image> Ref<Image>
systems::RenderingDevice::CreateAttachment(AttachmentCreateInfo const &createInfo) RenderingDevice::CreateAttachment(AttachmentCreateInfo const &createInfo)
{ {
constexpr VmaAllocationCreateInfo allocationCreateInfo = { constexpr VmaAllocationCreateInfo allocationCreateInfo = {
.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT, .flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT,
@ -280,7 +282,7 @@ systems::RenderingDevice::CreateAttachment(AttachmentCreateInfo const &createInf
} }
Ref<Image> Ref<Image>
systems::RenderingDevice::CreateDepthStencilImage(DepthStencilImageCreateInfo const &createInfo) RenderingDevice::CreateDepthStencilImage(DepthStencilImageCreateInfo const &createInfo)
{ {
constexpr VmaAllocationCreateInfo allocationCreateInfo = { constexpr VmaAllocationCreateInfo allocationCreateInfo = {
.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT, .flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT,
@ -307,7 +309,7 @@ systems::RenderingDevice::CreateDepthStencilImage(DepthStencilImageCreateInfo co
} }
vk::ImageCreateInfo vk::ImageCreateInfo
ToImageCreateInfo(systems::Texture2DCreateInfo const &createInfo) ToImageCreateInfo(Texture2DCreateInfo const &createInfo)
{ {
auto &[format, extent, name, isSampled, isMipMapped, isStorage] = createInfo; auto &[format, extent, name, isSampled, isMipMapped, isStorage] = createInfo;
@ -335,7 +337,7 @@ ToImageCreateInfo(systems::Texture2DCreateInfo const &createInfo)
} }
vk::ImageCreateInfo vk::ImageCreateInfo
ToImageCreateInfo(systems::TextureCubeCreateInfo const &createInfo) ToImageCreateInfo(TextureCubeCreateInfo const &createInfo)
{ {
auto &[format, side, name, isSampled, isMipMapped, isStorage] = createInfo; auto &[format, side, name, isSampled, isMipMapped, isStorage] = createInfo;
@ -363,7 +365,7 @@ ToImageCreateInfo(systems::TextureCubeCreateInfo const &createInfo)
} }
vk::ImageCreateInfo vk::ImageCreateInfo
ToImageCreateInfo(systems::AttachmentCreateInfo const &createInfo) ToImageCreateInfo(AttachmentCreateInfo const &createInfo)
{ {
auto &[format, extent, name] = createInfo; auto &[format, extent, name] = createInfo;
@ -380,7 +382,7 @@ ToImageCreateInfo(systems::AttachmentCreateInfo const &createInfo)
} }
vk::ImageCreateInfo vk::ImageCreateInfo
ToImageCreateInfo(systems::DepthStencilImageCreateInfo const &createInfo) ToImageCreateInfo(DepthStencilImageCreateInfo const &createInfo)
{ {
auto &[extent, name] = createInfo; auto &[extent, name] = createInfo;
@ -404,7 +406,7 @@ ToImageCreateInfo(systems::DepthStencilImageCreateInfo const &createInfo)
// ==================================================================================================== // ====================================================================================================
Ref<ImageView> Ref<ImageView>
systems::RenderingDevice::CreateView(ViewCreateInfo<Image> const &createInfo) RenderingDevice::CreateView(ViewCreateInfo<Image> const &createInfo)
{ {
auto const layerCount = createInfo.GetLayerCount(); auto const layerCount = createInfo.GetLayerCount();
auto const mipCount = createInfo.GetMipLevelCount(); auto const mipCount = createInfo.GetMipLevelCount();
@ -432,7 +434,7 @@ systems::RenderingDevice::CreateView(ViewCreateInfo<Image> const &createInfo)
// ==================================================================================================== // ====================================================================================================
Ref<TextureView> Ref<TextureView>
systems::RenderingDevice::CreateTexture2DWithView(Texture2DCreateInfo const &createInfo) RenderingDevice::CreateTexture2DWithView(Texture2DCreateInfo const &createInfo)
{ {
return CreateView<TextureView>({ return CreateView<TextureView>({
.m_Image = CastImage<Texture>(CreateTexture2D(createInfo)), .m_Image = CastImage<Texture>(CreateTexture2D(createInfo)),
@ -443,7 +445,7 @@ systems::RenderingDevice::CreateTexture2DWithView(Texture2DCreateInfo const &cre
} }
Ref<ImageCubeView> Ref<ImageCubeView>
systems::RenderingDevice::CreateTextureCubeWithView(TextureCubeCreateInfo const &createInfo) RenderingDevice::CreateTextureCubeWithView(TextureCubeCreateInfo const &createInfo)
{ {
return CreateView<ImageCubeView>({ return CreateView<ImageCubeView>({
.m_Image = CreateTextureCube(createInfo), .m_Image = CreateTextureCube(createInfo),
@ -454,7 +456,7 @@ systems::RenderingDevice::CreateTextureCubeWithView(TextureCubeCreateInfo const
} }
Ref<ImageView> Ref<ImageView>
systems::RenderingDevice::CreateAttachmentWithView(AttachmentCreateInfo const &createInfo) RenderingDevice::CreateAttachmentWithView(AttachmentCreateInfo const &createInfo)
{ {
return CreateView({ return CreateView({
.m_Image = CreateAttachment(createInfo), .m_Image = CreateAttachment(createInfo),
@ -465,7 +467,7 @@ systems::RenderingDevice::CreateAttachmentWithView(AttachmentCreateInfo const &c
} }
Ref<ImageView> Ref<ImageView>
systems::RenderingDevice::CreateDepthStencilImageWithView(DepthStencilImageCreateInfo const &createInfo) RenderingDevice::CreateDepthStencilImageWithView(DepthStencilImageCreateInfo const &createInfo)
{ {
return CreateView({ return CreateView({
.m_Image = CreateDepthStencilImage(createInfo), .m_Image = CreateDepthStencilImage(createInfo),
@ -482,7 +484,7 @@ systems::RenderingDevice::CreateDepthStencilImageWithView(DepthStencilImageCreat
// ==================================================================================================== // ====================================================================================================
Ref<Sampler> Ref<Sampler>
systems::RenderingDevice::CreateSampler(SamplerCreateInfo const &createInfo) RenderingDevice::CreateSampler(SamplerCreateInfo const &createInfo)
{ {
auto vkCreateInfo = static_cast<vk::SamplerCreateInfo>(createInfo); auto vkCreateInfo = static_cast<vk::SamplerCreateInfo>(createInfo);
@ -501,8 +503,8 @@ systems::RenderingDevice::CreateSampler(SamplerCreateInfo const &createInfo)
// Pipelines // Pipelines
// ---------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------
systems::PipelineCreationError PipelineCreationError
systems::RenderingDevice::CreateGraphicsPipeline(Pipeline &pipelineOut, GraphicsPipelineCreateInfo const &createInfo) RenderingDevice::CreateGraphicsPipeline(Pipeline &pipelineOut, GraphicsPipelineCreateInfo const &createInfo)
{ {
eastl::fixed_vector<vk::PipelineShaderStageCreateInfo, ShaderTypeCount, false> shaders; eastl::fixed_vector<vk::PipelineShaderStageCreateInfo, ShaderTypeCount, false> shaders;
Slang::ComPtr<slang::IComponentType> program; Slang::ComPtr<slang::IComponentType> program;
@ -640,8 +642,8 @@ systems::RenderingDevice::CreateGraphicsPipeline(Pipeline &pipelineOut, Graphics
return {}; return {};
} }
systems::PipelineCreationError PipelineCreationError
systems::RenderingDevice::CreateComputePipeline(Pipeline &pipelineOut, ComputePipelineCreateInfo const &createInfo) RenderingDevice::CreateComputePipeline(Pipeline &pipelineOut, ComputePipelineCreateInfo const &createInfo)
{ {
eastl::fixed_vector<vk::PipelineShaderStageCreateInfo, ShaderTypeCount, false> shaders; eastl::fixed_vector<vk::PipelineShaderStageCreateInfo, ShaderTypeCount, false> shaders;
Slang::ComPtr<slang::IComponentType> program; Slang::ComPtr<slang::IComponentType> program;
@ -698,8 +700,8 @@ systems::RenderingDevice::CreateComputePipeline(Pipeline &pipelineOut, ComputePi
ERROR("Unimplemented Stage " #STAGE); \ ERROR("Unimplemented Stage " #STAGE); \
return SLANG_FAIL return SLANG_FAIL
systems::PipelineCreationError PipelineCreationError
systems::RenderingDevice::CreateShaders( RenderingDevice::CreateShaders(
eastl::fixed_vector<vk::PipelineShaderStageCreateInfo, ShaderTypeCount, false> &shadersOut, eastl::fixed_vector<vk::PipelineShaderStageCreateInfo, ShaderTypeCount, false> &shadersOut,
Slang::ComPtr<slang::IComponentType> &program, std::span<ShaderInfo const> const &shaders) Slang::ComPtr<slang::IComponentType> &program, std::span<ShaderInfo const> const &shaders)
{ {
@ -836,7 +838,7 @@ systems::RenderingDevice::CreateShaders(
if (auto entryPointReflection = progLayout->getEntryPointByIndex(entryPoint)) if (auto entryPointReflection = progLayout->getEntryPointByIndex(entryPoint))
{ {
outShader.pName = entryPointReflection->getName(); outShader.pName = entryPointReflection->getName();
outShader.stage = SlangToVulkanShaderStage(entryPointReflection->getStage()); outShader.stage = _internal::SlangToVulkanShaderStage(entryPointReflection->getStage());
} }
} }
@ -870,20 +872,20 @@ systems::RenderingDevice::CreateShaders(
struct PipelineLayoutBuilder struct PipelineLayoutBuilder
{ {
systems::RenderingDevice *m_Device; RenderingDevice *m_Device;
eastl::vector<vk::DescriptorSetLayout> m_DescriptorSetLayouts; eastl::vector<vk::DescriptorSetLayout> m_DescriptorSetLayouts;
eastl::vector<vk::PushConstantRange> m_PushConstantRanges; eastl::vector<vk::PushConstantRange> m_PushConstantRanges;
explicit PipelineLayoutBuilder(systems::RenderingDevice *device) explicit PipelineLayoutBuilder(RenderingDevice *device)
: m_Device{device} : m_Device{device}
{ {
} }
systems::PipelineCreationError PipelineCreationError
Build(vk::PipelineLayout &pipelineLayout, eastl::vector<vk::DescriptorSetLayout> &descriptorSetLayouts); Build(vk::PipelineLayout &pipelineLayout, eastl::vector<vk::DescriptorSetLayout> &descriptorSetLayouts);
}; };
systems::PipelineCreationError PipelineCreationError
PipelineLayoutBuilder::Build(vk::PipelineLayout &pipelineLayout, PipelineLayoutBuilder::Build(vk::PipelineLayout &pipelineLayout,
eastl::vector<vk::DescriptorSetLayout> &descriptorSetLayouts) eastl::vector<vk::DescriptorSetLayout> &descriptorSetLayouts)
{ {
@ -901,8 +903,8 @@ PipelineLayoutBuilder::Build(vk::PipelineLayout &pipelineLayout,
return result; return result;
} }
systems::PipelineCreationError PipelineCreationError
systems::RenderingDevice::CreatePipelineLayout(vk::PipelineLayout &pipelineLayout, RenderingDevice::CreatePipelineLayout(vk::PipelineLayout &pipelineLayout,
Slang::ComPtr<slang::IComponentType> const &program) Slang::ComPtr<slang::IComponentType> const &program)
{ {
using Slang::ComPtr; using Slang::ComPtr;
@ -993,7 +995,7 @@ FindAsyncComputeQueue(PhysicalDevice const &physicalDevice, u32 primaryQueueFami
return std::nullopt; return std::nullopt;
} }
systems::RenderingDevice::RenderingDevice(DeviceCreateInfo const &createInfo) RenderingDevice::RenderingDevice(DeviceCreateInfo const &createInfo)
: m_Window{createInfo.m_Window} : m_Window{createInfo.m_Window}
, m_SyncServer{new _internal::SyncServer{*this}} , m_SyncServer{new _internal::SyncServer{*this}}
{ {
@ -1110,7 +1112,7 @@ systems::RenderingDevice::RenderingDevice(DeviceCreateInfo const &createInfo)
} }
} }
systems::RenderingDevice::~RenderingDevice() RenderingDevice::~RenderingDevice()
{ {
for (auto &frame : m_Frames) for (auto &frame : m_Frames)
{ {
@ -1125,8 +1127,8 @@ systems::RenderingDevice::~RenderingDevice()
#pragma region Frames #pragma region Frames
// ==================================================================================================== // ====================================================================================================
systems::Frame & Frame &
systems::RenderingDevice::GetNextFrame() RenderingDevice::GetNextFrame()
{ {
if (m_CommitManager) if (m_CommitManager)
m_CommitManager->Update(); m_CommitManager->Update();
@ -1167,7 +1169,7 @@ systems::RenderingDevice::GetNextFrame()
} }
void void
systems::RenderingDevice::Present(Frame &frame, GraphicsContext &graphicsContext) RenderingDevice::Present(Frame &frame, GraphicsContext &graphicsContext)
{ {
vk::PipelineStageFlags waitDstStage = vk::PipelineStageFlagBits::eColorAttachmentOutput; vk::PipelineStageFlags waitDstStage = vk::PipelineStageFlagBits::eColorAttachmentOutput;
vk::SubmitInfo const submitInfo = { vk::SubmitInfo const submitInfo = {
@ -1205,20 +1207,20 @@ systems::RenderingDevice::Present(Frame &frame, GraphicsContext &graphicsContext
} }
} }
systems::TransferContext TransferContext
systems::RenderingDevice::CreateTransferContext() RenderingDevice::CreateTransferContext()
{ {
return m_TransferContextPool.CreateTransferContext(); return m_TransferContextPool.CreateTransferContext();
} }
systems::ComputeContext ComputeContext
systems::RenderingDevice::CreateComputeContext() RenderingDevice::CreateComputeContext()
{ {
return m_ComputeContextPool.CreateComputeContext(); return m_ComputeContextPool.CreateComputeContext();
} }
systems::Receipt Receipt
systems::RenderingDevice::Submit(Context &context) RenderingDevice::Submit(Context &context)
{ {
auto const rect = m_SyncServer->Allocate(); auto const rect = m_SyncServer->Allocate();
auto &entry = m_SyncServer->GetEntry(rect); auto &entry = m_SyncServer->GetEntry(rect);
@ -1254,13 +1256,13 @@ systems::RenderingDevice::Submit(Context &context)
} }
void void
systems::RenderingDevice::WaitOn(Receipt recpt) RenderingDevice::WaitOn(Receipt recpt)
{ {
m_SyncServer->WaitOn(recpt); m_SyncServer->WaitOn(recpt);
} }
void void
systems::Frame::Reset(u32 imageIdx, vk::Image swapchainImage, vk::ImageView swapchainImageView, Size2D swapchainSize) Frame::Reset(u32 imageIdx, vk::Image swapchainImage, vk::ImageView swapchainImageView, Size2D swapchainSize)
{ {
AbortIfFailedMV(m_Device->m_Device->resetFences(1, &m_FrameAvailableFence), "Fence {} reset failed.", m_FrameIdx); AbortIfFailedMV(m_Device->m_Device->resetFences(1, &m_FrameAvailableFence), "Fence {} reset failed.", m_FrameIdx);
@ -1274,33 +1276,33 @@ systems::Frame::Reset(u32 imageIdx, vk::Image swapchainImage, vk::ImageView swap
m_SwapchainSize = swapchainSize; m_SwapchainSize = swapchainSize;
} }
systems::GraphicsContext GraphicsContext
systems::Frame::CreateGraphicsContext() Frame::CreateGraphicsContext()
{ {
return m_PrimaryPool.CreateGraphicsContext(); return m_PrimaryPool.CreateGraphicsContext();
} }
systems::TransferContext TransferContext
systems::Frame::CreateAsyncTransferContext() Frame::CreateAsyncTransferContext()
{ {
return m_AsyncTransferPool.CreateTransferContext(); return m_AsyncTransferPool.CreateTransferContext();
} }
systems::ComputeContext ComputeContext
systems::Frame::CreateAsyncComputeContext() Frame::CreateAsyncComputeContext()
{ {
return m_AsyncComputePool.CreateComputeContext(); return m_AsyncComputePool.CreateComputeContext();
} }
void void
systems::Frame::WaitUntilReady() Frame::WaitUntilReady()
{ {
AbortIfFailedMV(m_Device->m_Device->waitForFences(1, &m_FrameAvailableFence, true, MaxValue<u64>), AbortIfFailedMV(m_Device->m_Device->waitForFences(1, &m_FrameAvailableFence, true, MaxValue<u64>),
"Waiting for fence {} failed.", m_FrameIdx); "Waiting for fence {} failed.", m_FrameIdx);
} }
systems::Frame & Frame &
systems::Frame::operator=(Frame &&other) noexcept Frame::operator=(Frame &&other) noexcept
{ {
if (this == &other) if (this == &other)
return *this; return *this;
@ -1319,7 +1321,7 @@ systems::Frame::operator=(Frame &&other) noexcept
return *this; return *this;
} }
systems::Frame::Frame(RenderingDevice &device, u32 frameIndex, u32 const primaryQueueFamily, Frame::Frame(RenderingDevice &device, u32 frameIndex, u32 const primaryQueueFamily,
u32 const asyncTransferQueue, u32 const asyncComputeQueue) u32 const asyncTransferQueue, u32 const asyncComputeQueue)
: m_Device{&device} : m_Device{&device}
, m_PrimaryPool{device, primaryQueueFamily, _internal::ContextPool::ManagedBy::eFrame} , m_PrimaryPool{device, primaryQueueFamily, _internal::ContextPool::ManagedBy::eFrame}
@ -1348,7 +1350,7 @@ systems::Frame::Frame(RenderingDevice &device, u32 frameIndex, u32 const primary
DEBUG("Frame {} created successfully.", frameIndex); DEBUG("Frame {} created successfully.", frameIndex);
} }
systems::Frame::Frame(Frame &&other) noexcept Frame::Frame(Frame &&other) noexcept
: m_Device{Take(other.m_Device)} : m_Device{Take(other.m_Device)}
, m_PrimaryPool{std::move(other.m_PrimaryPool)} , m_PrimaryPool{std::move(other.m_PrimaryPool)}
, m_AsyncTransferPool{std::move(other.m_AsyncTransferPool)} , m_AsyncTransferPool{std::move(other.m_AsyncTransferPool)}

View File

@ -7,7 +7,8 @@
#include "aster/systems/rendering_device.h" #include "aster/systems/rendering_device.h"
using namespace systems::_internal; using namespace aster;
using namespace aster::_internal;
SyncServer::Entry::Entry(RenderingDevice &device) SyncServer::Entry::Entry(RenderingDevice &device)
: m_CurrentPoint{0, 1} : m_CurrentPoint{0, 1}
@ -67,7 +68,7 @@ SyncServer::Entry::AttachPool(ContextPool *pool)
m_AttachedPool = pool; m_AttachedPool = pool;
} }
systems::Receipt Receipt
SyncServer::Allocate() SyncServer::Allocate()
{ {
auto &entry = AllocateEntry(); auto &entry = AllocateEntry();

View File

@ -5,8 +5,10 @@
#include "aster/util/files.h" #include "aster/util/files.h"
using namespace aster;
eastl::vector<u32> eastl::vector<u32>
ReadFile(std::string_view fileName) aster::ReadFile(std::string_view fileName)
{ {
FILE *filePtr = fopen(fileName.data(), "rb"); FILE *filePtr = fopen(fileName.data(), "rb");
@ -32,7 +34,7 @@ ReadFile(std::string_view fileName)
} }
eastl::vector<u8> eastl::vector<u8>
ReadFileBytes(std::string_view fileName, bool errorOnFail) aster::ReadFileBytes(std::string_view fileName, bool errorOnFail)
{ {
FILE *filePtr = fopen(fileName.data(), "rb"); FILE *filePtr = fopen(fileName.data(), "rb");
@ -61,7 +63,7 @@ ReadFileBytes(std::string_view fileName, bool errorOnFail)
} }
bool bool
WriteFileBytes(std::string_view fileName, eastl::span<u8> const data) aster::WriteFileBytes(std::string_view fileName, eastl::span<u8> const data)
{ {
FILE *filePtr = fopen(fileName.data(), "wb"); FILE *filePtr = fopen(fileName.data(), "wb");

View File

@ -5,7 +5,7 @@
#include "aster/util/logger.h" #include "aster/util/logger.h"
auto g_Logger = Logger(); auto g_Logger = aster::Logger();
// ReSharper disable once CppInconsistentNaming // ReSharper disable once CppInconsistentNaming
/* Credits to Const-me */ /* Credits to Const-me */

View File

@ -5,10 +5,10 @@ cmake_minimum_required(VERSION 3.13)
find_package(imgui CONFIG REQUIRED) find_package(imgui CONFIG REQUIRED)
add_library(util_helper STATIC add_library(util_helper STATIC
"helpers.h"
"helpers.cpp"
"frame.cpp"
"frame.h"
"gui.cpp" "gui.cpp"
"gui.h") "gui.h")

View File

@ -1,174 +0,0 @@
// =============================================
// Aster: frame.cpp
// Copyright (c) 2020-2025 Anish Bhobe
// =============================================
#include "frame.h"
#include "aster/core/device.h"
#include "aster/core/swapchain.h"
#include "helpers.h"
Frame::Frame(const Device *device, const u32 queueFamilyIndex, const u32 frameCount)
: m_FrameIdx(frameCount)
, m_ImageIdx(0)
{
m_Device = device;
eastl::fixed_string<char, 50, false> name = "Frame ";
name += static_cast<char>('0' + frameCount);
const vk::CommandPoolCreateInfo commandPoolCreateInfo = {
.flags = vk::CommandPoolCreateFlagBits::eTransient,
.queueFamilyIndex = queueFamilyIndex,
};
AbortIfFailedMV(device->m_Device.createCommandPool(&commandPoolCreateInfo, nullptr, &m_Pool),
"Could not command pool for frame {}", frameCount);
constexpr vk::FenceCreateInfo fenceCreateInfo = {.flags = vk::FenceCreateFlagBits::eSignaled};
AbortIfFailedMV(device->m_Device.createFence(&fenceCreateInfo, nullptr, &m_FrameAvailableFence),
"Could not create a fence for frame {}", frameCount);
constexpr vk::SemaphoreCreateInfo semaphoreCreateInfo = {};
AbortIfFailedMV(device->m_Device.createSemaphore(&semaphoreCreateInfo, nullptr, &m_ImageAcquireSem),
"Could not create IA semaphore for frame {}.", frameCount);
AbortIfFailedMV(device->m_Device.createSemaphore(&semaphoreCreateInfo, nullptr, &m_RenderFinishSem),
"Could not create RF semaphore for frame {}.", frameCount);
const vk::CommandBufferAllocateInfo allocateInfo = {
.commandPool = m_Pool,
.level = vk::CommandBufferLevel::ePrimary,
.commandBufferCount = 1,
};
AbortIfFailed(m_Device->m_Device.allocateCommandBuffers(&allocateInfo, &m_CommandBuffer));
device->SetName(m_Pool, name.c_str());
device->SetName(m_FrameAvailableFence, name.c_str());
device->SetName(m_ImageAcquireSem, name.c_str());
device->SetName(m_RenderFinishSem, name.c_str());
device->SetName(m_CommandBuffer, name.c_str());
DEBUG("Frame {} created successfully.", frameCount);
}
void
Frame::Present(const vk::Queue commandQueue, Swapchain *swapchain, const Surface *surface, Size2D size)
{
vk::PresentInfoKHR presentInfo = {
.waitSemaphoreCount = 1,
.pWaitSemaphores = &m_RenderFinishSem,
.swapchainCount = 1,
.pSwapchains = &swapchain->m_Swapchain,
.pImageIndices = &m_ImageIdx,
.pResults = nullptr,
};
switch (auto result = commandQueue.presentKHR(&presentInfo))
{
case vk::Result::eSuccess:
break;
case vk::Result::eErrorOutOfDateKHR:
case vk::Result::eSuboptimalKHR:
DEBUG("Recreating Swapchain. Cause: {}", result);
swapchain->Create(*surface, size);
break; // Present failed. We do nothing. Frame is skipped.
default:
AbortIfFailedM(result, "Swapchain Present failed.");
}
}
Frame::~Frame()
{
m_Device->m_Device.destroy(m_RenderFinishSem, nullptr);
m_Device->m_Device.destroy(m_ImageAcquireSem, nullptr);
m_Device->m_Device.destroy(m_FrameAvailableFence, nullptr);
m_Device->m_Device.destroy(m_Pool, nullptr);
DEBUG("Destoryed Frame");
}
Frame::Frame(Frame &&other) noexcept
: m_Device(other.m_Device)
, m_Pool(Take(other.m_Pool))
, m_CommandBuffer(Take(other.m_CommandBuffer))
, m_FrameAvailableFence(Take(other.m_FrameAvailableFence))
, m_ImageAcquireSem(Take(other.m_ImageAcquireSem))
, m_RenderFinishSem(Take(other.m_RenderFinishSem))
, m_FrameIdx(other.m_FrameIdx)
, m_ImageIdx(other.m_ImageIdx)
{
}
Frame &
Frame::operator=(Frame &&other) noexcept
{
if (this == &other)
return *this;
m_Device = other.m_Device;
m_Pool = Take(other.m_Pool);
m_CommandBuffer = Take(other.m_CommandBuffer);
m_FrameAvailableFence = Take(other.m_FrameAvailableFence);
m_ImageAcquireSem = Take(other.m_ImageAcquireSem);
m_RenderFinishSem = Take(other.m_RenderFinishSem);
m_FrameIdx = other.m_FrameIdx;
m_ImageIdx = other.m_ImageIdx;
return *this;
}
// Frame Manager
FrameManager::FrameManager(const Device *device, u32 queueFamilyIndex, u32 framesInFlight)
: m_Device(device)
, m_FramesInFlight(framesInFlight)
{
for (u32 i = 0; i < framesInFlight; ++i)
{
m_Frames.emplace_back(device, queueFamilyIndex, i);
}
}
Frame *
FrameManager::GetNextFrame(Swapchain *swapchain, const Surface *surface, Size2D size)
{
Frame *currentFrame = &m_Frames[m_CurrentFrameIdx];
u32 frameIndex = m_CurrentFrameIdx;
m_CurrentFrameIdx = (m_CurrentFrameIdx + 1) % m_FramesInFlight;
AbortIfFailedMV(m_Device->m_Device.waitForFences(1, &currentFrame->m_FrameAvailableFence, true, MaxValue<u64>),
"Waiting for fence {} failed.", frameIndex);
u32 imageIndex = 0;
bool imageAcquired = false;
while (!imageAcquired)
{
auto result = m_Device->m_Device.acquireNextImageKHR(swapchain->m_Swapchain, MaxValue<u64>,
currentFrame->m_ImageAcquireSem, nullptr, &imageIndex);
switch (result)
{
case vk::Result::eSuccess:
case vk::Result::eSuboptimalKHR: // Suboptimal can still render. Better to let this go for semaphores etc.
imageAcquired = true;
break; // Image acquired. Break out of loop.
case vk::Result::eErrorOutOfDateKHR:
DEBUG("Recreating Swapchain. Cause: {}", result);
swapchain->Create(*surface, size);
break; // Image acquire has failed. We move to the next frame.
default:
AbortIfFailedMV(result, "Waiting for swapchain image {} failed.", frameIndex);
}
}
// Reset fences here. In case swapchain was out of date, we leave the fences signalled.
AbortIfFailedMV(m_Device->m_Device.resetFences(1, &currentFrame->m_FrameAvailableFence), "Fence {} reset failed.",
frameIndex);
AbortIfFailedMV(m_Device->m_Device.resetCommandPool(currentFrame->m_Pool, {}), "Command pool {} reset failed.",
frameIndex);
currentFrame->m_ImageIdx = imageIndex;
return currentFrame;
}

View File

@ -1,55 +0,0 @@
// =============================================
// Aster: frame.h
// Copyright (c) 2020-2025 Anish Bhobe
// =============================================
#pragma once
#include "aster/aster.h"
#include "helpers.h"
#include "aster/core/size.h"
#include <EASTL/fixed_vector.h>
struct Device;
struct Window;
struct Swapchain;
struct Surface;
struct Frame
{
// Persistent
const Device *m_Device;
vk::CommandPool m_Pool;
vk::CommandBuffer m_CommandBuffer;
vk::Fence m_FrameAvailableFence;
vk::Semaphore m_ImageAcquireSem;
vk::Semaphore m_RenderFinishSem;
u32 m_FrameIdx;
// Transient
u32 m_ImageIdx;
void Present(vk::Queue commandQueue, Swapchain *swapchain, const Surface *surface, Size2D size);
Frame(const Device *device, u32 queueFamilyIndex, u32 frameCount);
~Frame();
Frame(Frame &&other) noexcept;
Frame &operator=(Frame &&other) noexcept;
DISALLOW_COPY_AND_ASSIGN(Frame);
};
struct FrameManager
{
const Device *m_Device;
eastl::fixed_vector<Frame, 4> m_Frames{};
u32 m_CurrentFrameIdx = 0;
u32 m_FramesInFlight = 0;
FrameManager(const Device *device, u32 queueFamilyIndex, u32 framesInFlight);
Frame *GetNextFrame(Swapchain *swapchain, const Surface *surface, Size2D size);
};

View File

@ -5,11 +5,7 @@
#include "gui.h" #include "gui.h"
#include "aster/core/device.h" #include "aster/aster.h"
#include "aster/core/instance.h"
#include "aster/core/window.h"
#include "aster/systems/rendering_device.h"
#include "helpers.h"
#include <imgui_impl_glfw.h> #include <imgui_impl_glfw.h>
#include <imgui_impl_vulkan.h> #include <imgui_impl_vulkan.h>
@ -27,8 +23,10 @@ VulkanAssert(VkResult result)
} }
void void
Init(systems::RenderingDevice &device, Window &window) Init(aster::RenderingDevice &device, aster::Window &window)
{ {
using namespace aster;
g_AttachmentFormat = device.m_Swapchain.m_Format; g_AttachmentFormat = device.m_Swapchain.m_Format;
eastl::vector<vk::DescriptorPoolSize> poolSizes = { eastl::vector<vk::DescriptorPoolSize> poolSizes = {
@ -93,72 +91,7 @@ Init(systems::RenderingDevice &device, Window &window)
} }
void void
Init(Instance const *context, Device const *device, Window const *window, vk::Format attachmentFormat, Destroy(aster::RenderingDevice const &device)
u32 const imageCount, u32 const queueFamily, vk::Queue const queue)
{
g_AttachmentFormat = attachmentFormat;
eastl::vector<vk::DescriptorPoolSize> poolSizes = {
{vk::DescriptorType::eSampler, 1000},
{vk::DescriptorType::eCombinedImageSampler, 1000},
{vk::DescriptorType::eSampledImage, 1000},
{vk::DescriptorType::eStorageImage, 1000},
{vk::DescriptorType::eUniformTexelBuffer, 1000},
{vk::DescriptorType::eStorageTexelBuffer, 1000},
{vk::DescriptorType::eUniformBuffer, 1000},
{vk::DescriptorType::eStorageBuffer, 1000},
{vk::DescriptorType::eUniformBufferDynamic, 1000},
{vk::DescriptorType::eStorageBufferDynamic, 1000},
{vk::DescriptorType::eInputAttachment, 1000},
};
vk::DescriptorPoolCreateInfo const descriptorPoolCreateInfo = {
.flags = vk::DescriptorPoolCreateFlagBits::eFreeDescriptorSet,
.maxSets = 1000,
.poolSizeCount = static_cast<u32>(poolSizes.size()),
.pPoolSizes = poolSizes.data(),
};
AbortIfFailed(device->m_Device.createDescriptorPool(&descriptorPoolCreateInfo, nullptr, &g_DescriptorPool));
IMGUI_CHECKVERSION();
CreateContext();
ImGuiIO &io = GetIO();
(void)io;
// io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;
// io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Viewports bad
StyleColorsDark();
ImGui_ImplGlfw_InitForVulkan(window->m_Window, true);
vk::PipelineRenderingCreateInfo renderingCreateInfo = {
.colorAttachmentCount = 1,
.pColorAttachmentFormats = &g_AttachmentFormat,
};
ImGui_ImplVulkan_InitInfo imguiVulkanInitInfo = {
.Instance = context->m_Instance,
.PhysicalDevice = device->m_PhysicalDevice,
.Device = device->m_Device,
.QueueFamily = queueFamily,
.Queue = queue,
.DescriptorPool = g_DescriptorPool,
.MinImageCount = imageCount,
.ImageCount = imageCount,
.PipelineCache = nullptr,
.UseDynamicRendering = true,
.PipelineRenderingCreateInfo = renderingCreateInfo,
.Allocator = nullptr,
.CheckVkResultFn = VulkanAssert,
};
ImGui_ImplVulkan_Init(&imguiVulkanInitInfo);
ImGui_ImplVulkan_CreateFontsTexture();
}
void
Destroy(systems::RenderingDevice const &device)
{ {
ImGui_ImplVulkan_Shutdown(); ImGui_ImplVulkan_Shutdown();
ImGui_ImplGlfw_Shutdown(); ImGui_ImplGlfw_Shutdown();
@ -167,16 +100,6 @@ Destroy(systems::RenderingDevice const &device)
device.m_Device->destroy(Take(g_DescriptorPool), nullptr); device.m_Device->destroy(Take(g_DescriptorPool), nullptr);
} }
void
Destroy(Device const *device)
{
ImGui_ImplVulkan_Shutdown();
ImGui_ImplGlfw_Shutdown();
DestroyContext();
device->m_Device.destroy(Take(g_DescriptorPool), nullptr);
}
void void
StartBuild() StartBuild()
{ {
@ -277,7 +200,7 @@ Draw(vk::CommandBuffer const commandBuffer, vk::Extent2D const extent, vk::Image
} }
void void
Draw(systems::Frame &frame, systems::GraphicsContext &context) Draw(aster::Frame &frame, aster::GraphicsContext &context)
{ {
context.BeginDebugRegion("UI Pass", {0.9f, 0.9f, 1.0f, 1.0f}); context.BeginDebugRegion("UI Pass", {0.9f, 0.9f, 1.0f, 1.0f});

View File

@ -10,13 +10,12 @@
#include <imgui.h> #include <imgui.h>
namespace aster
{
struct Device; struct Device;
struct Instance; struct Instance;
struct Window; struct Window;
struct Swapchain; struct Swapchain;
namespace systems
{
class RenderingDevice; class RenderingDevice;
class GraphicsContext; class GraphicsContext;
struct Frame; struct Frame;
@ -25,17 +24,13 @@ struct Frame;
// ReSharper disable once CppInconsistentNaming // ReSharper disable once CppInconsistentNaming
namespace ImGui namespace ImGui
{ {
void Init(systems::RenderingDevice &device, Window &window); void Init(aster::RenderingDevice &device, aster::Window &window);
void Init(const Instance *context, const Device *device, const Window *window, vk::Format attachmentFormat, void Destroy(const aster::RenderingDevice &device);
u32 imageCount, u32 queueFamily, vk::Queue queue);
void Destroy(const systems::RenderingDevice &device);
void Destroy(const Device *device);
void Recreate(); void Recreate();
void StartBuild(); void StartBuild();
void EndBuild(); void EndBuild();
void Draw(vk::CommandBuffer commandBuffer, vk::Extent2D extent, vk::ImageView view); void Draw(aster::Frame &frame, aster::GraphicsContext &context);
void Draw(systems::Frame &frame, systems::GraphicsContext &context);
void PushDisable(); void PushDisable();
void PopDisable(); void PopDisable();

View File

@ -1,64 +0,0 @@
// =============================================
// Aster: helpers.cpp
// Copyright (c) 2020-2025 Anish Bhobe
// =============================================
#include "helpers.h"
#include "aster/core/device.h"
#include "aster/core/physical_device.h"
#include <EASTL/array.h>
constexpr QueueSupportFlags REQUIRED_QUEUE_SUPPORT = QueueSupportFlags{} | QueueSupportFlagBits::eGraphics |
QueueSupportFlagBits::eCompute | QueueSupportFlagBits::ePresent |
QueueSupportFlagBits::eTransfer;
bool
IsSuitableDevice(PhysicalDevice const *physicalDevice)
{
bool const hasAllRequiredQueues =
std::ranges::any_of(physicalDevice->m_QueueFamilies, [](auto const &queueFamilyProp) {
return (queueFamilyProp.m_Support & REQUIRED_QUEUE_SUPPORT) == REQUIRED_QUEUE_SUPPORT;
});
bool const isNotCpu = physicalDevice->m_DeviceProperties.deviceType != vk::PhysicalDeviceType::eCpu;
bool const hasPresentMode = !physicalDevice->m_PresentModes.empty();
bool const hasSurfaceFormat = !physicalDevice->m_SurfaceFormats.empty();
return hasSurfaceFormat && hasPresentMode && isNotCpu && hasAllRequiredQueues;
}
PhysicalDevice
FindSuitableDevice(PhysicalDevices const &physicalDevices)
{
for (auto &physicalDevice : physicalDevices)
{
if (IsSuitableDevice(&physicalDevice))
{
return physicalDevice;
}
}
ERROR("No suitable GPU available on the system.")
THEN_ABORT(vk::Result::eErrorUnknown);
}
QueueAllocation
FindAppropriateQueueAllocation(PhysicalDevice const *physicalDevice)
{
for (auto &queueFamilyInfo : physicalDevice->m_QueueFamilies)
{
if ((queueFamilyInfo.m_Support & REQUIRED_QUEUE_SUPPORT) == REQUIRED_QUEUE_SUPPORT)
{
return {
.m_Family = queueFamilyInfo.m_Index,
.m_Count = queueFamilyInfo.m_Count,
};
}
}
ERROR("No suitable queue family on the GPU.")
THEN_ABORT(vk::Result::eErrorUnknown);
}

View File

@ -1,46 +0,0 @@
// =============================================
// Aster: helpers.h
// Copyright (c) 2020-2025 Anish Bhobe
// =============================================
#pragma once
#include "aster/aster.h"
#include "aster/core/queue_allocation.h"
#include "EASTL/span.h"
#include <EASTL/vector.h>
#include <glm/gtc/matrix_transform.hpp>
struct PhysicalDevice;
class PhysicalDevices;
PhysicalDevice FindSuitableDevice(const PhysicalDevices &physicalDevices);
QueueAllocation FindAppropriateQueueAllocation(const PhysicalDevice *physicalDevice);
template <usize TSize>
using StackString = eastl::fixed_string<char, TSize, false>;
#define AbortIfFailed(RESULT) \
do \
{ \
vk::Result _checkResultValue_; \
ERROR_IF(Failed(_checkResultValue_ = static_cast<vk::Result>(RESULT)), "Cause: {}", _checkResultValue_) \
THEN_ABORT(_checkResultValue_); \
} while (false)
#define AbortIfFailedMV(RESULT, MSG, EXTRA) \
do \
{ \
vk::Result _checkResultValue_; \
ERROR_IF(Failed(_checkResultValue_ = static_cast<vk::Result>(RESULT)), MSG " Cause: {}", EXTRA, _checkResultValue_) \
THEN_ABORT(_checkResultValue_); \
} while (false)
#define AbortIfFailedM(RESULT, MSG) \
do \
{ \
auto _checkResultValue_ = static_cast<vk::Result>(RESULT); \
ERROR_IF(Failed(_checkResultValue_), MSG " Cause: {}", _checkResultValue_) THEN_ABORT(_checkResultValue_); \
} while (false)

View File

@ -4,19 +4,9 @@
// ============================================= // =============================================
#include "aster/aster.h" #include "aster/aster.h"
#include "aster/import_types.h"
#include "aster/core/buffer.h"
#include "aster/core/constants.h"
#include "aster/core/instance.h"
#include "aster/core/physical_device.h"
#include "aster/core/pipeline.h"
#include "aster/core/swapchain.h"
#include "aster/core/window.h"
#include "aster/core/pipeline.h"
#include "aster/systems/rendering_device.h"
#include "aster/util/files.h" #include "aster/util/files.h"
#include "helpers.h"
#include <EASTL/array.h> #include <EASTL/array.h>
@ -27,19 +17,19 @@ struct Vertex
vec3 m_Position; vec3 m_Position;
vec3 m_Color; vec3 m_Color;
static eastl::vector<systems::AttributeInfo> static eastl::vector<aster::AttributeInfo>
GetAttributes() GetAttributes()
{ {
return { return {
{ {
.m_Location = 0, .m_Location = 0,
.m_Offset = offsetof(Vertex, m_Position), .m_Offset = offsetof(Vertex, m_Position),
.m_Format = systems::AttributeInfo::Format::eFloat32X3, .m_Format = aster::AttributeInfo::Format::eFloat32X3,
}, },
{ {
.m_Location = 1, .m_Location = 1,
.m_Offset = offsetof(Vertex, m_Color), .m_Offset = offsetof(Vertex, m_Color),
.m_Format = systems::AttributeInfo::Format::eFloat32X3, .m_Format = aster::AttributeInfo::Format::eFloat32X3,
}, },
}; };
} }
@ -48,10 +38,12 @@ struct Vertex
int int
main(int, char **) main(int, char **)
{ {
using namespace aster;
MIN_LOG_LEVEL(Logger::LogType::eInfo); MIN_LOG_LEVEL(Logger::LogType::eInfo);
Window window = {"Triangle (Aster)", {640, 480}}; Window window = {"Triangle (Aster)", {640, 480}};
systems::RenderingDevice device{{ RenderingDevice device{{
.m_Window = window, .m_Window = window,
.m_Features = {.m_Vulkan12Features = {.bufferDeviceAddress = true}, .m_Features = {.m_Vulkan12Features = {.bufferDeviceAddress = true},
.m_Vulkan13Features = {.synchronization2 = true, .dynamicRendering = true}}, .m_Vulkan13Features = {.synchronization2 = true, .dynamicRendering = true}},
@ -126,7 +118,7 @@ main(int, char **)
INFO("Starting loop"); INFO("Starting loop");
while (window.Poll()) while (window.Poll())
{ {
systems::Frame &currentFrame = device.GetNextFrame(); aster::Frame &currentFrame = device.GetNextFrame();
Size2D swapchainSize = currentFrame.m_SwapchainSize; Size2D swapchainSize = currentFrame.m_SwapchainSize;

View File

@ -25,6 +25,8 @@ constexpr auto VERTEX_SHADER_FILE = "shader/box.vs.hlsl.spv";
constexpr auto FRAGMENT_SHADER_FILE = "shader/box.ps.hlsl.spv"; constexpr auto FRAGMENT_SHADER_FILE = "shader/box.ps.hlsl.spv";
constexpr auto SHADER_FILE = "box"; constexpr auto SHADER_FILE = "box";
using namespace aster;
struct ImageFile struct ImageFile
{ {
void *m_Data = nullptr; void *m_Data = nullptr;
@ -117,7 +119,7 @@ main(int, char **)
.m_Vulkan13Features = {.synchronization2 = true, .dynamicRendering = true}, .m_Vulkan13Features = {.synchronization2 = true, .dynamicRendering = true},
}; };
systems::RenderingDevice device{{ RenderingDevice device{{
.m_Window = window, .m_Window = window,
.m_Features = enabledDeviceFeatures, .m_Features = enabledDeviceFeatures,
.m_AppName = "Box", .m_AppName = "Box",
@ -332,11 +334,11 @@ main(int, char **)
{ {
uptr m_VertexBuffer; uptr m_VertexBuffer;
uptr m_Camera; uptr m_Camera;
systems::ResId<TextureView> m_Texture; ResId<TextureView> m_Texture;
}; };
static_assert(sizeof(PCB) == 24); static_assert(sizeof(PCB) == 24);
auto &commitManager = systems::CommitManager::Instance(); auto &commitManager = CommitManager::Instance();
PCB pcb = { PCB pcb = {
.m_VertexBuffer = vbo->GetDeviceAddress(), .m_VertexBuffer = vbo->GetDeviceAddress(),

View File

@ -8,7 +8,6 @@
#include "aster/core/image.h" #include "aster/core/image.h"
#include "asset_loader.h" #include "asset_loader.h"
#include "helpers.h"
#include "aster/systems/commit_manager.h" #include "aster/systems/commit_manager.h"
#include "aster/systems/rendering_device.h" #include "aster/systems/rendering_device.h"
@ -27,6 +26,8 @@
#undef LoadImage #undef LoadImage
#endif #endif
using namespace aster;
constexpr vk::CommandBufferBeginInfo OneTimeCmdBeginInfo = {.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit}; constexpr vk::CommandBufferBeginInfo OneTimeCmdBeginInfo = {.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit};
vec4 vec4
@ -140,7 +141,7 @@ AssetLoader::LoadHdrImage(cstr path, cstr name) const
auto context = m_Device->CreateTransferContext(); auto context = m_Device->CreateTransferContext();
context.Begin(); context.Begin();
StackString<128> loadActionName = "Load: "; eastl::fixed_string<char, 128> loadActionName = "Load: ";
loadActionName += name ? name : path; loadActionName += name ? name : path;
context.BeginDebugRegion(loadActionName.c_str()); context.BeginDebugRegion(loadActionName.c_str());
@ -161,7 +162,7 @@ AssetLoader::LoadHdrImage(cstr path, cstr name) const
} }
void void
GenerateMipMaps(systems::TransferContext &context, Ref<Texture> const &texture, vk::ImageLayout initialLayout, GenerateMipMaps(TransferContext &context, Ref<Texture> const &texture, vk::ImageLayout initialLayout,
vk::ImageLayout finalLayout, vk::PipelineStageFlags2 prevStage, vk::PipelineStageFlags2 finalStage) vk::ImageLayout finalLayout, vk::PipelineStageFlags2 prevStage, vk::PipelineStageFlags2 finalStage)
{ {
#if !defined(ASTER_NDEBUG) #if !defined(ASTER_NDEBUG)
@ -330,8 +331,8 @@ GenerateMipMaps(systems::TransferContext &context, Ref<Texture> const &texture,
#endif #endif
} }
systems::ResId<TextureView> ResId<TextureView>
AssetLoader::LoadImageToGpu(systems::TransferContext &context, tinygltf::Image *image, bool isSrgb, cstr name) const AssetLoader::LoadImageToGpu(TransferContext &context, tinygltf::Image *image, bool isSrgb, cstr name) const
{ {
// TODO(Something not loading properly). // TODO(Something not loading properly).
@ -358,7 +359,7 @@ AssetLoader::LoadImageToGpu(systems::TransferContext &context, tinygltf::Image *
.m_IsStorage = false, .m_IsStorage = false,
}); });
StackString<128> loadActionName = "Load: "; eastl::fixed_string<char,128> loadActionName = "Load: ";
loadActionName += assignedName; loadActionName += assignedName;
context.BeginDebugRegion(loadActionName.c_str()); context.BeginDebugRegion(loadActionName.c_str());
@ -467,11 +468,11 @@ AssetLoader::LoadModelToGpu(cstr path, cstr name)
context.Begin(); context.Begin();
StackString<128> loadActionName = "Load: "; eastl::fixed_string<char,128> loadActionName = "Load: ";
loadActionName += name ? name : path; loadActionName += name ? name : path;
context.BeginDebugRegion(loadActionName.c_str()); context.BeginDebugRegion(loadActionName.c_str());
eastl::hash_map<i32, systems::ResId<TextureView>> textureHandleMap; eastl::hash_map<i32, ResId<TextureView>> textureHandleMap;
eastl::vector<Material> materials; eastl::vector<Material> materials;
Ref<Buffer> materialsBuffer; Ref<Buffer> materialsBuffer;
@ -480,10 +481,10 @@ AssetLoader::LoadModelToGpu(cstr path, cstr name)
{ {
// TODO("Something broken on load here."); // TODO("Something broken on load here.");
auto getTextureHandle = [this, &context, &textureHandleMap, auto getTextureHandle = [this, &context, &textureHandleMap,
&model](i32 index, bool const isSrgb) -> systems::ResId<TextureView> { &model](i32 index, bool const isSrgb) -> ResId<TextureView> {
if (index < 0) if (index < 0)
{ {
return systems::NullId{}; return NullId{};
} }
if (auto const iter = textureHandleMap.find(index); iter != textureHandleMap.end()) if (auto const iter = textureHandleMap.find(index); iter != textureHandleMap.end())
{ {
@ -804,8 +805,8 @@ AssetLoader::LoadModelToGpu(cstr path, cstr name)
nodeBuffer->Write(0, nodes.GetGlobalTransformByteSize(), nodes.GetGlobalTransformPtr()); nodeBuffer->Write(0, nodes.GetGlobalTransformByteSize(), nodes.GetGlobalTransformPtr());
#pragma region Staging / Transfer / Uploads #pragma region Staging / Transfer / Uploads
systems::ResId<Buffer> positionBufferHandle = systems::ResId<Buffer>::Null(); ResId<Buffer> positionBufferHandle = ResId<Buffer>::Null();
systems::ResId<Buffer> vertexDataHandle = systems::ResId<Buffer>::Null(); ResId<Buffer> vertexDataHandle = ResId<Buffer>::Null();
Ref<IndexBuffer> indexBuffer; Ref<IndexBuffer> indexBuffer;
auto positionBuffer = m_Device->CreateStorageBuffer(vertexPositions.size() * sizeof vertexPositions[0]); auto positionBuffer = m_Device->CreateStorageBuffer(vertexPositions.size() * sizeof vertexPositions[0]);
@ -815,7 +816,7 @@ AssetLoader::LoadModelToGpu(cstr path, cstr name)
context.UploadBuffer(vertexDataBuffer, vertexData); context.UploadBuffer(vertexDataBuffer, vertexData);
// TODO: Index buffer needs to be separated. // TODO: Index buffer needs to be separated.
indexBuffer = systems::CastBuffer<IndexBuffer>( indexBuffer = CastBuffer<IndexBuffer>(
m_Device->CreateIndexBuffer(indices.size() * sizeof indices[0], "Index Buffer")); m_Device->CreateIndexBuffer(indices.size() * sizeof indices[0], "Index Buffer"));
context.UploadBuffer(indexBuffer, indices); context.UploadBuffer(indexBuffer, indices);
@ -839,7 +840,7 @@ AssetLoader::LoadModelToGpu(cstr path, cstr name)
auto handlesBuffer = m_Device->CreateStorageBuffer(sizeof handlesData, "Materials"); auto handlesBuffer = m_Device->CreateStorageBuffer(sizeof handlesData, "Materials");
handlesBuffer->Write(0, sizeof handlesData, &handlesData); handlesBuffer->Write(0, sizeof handlesData, &handlesData);
eastl::vector<systems::ResId<TextureView>> textureHandles; eastl::vector<ResId<TextureView>> textureHandles;
textureHandles.reserve(textureHandleMap.size()); textureHandles.reserve(textureHandleMap.size());
for (auto &[key, val] : textureHandleMap) for (auto &[key, val] : textureHandleMap)
@ -852,7 +853,7 @@ AssetLoader::LoadModelToGpu(cstr path, cstr name)
}; };
} }
Model::Model(eastl::vector<systems::ResId<TextureView>> &textureHandles, Nodes &&nodes, Ref<Buffer> nodeBuffer, Model::Model(eastl::vector<ResId<TextureView>> &textureHandles, Nodes &&nodes, Ref<Buffer> nodeBuffer,
ModelHandles &handles, Ref<Buffer> modelHandlesBuffer, Ref<IndexBuffer> indexBuffer, ModelHandles &handles, Ref<Buffer> modelHandlesBuffer, Ref<IndexBuffer> indexBuffer,
eastl::vector<MeshPrimitive> const &meshPrimitives) eastl::vector<MeshPrimitive> const &meshPrimitives)
: m_TextureHandles(std::move(textureHandles)) : m_TextureHandles(std::move(textureHandles))
@ -886,7 +887,7 @@ Model::Update()
} }
} }
AssetLoader::AssetLoader(systems::RenderingDevice &device) AssetLoader::AssetLoader(RenderingDevice &device)
: m_Device{&device} : m_Device{&device}
{ {
} }

View File

@ -13,12 +13,7 @@
#include "nodes.h" #include "nodes.h"
#include "tiny_gltf.h" #include "tiny_gltf.h"
namespace systems namespace aster
{
class TransferContext;
}
namespace systems
{ {
class RenderingDevice; class RenderingDevice;
class ResourceManager; class ResourceManager;
@ -26,6 +21,9 @@ class SamplerManager;
class BufferManager; class BufferManager;
class ImageManager; class ImageManager;
class CommitManager; class CommitManager;
class TransferContext;
struct Image;
struct Texture;
} // namespace systems } // namespace systems
namespace tinygltf namespace tinygltf
@ -33,9 +31,6 @@ namespace tinygltf
struct Image; struct Image;
} }
struct Image;
struct Texture;
constexpr auto GLTF_ASCII_FILE_EXTENSION = ".gltf"; constexpr auto GLTF_ASCII_FILE_EXTENSION = ".gltf";
constexpr auto GLTF_BINARY_FILE_EXTENSION = ".glb"; constexpr auto GLTF_BINARY_FILE_EXTENSION = ".glb";
@ -52,11 +47,11 @@ struct Material
{ {
vec4 m_AlbedoFactor; // 16 16 vec4 m_AlbedoFactor; // 16 16
vec4 m_EmissionFactor; // 16 32 vec4 m_EmissionFactor; // 16 32
systems::ResId<TextureView> m_AlbedoTex; // 08 40 aster::ResId<aster::TextureView> m_AlbedoTex; // 08 40
systems::ResId<TextureView> m_NormalTex; // 08 48 aster::ResId<aster::TextureView> m_NormalTex; // 08 48
systems::ResId<TextureView> m_MetalRoughTex; // 08 56 aster::ResId<aster::TextureView> m_MetalRoughTex; // 08 56
systems::ResId<TextureView> m_OcclusionTex; // 08 64 aster::ResId<aster::TextureView> m_OcclusionTex; // 08 64
systems::ResId<TextureView> m_EmissionTex; // 08 72 aster::ResId<aster::TextureView> m_EmissionTex; // 08 72
f32 m_MetalFactor; // 04 76 f32 m_MetalFactor; // 04 76
f32 m_RoughFactor; // 04 80 f32 m_RoughFactor; // 04 80
}; };
@ -71,7 +66,7 @@ struct VertexData
struct Model struct Model
{ {
eastl::vector<systems::ResId<TextureView>> m_TextureHandles; eastl::vector<aster::ResId<aster::TextureView>> m_TextureHandles;
Nodes m_Nodes; Nodes m_Nodes;
struct ModelHandlesData struct ModelHandlesData
@ -84,10 +79,10 @@ struct Model
struct ModelHandles struct ModelHandles
{ {
Ref<Buffer> m_VertexPositionHandle; aster::Ref<aster::Buffer> m_VertexPositionHandle;
Ref<Buffer> m_VertexDataHandle; aster::Ref<aster::Buffer> m_VertexDataHandle;
Ref<Buffer> m_MaterialsHandle; aster::Ref<aster::Buffer> m_MaterialsHandle;
Ref<Buffer> m_NodeHandle; aster::Ref<aster::Buffer> m_NodeHandle;
operator ModelHandlesData() const operator ModelHandlesData() const
{ {
@ -100,17 +95,17 @@ struct Model
} }
} m_Handles; } m_Handles;
Ref<Buffer> m_NodeBuffer; aster::Ref<aster::Buffer> m_NodeBuffer;
Ref<IndexBuffer> m_IndexBuffer; aster::Ref<aster::IndexBuffer> m_IndexBuffer;
Ref<Buffer> m_ModelHandlesBuffer; aster::Ref<aster::Buffer> m_ModelHandlesBuffer;
eastl::vector<MeshPrimitive> m_MeshPrimitives; eastl::vector<MeshPrimitive> m_MeshPrimitives;
[[nodiscard]] mat4 const &GetModelTransform() const; [[nodiscard]] mat4 const &GetModelTransform() const;
void SetModelTransform(mat4 const &transform); void SetModelTransform(mat4 const &transform);
void Update(); void Update();
Model(eastl::vector<systems::ResId<TextureView>> &textureHandles, Nodes &&nodes, Ref<Buffer> nodeBuffer, Model(eastl::vector<aster::ResId<aster::TextureView>> &textureHandles, Nodes &&nodes, aster::Ref<aster::Buffer> nodeBuffer,
ModelHandles &handles, Ref<Buffer> modelHandlesBuffer, Ref<IndexBuffer> indexBuffer, ModelHandles &handles, aster::Ref<aster::Buffer> modelHandlesBuffer, aster::Ref<aster::IndexBuffer> indexBuffer,
eastl::vector<MeshPrimitive> const &meshPrimitives); eastl::vector<MeshPrimitive> const &meshPrimitives);
~Model() = default; ~Model() = default;
@ -123,9 +118,9 @@ struct Model
struct AssetLoader struct AssetLoader
{ {
systems::RenderingDevice *m_Device; aster::RenderingDevice *m_Device;
Ref<TextureView> LoadHdrImage(cstr path, cstr name = nullptr) const; aster::Ref<aster::TextureView> LoadHdrImage(cstr path, cstr name = nullptr) const;
Model LoadModelToGpu(cstr path, cstr name = nullptr); Model LoadModelToGpu(cstr path, cstr name = nullptr);
constexpr static auto ANormal = "NORMAL"; constexpr static auto ANormal = "NORMAL";
@ -137,32 +132,32 @@ struct AssetLoader
constexpr static auto AJoints0 = "JOINTS_0"; constexpr static auto AJoints0 = "JOINTS_0";
constexpr static auto AWeights0 = "WEIGHTS_0"; constexpr static auto AWeights0 = "WEIGHTS_0";
explicit AssetLoader(systems::RenderingDevice &device); explicit AssetLoader(aster::RenderingDevice &device);
private: private:
systems::ResId<TextureView> aster::ResId<aster::TextureView>
LoadImageToGpu(systems::TransferContext &context, tinygltf::Image *image, bool isSrgb, cstr name = nullptr) const; LoadImageToGpu(aster::TransferContext &context, tinygltf::Image *image, bool isSrgb, cstr name = nullptr) const;
}; };
void void
GenerateMipMaps(systems::TransferContext &context, Ref<Texture> const &textureView, vk::ImageLayout initialLayout, GenerateMipMaps(aster::TransferContext &context, aster::Ref<aster::Texture> const &textureView, vk::ImageLayout initialLayout,
vk::ImageLayout finalLayout, vk::PipelineStageFlags2 prevStage, vk::PipelineStageFlags2 finalStage); vk::ImageLayout finalLayout, vk::PipelineStageFlags2 prevStage, vk::PipelineStageFlags2 finalStage);
void void
GenerateMipMaps(systems::TransferContext &context, concepts::ImageRefTo<Texture> auto &texture, GenerateMipMaps(aster::TransferContext &context, aster::concepts::ImageRefTo<aster::Texture> auto &texture,
vk::ImageLayout initialLayout, vk::ImageLayout finalLayout, vk::ImageLayout initialLayout, vk::ImageLayout finalLayout,
vk::PipelineStageFlags2 prevStage = vk::PipelineStageFlagBits2::eAllCommands, vk::PipelineStageFlags2 prevStage = vk::PipelineStageFlagBits2::eAllCommands,
vk::PipelineStageFlags2 finalStage = vk::PipelineStageFlagBits2::eAllCommands) vk::PipelineStageFlags2 finalStage = vk::PipelineStageFlagBits2::eAllCommands)
{ {
GenerateMipMaps(context, systems::CastImage<Texture>(texture), initialLayout, finalLayout, prevStage, finalStage); GenerateMipMaps(context, aster::CastImage<aster::Texture>(texture), initialLayout, finalLayout, prevStage, finalStage);
} }
void void
GenerateMipMaps(systems::TransferContext &context, concepts::ViewRefTo<Texture> auto &texture, GenerateMipMaps(aster::TransferContext &context, aster::concepts::ViewRefTo<aster::Texture> auto &texture,
vk::ImageLayout initialLayout, vk::ImageLayout finalLayout, vk::ImageLayout initialLayout, vk::ImageLayout finalLayout,
vk::PipelineStageFlags2 prevStage = vk::PipelineStageFlagBits2::eAllCommands, vk::PipelineStageFlags2 prevStage = vk::PipelineStageFlagBits2::eAllCommands,
vk::PipelineStageFlags2 finalStage = vk::PipelineStageFlagBits2::eAllCommands) vk::PipelineStageFlags2 finalStage = vk::PipelineStageFlagBits2::eAllCommands)
{ {
GenerateMipMaps(context, systems::CastImage<Texture>(texture->m_Image), initialLayout, finalLayout, prevStage, GenerateMipMaps(context, aster::CastImage<aster::Texture>(texture->m_Image), initialLayout, finalLayout, prevStage,
finalStage); finalStage);
} }

View File

@ -9,7 +9,6 @@
#include "aster/core/image.h" #include "aster/core/image.h"
#include "asset_loader.h" #include "asset_loader.h"
#include "helpers.h"
#include "aster/systems/commit_manager.h" #include "aster/systems/commit_manager.h"
#include "aster/systems/rendering_device.h" #include "aster/systems/rendering_device.h"
@ -23,10 +22,12 @@ constexpr auto DIFFUSE_IRRADIANCE_ENTRY = "diffuseIrradiance";
constexpr auto PREFILTER_ENTRY = "prefilter"; constexpr auto PREFILTER_ENTRY = "prefilter";
constexpr auto BRDF_LUT_ENTRY = "brdfLut"; constexpr auto BRDF_LUT_ENTRY = "brdfLut";
using namespace aster;
Environment Environment
CreateCubeFromHdrEnv(AssetLoader &assetLoader, u32 const cubeSide, systems::ResId<TextureView> hdrEnv) CreateCubeFromHdrEnv(AssetLoader &assetLoader, u32 const cubeSide, ResId<TextureView> hdrEnv)
{ {
systems::RenderingDevice &device = *assetLoader.m_Device; RenderingDevice &device = *assetLoader.m_Device;
auto *commitManager = device.m_CommitManager.get(); auto *commitManager = device.m_CommitManager.get();
auto skybox = device.CreateTextureCubeWithView<StorageTextureCubeView>({ auto skybox = device.CreateTextureCubeWithView<StorageTextureCubeView>({
@ -62,12 +63,12 @@ CreateCubeFromHdrEnv(AssetLoader &assetLoader, u32 const cubeSide, systems::ResI
}); });
auto prefilterHandle = commitManager->CommitTexture(prefilterCube); // This stores the original view for us. auto prefilterHandle = commitManager->CommitTexture(prefilterCube); // This stores the original view for us.
constexpr u32 prefilterMipCountMax = 6; constexpr u32 prefilterMipCountMax = 6;
eastl::fixed_vector<systems::ResId<StorageImageView>, prefilterMipCountMax> prefilterStorageHandles; eastl::fixed_vector<ResId<StorageImageView>, prefilterMipCountMax> prefilterStorageHandles;
// All non-owning copies. // All non-owning copies.
for (u8 mipLevel = 0; mipLevel < prefilterMipCountMax; ++mipLevel) for (u8 mipLevel = 0; mipLevel < prefilterMipCountMax; ++mipLevel)
{ {
auto view = device.CreateView<StorageTextureCubeView>({ auto view = device.CreateView<StorageTextureCubeView>({
.m_Image = systems::CastImage<StorageTextureCube>(prefilterCube->m_Image), .m_Image = CastImage<StorageTextureCube>(prefilterCube->m_Image),
.m_ViewType = vk::ImageViewType::eCube, .m_ViewType = vk::ImageViewType::eCube,
.m_AspectMask = vk::ImageAspectFlagBits::eColor, .m_AspectMask = vk::ImageAspectFlagBits::eColor,
.m_MipLevelCount = 1, .m_MipLevelCount = 1,
@ -178,27 +179,27 @@ CreateCubeFromHdrEnv(AssetLoader &assetLoader, u32 const cubeSide, systems::ResI
struct SkyboxPushConstants struct SkyboxPushConstants
{ {
systems::ResId<TextureView> m_HdrEnvHandle; ResId<TextureView> m_HdrEnvHandle;
systems::ResId<StorageImageView> m_OutputTexture; ResId<StorageImageView> m_OutputTexture;
u32 m_CubeSide; u32 m_CubeSide;
}; };
struct DiffuseIrradiancePushConstants struct DiffuseIrradiancePushConstants
{ {
systems::ResId<TextureView> m_SkyboxHandle; ResId<TextureView> m_SkyboxHandle;
systems::ResId<StorageImageView> m_OutputTexture; ResId<StorageImageView> m_OutputTexture;
u32 m_CubeSide; u32 m_CubeSide;
}; };
struct PrefilterPushConstants struct PrefilterPushConstants
{ {
systems::ResId<TextureView> m_SkyboxHandle; ResId<TextureView> m_SkyboxHandle;
systems::ResId<StorageImageView> m_OutputTexture; ResId<StorageImageView> m_OutputTexture;
u32 m_CubeSide; u32 m_CubeSide;
f32 m_Roughness; f32 m_Roughness;
u32 m_EnvSide; u32 m_EnvSide;
}; };
struct BrdfLutPushConstants struct BrdfLutPushConstants
{ {
systems::ResId<StorageImageView> m_OutputTexture; ResId<StorageImageView> m_OutputTexture;
}; };
#pragma region Pipeline Creation etc #pragma region Pipeline Creation etc
@ -332,7 +333,7 @@ CreateCubeFromHdrEnv(AssetLoader &assetLoader, u32 const cubeSide, systems::ResI
}; };
PrefilterPushConstants prefilterPushConstants = { PrefilterPushConstants prefilterPushConstants = {
.m_SkyboxHandle = skyboxHandle, .m_SkyboxHandle = skyboxHandle,
.m_OutputTexture = systems::NullId{}, .m_OutputTexture = NullId{},
.m_EnvSide = cubeSide, .m_EnvSide = cubeSide,
}; };
BrdfLutPushConstants brdfLutPushConstants = { BrdfLutPushConstants brdfLutPushConstants = {

View File

@ -6,21 +6,23 @@
#pragma once #pragma once
#include "aster/aster.h" #include "aster/aster.h"
#include "aster/core/image.h" #include "aster/import_types.h"
#include "aster/core/image_view.h"
#include "aster/systems/resource.h"
namespace aster
{
struct Pipeline; struct Pipeline;
struct Texture; struct Texture;
struct TextureCube; struct TextureCube;
} // namespace aster
struct AssetLoader; struct AssetLoader;
struct Environment struct Environment
{ {
systems::ResId<TextureView> m_Skybox; aster::ResId<aster::TextureView> m_Skybox;
systems::ResId<TextureView> m_Diffuse; aster::ResId<aster::TextureView> m_Diffuse;
systems::ResId<TextureView> m_Prefilter; aster::ResId<aster::TextureView> m_Prefilter;
systems::ResId<TextureView> m_BrdfLut; aster::ResId<aster::TextureView> m_BrdfLut;
}; };
Environment CreateCubeFromHdrEnv(AssetLoader &assetLoader, u32 cubeSide, systems::ResId<TextureView> hdrEnv); Environment CreateCubeFromHdrEnv(AssetLoader &assetLoader, u32 cubeSide, aster::ResId<aster::TextureView> hdrEnv);

View File

@ -55,7 +55,7 @@ ToColor32(vec3 const &col)
return r << 24 | g << 16 | b << 8 | a; return r << 24 | g << 16 | b << 8 | a;
} }
LightManager::LightManager(systems::RenderingDevice &device) LightManager::LightManager(aster::RenderingDevice &device)
: m_Device{&device} : m_Device{&device}
, m_DirectionalLightCount{} , m_DirectionalLightCount{}
, m_PointLightCount{} , m_PointLightCount{}

View File

@ -6,20 +6,16 @@
#pragma once #pragma once
#include "aster/aster.h" #include "aster/aster.h"
#include "aster/import_types.h"
// TODO: Separate files so you only import handles. // TODO: Separate files so you only import handles.
#include "aster/core/buffer.h"
#include "aster/systems/resource.h" #include "aster/systems/resource.h"
#include <EASTL/vector.h> #include <EASTL/vector.h>
namespace systems namespace aster
{ {
class RenderingDevice; class RenderingDevice;
}
namespace systems
{
class ResourceManager; class ResourceManager;
class CommitManager; class CommitManager;
} // namespace systems } // namespace systems
@ -89,9 +85,9 @@ struct LightManager
u16 m_UnusedPadding0 = 0; // 02 16 u16 m_UnusedPadding0 = 0; // 02 16
}; };
systems::RenderingDevice *m_Device; aster::RenderingDevice *m_Device;
eastl::vector<Light> m_Lights; eastl::vector<Light> m_Lights;
Ref<Buffer> m_LightBuffer; aster::Ref<aster::Buffer> m_LightBuffer;
// We don't need a Directional Light free list. We will just brute force iterate. // We don't need a Directional Light free list. We will just brute force iterate.
u16 m_DirectionalLightCount; u16 m_DirectionalLightCount;
@ -114,7 +110,7 @@ struct LightManager
~LightManager() = default; ~LightManager() = default;
explicit LightManager(systems::RenderingDevice &device); explicit LightManager(aster::RenderingDevice &device);
LightManager(LightManager &&other) noexcept = default; LightManager(LightManager &&other) noexcept = default;
LightManager &operator=(LightManager &&other) noexcept = default; LightManager &operator=(LightManager &&other) noexcept = default;

View File

@ -133,6 +133,8 @@ struct CameraController
int int
main(int, char **) main(int, char **)
{ {
using namespace aster;
MIN_LOG_LEVEL(Logger::LogType::eInfo); MIN_LOG_LEVEL(Logger::LogType::eInfo);
Window window = {"ModelRender (Aster)", {INIT_WIDTH, INIT_HEIGHT}}; Window window = {"ModelRender (Aster)", {INIT_WIDTH, INIT_HEIGHT}};
@ -168,7 +170,7 @@ main(int, char **)
}; };
auto pipelineCacheData = ReadFileBytes(PIPELINE_CACHE_FILE, false); auto pipelineCacheData = ReadFileBytes(PIPELINE_CACHE_FILE, false);
systems::RenderingDevice device{{ RenderingDevice device{{
.m_Window = window, .m_Window = window,
.m_Features = enabledDeviceFeatures, .m_Features = enabledDeviceFeatures,
.m_AppName = "ModelRender", .m_AppName = "ModelRender",
@ -207,8 +209,8 @@ main(int, char **)
.m_ShaderFile = BACKGROUND_SHADER_FILE, .m_ShaderFile = BACKGROUND_SHADER_FILE,
.m_EntryPoints = {"vsmain", "fsmain"}, .m_EntryPoints = {"vsmain", "fsmain"},
}}, }},
.m_DepthTest = systems::GraphicsPipelineCreateInfo::DepthTest::eReadOnly, .m_DepthTest = GraphicsPipelineCreateInfo::DepthTest::eReadOnly,
.m_DepthOp = systems::GraphicsPipelineCreateInfo::CompareOp::eLessThanOrEqualTo, .m_DepthOp = GraphicsPipelineCreateInfo::CompareOp::eLessThanOrEqualTo,
.m_Name = "Background", .m_Name = "Background",
})) }))
{ {

View File

@ -6,6 +6,7 @@
#pragma once #pragma once
#include "aster/aster.h" #include "aster/aster.h"
#include "aster/import_types.h"
#include <EASTL/vector.h> #include <EASTL/vector.h>