Compare commits

..

1 Commits

Author SHA1 Message Date
cat
ca622d56f6 Testing Corrade on Logging 2026-03-06 16:34:53 +02:00
13 changed files with 125 additions and 176 deletions

View File

@@ -52,7 +52,7 @@ foreach(dep
add_subdirectory(external/${dep}) add_subdirectory(external/${dep})
endforeach() endforeach()
# Building # Building SO
add_library(${PROJECT_NAME} SHARED add_library(${PROJECT_NAME} SHARED
"source/Systems/ECS/Components.cpp" "source/Systems/ECS/Components.cpp"
"source/Systems/ECS/World.cpp" "source/Systems/ECS/World.cpp"
@@ -63,25 +63,15 @@ add_library(${PROJECT_NAME} SHARED
# Actual linking # Actual linking
target_link_libraries(${PROJECT_NAME} PUBLIC target_link_libraries(${PROJECT_NAME} PUBLIC
Corrade::Main Corrade::Main
Corrade::Containers Corrade::Containers
Corrade::Utility Corrade::Utility
Corrade::PluginManager Corrade::PluginManager
) )
# Module stuff # Module stuff
set_target_properties(${PROJECT_NAME} PROPERTIES VERSION ${PROJECT_VERSION}) set_target_properties(${PROJECT_NAME} PROPERTIES VERSION ${PROJECT_VERSION})
target_include_directories(${PROJECT_NAME}
PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/headers>
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/>
$<BUILD_INTERFACE:${corrade_SOURCE_DIR}/src>
$<INSTALL_INTERFACE:include/${PROJECT_NAME}>
$<INSTALL_INTERFACE:include/${PROJECT_NAME}External>
)
FetchContent_GetProperties(Corrade SOURCE_DIR corrade_SOURCE_DIR) FetchContent_GetProperties(Corrade SOURCE_DIR corrade_SOURCE_DIR)
FetchContent_GetProperties(Corrade BINARY_DIR corrade_BINARY_DIR) FetchContent_GetProperties(Corrade BINARY_DIR corrade_BINARY_DIR)
@@ -95,9 +85,13 @@ install(
PATTERN "*.hpp" PATTERN "*.hpp"
) )
# A way to live forever target_include_directories(${PROJECT_NAME}
add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD PUBLIC
COMMAND printf "Dedicated to my beloved Goma, I love you. - Dora" >> $<TARGET_FILE:${PROJECT_NAME}> $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/headers>
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/>
$<BUILD_INTERFACE:${corrade_SOURCE_DIR}/src>
$<INSTALL_INTERFACE:include/${PROJECT_NAME}>
$<INSTALL_INTERFACE:include/${PROJECT_NAME}External>
) )
install( install(
@@ -105,14 +99,7 @@ install(
EXPORT ${PROJECT_NAME}Targets EXPORT ${PROJECT_NAME}Targets
LIBRARY DESTINATION lib LIBRARY DESTINATION lib
ARCHIVE DESTINATION lib ARCHIVE DESTINATION lib
INCLUDES DESTINATION include/${PROJECT_NAME} INCLUDES DESTINATION include
)
install(
TARGETS CorradeMain CorradeUtility CorradeContainers CorradePluginManager
LIBRARY DESTINATION lib
ARCHIVE DESTINATION lib
INCLUDES DESTINATION include/${PROJECT_NAME}External
) )
install(DIRECTORY headers/ DESTINATION include/${PROJECT_NAME}) install(DIRECTORY headers/ DESTINATION include/${PROJECT_NAME})

View File

@@ -18,9 +18,7 @@ Tormaline Engine is a game engine created for C++23. [Source Code](https://git.t
Tourmaline is by no means currently usable. The project is incredible volatile with constant changes and improvements. Please wait until a release is made. Tourmaline is by no means currently usable. The project is incredible volatile with constant changes and improvements. Please wait until a release is made.
However if you cannot just help yourself you can compile a tourmaline demo by running However if you cannot just help yourself you can compile a tourmaline demo by running
``` g++ program.cpp -std=c++23 -lTourmaline -I/usr/local/include/TourmalineExternal -o program
g++ program.cpp -std=c++23 -lTourmaline -lCorradeUtility -lCorradePluginManager -I/usr/local/include/TourmalineExternal -o program
```
# 3rd Party Libraries Credits # 3rd Party Libraries Credits
- [Corrade/Magnum](https://magnum.graphics/) - graphics middleware by Vladimír "Mosra" Vondruš. - [Corrade/Magnum](https://magnum.graphics/) - graphics middleware by Vladimír "Mosra" Vondruš.

View File

@@ -1,7 +1,7 @@
include(FetchContent) include(FetchContent)
# Building options # Building options
set(CORRADE_BUILD_STATIC OFF) set(CORRADE_BUILD_STATIC ON)
# Feature options # Feature options
set(CORRADE_WITH_MAIN ON) set(CORRADE_WITH_MAIN ON)

View File

@@ -11,8 +11,6 @@
#define GUARD_TOURMALINE_CONCEPTS_H #define GUARD_TOURMALINE_CONCEPTS_H
#include <concepts> #include <concepts>
#include <functional> #include <functional>
#include <tuple>
#include <type_traits>
namespace Tourmaline::Concepts { namespace Tourmaline::Concepts {
template <typename T> template <typename T>
@@ -32,29 +30,5 @@ template <typename Base, typename Type1, typename Type2>
requires Either<Base, Type1, Type2> requires Either<Base, Type1, Type2>
using OppositeOf = _opposite_of<Base, Type1, Type2>::type; using OppositeOf = _opposite_of<Base, Type1, Type2>::type;
// heavily inspired by
// https://github.com/aminroosta/sqlite_modern_cpp/blob/master/hdr/sqlite_modern_cpp/utility/function_traits.h
template <typename> struct FunctionTraits;
template <typename Function>
struct FunctionTraits
: public FunctionTraits<
decltype(&std::remove_reference_t<Function>::operator())> {};
template <typename Return, typename Class, typename... Arguments>
struct FunctionTraits<Return (Class::*)(Arguments...) const>
: FunctionTraits<Return (*)(Arguments...)> {};
template <typename Return, typename Class, typename... Arguments>
struct FunctionTraits<Return (Class::*)(Arguments...)>
: FunctionTraits<Return (*)(Arguments...)> {};
template <typename Return, typename... Arguments>
struct FunctionTraits<Return (*)(Arguments...)> {
using returnType = Return;
using arguments = std::tuple<Arguments...>;
template <std::size_t index>
using argument = std::tuple_element_t<index, arguments>;
static constexpr std::size_t argumentCount = sizeof...(Arguments);
};
} // namespace Tourmaline::Concepts } // namespace Tourmaline::Concepts
#endif #endif

View File

@@ -13,9 +13,8 @@
#include "ContainerOptions.hpp" #include "ContainerOptions.hpp"
#include "Hashmap.hpp" #include "Hashmap.hpp"
#include "Corrade/Containers/Array.h"
#include <algorithm> #include <algorithm>
#include <array>
#include <cmath> #include <cmath>
#include <cstddef> #include <cstddef>
#include <cstdint> #include <cstdint>
@@ -34,14 +33,14 @@ template <Concepts::Hashable AKey, Concepts::Hashable BKey, typename Value,
class DualkeyMap { class DualkeyMap {
public: public:
// Return Types // Return Types
template <typename OppositeKey> template <typename OppositeKey, std::size_t keyCount>
requires Concepts::Either<OppositeKey, AKey, BKey> requires Concepts::Either<OppositeKey, AKey, BKey>
struct MultiQueryResult { struct MultiQueryResult {
// Having to use pointers here over references was not fun // Having to use pointers here over references was not fun
// but it was for greater good // but it was for greater good
const OppositeKey *oppositeKey; const OppositeKey *oppositeKey;
Corrade::Containers::Array<Value *> valueQueryResults;
std::size_t howManyFound = 1; std::size_t howManyFound = 1;
std::array<Value *, keyCount> valueQueryResults;
}; };
using QueryResult = using QueryResult =
@@ -206,19 +205,19 @@ public:
} }
template <typename Key, template <typename Key,
typename OppositeKey = Concepts::OppositeOf<Key, AKey, BKey>> typename OppositeKey = Concepts::OppositeOf<Key, AKey, BKey>,
std::size_t keyCount>
requires Concepts::Either<Key, AKey, BKey> requires Concepts::Either<Key, AKey, BKey>
[[nodiscard("Discarding a very expensive query!")]] [[nodiscard("Discarding a very expensive query!")]]
std::vector<MultiQueryResult<OppositeKey>> std::vector<MultiQueryResult<OppositeKey, keyCount>>
QueryWithAll(const Corrade::Containers::Array<Key> &keys) { QueryWithAll(const Key (&keys)[keyCount]) {
std::vector<MultiQueryResult<OppositeKey>> queryResult = std::vector<MultiQueryResult<OppositeKey, keyCount>> queryResult =
queryWithMany<Key>(keys); queryWithMany<Key>(keys);
std::erase_if(
std::erase_if(queryResult, queryResult,
[keyCount = keys.size()]( [](const MultiQueryResult<OppositeKey, keyCount> &queryRecord) {
const MultiQueryResult<OppositeKey> &queryRecord) { return queryRecord.howManyFound != keyCount;
return queryRecord.howManyFound != keyCount; });
});
return queryResult; return queryResult;
} }
@@ -270,14 +269,14 @@ private:
// Interal querying // Interal querying
template <typename Key, template <typename Key,
typename OppositeKey = Concepts::OppositeOf<Key, AKey, BKey>> typename OppositeKey = Concepts::OppositeOf<Key, AKey, BKey>,
inline std::vector<MultiQueryResult<OppositeKey>> std::size_t keyCount>
queryWithMany(const Corrade::Containers::Array<Key> &keys) { inline std::vector<MultiQueryResult<OppositeKey, keyCount>>
queryWithMany(const Key (&keys)[keyCount]) {
constexpr bool searchingInFirstKey = std::is_same_v<Key, AKey>; constexpr bool searchingInFirstKey = std::is_same_v<Key, AKey>;
std::size_t keyCount = keys.size();
// I really can't wait for C++26 contracts // I really can't wait for C++26 contracts
if (keyCount == 0) { if constexpr (keyCount == 0) {
Systems::Logging::Log("Failed to Query! QueryWithAll require at least 2 " Systems::Logging::Log("Failed to Query! QueryWithAll require at least 2 "
"key to be given, zero was given! Terminating", "key to be given, zero was given! Terminating",
"Dualkey Map", "Dualkey Map",
@@ -285,7 +284,7 @@ private:
} }
// Hoping this never ever gets triggered :sigh: // Hoping this never ever gets triggered :sigh:
if (keyCount == 1) { if constexpr (keyCount == 1) {
Systems::Logging::Log("QueryWithAll should not be used for single key " Systems::Logging::Log("QueryWithAll should not be used for single key "
"entry! Please use Query for this instead.", "entry! Please use Query for this instead.",
"Dualkey Map", Systems::Logging::LogLevel::Error); "Dualkey Map", Systems::Logging::LogLevel::Error);
@@ -293,7 +292,7 @@ private:
// While we don't necessary need the hashes, // While we don't necessary need the hashes,
// it just helps us tremendously benefit from short circuit checks // it just helps us tremendously benefit from short circuit checks
Corrade::Containers::Array<std::size_t> keyHashes{keyCount}; std::array<std::size_t, keyCount> keyHashes;
for (uint64_t index = 0; index < keyCount; index++) { for (uint64_t index = 0; index < keyCount; index++) {
keyHashes[index] = std::hash<Key>{}(keys[index]); keyHashes[index] = std::hash<Key>{}(keys[index]);
} }
@@ -302,7 +301,7 @@ private:
Key *keyToCompare; Key *keyToCompare;
OppositeKey *oppositeKey; OppositeKey *oppositeKey;
Containers::Hashmap<OppositeKey, MultiQueryResult<OppositeKey>, Containers::Hashmap<OppositeKey, MultiQueryResult<OppositeKey, keyCount>,
{8.0f, 0.01f, 2.5f, 2048, 8}> // Aggressive hashmap :o {8.0f, 0.01f, 2.5f, 2048, 8}> // Aggressive hashmap :o
queryResults; queryResults;
@@ -335,9 +334,8 @@ private:
} }
queryResults queryResults
.Insert( .Insert(*oppositeKey,
*oppositeKey, MultiQueryResult<OppositeKey, keyCount>(oppositeKey))
{oppositeKey, Corrade::Containers::Array<Value *>{keyCount}})
.valueQueryResults[index] = &hash->value; .valueQueryResults[index] = &hash->value;
} }
} }

View File

@@ -34,7 +34,8 @@ public:
if (!storage[keyHashPosition].empty()) { if (!storage[keyHashPosition].empty()) {
// Throws // Throws
Systems::Logging::Log("Trying to insert the same key twice! Throwing...", Systems::Logging::Log("Trying to insert the same key twice! Throwing...",
"Hashmap", Systems::Logging::Error, Has(key)); "Hashmap", Systems::Logging::LogLevel::Error,
Has(key));
} else { } else {
storage[keyHashPosition].reserve(Options.reservedBucketSpace); storage[keyHashPosition].reserve(Options.reservedBucketSpace);
} }
@@ -50,7 +51,7 @@ public:
// Throws // Throws
Systems::Logging::Log("Trying to remove a non-existant key! Throwing...", Systems::Logging::Log("Trying to remove a non-existant key! Throwing...",
"Hashmap", Systems::Logging::Error, "Hashmap", Systems::Logging::LogLevel::Error,
storage[keyHashPosition].empty()); storage[keyHashPosition].empty());
std::erase_if(storage[keyHashPosition], std::erase_if(storage[keyHashPosition],
[keyHash, &key](const hashStorage &hash) { [keyHash, &key](const hashStorage &hash) {
@@ -89,7 +90,8 @@ public:
Systems::Logging::Log( Systems::Logging::Log(
"Trying to access a non-existant bucket for a key! Throwing...", "Trying to access a non-existant bucket for a key! Throwing...",
"Hashmap", Systems::Logging::Error, storage[keyHashPosition].empty()); "Hashmap", Systems::Logging::LogLevel::Error,
storage[keyHashPosition].empty());
for (hashStorage &hash : storage[keyHashPosition]) { for (hashStorage &hash : storage[keyHashPosition]) {
if (hash.hash == keyHash && hash.key == key) { if (hash.hash == keyHash && hash.key == key) {
@@ -98,8 +100,7 @@ public:
} }
Systems::Logging::Log("Trying to access a non-existant key! Throwing...", Systems::Logging::Log("Trying to access a non-existant key! Throwing...",
"Hashmap", Systems::Logging::Error); "Hashmap", Systems::Logging::LogLevel::Error);
throw;
} }
[[nodiscard("Discarding an expensive operation!")]] [[nodiscard("Discarding an expensive operation!")]]
@@ -159,8 +160,8 @@ private:
// Repopulate and cleanup // Repopulate and cleanup
for (bucket &entry : oldStorage) { for (bucket &entry : oldStorage) {
for (hashStorage &hash : entry) { for (const hashStorage &hash : entry) {
Insert(std::move(hash.key), std::move(hash.value)); Insert(hash.key, hash.value);
} }
entry.clear(); entry.clear();

View File

@@ -10,60 +10,64 @@
#ifndef GUARD_TOURMALINE_ECS_H #ifndef GUARD_TOURMALINE_ECS_H
#define GUARD_TOURMALINE_ECS_H #define GUARD_TOURMALINE_ECS_H
#include <any> #include <any>
#include <format>
#include <typeindex> #include <typeindex>
#include "../Containers/DualkeyMap.hpp" #include "../Containers/DualkeyMap.hpp"
#include "../Containers/Hashmap.hpp"
#include "../Types.hpp" #include "../Types.hpp"
#include "ECS/BuiltinComponents.hpp" #include "ECS/BuiltinComponents.hpp"
#include "Logging.hpp" #include "Logging.hpp"
namespace Tourmaline::Systems::ECS { namespace Tourmaline::Systems::ECS {
using Entity = Tourmaline::Type::UUID; using Entity = Tourmaline::Type::UUID;
using System = Tourmaline::Type::UUID; class World;
class World { class World {
public: public:
World() {}
// ====== World controls ====== // ====== World controls ======
void Step(); void Step();
// ======== Entities ======== // ======== Entities ========
[[nodiscard]] [[nodiscard]]
Entity CreateEntity(); Entity CreateEntity();
[[nodiscard("Pointless call of EntityExists")]]
bool EntityExists(const Entity &entity) noexcept; bool EntityExists(const Entity &entity) noexcept;
[[nodiscard("It is not guaranteed that an entity can always be destroyed, "
"please make sure by checking the returned bool")]]
bool DestroyEntity(Entity entity); bool DestroyEntity(Entity entity);
// ======== Components ======== // ======== Components ========
template <isAComponent Component, typename... ComponentArgs> template <isAComponent component, typename... Args>
Component &AddComponent(const Entity &entity, ComponentArgs &&...args) { component &AddComponent(const Entity &entity,
auto newComponent = entityComponentMap.Insert(entity, typeid(Component), Args &&...constructionArguments) {
Component(args...)); auto newComponent = entityComponentMap.Insert(
entity, typeid(component), component(constructionArguments...));
return std::any_cast<Component &>(std::get<2>(newComponent)); return std::any_cast<component &>(std::get<2>(newComponent));
} }
template <isAComponent Component> template <isAComponent component>
[[nodiscard("Pointless call of GetComponent")]] [[nodiscard("Discarding an expensive operation's result!")]]
Component &GetComponent(const Entity &entity) { component &GetComponent(const Entity &entity) {
auto result = entityComponentMap.Query(entity, typeid(Component)); auto result = entityComponentMap.Query(entity, typeid(component));
if (result.empty()) { if (result.empty()) {
Logging::LogFormatted("Entity {} does not have component {}!", Logging::Log(std::format("Entity {} does not have component {}!",
"ECS/GetComponent", Logging::LogLevel::Error, entity.asString(), typeid(component).name()),
entity.asString(), typeid(Component).name()); "ECS/GetComponent", Logging::LogLevel::Error);
} }
return std::any_cast<Component &>(result.begin()->second); return std::any_cast<component &>(result.begin()->second);
} }
template <isAComponent Component> template <isAComponent component>
[[nodiscard("Pointless call of HasComponent")]] [[nodiscard("Discarding an expensive operation's result!")]]
bool HasComponent(const Entity &entity) { bool HasComponent(const Entity &entity) {
return entityComponentMap.Query(entity, typeid(Component)).size(); return entityComponentMap.Query(entity, typeid(component)).size();
} }
template <isAComponent Component> bool RemoveComponent(const Entity &entity) { template <isAComponent component>
return entityComponentMap.Remove(entity, typeid(Component)); [[nodiscard("It is not guaranteed that a component can always be removed, "
"please make sure by checking the returned bool")]]
bool RemoveComponent(const Entity &entity) {
return entityComponentMap.Remove(entity, typeid(component));
} }
// Copying is not allowed since the ECS world is meant to be // Copying is not allowed since the ECS world is meant to be
@@ -72,11 +76,8 @@ public:
World &operator=(const World &) = delete; World &operator=(const World &) = delete;
private: private:
using systemFunction = Tourmaline::Containers::DualkeyMap<Entity, std::type_index, std::any>
std::function<void(const Entity &, std::span<std::any *>)>;
Containers::DualkeyMap<Entity, std::type_index, std::any>
entityComponentMap{}; entityComponentMap{};
Containers::Hashmap<System, systemFunction> registeredSystems{};
// ======== Life-cycle ======== // ======== Life-cycle ========
void preSystems(); void preSystems();

View File

@@ -24,7 +24,7 @@ concept isAComponent = std::derived_from<T, ECS::Component>;
namespace Tourmaline::Systems::Components { namespace Tourmaline::Systems::Components {
// Builtin // Builtin
struct Base : public ECS::Component { struct Base : public ECS::Component {
double x = 0, y = 0, z = 0; Base() {}
}; };
} // namespace Tourmaline::Systems::Components } // namespace Tourmaline::Systems::Components
#endif #endif

View File

@@ -8,36 +8,31 @@
*/ */
#ifndef GUARD_TOURMALINE_LOGGING_H #ifndef GUARD_TOURMALINE_LOGGING_H
#define GUARD_TOURMALINE_LOGGING_H #define GUARD_TOURMALINE_LOGGING_H
#include <array>
#include "Corrade/Containers/String.h"
#include "Corrade/Containers/StringView.h"
#include "Corrade/Utility/Format.h"
#include <fstream> #include <fstream>
#include <string_view>
namespace Tourmaline::Systems { namespace Tourmaline::Systems {
class Logging { class Logging {
public: public:
enum LogLevel { Critical, Error, Warning, Info, Debug, Trace }; enum class LogLevel {
Critical = 0,
Error = 1,
Warning = 2,
Info = 3,
Debug = 4,
Trace = 5
};
static void LogToFile(Corrade::Containers::String File = ""); static void LogToFile(std::string File = "");
static void Log(Corrade::Containers::StringView message, static void Log(std::string_view message,
Corrade::Containers::StringView position = "Unknown", std::string_view position = "Unknown",
LogLevel severity = LogLevel::Info, bool assertion = true); LogLevel severity = LogLevel::Info, bool assertion = true);
template <class... Args>
static void LogFormatted(const char *format, const char *position,
LogLevel severity, const Args &...args) {
static Corrade::Containers::String output{Corrade::ValueInit, 4096};
std::size_t size = Corrade::Utility::formatInto(output, format, args...);
Log(Corrade::Containers::StringView{output.begin(), size}, position,
severity);
}
private: private:
static std::fstream File; static std::fstream File;
static const char *LogLevelToColour[Trace + 1]; static std::array<std::pair<const std::string, const std::string>, 6>
static const char *LogLevelToString[Trace + 1]; LogLevelToString;
}; };
} // namespace Tourmaline::Systems } // namespace Tourmaline::Systems
#endif #endif

View File

@@ -10,7 +10,7 @@
#ifndef GUARD_TOURMALINE_RANDOM_H #ifndef GUARD_TOURMALINE_RANDOM_H
#define GUARD_TOURMALINE_RANDOM_H #define GUARD_TOURMALINE_RANDOM_H
#include "../Types.hpp" #include "../Types.hpp"
#include "TourmalineExternal/random/xoshiro.h" #include <TourmalineExternal/random/xoshiro.h>
#include <type_traits> #include <type_traits>

View File

@@ -10,9 +10,7 @@
#ifndef GUARD_TOURMALINE_TYPES_H #ifndef GUARD_TOURMALINE_TYPES_H
#define GUARD_TOURMALINE_TYPES_H #define GUARD_TOURMALINE_TYPES_H
#include "Corrade/Containers/String.h"
#include "TourmalineExternal/random/xoshiro.h" #include "TourmalineExternal/random/xoshiro.h"
#include <cstdint> #include <cstdint>
#include <functional> #include <functional>
#include <string> #include <string>
@@ -21,7 +19,7 @@ namespace Tourmaline::Type {
class UUID { class UUID {
public: public:
[[nodiscard]] [[nodiscard]]
Corrade::Containers::String asString() const; std::string asString() const;
bool operator==(const UUID &rhs) const; bool operator==(const UUID &rhs) const;
UUID(uint64_t firstHalf, uint64_t secondHalf); UUID(uint64_t firstHalf, uint64_t secondHalf);

View File

@@ -8,12 +8,9 @@
*/ */
#include "Systems/Logging.hpp" #include "Systems/Logging.hpp"
#include "Corrade/Containers/Array.h"
#include "Corrade/Containers/String.h" #include <Corrade/Tags.h>
#include "Corrade/Containers/StringView.h"
#include "Corrade/Tags.h"
#include "Corrade/Utility/Format.h"
#include <cerrno> #include <cerrno>
#include <chrono> #include <chrono>
#include <cstddef> #include <cstddef>
@@ -21,63 +18,65 @@
#include <exception> #include <exception>
#include <format> #include <format>
#include <fstream> #include <fstream>
#include <iterator>
#include <print> #include <print>
#include <stdexcept> #include <stdexcept>
#include <string>
#include <string_view> #include <string_view>
#include <utility>
using namespace Tourmaline::Systems; using namespace Tourmaline::Systems;
using namespace Corrade::Containers; using namespace Corrade::Containers;
using namespace Corrade::Utility;
// This is what happens when it takes you 50 years to implement // This is what happens when it takes you 50 years to implement
// reflections to a language // reflections to a language
const char *Logging::LogLevelToColour[Logging::Trace + 1]{ Array<std::pair<const std::string, const std::string>>
"[0;31m", "[0;91m", "[0;33m", "[0;37m", "[0;92m", "[0;36m"}; Logging::LogLevelToString{Corrade::InPlaceInit,
const char *Logging::LogLevelToString[Logging::Trace + 1]{ {std::pair{"Critical", "[0;31m"},
"Critical", "Error", "Warning", "Info", "Debug", "Trace"}; {"Error", "[0;91m"},
{"Warning", "[0;33m"},
{"Info", "[0;37m"},
{"Debug", "[0;92m"},
{"Trace", "[0;36m"}}};
std::fstream Logging::File; std::fstream Logging::File;
void Logging::LogToFile(String File) { void Logging::LogToFile(std::string File) {
if (File == "") { if (File == "") {
const auto now = std::chrono::system_clock::now(); const auto now = std::chrono::system_clock::now();
std::chrono::year_month_day ymd{std::chrono::floor<std::chrono::days>(now)}; File = std::format("Tourmaline-{:%Y-%j}.txt", now);
File = String{Corrade::ValueInit, 128};
formatInto(File, "Tourmaline-{}-{}-{}.txt", static_cast<int>(ymd.year()),
static_cast<unsigned>(ymd.month()),
static_cast<unsigned>(ymd.day()));
} }
Logging::File.open(File.data(), std::fstream::out); Logging::File.open(File, std::fstream::out);
if (Logging::File.fail()) { if (Logging::File.fail()) {
String error = throw std::runtime_error("FAILED! Could not open or create the file: " +
format("FAILED! Could not open or create the file: {}! Error: {}", File, File + "!\n" + strerror(errno));
strerror(errno));
throw std::runtime_error(error.data());
} }
} }
void Logging::Log(StringView message, StringView position, void Logging::Log(std::string_view message, std::string_view position,
Logging::LogLevel severity, bool assertion) { Logging::LogLevel severity, bool assertion) {
if (assertion) { if (assertion) [[likely]] {
static String output{Corrade::ValueInit, static std::string
4096}; // This is done to stop allocations output; // This is done to stop allocations per std::format
std::size_t formattedSize = formatInto( const auto &loglevelData =
output, "[{}@{}] {}\n", LogLevelToString[severity], position, message); Logging::LogLevelToString[static_cast<size_t>(severity)];
std::format_to(std::back_inserter(output), "[{}@{}] {}\n",
loglevelData.first, position, message);
std::print( std::print("\033{} {}\033[0m", loglevelData.second, output);
"\033{} {}\033[0m", LogLevelToColour[severity],
std::string_view{output.begin(), output.begin() + formattedSize});
if (Logging::File.is_open()) { if (Logging::File.is_open()) {
Logging::File.write(output.data(), formattedSize); Logging::File.write(output.c_str(), output.size());
Logging::File.flush(); // Terrible but necessary sadly Logging::File.flush(); // Terrible but necessary sadly
} }
if (severity == Logging::LogLevel::Error) { if (severity == Logging::LogLevel::Error) {
throw std::runtime_error(output.data()); throw std::runtime_error(output);
} }
if (severity == Logging::LogLevel::Critical) { if (severity == Logging::LogLevel::Critical) {
std::terminate(); std::terminate();
} }
output.clear();
} }
} }

View File

@@ -7,19 +7,17 @@
* obtain one at http://mozilla.org/MPL/2.0/. * obtain one at http://mozilla.org/MPL/2.0/.
*/ */
#include "Corrade/Utility/Format.h"
#include "Types.hpp" #include "Types.hpp"
#include <charconv> #include <charconv>
#include <cstdint> #include <cstdint>
#include <cstring> #include <cstring>
#include <format>
#include <string> #include <string>
using namespace Tourmaline::Type; using namespace Tourmaline::Type;
using namespace Corrade::Containers; std::string UUID::asString() const {
using namespace Corrade::Utility; return std::format("{:016X}{:016X}", firstHalf, secondHalf);
String UUID::asString() const {
return format("{:.16X}{:.16X}", firstHalf, secondHalf);
} }
bool UUID::operator==(const UUID &rhs) const { bool UUID::operator==(const UUID &rhs) const {