aboutsummaryrefslogtreecommitdiff
path: root/src/crepe
diff options
context:
space:
mode:
Diffstat (limited to 'src/crepe')
-rw-r--r--src/crepe/Asset.cpp14
-rw-r--r--src/crepe/Asset.h33
-rw-r--r--src/crepe/CMakeLists.txt28
-rw-r--r--src/crepe/Collider.cpp2
-rw-r--r--src/crepe/Collider.h13
-rw-r--r--src/crepe/Component.cpp13
-rw-r--r--src/crepe/Component.h71
-rw-r--r--src/crepe/ComponentManager.cpp34
-rw-r--r--src/crepe/ComponentManager.h63
-rw-r--r--src/crepe/ComponentManager.hpp142
-rw-r--r--src/crepe/GameObject.cpp7
-rw-r--r--src/crepe/GameObject.h24
-rw-r--r--src/crepe/GameObject.hpp15
-rw-r--r--src/crepe/Particle.cpp34
-rw-r--r--src/crepe/Particle.h63
-rw-r--r--src/crepe/Position.h10
-rw-r--r--src/crepe/Resource.cpp6
-rw-r--r--src/crepe/Resource.h30
-rw-r--r--src/crepe/Rigidbody.cpp6
-rw-r--r--src/crepe/Rigidbody.h16
-rw-r--r--src/crepe/Script.cpp7
-rw-r--r--src/crepe/Script.h16
-rw-r--r--src/crepe/ScriptSystem.cpp22
-rw-r--r--src/crepe/ScriptSystem.h18
-rw-r--r--src/crepe/Sound.cpp60
-rw-r--r--src/crepe/Sound.h82
-rw-r--r--src/crepe/SoundContext.cpp20
-rw-r--r--src/crepe/SoundContext.h26
-rw-r--r--src/crepe/Sprite.cpp8
-rw-r--r--src/crepe/Sprite.h16
-rw-r--r--src/crepe/System.h23
-rw-r--r--src/crepe/ValueBroker.h41
-rw-r--r--src/crepe/ValueBroker.hpp22
-rw-r--r--src/crepe/api/AI.cpp89
-rw-r--r--src/crepe/api/AI.h128
-rw-r--r--src/crepe/api/Animator.cpp57
-rw-r--r--src/crepe/api/Animator.h104
-rw-r--r--src/crepe/api/Asset.cpp54
-rw-r--r--src/crepe/api/Asset.h84
-rw-r--r--src/crepe/api/AudioSource.cpp23
-rw-r--r--src/crepe/api/AudioSource.h69
-rw-r--r--src/crepe/api/BehaviorScript.cpp17
-rw-r--r--src/crepe/api/BehaviorScript.h70
-rw-r--r--src/crepe/api/BehaviorScript.hpp22
-rw-r--r--src/crepe/api/BoxCollider.cpp10
-rw-r--r--src/crepe/api/BoxCollider.h23
-rw-r--r--src/crepe/api/Button.cpp8
-rw-r--r--src/crepe/api/Button.h48
-rw-r--r--src/crepe/api/CMakeLists.txt53
-rw-r--r--src/crepe/api/Camera.cpp18
-rw-r--r--src/crepe/api/Camera.h67
-rw-r--r--src/crepe/api/CircleCollider.cpp8
-rw-r--r--src/crepe/api/CircleCollider.h23
-rw-r--r--src/crepe/api/Color.cpp12
-rw-r--r--src/crepe/api/Color.h23
-rw-r--r--src/crepe/api/Config.cpp8
-rw-r--r--src/crepe/api/Config.h103
-rw-r--r--src/crepe/api/Engine.cpp63
-rw-r--r--src/crepe/api/Engine.h81
-rw-r--r--src/crepe/api/Engine.hpp12
-rw-r--r--src/crepe/api/Event.h154
-rw-r--r--src/crepe/api/EventHandler.cpp5
-rw-r--r--src/crepe/api/EventHandler.h96
-rw-r--r--src/crepe/api/EventHandler.hpp20
-rw-r--r--src/crepe/api/GameObject.cpp35
-rw-r--r--src/crepe/api/GameObject.h86
-rw-r--r--src/crepe/api/GameObject.hpp15
-rw-r--r--src/crepe/api/KeyCodes.h160
-rw-r--r--src/crepe/api/Metadata.cpp9
-rw-r--r--src/crepe/api/Metadata.h42
-rw-r--r--src/crepe/api/ParticleEmitter.cpp28
-rw-r--r--src/crepe/api/ParticleEmitter.h104
-rw-r--r--src/crepe/api/Rigidbody.cpp13
-rw-r--r--src/crepe/api/Rigidbody.h178
-rw-r--r--src/crepe/api/Scene.cpp15
-rw-r--r--src/crepe/api/Scene.h94
-rw-r--r--src/crepe/api/Scene.hpp19
-rw-r--r--src/crepe/api/Script.cpp63
-rw-r--r--src/crepe/api/Script.h276
-rw-r--r--src/crepe/api/Script.hpp105
-rw-r--r--src/crepe/api/Sprite.cpp21
-rw-r--r--src/crepe/api/Sprite.h114
-rw-r--r--src/crepe/api/Text.cpp12
-rw-r--r--src/crepe/api/Text.h66
-rw-r--r--src/crepe/api/Transform.cpp22
-rw-r--r--src/crepe/api/Transform.h46
-rw-r--r--src/crepe/api/UIObject.cpp8
-rw-r--r--src/crepe/api/UIObject.h25
-rw-r--r--src/crepe/api/Vector2.h97
-rw-r--r--src/crepe/api/Vector2.hpp166
-rw-r--r--src/crepe/facade/CMakeLists.txt20
-rw-r--r--src/crepe/facade/DB.cpp61
-rw-r--r--src/crepe/facade/DB.h75
-rw-r--r--src/crepe/facade/EventData.h54
-rw-r--r--src/crepe/facade/Font.cpp21
-rw-r--r--src/crepe/facade/Font.h42
-rw-r--r--src/crepe/facade/FontFacade.cpp43
-rw-r--r--src/crepe/facade/FontFacade.h34
-rw-r--r--src/crepe/facade/SDLContext.cpp419
-rw-r--r--src/crepe/facade/SDLContext.h365
-rw-r--r--src/crepe/facade/Sound.cpp13
-rw-r--r--src/crepe/facade/Sound.h31
-rw-r--r--src/crepe/facade/SoundContext.cpp36
-rw-r--r--src/crepe/facade/SoundContext.h81
-rw-r--r--src/crepe/facade/SoundHandle.h12
-rw-r--r--src/crepe/facade/Texture.cpp29
-rw-r--r--src/crepe/facade/Texture.h69
-rw-r--r--src/crepe/manager/CMakeLists.txt30
-rw-r--r--src/crepe/manager/ComponentManager.cpp99
-rw-r--r--src/crepe/manager/ComponentManager.h252
-rw-r--r--src/crepe/manager/ComponentManager.hpp196
-rw-r--r--src/crepe/manager/EventManager.cpp44
-rw-r--r--src/crepe/manager/EventManager.h148
-rw-r--r--src/crepe/manager/EventManager.hpp36
-rw-r--r--src/crepe/manager/LoopTimerManager.cpp91
-rw-r--r--src/crepe/manager/LoopTimerManager.h177
-rw-r--r--src/crepe/manager/Manager.cpp5
-rw-r--r--src/crepe/manager/Manager.h24
-rw-r--r--src/crepe/manager/Mediator.h41
-rw-r--r--src/crepe/manager/ReplayManager.cpp70
-rw-r--r--src/crepe/manager/ReplayManager.h96
-rw-r--r--src/crepe/manager/ResourceManager.cpp30
-rw-r--r--src/crepe/manager/ResourceManager.h78
-rw-r--r--src/crepe/manager/ResourceManager.hpp27
-rw-r--r--src/crepe/manager/SaveManager.cpp169
-rw-r--r--src/crepe/manager/SaveManager.h104
-rw-r--r--src/crepe/manager/SceneManager.cpp38
-rw-r--r--src/crepe/manager/SceneManager.h52
-rw-r--r--src/crepe/manager/SceneManager.hpp25
-rw-r--r--src/crepe/manager/SystemManager.cpp66
-rw-r--r--src/crepe/manager/SystemManager.h85
-rw-r--r--src/crepe/manager/SystemManager.hpp41
-rw-r--r--src/crepe/system/AISystem.cpp186
-rw-r--r--src/crepe/system/AISystem.h81
-rw-r--r--src/crepe/system/AnimatorSystem.cpp40
-rw-r--r--src/crepe/system/AnimatorSystem.h28
-rw-r--r--src/crepe/system/AudioSystem.cpp62
-rw-r--r--src/crepe/system/AudioSystem.h51
-rw-r--r--src/crepe/system/CMakeLists.txt28
-rw-r--r--src/crepe/system/CollisionSystem.cpp575
-rw-r--r--src/crepe/system/CollisionSystem.h311
-rw-r--r--src/crepe/system/EventSystem.cpp9
-rw-r--r--src/crepe/system/EventSystem.h21
-rw-r--r--src/crepe/system/InputSystem.cpp209
-rw-r--r--src/crepe/system/InputSystem.h132
-rw-r--r--src/crepe/system/ParticleSystem.cpp121
-rw-r--r--src/crepe/system/ParticleSystem.h62
-rw-r--r--src/crepe/system/PhysicsSystem.cpp106
-rw-r--r--src/crepe/system/PhysicsSystem.h24
-rw-r--r--src/crepe/system/RenderSystem.cpp160
-rw-r--r--src/crepe/system/RenderSystem.h83
-rw-r--r--src/crepe/system/ReplaySystem.cpp54
-rw-r--r--src/crepe/system/ReplaySystem.h44
-rw-r--r--src/crepe/system/ScriptSystem.cpp40
-rw-r--r--src/crepe/system/ScriptSystem.h37
-rw-r--r--src/crepe/system/System.cpp5
-rw-r--r--src/crepe/system/System.h32
-rw-r--r--src/crepe/types.h30
-rw-r--r--src/crepe/util/CMakeLists.txt12
-rw-r--r--src/crepe/util/Log.cpp38
-rw-r--r--src/crepe/util/Log.h63
-rw-r--r--src/crepe/util/Log.hpp17
-rw-r--r--src/crepe/util/LogColor.cpp46
-rw-r--r--src/crepe/util/LogColor.h80
-rw-r--r--src/crepe/util/OptionalRef.h66
-rw-r--r--src/crepe/util/OptionalRef.hpp44
-rw-r--r--src/crepe/util/Proxy.h34
-rw-r--r--src/crepe/util/Proxy.hpp27
-rw-r--r--src/crepe/util/color.h41
-rw-r--r--src/crepe/util/dbg.h18
-rw-r--r--src/crepe/util/log.cpp50
-rw-r--r--src/crepe/util/log.h36
172 files changed, 10029 insertions, 859 deletions
diff --git a/src/crepe/Asset.cpp b/src/crepe/Asset.cpp
deleted file mode 100644
index 15ddc27..0000000
--- a/src/crepe/Asset.cpp
+++ /dev/null
@@ -1,14 +0,0 @@
-#include <filesystem>
-
-#include "Asset.h"
-
-using namespace crepe;
-
-Asset::Asset(const std::string & src) {
- this->src = std::filesystem::canonical(src);
- this->file = std::ifstream(this->src, std::ios::in | std::ios::binary);
-}
-
-const std::istream & Asset::read() { return this->file; }
-
-const char * Asset::canonical() { return this->src.c_str(); }
diff --git a/src/crepe/Asset.h b/src/crepe/Asset.h
deleted file mode 100644
index 0cb5834..0000000
--- a/src/crepe/Asset.h
+++ /dev/null
@@ -1,33 +0,0 @@
-#pragma once
-
-#include <fstream>
-#include <iostream>
-#include <string>
-
-namespace crepe {
-
-/**
- * \brief Asset location helper
- *
- * This class is used to locate and canonicalize paths to game asset files, and
- * should *always* be used when retrieving files from disk.
- */
-class Asset {
-public:
- /**
- * \param src Unique identifier to asset
- */
- Asset(const std::string & src);
-
-public:
- //! Get an input stream to the contents of this resource
- const std::istream & read();
- //! Get the canonical path to this resource
- const char * canonical();
-
-private:
- std::string src;
- std::ifstream file;
-};
-
-} // namespace crepe
diff --git a/src/crepe/CMakeLists.txt b/src/crepe/CMakeLists.txt
index d85aef0..6cbb9fe 100644
--- a/src/crepe/CMakeLists.txt
+++ b/src/crepe/CMakeLists.txt
@@ -1,33 +1,21 @@
target_sources(crepe PUBLIC
- Asset.cpp
- Sound.cpp
- SoundContext.cpp
- ComponentManager.cpp
+ Particle.cpp
Component.cpp
- GameObject.cpp
Collider.cpp
- Rigidbody.cpp
- Sprite.cpp
- ScriptSystem.cpp
- Script.cpp
+ Resource.cpp
)
target_sources(crepe PUBLIC FILE_SET HEADERS FILES
- Asset.h
- Sound.h
- SoundContext.h
- ComponentManager.h
- ComponentManager.hpp
Component.h
- GameObject.h
- GameObject.hpp
Collider.h
- Rigidbody.h
- Sprite.h
- System.h
- ScriptSystem.h
+ ValueBroker.h
+ ValueBroker.hpp
+ Resource.h
)
add_subdirectory(api)
+add_subdirectory(facade)
+add_subdirectory(manager)
+add_subdirectory(system)
add_subdirectory(util)
diff --git a/src/crepe/Collider.cpp b/src/crepe/Collider.cpp
index 3f12afd..77e11c8 100644
--- a/src/crepe/Collider.cpp
+++ b/src/crepe/Collider.cpp
@@ -2,4 +2,4 @@
using namespace crepe;
-Collider::Collider(int size) : size(size) {}
+Collider::Collider(game_object_id_t id, const vec2 & offset) : Component(id), offset(offset) {}
diff --git a/src/crepe/Collider.h b/src/crepe/Collider.h
index 120da05..42ccfd4 100644
--- a/src/crepe/Collider.h
+++ b/src/crepe/Collider.h
@@ -1,14 +1,23 @@
#pragma once
#include "Component.h"
+#include "types.h"
namespace crepe {
class Collider : public Component {
public:
- Collider(int size);
+ Collider(game_object_id_t id, const vec2 & offset);
- int size;
+public:
+ /**
+ * \brief Offset of the collider relative to the rigidbody position.
+ *
+ * The `offset` defines the positional shift applied to the collider relative to the position of the rigidbody it is attached to.
+ * This allows the collider to be placed at a different position than the rigidbody.
+ *
+ */
+ vec2 offset;
};
} // namespace crepe
diff --git a/src/crepe/Component.cpp b/src/crepe/Component.cpp
index 737f30a..ae76e65 100644
--- a/src/crepe/Component.cpp
+++ b/src/crepe/Component.cpp
@@ -1,4 +1,17 @@
#include "Component.h"
using namespace crepe;
+using namespace std;
+Component::Component(game_object_id_t id) : game_object_id(id) {}
+
+Component & Component::operator=(const Component & other) {
+ this->active = other.active;
+ return *this;
+}
+
+unique_ptr<Component> Component::save() const {
+ return unique_ptr<Component>(new Component(*this));
+}
+
+void Component::restore(const Component & snapshot) { *this = snapshot; }
diff --git a/src/crepe/Component.h b/src/crepe/Component.h
index 00b2164..52e06d5 100644
--- a/src/crepe/Component.h
+++ b/src/crepe/Component.h
@@ -1,16 +1,79 @@
#pragma once
+#include <memory>
+
+#include "types.h"
+
namespace crepe {
+class ComponentManager;
+
+/**
+ * \brief Base class for all components
+ *
+ * This class is the base class for all components. It provides a common interface for all
+ * components.
+ */
class Component {
+public:
+ //! Whether the component is active
+ bool active = true;
+ /**
+ * \brief The id of the GameObject this component belongs to
+ *
+ * \note Only systems are supposed to use this member, but since friend
+ * relations aren't inherited this needs to be public.
+ */
+ const game_object_id_t game_object_id;
+
protected:
- Component() = default;
+ /**
+ * \param id The id of the GameObject this component belongs to
+ */
+ Component(game_object_id_t id);
+ //! Only ComponentManager can create components
+ friend class ComponentManager;
+
+ // components are never moved
+ Component(Component &&) = delete;
+ virtual Component & operator=(Component &&) = delete;
+
+protected:
+ /**
+ * \name ReplayManager (Memento) functions
+ * \{
+ */
+ /**
+ * \brief Save a snapshot of this component's state
+ * \note This function should only be implemented on components that should be saved/restored
+ * by ReplayManager.
+ * \returns Unique pointer to a deep copy of this component
+ */
+ virtual std::unique_ptr<Component> save() const;
+ //! Copy constructor (used by \c save())
+ Component(const Component &) = default;
+ /**
+ * \brief Restore this component from a snapshot
+ * \param snapshot Data to fill this component with (as returned by \c save())
+ */
+ virtual void restore(const Component & snapshot);
+ //! Copy assignment operator (used by \c restore())
+ virtual Component & operator=(const Component &);
+ //! \}
+
public:
virtual ~Component() = default;
- // TODO: shouldn't this constructor be deleted because this class will never
- // directly be instantiated?
- bool active = true;
+public:
+ /**
+ * \brief Get the maximum number of instances for this component
+ *
+ * This method returns -1 by default, which means that there is no limit for the number of
+ * instances. Concrete components can override this method to set a limit.
+ *
+ * \return The maximum number of instances for this component
+ */
+ virtual int get_instances_max() const { return -1; }
};
} // namespace crepe
diff --git a/src/crepe/ComponentManager.cpp b/src/crepe/ComponentManager.cpp
deleted file mode 100644
index 8aa9d4e..0000000
--- a/src/crepe/ComponentManager.cpp
+++ /dev/null
@@ -1,34 +0,0 @@
-#include "util/log.h"
-#include "ComponentManager.h"
-
-using namespace crepe;
-
-ComponentManager & ComponentManager::get_instance() {
- static ComponentManager instance;
- return instance;
-}
-
-void ComponentManager::delete_all_components_of_id(uint32_t id) {
- // Loop through all the types (in the unordered_map<>)
- for (auto & [type, componentArray] : components) {
- // Make sure that the id (that we are looking for) is within the boundaries of the vector<>
- if (id < componentArray.size()) {
- // Clear the components at this specific id
- componentArray[id].clear();
- }
- }
-}
-
-void ComponentManager::delete_all_components() {
- // Clear the whole unordered_map<>
- this->components.clear();
-}
-
-ComponentManager::ComponentManager() {
- dbg_trace();
-}
-
-ComponentManager::~ComponentManager() {
- dbg_trace();
-}
-
diff --git a/src/crepe/ComponentManager.h b/src/crepe/ComponentManager.h
deleted file mode 100644
index eab9b45..0000000
--- a/src/crepe/ComponentManager.h
+++ /dev/null
@@ -1,63 +0,0 @@
-#pragma once
-
-#include <cstdint>
-#include <memory>
-#include <typeindex>
-#include <unordered_map>
-#include <utility>
-#include <vector>
-
-#include "Component.h"
-
-namespace crepe {
-
-class ComponentManager {
-public:
- // Singleton
- static ComponentManager & get_instance();
- ComponentManager(const ComponentManager &) = delete;
- ComponentManager(ComponentManager &&) = delete;
- ComponentManager & operator=(const ComponentManager &) = delete;
- ComponentManager & operator=(ComponentManager &&) = delete;
-
-public:
- //! Add a component of a specific type
- template <typename T, typename... Args>
- void add_component(uint32_t id, Args &&... args);
- //! Deletes all components of a specific type and id
- template <typename T>
- void delete_components_by_id(uint32_t id);
- //! Deletes all components of a specific type
- template <typename T>
- void delete_components();
- //! Deletes all components of a specific id
- void delete_all_components_of_id(uint32_t id);
- //! Deletes all components
- void delete_all_components();
-
- //! Get a vector<> of all components at specific type and id
- template <typename T>
- std::vector<std::reference_wrapper<T>>
- get_components_by_id(uint32_t id) const;
- //! Get a vector<> of all components of a specific type
- template <typename T>
- std::vector<std::reference_wrapper<T>> get_components_by_type() const;
-
-private:
- ComponentManager();
- virtual ~ComponentManager();
-
- /*
- * The std::unordered_map<std::type_index, std::vector<std::vector<std::unique_ptr<Component>>>> below might seem a bit strange, let me explain this structure:
- * The std::unordered_map<> has a key and value. The key is a std::type_index and the value is a std::vector. So, a new std::vector will be created for each new std::type_index.
- * The first std::vector<> stores another vector<>. This first vector<> is to bind the entity's id to a component.
- * The second std::vector<> stores unique_ptrs. Each component can be gathered via an unique_ptr. This second vector<> allows multiple components of the same std::type_index for one entity (id).
- */
- std::unordered_map<std::type_index,
- std::vector<std::vector<std::unique_ptr<Component>>>>
- components;
-};
-
-} // namespace crepe
-
-#include "ComponentManager.hpp"
diff --git a/src/crepe/ComponentManager.hpp b/src/crepe/ComponentManager.hpp
deleted file mode 100644
index 8fc1cba..0000000
--- a/src/crepe/ComponentManager.hpp
+++ /dev/null
@@ -1,142 +0,0 @@
-#pragma once
-
-#include <type_traits>
-
-#include "ComponentManager.h"
-
-namespace crepe {
-
-template <class T, typename... Args>
-void ComponentManager::add_component(uint32_t id, Args &&... args) {
- using namespace std;
-
- static_assert(is_base_of<Component, T>::value, "add_component must recieve a derivative class of Component");
-
- // Determine the type of T (this is used as the key of the unordered_map<>)
- type_index type = typeid(T);
-
- // Check if this component type is already in the unordered_map<>
- if (components.find(type) == components.end()) {
- //If not, create a new (empty) vector<> of vector<unique_ptr<Component>>
- components[type] = vector<vector<unique_ptr<Component>>>();
- }
-
- // Resize the vector<> if the id is greater than the current size
- if (id >= components[type].size()) {
- // Initialize new slots to nullptr (resize does automatically init to nullptr)
- components[type].resize(id + 1);
- }
-
- // Create a new component of type T (arguments directly forwarded). The
- // constructor must be called by ComponentManager.
- T * instance = new T(forward<Args>(args)...);
- // store its unique_ptr in the vector<>
- components[type][id].push_back(unique_ptr<T>(instance));
-}
-
-template <typename T>
-void ComponentManager::delete_components_by_id(uint32_t id) {
- using namespace std;
-
- // Determine the type of T (this is used as the key of the unordered_map<>)
- type_index type = typeid(T);
-
- // Find the type (in the unordered_map<>)
- if (components.find(type) != components.end()) {
- // Get the correct vector<>
- vector<vector<unique_ptr<Component>>> & component_array
- = components[type];
-
- // Make sure that the id (that we are looking for) is within the boundaries of the vector<>
- if (id < component_array.size()) {
- // Clear the whole vector<> of this specific type and id
- component_array[id].clear();
- }
- }
-}
-
-template <typename T>
-void ComponentManager::delete_components() {
- // Determine the type of T (this is used as the key of the unordered_map<>)
- std::type_index type = typeid(T);
-
- if (components.find(type) == components.end()) return;
-
- components[type].clear();
-}
-
-template <typename T>
-std::vector<std::reference_wrapper<T>>
-ComponentManager::get_components_by_id(uint32_t id) const {
- using namespace std;
-
- // Determine the type of T (this is used as the key of the unordered_map<>)
- type_index type = typeid(T);
-
- // Create an empty vector<>
- vector<reference_wrapper<T>> component_vector;
-
- if (components.find(type) == components.end()) return component_vector;
-
- // Get the correct vector<>
- const vector<vector<unique_ptr<Component>>> & component_array = components.at(type);
-
- // Make sure that the id (that we are looking for) is within the boundaries of the vector<>
- if (id >= component_array.size()) return component_vector;
-
- // Loop trough the whole vector<>
- for (const unique_ptr<Component> & component_ptr : component_array[id]) {
- // Cast the unique_ptr to a raw pointer
- T * casted_component = static_cast<T *>(component_ptr.get());
-
- if (casted_component == nullptr) continue;
-
- // Add the dereferenced raw pointer to the vector<>
- component_vector.push_back(*casted_component);
- }
-
- return component_vector;
-}
-
-template <typename T>
-std::vector<std::reference_wrapper<T>>
-ComponentManager::get_components_by_type() const {
- using namespace std;
-
- // Determine the type of T (this is used as the key of the unordered_map<>)
- type_index type = typeid(T);
-
- // Create an empty vector<>
- vector<reference_wrapper<T>> component_vector;
- // Set the id to 0 (the id will also be stored in the returned vector<>)
- // uint32_t id = 0;
-
- // Find the type (in the unordered_map<>)
- if (components.find(type) == components.end()) return component_vector;
-
- // Get the correct vector<>
- const vector<vector<unique_ptr<Component>>> & component_array = components.at(type);
-
- // Loop through the whole vector<>
- for (const vector<unique_ptr<Component>> & component : component_array) {
- // Loop trough the whole vector<>
- for (const unique_ptr<Component> & component_ptr : component) {
- // Cast the unique_ptr to a raw pointer
- T * casted_component = static_cast<T *>(component_ptr.get());
-
- // Ensure that the cast was successful
- if (casted_component == nullptr) continue;
-
- // Pair the dereferenced raw pointer and the id and add it to the vector<>
- component_vector.emplace_back(ref(*casted_component));
- }
-
- // Increase the id (the id will also be stored in the returned vector<>)
- //++id;
- }
-
- // Return the vector<>
- return component_vector;
-}
-
-} // namespace crepe
diff --git a/src/crepe/GameObject.cpp b/src/crepe/GameObject.cpp
deleted file mode 100644
index de3beb6..0000000
--- a/src/crepe/GameObject.cpp
+++ /dev/null
@@ -1,7 +0,0 @@
-#include "GameObject.h"
-
-using namespace crepe;
-
-GameObject::GameObject(uint32_t id, std::string name, std::string tag,
- int layer)
- : id(id), name(name), tag(tag), active(true), layer(layer) {}
diff --git a/src/crepe/GameObject.h b/src/crepe/GameObject.h
deleted file mode 100644
index 3588d9a..0000000
--- a/src/crepe/GameObject.h
+++ /dev/null
@@ -1,24 +0,0 @@
-#pragma once
-
-#include <cstdint>
-#include <string>
-
-namespace crepe {
-
-class GameObject {
-public:
- GameObject(uint32_t id, std::string name, std::string tag, int layer);
-
- template <typename T, typename... Args>
- void add_component(Args &&... args);
-
- uint32_t id;
- std::string name;
- std::string tag;
- bool active;
- int layer;
-};
-
-} // namespace crepe
-
-#include "GameObject.hpp"
diff --git a/src/crepe/GameObject.hpp b/src/crepe/GameObject.hpp
deleted file mode 100644
index 5966fbf..0000000
--- a/src/crepe/GameObject.hpp
+++ /dev/null
@@ -1,15 +0,0 @@
-#pragma once
-
-#include "GameObject.h"
-
-#include "ComponentManager.h"
-
-namespace crepe {
-
-template <typename T, typename... Args>
-void GameObject::add_component(Args &&... args) {
- auto & mgr = ComponentManager::get_instance();
- mgr.add_component<T>(id, std::forward<Args>(args)...);
-}
-
-} // namespace crepe
diff --git a/src/crepe/Particle.cpp b/src/crepe/Particle.cpp
new file mode 100644
index 0000000..b340826
--- /dev/null
+++ b/src/crepe/Particle.cpp
@@ -0,0 +1,34 @@
+#include "Particle.h"
+
+using namespace crepe;
+
+void Particle::reset(unsigned int lifespan, const vec2 & position, const vec2 & velocity,
+ float angle) {
+ // Initialize the particle state
+ this->time_in_life = 0;
+ this->lifespan = lifespan;
+ this->position = position;
+ this->velocity = velocity;
+ this->angle = angle;
+ this->active = true;
+ // Reset force accumulation
+ this->force_over_time = {0, 0};
+}
+
+void Particle::update(double dt) {
+ // Deactivate particle if it has exceeded its lifespan
+ time_in_life += dt;
+ if (time_in_life >= lifespan) {
+ this->active = false;
+ return;
+ }
+
+ // Update velocity based on accumulated force and update position
+ this->velocity += force_over_time * dt;
+ this->position += velocity * dt;
+}
+
+void Particle::stop_movement() {
+ // Reset velocity to halt movement
+ this->velocity = {0, 0};
+}
diff --git a/src/crepe/Particle.h b/src/crepe/Particle.h
new file mode 100644
index 0000000..ee0cd66
--- /dev/null
+++ b/src/crepe/Particle.h
@@ -0,0 +1,63 @@
+#pragma once
+
+#include <cstdint>
+
+#include "types.h"
+
+namespace crepe {
+
+/**
+ * \brief Represents a particle in the particle emitter.
+ *
+ * This class stores information about a single particle, including its position, velocity,
+ * lifespan, and other properties. Particles can be updated over time to simulate movement and
+ * can also be reset or stopped.
+ */
+class Particle {
+public:
+ //! Position of the particle in 2D space.
+ vec2 position;
+ //! Velocity vector indicating the speed and direction of the particle.
+ vec2 velocity;
+ //! Accumulated force affecting the particle over time.
+ vec2 force_over_time;
+ //! Total lifespan of the particle in milliseconds.
+ float lifespan;
+ //! Active state of the particle; true if it is in use, false otherwise.
+ bool active = false;
+ //! The time the particle has been alive, in milliseconds.
+ float time_in_life = 0;
+ //! The angle at which the particle is oriented or moving.
+ float angle = 0;
+
+ /**
+ * \brief Resets the particle with new properties.
+ *
+ * This method initializes the particle with a specific lifespan, position, velocity, and
+ * angle, marking it as active and resetting its life counter.
+ *
+ * \param lifespan The lifespan of the particle in amount of updates.
+ * \param position The starting position of the particle.
+ * \param velocity The initial velocity of the particle.
+ * \param angle The angle of the particle's trajectory or orientation.
+ */
+ void reset(unsigned int lifespan, const vec2 & position, const vec2 & velocity,
+ float angle);
+ /**
+ * \brief Updates the particle's state.
+ *
+ * Advances the particle's position based on its velocity and applies accumulated forces.
+ * Deactivates the particle if its lifespan has expired.
+ * \param dt The amount of fixed delta time that has passed.
+ */
+ void update(double dt);
+ /**
+ * \brief Stops the particle's movement.
+ *
+ * Sets the particle's velocity to zero, effectively halting any further
+ * movement.
+ */
+ void stop_movement();
+};
+
+} // namespace crepe
diff --git a/src/crepe/Position.h b/src/crepe/Position.h
new file mode 100644
index 0000000..f84b63d
--- /dev/null
+++ b/src/crepe/Position.h
@@ -0,0 +1,10 @@
+#pragma once
+
+namespace crepe {
+
+struct Position {
+ float x = 0.0;
+ float y = 0.0;
+};
+
+} // namespace crepe
diff --git a/src/crepe/Resource.cpp b/src/crepe/Resource.cpp
new file mode 100644
index 0000000..85913ed
--- /dev/null
+++ b/src/crepe/Resource.cpp
@@ -0,0 +1,6 @@
+#include "Resource.h"
+#include "manager/Mediator.h"
+
+using namespace crepe;
+
+Resource::Resource(const Asset & asset, Mediator & mediator) {}
diff --git a/src/crepe/Resource.h b/src/crepe/Resource.h
new file mode 100644
index 0000000..d65206b
--- /dev/null
+++ b/src/crepe/Resource.h
@@ -0,0 +1,30 @@
+#pragma once
+
+namespace crepe {
+
+class ResourceManager;
+class Asset;
+class Mediator;
+
+/**
+ * \brief Resource interface
+ *
+ * Resource is an interface class used to represent a (deserialized) game resource (e.g.
+ * textures, sounds). Resources are always created from \ref Asset "assets" by ResourceManager.
+ *
+ * The game programmer has the ability to use the ResourceManager to keep instances of concrete
+ * resources between scenes, preventing them from being reinstantiated during a scene
+ * transition.
+ */
+class Resource {
+public:
+ Resource(const Asset & src, Mediator & mediator);
+ virtual ~Resource() = default;
+
+ Resource(const Resource &) = delete;
+ Resource(Resource &&) = delete;
+ Resource & operator=(const Resource &) = delete;
+ Resource & operator=(Resource &&) = delete;
+};
+
+} // namespace crepe
diff --git a/src/crepe/Rigidbody.cpp b/src/crepe/Rigidbody.cpp
deleted file mode 100644
index 495d908..0000000
--- a/src/crepe/Rigidbody.cpp
+++ /dev/null
@@ -1,6 +0,0 @@
-#include "Rigidbody.h"
-
-using namespace crepe;
-
-Rigidbody::Rigidbody(int mass, int gravityScale, int bodyType)
- : mass(mass), gravity_scale(gravityScale), body_type(bodyType) {}
diff --git a/src/crepe/Rigidbody.h b/src/crepe/Rigidbody.h
deleted file mode 100644
index 63a8877..0000000
--- a/src/crepe/Rigidbody.h
+++ /dev/null
@@ -1,16 +0,0 @@
-#pragma once
-
-#include "Component.h"
-
-namespace crepe {
-
-class Rigidbody : public Component {
-public:
- Rigidbody(int mass, int gravityScale, int bodyType);
-
- int mass;
- int gravity_scale;
- int body_type;
-};
-
-} // namespace crepe
diff --git a/src/crepe/Script.cpp b/src/crepe/Script.cpp
deleted file mode 100644
index 42e3666..0000000
--- a/src/crepe/Script.cpp
+++ /dev/null
@@ -1,7 +0,0 @@
-#include "Script.h"
-
-using namespace crepe;
-
-void Script::init() { }
-void Script::update() { }
-
diff --git a/src/crepe/Script.h b/src/crepe/Script.h
deleted file mode 100644
index ba4073a..0000000
--- a/src/crepe/Script.h
+++ /dev/null
@@ -1,16 +0,0 @@
-#pragma once
-
-namespace crepe {
-
-class Script {
-protected:
- virtual void init();
- virtual void update();
- // NOTE: additional *events* (like unity's OnDisable and OnEnable) should be
- // implemented as member methods in derivative user script classes and
- // registered in init(), otherwise this class will balloon in size with each
- // added event.
-};
-
-}
-
diff --git a/src/crepe/ScriptSystem.cpp b/src/crepe/ScriptSystem.cpp
deleted file mode 100644
index e301c71..0000000
--- a/src/crepe/ScriptSystem.cpp
+++ /dev/null
@@ -1,22 +0,0 @@
-#include "util/log.h"
-
-#include "ScriptSystem.h"
-
-using namespace crepe;
-
-ScriptSystem::ScriptSystem() {
- dbg_trace();
-}
-ScriptSystem::~ScriptSystem() {
- dbg_trace();
-}
-
-ScriptSystem & ScriptSystem::get_instance() {
- static ScriptSystem instance;
- return instance;
-}
-
-void ScriptSystem::update() {
- dbg_trace();
-}
-
diff --git a/src/crepe/ScriptSystem.h b/src/crepe/ScriptSystem.h
deleted file mode 100644
index e1ed290..0000000
--- a/src/crepe/ScriptSystem.h
+++ /dev/null
@@ -1,18 +0,0 @@
-#pragma once
-
-#include "System.h"
-
-namespace crepe {
-
-class ScriptSystem : public System {
-public:
- static ScriptSystem & get_instance();
- virtual void update();
-
-private:
- ScriptSystem();
- ~ScriptSystem();
-};
-
-}
-
diff --git a/src/crepe/Sound.cpp b/src/crepe/Sound.cpp
deleted file mode 100644
index 64fa281..0000000
--- a/src/crepe/Sound.cpp
+++ /dev/null
@@ -1,60 +0,0 @@
-#include "util/log.h"
-
-#include "Sound.h"
-#include "SoundContext.h"
-
-using namespace crepe;
-
-Sound::Sound(std::unique_ptr<Asset> res) {
- dbg_trace();
- this->load(std::move(res));
-}
-
-Sound::Sound(const char * src) {
- dbg_trace();
- this->load(std::make_unique<Asset>(src));
-}
-
-void Sound::load(std::unique_ptr<Asset> res) {
- this->sample.load(res->canonical());
-}
-
-void Sound::play() {
- SoundContext & ctx = SoundContext::get_instance();
- if (ctx.engine.getPause(this->handle)) {
- // resume if paused
- ctx.engine.setPause(this->handle, false);
- } else {
- // or start new sound
- this->handle = ctx.engine.play(this->sample, this->volume);
- ctx.engine.setLooping(this->handle, this->looping);
- }
-}
-
-void Sound::pause() {
- SoundContext & ctx = SoundContext::get_instance();
- if (ctx.engine.getPause(this->handle)) return;
- ctx.engine.setPause(this->handle, true);
-}
-
-void Sound::rewind() {
- SoundContext & ctx = SoundContext::get_instance();
- if (!ctx.engine.isValidVoiceHandle(this->handle)) return;
- ctx.engine.seek(this->handle, 0);
-}
-
-void Sound::set_volume(float volume) {
- this->volume = volume;
-
- SoundContext & ctx = SoundContext::get_instance();
- if (!ctx.engine.isValidVoiceHandle(this->handle)) return;
- ctx.engine.setVolume(this->handle, this->volume);
-}
-
-void Sound::set_looping(bool looping) {
- this->looping = looping;
-
- SoundContext & ctx = SoundContext::get_instance();
- if (!ctx.engine.isValidVoiceHandle(this->handle)) return;
- ctx.engine.setLooping(this->handle, this->looping);
-}
diff --git a/src/crepe/Sound.h b/src/crepe/Sound.h
deleted file mode 100644
index b7cfbb8..0000000
--- a/src/crepe/Sound.h
+++ /dev/null
@@ -1,82 +0,0 @@
-#pragma once
-
-#include <soloud/soloud.h>
-#include <soloud/soloud_wav.h>
-
-#include <memory>
-
-#include "Asset.h"
-
-namespace crepe {
-
-class Sound {
-public:
- /**
- * \brief Pause this sample
- *
- * Pauses this sound if it is playing, or does nothing if it is already
- * paused. The playhead position is saved, such that calling \c play() after
- * this function makes the sound resume.
- */
- void pause();
- /**
- * \brief Play this sample
- *
- * Resume playback if this sound is paused, or start from the beginning of
- * the sample.
- *
- * \note This class only saves a reference to the most recent 'voice' of this
- * sound. Calling \c play() while the sound is already playing causes
- * multiple instances of the sample to play simultaniously. The sample
- * started last is the one that is controlled afterwards.
- */
- void play();
- /**
- * \brief Reset playhead position
- *
- * Resets the playhead position so that calling \c play() after this function
- * makes it play from the start of the sample. If the sound is not paused
- * before calling this function, this function will stop playback.
- */
- void rewind();
- /**
- * \brief Set playback volume / gain
- *
- * \param volume Volume (0 = muted, 1 = full volume)
- */
- void set_volume(float volume);
- /**
- * \brief Get playback volume / gain
- *
- * \return Volume
- */
- float get_volume() const { return this->volume; }
- /**
- * \brief Set looping behavior for this sample
- *
- * \param looping Looping behavior (false = one-shot, true = loop)
- */
- void set_looping(bool looping);
- /**
- * \brief Get looping behavior
- *
- * \return true if looping, false if one-shot
- */
- bool get_looping() const { return this->looping; }
-
-public:
- Sound(const char * src);
- Sound(std::unique_ptr<Asset> res);
-
-private:
- void load(std::unique_ptr<Asset> res);
-
-private:
- SoLoud::Wav sample;
- SoLoud::handle handle;
-
- float volume = 1.0f;
- bool looping = false;
-};
-
-} // namespace crepe
diff --git a/src/crepe/SoundContext.cpp b/src/crepe/SoundContext.cpp
deleted file mode 100644
index 72047d2..0000000
--- a/src/crepe/SoundContext.cpp
+++ /dev/null
@@ -1,20 +0,0 @@
-#include "util/log.h"
-
-#include "SoundContext.h"
-
-using namespace crepe;
-
-SoundContext & SoundContext::get_instance() {
- static SoundContext instance;
- return instance;
-}
-
-SoundContext::SoundContext() {
- dbg_trace();
- engine.init();
-}
-
-SoundContext::~SoundContext() {
- dbg_trace();
- engine.deinit();
-}
diff --git a/src/crepe/SoundContext.h b/src/crepe/SoundContext.h
deleted file mode 100644
index d3123d2..0000000
--- a/src/crepe/SoundContext.h
+++ /dev/null
@@ -1,26 +0,0 @@
-#pragma once
-
-#include <soloud/soloud.h>
-
-#include "Sound.h"
-
-namespace crepe {
-
-class SoundContext {
-private:
- SoundContext();
- virtual ~SoundContext();
-
- // singleton
- static SoundContext & get_instance();
- SoundContext(const SoundContext &) = delete;
- SoundContext(SoundContext &&) = delete;
- SoundContext & operator=(const SoundContext &) = delete;
- SoundContext & operator=(SoundContext &&) = delete;
-
-private:
- SoLoud::Soloud engine;
- friend class Sound;
-};
-
-} // namespace crepe
diff --git a/src/crepe/Sprite.cpp b/src/crepe/Sprite.cpp
deleted file mode 100644
index a5a5e68..0000000
--- a/src/crepe/Sprite.cpp
+++ /dev/null
@@ -1,8 +0,0 @@
-#include <string>
-
-#include "Sprite.h"
-
-using namespace crepe;
-using namespace std;
-
-Sprite::Sprite(string path) : path(path) {}
diff --git a/src/crepe/Sprite.h b/src/crepe/Sprite.h
deleted file mode 100644
index 143e702..0000000
--- a/src/crepe/Sprite.h
+++ /dev/null
@@ -1,16 +0,0 @@
-#pragma once
-
-#include <string>
-
-#include "Component.h"
-
-namespace crepe {
-
-class Sprite : public Component {
-public:
- Sprite(std::string path);
-
- std::string path;
-};
-
-} // namespace crepe
diff --git a/src/crepe/System.h b/src/crepe/System.h
deleted file mode 100644
index 3fe3d66..0000000
--- a/src/crepe/System.h
+++ /dev/null
@@ -1,23 +0,0 @@
-#pragma once
-
-namespace crepe {
-
-class System {
-public:
- static System & get_instance();
- virtual void update() = 0;
-
-protected:
- System() { };
- virtual ~System() { };
-
-private:
- // singleton
- System(const System &) = delete;
- System(System &&) = delete;
- System & operator=(const System &) = delete;
- System & operator=(System &&) = delete;
-};
-
-}
-
diff --git a/src/crepe/ValueBroker.h b/src/crepe/ValueBroker.h
new file mode 100644
index 0000000..673b660
--- /dev/null
+++ b/src/crepe/ValueBroker.h
@@ -0,0 +1,41 @@
+#pragma once
+
+#include <functional>
+
+namespace crepe {
+
+/**
+ * \brief Give reference to value through custom set/get functions
+ *
+ * This class can be used to abstract direct access to any arbitrary value through a custom get
+ * and set function passed to its constructor. Consumers of this type may want to wrap it in a
+ * \c Proxy so it behaves like a regular variable.
+ *
+ * \tparam T Type of the underlying variable
+ */
+template <typename T>
+class ValueBroker {
+public:
+ //! Set the value
+ virtual void set(const T &);
+ //! Retrieve the value
+ virtual const T & get();
+
+ typedef std::function<void(const T & target)> setter_t;
+ typedef std::function<const T &()> getter_t;
+
+private:
+ setter_t setter;
+ getter_t getter;
+
+public:
+ /**
+ * \param setter Function that sets the variable
+ * \param getter Function that retrieves the variable
+ */
+ ValueBroker(const setter_t & setter, const getter_t & getter);
+};
+
+} // namespace crepe
+
+#include "ValueBroker.hpp"
diff --git a/src/crepe/ValueBroker.hpp b/src/crepe/ValueBroker.hpp
new file mode 100644
index 0000000..5c3bed9
--- /dev/null
+++ b/src/crepe/ValueBroker.hpp
@@ -0,0 +1,22 @@
+#pragma once
+
+#include "ValueBroker.h"
+
+namespace crepe {
+
+template <typename T>
+ValueBroker<T>::ValueBroker(const setter_t & setter, const getter_t & getter)
+ : setter(setter),
+ getter(getter) {}
+
+template <typename T>
+const T & ValueBroker<T>::get() {
+ return this->getter();
+}
+
+template <typename T>
+void ValueBroker<T>::set(const T & value) {
+ this->setter(value);
+}
+
+} // namespace crepe
diff --git a/src/crepe/api/AI.cpp b/src/crepe/api/AI.cpp
new file mode 100644
index 0000000..2195249
--- /dev/null
+++ b/src/crepe/api/AI.cpp
@@ -0,0 +1,89 @@
+#include <stdexcept>
+#include <type_traits>
+
+#include "AI.h"
+#include "types.h"
+
+namespace crepe {
+
+AI::AI(game_object_id_t id, float max_force) : Component(id), max_force(max_force) {}
+
+void AI::make_circle_path(float radius, const vec2 & center, float start_angle,
+ bool clockwise) {
+ if (radius <= 0) {
+ throw std::runtime_error("Radius must be greater than 0");
+ }
+
+ // The step size is determined by the radius (step size is in radians)
+ float step = RADIUS_TO_STEP / radius;
+ // Force at least MIN_STEP steps (in case of a small radius)
+ if (step > 2 * M_PI / MIN_STEP) {
+ step = 2 * M_PI / MIN_STEP;
+ }
+ // The path node distance is determined by the step size and the radius
+ this->path_node_distance = radius * step * PATH_NODE_DISTANCE_FACTOR;
+
+ if (clockwise) {
+ for (float i = start_angle; i < 2 * M_PI + start_angle; i += step) {
+ path.push_back(vec2{static_cast<float>(center.x + radius * cos(i)),
+ static_cast<float>(center.y + radius * sin(i))});
+ }
+ } else {
+ for (float i = start_angle; i > start_angle - 2 * M_PI; i -= step) {
+ path.push_back(vec2{static_cast<float>(center.x + radius * cos(i)),
+ static_cast<float>(center.y + radius * sin(i))});
+ }
+ }
+}
+
+void AI::make_oval_path(float radius_x, float radius_y, const vec2 & center, float start_angle,
+ bool clockwise, float rotation) {
+ if (radius_x <= 0 && radius_y <= 0) {
+ throw std::runtime_error("Radius must be greater than 0");
+ }
+
+ float max_radius = std::max(radius_x, radius_y);
+ // The step size is determined by the radius (step size is in radians)
+ float step = RADIUS_TO_STEP / max_radius;
+ // Force at least MIN_STEP steps (in case of a small radius)
+ if (step > 2 * M_PI / MIN_STEP) {
+ step = 2 * M_PI / MIN_STEP;
+ }
+ // The path node distance is determined by the step size and the radius
+ this->path_node_distance = max_radius * step * PATH_NODE_DISTANCE_FACTOR;
+
+ std::function<vec2(vec2, vec2)> rotate_point = [rotation](vec2 point, vec2 center) {
+ float s = sin(rotation);
+ float c = cos(rotation);
+
+ // Translate point back to origin
+ point.x -= center.x;
+ point.y -= center.y;
+
+ // Rotate point
+ float xnew = point.x * c - point.y * s;
+ float ynew = point.x * s + point.y * c;
+
+ // Translate point back
+ point.x = xnew + center.x;
+ point.y = ynew + center.y;
+
+ return point;
+ };
+
+ if (clockwise) {
+ for (float i = start_angle; i < 2 * M_PI + start_angle; i += step) {
+ vec2 point = {static_cast<float>(center.x + radius_x * cos(i)),
+ static_cast<float>(center.y + radius_y * sin(i))};
+ path.push_back(rotate_point(point, center));
+ }
+ } else {
+ for (float i = start_angle; i > start_angle - 2 * M_PI; i -= step) {
+ vec2 point = {static_cast<float>(center.x + radius_x * cos(i)),
+ static_cast<float>(center.y + radius_y * sin(i))};
+ path.push_back(rotate_point(point, center));
+ }
+ }
+}
+
+} // namespace crepe
diff --git a/src/crepe/api/AI.h b/src/crepe/api/AI.h
new file mode 100644
index 0000000..c780a91
--- /dev/null
+++ b/src/crepe/api/AI.h
@@ -0,0 +1,128 @@
+#pragma once
+
+#include "Component.h"
+#include "types.h"
+
+namespace crepe {
+
+/**
+ * \brief The AI component is used to control the movement of an entity using AI.
+ *
+ * The AI component can be used to control the movement of an entity. The AI component can be used
+ * to implement different behaviors such as seeking, fleeing, arriving, and path following.
+ */
+class AI : public Component {
+public:
+ //! The different types of behaviors that can be used
+ enum BehaviorTypeMask {
+ SEEK = 0x00002,
+ FLEE = 0x00004,
+ ARRIVE = 0x00008,
+ PATH_FOLLOW = 0x00010,
+ };
+
+public:
+ /**
+ * \param id The id of the game object
+ * \param max_force The maximum force that can be applied to the entity
+ */
+ AI(game_object_id_t id, float max_force);
+
+ /**
+ * \brief Check if a behavior is on (aka activated)
+ *
+ * \param behavior The behavior to check
+ * \return true if the behavior is on, false otherwise
+ */
+ bool on(BehaviorTypeMask behavior) const { return (flags & behavior); }
+ //! Turn on the seek behavior
+ void seek_on() { flags |= SEEK; }
+ //! Turn off the seek behavior
+ void seek_off() { flags &= ~SEEK; }
+ //! Turn on the flee behavior
+ void flee_on() { flags |= FLEE; }
+ //! Turn off the flee behavior
+ void flee_off() { flags &= ~FLEE; }
+ //! Turn on the arrive behavior
+ void arrive_on() { flags |= ARRIVE; }
+ //! Turn off the arrive behavior
+ void arrive_off() { flags &= ~ARRIVE; }
+ //! Turn on the path follow behavior
+ void path_follow_on() { flags |= PATH_FOLLOW; }
+ //! Turn off the path follow behavior
+ void path_follow_off() { flags &= ~PATH_FOLLOW; }
+
+ /**
+ * \brief Add a path node (for the path following behavior)
+ *
+ * \note The path is not relative to the entity's position (it is an absolute path)
+ *
+ * \param node The path node to add
+ */
+ void add_path_node(const vec2 & node) { path.push_back(node); }
+ /**
+ * \brief Make a circle path (for the path following behavior)
+ *
+ * \note The path is not relative to the entity's position (it is an absolute path)
+ *
+ * \param radius The radius of the circle (in game units)
+ * \param center The center of the circle (in game units)
+ * \param start_angle The start angle of the circle (in radians)
+ * \param clockwise The direction of the circle
+ */
+ void make_circle_path(float radius, const vec2 & center = {0, 0}, float start_angle = 0,
+ bool clockwise = true);
+ /**
+ * \brief Make an oval path (for the path following behavior)
+ *
+ * \note The path is not relative to the entity's position (it is an absolute path)
+ *
+ * \param radius_x The x radius of the oval (in game units)
+ * \param radius_y The y radius of the oval (in game units)
+ * \param center The center of the oval (in game units)
+ * \param start_angle The start angle of the oval (in radians)
+ * \param clockwise The direction of the oval
+ * \param rotation The rotation of the oval (in radians)
+ */
+ void make_oval_path(float radius_x, float radius_y, const vec2 & center = {0, 0},
+ float start_angle = 0, bool clockwise = true, float rotation = 0);
+
+public:
+ //! The maximum force that can be applied to the entity (higher values will make the entity adjust faster)
+ float max_force;
+
+ //! The target to seek at
+ vec2 seek_target;
+ //! The target to arrive at
+ vec2 arrive_target;
+ //! The target to flee from
+ vec2 flee_target;
+ //! The distance at which the entity will start to flee from the target
+ float square_flee_panic_distance = 200.0f * 200.0f;
+ //! The deceleration rate for the arrive behavior (higher values will make the entity decelerate faster (less overshoot))
+ float arrive_deceleration = 40.0f;
+ //! The path to follow (for the path following behavior)
+ std::vector<vec2> path;
+ //! The distance from the path node at which the entity will move to the next node (automatically set by make_circle_path())
+ float path_node_distance = 400.0f;
+ //! Looping behavior for the path
+ bool path_loop = true;
+
+private:
+ //! The flags for the behaviors
+ int flags = 0;
+ //! The current path index
+ size_t path_index = 0;
+
+ //! The AISystem is the only class that should access the flags and path_index variables
+ friend class AISystem;
+
+ //! The minimum amount of steps for the path following behavior
+ static constexpr int MIN_STEP = 16;
+ //! The radius to step size ratio for the path following behavior
+ static constexpr float RADIUS_TO_STEP = 400.0f;
+ //! The path node distance factor for the path following behavior
+ static constexpr float PATH_NODE_DISTANCE_FACTOR = 0.75f;
+};
+
+} // namespace crepe
diff --git a/src/crepe/api/Animator.cpp b/src/crepe/api/Animator.cpp
new file mode 100644
index 0000000..203cef3
--- /dev/null
+++ b/src/crepe/api/Animator.cpp
@@ -0,0 +1,57 @@
+
+#include "util/dbg.h"
+
+#include "Animator.h"
+#include "Component.h"
+#include "Sprite.h"
+
+using namespace crepe;
+
+Animator::Animator(game_object_id_t id, Sprite & spritesheet, const ivec2 & single_frame_size,
+ const uvec2 & grid_size, const Animator::Data & data)
+ : Component(id),
+ spritesheet(spritesheet),
+ grid_size(grid_size),
+ data(data) {
+ dbg_trace();
+
+ this->spritesheet.mask.w = single_frame_size.x;
+ this->spritesheet.mask.h = single_frame_size.y;
+ this->spritesheet.mask.x = 0;
+ this->spritesheet.mask.y = 0;
+
+ this->spritesheet.aspect_ratio
+ = static_cast<float>(single_frame_size.x) / single_frame_size.y;
+}
+
+Animator::~Animator() { dbg_trace(); }
+
+void Animator::loop() { this->data.looping = true; }
+
+void Animator::play() { this->active = true; }
+
+void Animator::pause() { this->active = false; }
+
+void Animator::stop() {
+ this->active = false;
+ this->data.col = 0;
+ this->data.row = 0;
+}
+void Animator::set_fps(int fps) { this->data.fps = fps; }
+
+void Animator::set_cycle_range(int start, int end) {
+ this->data.cycle_start = start, this->data.cycle_end = end;
+}
+
+void Animator::set_anim(int col) {
+ Animator::Data & ctx = this->data;
+ this->spritesheet.mask.x = ctx.row = 0;
+ ctx.col = col;
+ this->spritesheet.mask.y = ctx.col * this->spritesheet.mask.h;
+}
+
+void Animator::next_anim() {
+ Animator::Data & ctx = this->data;
+ ctx.row = ctx.row++ % this->grid_size.x;
+ this->spritesheet.mask.x = ctx.row * this->spritesheet.mask.w;
+}
diff --git a/src/crepe/api/Animator.h b/src/crepe/api/Animator.h
new file mode 100644
index 0000000..5918800
--- /dev/null
+++ b/src/crepe/api/Animator.h
@@ -0,0 +1,104 @@
+#pragma once
+
+#include "../types.h"
+
+#include "Component.h"
+#include "Sprite.h"
+
+namespace crepe {
+
+class AnimatorSystem;
+class SDLContext;
+
+/**
+ * \brief The Animator component is used to animate sprites by managing the movement and frame
+ * changes within a sprite sheet.
+ *
+ * This component allows for controlling sprite animation through rows and columns of a sprite
+ * sheet. It can be used to play animations, loop them, or stop them.
+ */
+class Animator : public Component {
+public:
+ struct Data {
+ //! frames per second for animation
+ unsigned int fps = 1;
+ //! The current col being animated.
+ unsigned int col = 0;
+ //! The current row being animated.
+ unsigned int row = 0;
+ //! should the animation loop
+ bool looping = false;
+ //! starting frame for cycling
+ unsigned int cycle_start = 0;
+ //! end frame for cycling (-1 = use last frame)
+ int cycle_end = -1;
+ };
+
+public:
+ //! Animator will repeat the animation
+ void loop();
+ //! starts the animation
+ void play();
+ //! pauses the animation
+ void pause();
+ /**
+ * \brief stops the animation
+ *
+ * sets the active on false and resets all the current rows and columns
+ */
+ void stop();
+ /**
+ * \brief set frames per second
+ *
+ * \param fps frames per second
+ */
+ void set_fps(int fps);
+ /**
+ * \brief set the range in the row
+ *
+ * \param start of row animation
+ * \param end of row animation
+ */
+ void set_cycle_range(int start, int end);
+ /**
+ * \brief select which column to animate from
+ *
+ * \param col animation column
+ */
+ void set_anim(int col);
+ //! will go to the next animaiton of current row
+ void next_anim();
+
+public:
+ /**
+ * \brief Constructs an Animator object that will control animations for a sprite sheet.
+ *
+ * \param id The unique identifier for the component, typically assigned automatically.
+ * \param spritesheet the reference to the spritesheet
+ * \param single_frame_size the width and height in pixels of a single frame inside the
+ * spritesheet
+ * \param grid_size the max rows and columns inside the given spritesheet
+ * \param data extra animation data for more control
+ *
+ * This constructor sets up the Animator with the given parameters, and initializes the
+ * animation system.
+ */
+ Animator(game_object_id_t id, Sprite & spritesheet, const ivec2 & single_frame_size,
+ const uvec2 & grid_size, const Animator::Data & data);
+ ~Animator(); // dbg_trace
+
+public:
+ Animator::Data data;
+
+private:
+ //! A reference to the Sprite sheet containing.
+ Sprite & spritesheet;
+
+ //! The maximum number of rows and columns inside the spritesheet
+ const uvec2 grid_size;
+
+ //! Uses the spritesheet
+ friend AnimatorSystem;
+};
+
+} // namespace crepe
diff --git a/src/crepe/api/Asset.cpp b/src/crepe/api/Asset.cpp
new file mode 100644
index 0000000..e148367
--- /dev/null
+++ b/src/crepe/api/Asset.cpp
@@ -0,0 +1,54 @@
+#include <filesystem>
+#include <stdexcept>
+#include <whereami.h>
+
+#include "api/Config.h"
+
+#include "Asset.h"
+
+using namespace crepe;
+using namespace std;
+
+Asset::Asset(const string & src) : src(find_asset(src)) {}
+Asset::Asset(const char * src) : src(find_asset(src)) {}
+
+const string & Asset::get_path() const noexcept { return this->src; }
+
+string Asset::find_asset(const string & src) const {
+ auto & cfg = Config::get_instance();
+ string & root_pattern = cfg.asset.root_pattern;
+
+ // if root_pattern is empty, find_asset must return all paths as-is
+ if (root_pattern.empty()) return src;
+
+ // absolute paths do not need to be resolved, only canonicalized
+ filesystem::path path = src;
+ if (path.is_absolute()) return filesystem::canonical(path);
+
+ // find directory matching root_pattern
+ filesystem::path root = this->whereami();
+ while (1) {
+ if (filesystem::exists(root / root_pattern)) break;
+ if (!root.has_parent_path())
+ throw runtime_error(format("Asset: Cannot find root pattern ({})", root_pattern));
+ root = root.parent_path();
+ }
+
+ // join path to root (base directory) and canonicalize
+ return filesystem::canonical(root / path);
+}
+
+string Asset::whereami() const noexcept {
+ string path;
+ size_t path_length = wai_getExecutablePath(NULL, 0, NULL);
+ path.resize(path_length + 1); // wai writes null byte
+ wai_getExecutablePath(path.data(), path_length, NULL);
+ path.resize(path_length);
+ return path;
+}
+
+bool Asset::operator==(const Asset & other) const noexcept { return this->src == other.src; }
+
+size_t std::hash<const Asset>::operator()(const Asset & asset) const noexcept {
+ return std::hash<string>{}(asset.get_path());
+};
diff --git a/src/crepe/api/Asset.h b/src/crepe/api/Asset.h
new file mode 100644
index 0000000..bfd0ac7
--- /dev/null
+++ b/src/crepe/api/Asset.h
@@ -0,0 +1,84 @@
+#pragma once
+
+#include <string>
+
+namespace crepe {
+
+/**
+ * \brief Asset location helper
+ *
+ * This class is used to locate game asset files, and should *always* be used
+ * instead of reading file paths directly.
+ */
+class Asset {
+public:
+ /**
+ * \param src Unique identifier to asset
+ */
+ Asset(const std::string & src);
+ /**
+ * \param src Unique identifier to asset
+ */
+ Asset(const char * src);
+
+public:
+ /**
+ * \brief Get the path to this asset
+ * \return path to this asset
+ */
+ const std::string & get_path() const noexcept;
+
+ /**
+ * \brief Comparison operator
+ * \param other Possibly different instance of \c Asset to test equality against
+ * \return True if \c this and \c other are equal
+ */
+ bool operator==(const Asset & other) const noexcept;
+
+private:
+ //! path to asset
+ const std::string src;
+
+private:
+ /**
+ * \brief Locate asset path, or throw exception if it cannot be found
+ *
+ * This function resolves asset locations relative to crepe::Config::root_pattern if it is
+ * set and \p src is a relative path. If \p src is an absolute path, it is canonicalized.
+ * This function only returns if the file can be found.
+ *
+ * \param src Arbitrary path to resource file
+ *
+ * \returns \p src if crepe::Config::root_pattern is empty
+ * \returns Canonical path to \p src
+ *
+ * \throws std::runtime_error if root_pattern cannot be found
+ * \throws std::filesystem::filesystem_error if the resolved path does not exist
+ * \throws std::filesystem::filesystem_error if the path cannot be canonicalized
+ */
+ std::string find_asset(const std::string & src) const;
+ /**
+ * \returns The path to the current executable
+ */
+ std::string whereami() const noexcept;
+};
+
+} // namespace crepe
+
+namespace std {
+
+//! Hash helper struct
+template <>
+struct hash<const crepe::Asset> {
+ /**
+ * \brief Hash operator for crepe::Asset
+ *
+ * This function hashes a crepe::Asset instance, allowing it to be used as a key in an \c
+ * std::unordered_map.
+ *
+ * \returns Hash value
+ */
+ size_t operator()(const crepe::Asset & asset) const noexcept;
+};
+
+} // namespace std
diff --git a/src/crepe/api/AudioSource.cpp b/src/crepe/api/AudioSource.cpp
index b512d27..7b05cb1 100644
--- a/src/crepe/api/AudioSource.cpp
+++ b/src/crepe/api/AudioSource.cpp
@@ -1,22 +1,15 @@
#include "AudioSource.h"
-#include "../Sound.h"
-#include <memory>
+using namespace crepe;
+using namespace std;
-using namespace crepe::api;
-
-AudioSource::AudioSource(std::unique_ptr<Asset> audio_clip) {
- this->sound = std::make_unique<crepe::Sound>(std::move(audio_clip));
-}
-
-void AudioSource::play() { return this->play(false); }
+AudioSource::AudioSource(game_object_id_t id, const Asset & src)
+ : Component(id),
+ source(src) {}
void AudioSource::play(bool looping) {
- this->sound->set_looping(looping);
- this->sound->play();
+ this->loop = looping;
+ this->oneshot_play = true;
}
-void AudioSource::stop() {
- this->sound->pause();
- this->sound->rewind();
-}
+void AudioSource::stop() { this->oneshot_stop = true; }
diff --git a/src/crepe/api/AudioSource.h b/src/crepe/api/AudioSource.h
index 2d26cda..b20e490 100644
--- a/src/crepe/api/AudioSource.h
+++ b/src/crepe/api/AudioSource.h
@@ -1,41 +1,74 @@
#pragma once
-#include <memory>
+#include "../Component.h"
+#include "../facade/SoundHandle.h"
+#include "../types.h"
#include "Asset.h"
-#include "Component.h"
+#include "GameObject.h"
namespace crepe {
-class Sound;
-}
-namespace crepe::api {
+class AudioSystem;
//! Audio source component
-class AudioSource : Component {
+class AudioSource : public Component {
+ //! AudioSource components are handled by AudioSystem
+ friend class AudioSystem;
+
+protected:
+ /**
+ * \param source Sound sample to load
+ */
+ AudioSource(game_object_id_t id, const Asset & source);
+ //! Only ComponentManager creates components
+ friend class ComponentManager;
+
public:
- AudioSource(std::unique_ptr<Asset> audio_clip);
+ // std::unique_ptr needs to be able to destoy this component
virtual ~AudioSource() = default;
public:
- //! Start or resume this audio source
- void play();
- void play(bool looping);
+ //! Start this audio source
+ void play(bool looping = false);
//! Stop this audio source
void stop();
public:
- //! Sample file location
- std::unique_ptr<Asset> audio_clip;
- //! TODO: ?????
- bool play_on_awake;
+ //! Play when this component becomes active
+ bool play_on_awake = false;
//! Repeat the current audio clip during playback
- bool loop;
+ bool loop = false;
//! Normalized volume (0.0 - 1.0)
- float volume;
+ float volume = 1.0;
private:
- std::unique_ptr<crepe::Sound> sound;
+ //! This audio source's clip
+ const Asset source;
+
+ /**
+ * \name One-shot state variables
+ *
+ * These variables trigger function calls when set to true, and are unconditionally reset on
+ * every system update.
+ *
+ * \{
+ */
+ //! Play this sample
+ bool oneshot_play = false;
+ //! Stop this sample
+ bool oneshot_stop = false;
+ //! \}
+ /**
+ * \name State diffing variables
+ * \{
+ */
+ typeof(active) last_active = false;
+ typeof(volume) last_volume = volume;
+ typeof(loop) last_loop = loop;
+ //! \}
+ //! This source's voice handle
+ SoundHandle voice{};
};
-} // namespace crepe::api
+} // namespace crepe
diff --git a/src/crepe/api/BehaviorScript.cpp b/src/crepe/api/BehaviorScript.cpp
index 2dd933e..af7572c 100644
--- a/src/crepe/api/BehaviorScript.cpp
+++ b/src/crepe/api/BehaviorScript.cpp
@@ -1,10 +1,15 @@
-#include "../util/log.h"
-
#include "BehaviorScript.h"
+#include "Component.h"
+#include "GameObject.h"
-using namespace crepe::api;
+using namespace crepe;
-BehaviorScript::BehaviorScript() {
- dbg_trace();
-}
+BehaviorScript::BehaviorScript(game_object_id_t id, Mediator & mediator)
+ : Component(id),
+ mediator(mediator) {}
+template <>
+BehaviorScript & GameObject::add_component<BehaviorScript>() {
+ ComponentManager & mgr = this->mediator.component_manager;
+ return mgr.add_component<BehaviorScript>(this->id, this->mediator);
+}
diff --git a/src/crepe/api/BehaviorScript.h b/src/crepe/api/BehaviorScript.h
index ba60a8c..3909b96 100644
--- a/src/crepe/api/BehaviorScript.h
+++ b/src/crepe/api/BehaviorScript.h
@@ -1,20 +1,74 @@
#pragma once
-#include "../Script.h"
+#include <memory>
+
#include "../Component.h"
-namespace crepe::api {
+#include "GameObject.h"
+
+namespace crepe {
-class BehaviorScript : public Script, public Component {
+class ScriptSystem;
+class ComponentManager;
+class Script;
+
+/**
+ * \brief Script component
+ *
+ * This class acts as a (component) wrapper around an instance of (a class derivatived from) \c
+ * Script. \c BehaviorScript is the only ECS component that stores member function
+ * implementations as data.
+ */
+class BehaviorScript : public Component {
protected:
- // only allow ComponentManager to instantiate scripts
+ /**
+ * \param id Parent \c GameObject id
+ * \param mediator Mediator reference
+ *
+ * \note Calls to this constructor (should) always pass through \c GameObject::add_component,
+ * which has an exception for this specific component type. This was done so the user does
+ * not have to pass references used within \c Script to each \c BehaviorScript instance.
+ */
+ BehaviorScript(game_object_id_t id, Mediator & mediator);
+ //! Only ComponentManager is allowed to instantiate BehaviorScript
friend class ComponentManager;
- BehaviorScript();
+
public:
- // but allow uniqe_ptr to call the destructor (THIS IS VERY IMPORTANT)
- virtual ~BehaviorScript() = default;
+ /**
+ * \brief Set the concrete script of this component
+ *
+ * \tparam T Concrete script type (derived from \c crepe::Script)
+ * \tparam Args Arguments for concrete script constructor
+ *
+ * \param args Arguments for concrete script constructor (forwarded using perfect forwarding)
+ *
+ * \returns Reference to BehaviorScript component (`*this`)
+ */
+ template <class T, typename... Args>
+ BehaviorScript & set_script(Args &&... args);
+protected:
+ //! Script instance
+ std::unique_ptr<Script> script = nullptr;
+ //! ScriptSystem needs direct access to the script instance
+ friend class ScriptSystem;
+
+protected:
+ //! Reference mediator
+ Mediator & mediator;
};
-}
+/**
+ * \brief Add a BehaviorScript component to this game object
+ *
+ * The \c BehaviorScript class is the only exception to the ECS harmony, and requires a
+ * reference to the component manager passed to its constructor in order to function normally.
+ * This is because the \c BehaviorScript (and \c Script) classes are the only component-related
+ * classes that store implemented member functions as data.
+ */
+template <>
+BehaviorScript & GameObject::add_component<BehaviorScript>();
+
+} // namespace crepe
+#include "BehaviorScript.hpp"
diff --git a/src/crepe/api/BehaviorScript.hpp b/src/crepe/api/BehaviorScript.hpp
new file mode 100644
index 0000000..353d5e2
--- /dev/null
+++ b/src/crepe/api/BehaviorScript.hpp
@@ -0,0 +1,22 @@
+#pragma once
+
+#include <type_traits>
+
+#include "BehaviorScript.h"
+#include "Script.h"
+
+namespace crepe {
+
+template <class T, typename... Args>
+BehaviorScript & BehaviorScript::set_script(Args &&... args) {
+ static_assert(std::is_base_of<Script, T>::value);
+ this->script = std::unique_ptr<Script>(new T(std::forward<Args>(args)...));
+
+ this->script->game_object_id = this->game_object_id;
+ this->script->active = this->active;
+ this->script->mediator = this->mediator;
+
+ return *this;
+}
+
+} // namespace crepe
diff --git a/src/crepe/api/BoxCollider.cpp b/src/crepe/api/BoxCollider.cpp
new file mode 100644
index 0000000..a893d41
--- /dev/null
+++ b/src/crepe/api/BoxCollider.cpp
@@ -0,0 +1,10 @@
+#include "BoxCollider.h"
+
+#include "../Collider.h"
+
+using namespace crepe;
+
+BoxCollider::BoxCollider(game_object_id_t game_object_id, const vec2 & dimensions,
+ const vec2 & offset)
+ : Collider(game_object_id, offset),
+ dimensions(dimensions) {}
diff --git a/src/crepe/api/BoxCollider.h b/src/crepe/api/BoxCollider.h
new file mode 100644
index 0000000..d643e7f
--- /dev/null
+++ b/src/crepe/api/BoxCollider.h
@@ -0,0 +1,23 @@
+#pragma once
+
+#include "../Collider.h"
+#include "Vector2.h"
+#include "types.h"
+
+namespace crepe {
+
+/**
+ * \brief A class representing a box-shaped collider.
+ *
+ * This class is used for collision detection with other colliders (e.g., CircleCollider).
+ */
+class BoxCollider : public Collider {
+public:
+ BoxCollider(game_object_id_t game_object_id, const vec2 & dimensions,
+ const vec2 & offset = {0, 0});
+
+ //! Width and height of the box collider
+ vec2 dimensions;
+};
+
+} // namespace crepe
diff --git a/src/crepe/api/Button.cpp b/src/crepe/api/Button.cpp
new file mode 100644
index 0000000..40153c9
--- /dev/null
+++ b/src/crepe/api/Button.cpp
@@ -0,0 +1,8 @@
+#include "Button.h"
+
+namespace crepe {
+
+Button::Button(game_object_id_t id, const vec2 & dimensions, const vec2 & offset)
+ : UIObject(id, dimensions, offset) {}
+
+} // namespace crepe
diff --git a/src/crepe/api/Button.h b/src/crepe/api/Button.h
new file mode 100644
index 0000000..d42527e
--- /dev/null
+++ b/src/crepe/api/Button.h
@@ -0,0 +1,48 @@
+#pragma once
+
+#include <functional>
+
+#include "Event.h"
+#include "UIObject.h"
+
+namespace crepe {
+
+/**
+ * \brief Button component.
+ *
+ * This component creates a clickable surface at the transform location with the specified width and height.
+ *
+ * The Button can be used in scripts by subscribing a EventHandler to the following events:
+ * - ButtonPressEvent
+ * - ButtonEnterEvent
+ * - ButtonExitEvent
+ * \see EventManager
+ *
+ */
+class Button : public UIObject {
+public:
+ /**
+ * \brief Constructs a Button with the specified game object ID and dimensions.
+ *
+ * \param id The unique ID of the game object associated with this button.
+ * \param dimensions The width and height of the UIObject
+ * \param offset The offset relative this GameObjects Transform
+ */
+ Button(game_object_id_t id, const vec2 & dimensions, const vec2 & offset);
+ /**
+ * \brief Get the maximum number of instances for this component
+ *
+ * Since the button Event transfers the GameObject Metadata it will be the same for each button so only one button is allowed per GameObject
+ *
+ * \return 1
+ */
+ virtual int get_instances_max() const { return 1; }
+
+private:
+ //! friend relation hover variable
+ friend class InputSystem;
+ //! Indicates whether the mouse is currently hovering over the button
+ bool hover = false;
+};
+
+} // namespace crepe
diff --git a/src/crepe/api/CMakeLists.txt b/src/crepe/api/CMakeLists.txt
index 86623de..2bee3fb 100644
--- a/src/crepe/api/CMakeLists.txt
+++ b/src/crepe/api/CMakeLists.txt
@@ -1,10 +1,57 @@
target_sources(crepe PUBLIC
- # AudioSource.cpp
+ AudioSource.cpp
BehaviorScript.cpp
+ GameObject.cpp
+ Rigidbody.cpp
+ ParticleEmitter.cpp
+ Transform.cpp
+ Color.cpp
+ Sprite.cpp
+ Config.cpp
+ Metadata.cpp
+ Camera.cpp
+ Animator.cpp
+ BoxCollider.cpp
+ CircleCollider.cpp
+ Engine.cpp
+ Asset.cpp
+ EventHandler.cpp
+ Script.cpp
+ Button.cpp
+ UIObject.cpp
+ AI.cpp
+ Text.cpp
+ Scene.cpp
)
target_sources(crepe PUBLIC FILE_SET HEADERS FILES
- # AudioSource.h
+ AudioSource.h
BehaviorScript.h
+ Config.h
+ Script.h
+ Script.hpp
+ GameObject.h
+ GameObject.hpp
+ Rigidbody.h
+ Sprite.h
+ Vector2.h
+ Vector2.hpp
+ Color.h
+ Scene.h
+ Scene.hpp
+ Metadata.h
+ Camera.h
+ Animator.h
+ BoxCollider.h
+ CircleCollider.h
+ EventHandler.h
+ EventHandler.hpp
+ Event.h
+ Engine.h
+ Engine.hpp
+ Asset.h
+ Button.h
+ UIObject.h
+ AI.h
+ Text.h
)
-
diff --git a/src/crepe/api/Camera.cpp b/src/crepe/api/Camera.cpp
new file mode 100644
index 0000000..19a3296
--- /dev/null
+++ b/src/crepe/api/Camera.cpp
@@ -0,0 +1,18 @@
+#include "util/dbg.h"
+
+#include "Camera.h"
+#include "Component.h"
+#include "types.h"
+
+using namespace crepe;
+
+Camera::Camera(game_object_id_t id, const ivec2 & screen, const vec2 & viewport_size,
+ const Data & data)
+ : Component(id),
+ screen(screen),
+ viewport_size(viewport_size),
+ data(data) {
+ dbg_trace();
+}
+
+Camera::~Camera() { dbg_trace(); }
diff --git a/src/crepe/api/Camera.h b/src/crepe/api/Camera.h
new file mode 100644
index 0000000..54d9a73
--- /dev/null
+++ b/src/crepe/api/Camera.h
@@ -0,0 +1,67 @@
+#pragma once
+
+#include "Color.h"
+#include "Component.h"
+#include "types.h"
+
+namespace crepe {
+
+/**
+ * \class Camera
+ * \brief Represents a camera component for rendering in the game.
+ *
+ * The Camera class defines the view parameters, including background color, aspect ratio,
+ * position, and zoom level. It controls what part of the game world is visible on the screen.
+ */
+class Camera : public Component {
+public:
+ struct Data {
+ /**
+ * \bg_color background color of the game
+ *
+ * This will make the background the same color as the given value.
+ */
+ const Color bg_color = Color::BLACK;
+
+ /**
+ * \zoom Zooming level of the game
+ *
+ * zoom = 1 --> no zoom.
+ * zoom < 1 --> zoom out
+ * zoom > 1 --> zoom in
+ */
+ double zoom = 1;
+
+ //! offset postion from the game object transform component
+ vec2 postion_offset;
+ };
+
+public:
+ /**
+ * \brief Constructs a Camera with the specified ID and background color.
+ * \param id Unique identifier for the camera component.
+ * \param screen is the actual screen size in pixels
+ * \param viewport_size is the view of the world in game units
+ * \param data the camera component data
+ */
+ Camera(game_object_id_t id, const ivec2 & screen, const vec2 & viewport_size,
+ const Camera::Data & data);
+ ~Camera(); // dbg_trace only
+
+public:
+ Camera::Data data;
+
+ //! screen the display size in pixels ( output resolution )
+ const ivec2 screen;
+
+ //! viewport is the area of the world visible through the camera (in world units)
+ const vec2 viewport_size;
+
+public:
+ /**
+ * \brief Gets the maximum number of camera instances allowed.
+ * \return Maximum instance count as an integer.
+ */
+ virtual int get_instances_max() const { return 1; }
+};
+} // namespace crepe
diff --git a/src/crepe/api/CircleCollider.cpp b/src/crepe/api/CircleCollider.cpp
new file mode 100644
index 0000000..90ab5e7
--- /dev/null
+++ b/src/crepe/api/CircleCollider.cpp
@@ -0,0 +1,8 @@
+#include "CircleCollider.h"
+
+using namespace crepe;
+
+CircleCollider::CircleCollider(game_object_id_t game_object_id, float radius,
+ const vec2 & offset)
+ : Collider(game_object_id, offset),
+ radius(radius) {}
diff --git a/src/crepe/api/CircleCollider.h b/src/crepe/api/CircleCollider.h
new file mode 100644
index 0000000..22da836
--- /dev/null
+++ b/src/crepe/api/CircleCollider.h
@@ -0,0 +1,23 @@
+#pragma once
+
+#include "Vector2.h"
+
+#include "../Collider.h"
+
+namespace crepe {
+
+/**
+ * \brief A class representing a circle-shaped collider.
+ *
+ * This class is used for collision detection with other colliders (e.g., BoxCollider).
+ */
+class CircleCollider : public Collider {
+public:
+ CircleCollider(game_object_id_t game_object_id, float radius,
+ const vec2 & offset = {0, 0});
+
+ //! Radius of the circle collider.
+ float radius;
+};
+
+} // namespace crepe
diff --git a/src/crepe/api/Color.cpp b/src/crepe/api/Color.cpp
new file mode 100644
index 0000000..29bd77a
--- /dev/null
+++ b/src/crepe/api/Color.cpp
@@ -0,0 +1,12 @@
+#include "Color.h"
+
+using namespace crepe;
+
+const Color Color::WHITE{0xff, 0xff, 0xff};
+const Color Color::RED{0xff, 0x00, 0x00};
+const Color Color::GREEN{0x00, 0xff, 0x00};
+const Color Color::BLUE{0x00, 0x00, 0xff};
+const Color Color::BLACK{0x00, 0x00, 0x00};
+const Color Color::CYAN{0x00, 0xff, 0xff};
+const Color Color::YELLOW{0xff, 0xff, 0x00};
+const Color Color::MAGENTA{0xff, 0x00, 0xff};
diff --git a/src/crepe/api/Color.h b/src/crepe/api/Color.h
new file mode 100644
index 0000000..84edb5c
--- /dev/null
+++ b/src/crepe/api/Color.h
@@ -0,0 +1,23 @@
+#pragma once
+
+#include <cstdint>
+
+namespace crepe {
+
+struct Color {
+ uint8_t r = 0x00;
+ uint8_t g = 0x00;
+ uint8_t b = 0x00;
+ uint8_t a = 0xff;
+
+ static const Color WHITE;
+ static const Color RED;
+ static const Color GREEN;
+ static const Color BLUE;
+ static const Color CYAN;
+ static const Color MAGENTA;
+ static const Color YELLOW;
+ static const Color BLACK;
+};
+
+} // namespace crepe
diff --git a/src/crepe/api/Config.cpp b/src/crepe/api/Config.cpp
new file mode 100644
index 0000000..0100bcc
--- /dev/null
+++ b/src/crepe/api/Config.cpp
@@ -0,0 +1,8 @@
+#include "Config.h"
+
+using namespace crepe;
+
+Config & Config::get_instance() {
+ static Config instance;
+ return instance;
+}
diff --git a/src/crepe/api/Config.h b/src/crepe/api/Config.h
new file mode 100644
index 0000000..6b9e3ca
--- /dev/null
+++ b/src/crepe/api/Config.h
@@ -0,0 +1,103 @@
+#pragma once
+
+#include <string>
+
+#include "../util/Log.h"
+
+#include "types.h"
+
+namespace crepe {
+
+/**
+ * \brief Global configuration interface
+ *
+ * This class stores engine default settings. Properties on this class are only supposed to be
+ * modified *before* execution is handed over from the game programmer to the engine (i.e. the
+ * main loop is started).
+ */
+struct Config final {
+ //! Retrieve handle to global Config instance
+ static Config & get_instance();
+
+ //! Logging-related settings
+ struct {
+ /**
+ * \brief Log level
+ *
+ * Only messages with equal or higher priority than this value will be logged.
+ */
+ Log::Level level = Log::Level::INFO;
+ /**
+ * \brief Colored log output
+ *
+ * Enables log coloring using ANSI escape codes.
+ */
+ bool color = true;
+ } log;
+
+ //! Save manager
+ struct {
+ /**
+ * \brief Save file location
+ *
+ * This location is used by the constructor of SaveManager, and should be set before save
+ * manager functionality is attempted to be used.
+ */
+ std::string location = "save.crepe.db";
+ } savemgr;
+
+ //! physics-related settings
+ struct {
+ /**
+ * \brief gravity value of physics system
+ *
+ * Gravity value of game.
+ */
+ float gravity = 10;
+ } physics;
+
+ //! default window settings
+ struct {
+ //! default screen size in pixels
+ ivec2 default_size = {1280, 720};
+ std::string window_title = "Jetpack joyride clone";
+ } window_settings;
+
+ //! Asset loading options
+ struct {
+ /**
+ * \brief Pattern to match for Asset base directory
+ *
+ * All non-absolute paths resolved using \c Asset will be made relative to
+ * the first parent directory relative to the calling executable where
+ * appending this pattern results in a path that exists. If this string is
+ * empty, path resolution is disabled, and Asset will return all paths
+ * as-is.
+ */
+ std::string root_pattern = ".crepe-root";
+ } asset;
+ //! Default font options
+ struct {
+ /**
+ * \brief Default font size
+ *
+ * Using the SDL_ttf library the font size needs to be set when loading the font.
+ * This config option is the font size at which all fonts will be loaded initially.
+ *
+ */
+ unsigned int size = 16;
+ } font;
+ //! Configuration for click tolerance.
+ struct {
+ //! The maximum number of pixels the mouse can move between MouseDown and MouseUp events to be considered a click.
+ int click_tolerance = 5;
+ } input;
+
+ //! Audio system settings
+ struct {
+ //! Max amount of simultanious voices
+ unsigned int voices = 32;
+ } audio;
+};
+
+} // namespace crepe
diff --git a/src/crepe/api/Engine.cpp b/src/crepe/api/Engine.cpp
new file mode 100644
index 0000000..2e9d35a
--- /dev/null
+++ b/src/crepe/api/Engine.cpp
@@ -0,0 +1,63 @@
+#include "../util/Log.h"
+
+#include "Engine.h"
+
+using namespace crepe;
+using namespace std;
+
+int Engine::main() noexcept {
+ try {
+ this->setup();
+ } catch (const exception & e) {
+ Log::logf(Log::Level::ERROR, "Uncaught exception in setup: {}\n", e.what());
+ return EXIT_FAILURE;
+ }
+
+ try {
+ this->loop();
+ } catch (const exception & e) {
+ Log::logf(Log::Level::ERROR, "Uncaught exception in main loop: {}\n", e.what());
+ this->event_manager.trigger_event<ShutDownEvent>();
+ }
+
+ return EXIT_SUCCESS;
+}
+
+void Engine::setup() {
+ this->loop_timer.start();
+ this->scene_manager.load_next_scene();
+
+ this->event_manager.subscribe<ShutDownEvent>([this](const ShutDownEvent & event) {
+ this->game_running = false;
+
+ // propagate to possible user ShutDownEvent listeners
+ return false;
+ });
+}
+
+void Engine::loop() {
+ LoopTimerManager & timer = this->loop_timer;
+ SystemManager & systems = this->system_manager;
+
+ while (this->game_running) {
+ timer.update();
+
+ while (timer.get_lag() >= timer.get_fixed_delta_time()) {
+ try {
+ systems.fixed_update();
+ } catch (const exception & e) {
+ Log::logf(Log::Level::WARNING,
+ "Uncaught exception in fixed update function: {}\n", e.what());
+ }
+ timer.advance_fixed_elapsed_time();
+ }
+
+ try {
+ systems.frame_update();
+ } catch (const exception & e) {
+ Log::logf(Log::Level::WARNING, "Uncaught exception in frame update function: {}\n",
+ e.what());
+ }
+ timer.enforce_frame_rate();
+ }
+}
diff --git a/src/crepe/api/Engine.h b/src/crepe/api/Engine.h
new file mode 100644
index 0000000..700a0cd
--- /dev/null
+++ b/src/crepe/api/Engine.h
@@ -0,0 +1,81 @@
+#pragma once
+
+#include "../facade/SDLContext.h"
+#include "../manager/ComponentManager.h"
+#include "../manager/EventManager.h"
+#include "../manager/LoopTimerManager.h"
+#include "../manager/ReplayManager.h"
+#include "../manager/ResourceManager.h"
+#include "../manager/SaveManager.h"
+#include "../manager/SceneManager.h"
+#include "../manager/SystemManager.h"
+
+namespace crepe {
+
+/**
+ * \brief Main game entrypoint
+ *
+ * This class is responsible for managing the game loop, including initialization and updating.
+ */
+class Engine {
+public:
+ /**
+ * \brief Engine entrypoint
+ *
+ * This function is called by the game programmer after registering all scenes
+ *
+ * \returns process exit code
+ */
+ int main() noexcept;
+
+ //! \copydoc SceneManager::add_scene
+ template <typename T>
+ void add_scene();
+
+private:
+ /**
+ * \brief Setup function for one-time initialization.
+ *
+ * This function initializes necessary components for the game.
+ */
+ void setup();
+ /**
+ * \brief Main game loop function.
+ *
+ * This function runs the main loop, handling game updates and rendering.
+ */
+ void loop();
+
+ //! Game loop condition
+ bool game_running = true;
+
+private:
+ //! Global context
+ Mediator mediator;
+
+ //! SystemManager
+ SystemManager system_manager{mediator};
+
+ //! SDLContext instance
+ SDLContext sdl_context{mediator};
+
+ //! Resource manager instance
+ ResourceManager resource_manager{mediator};
+
+ //! Component manager instance
+ ComponentManager component_manager{mediator};
+ //! Scene manager instance
+ SceneManager scene_manager{mediator};
+ //! LoopTimerManager instance
+ LoopTimerManager loop_timer{mediator};
+ //! EventManager instance
+ EventManager event_manager{mediator};
+ //! Save manager instance
+ SaveManager save_manager{mediator};
+ //! ReplayManager instance
+ ReplayManager replay_manager{mediator};
+};
+
+} // namespace crepe
+
+#include "Engine.hpp"
diff --git a/src/crepe/api/Engine.hpp b/src/crepe/api/Engine.hpp
new file mode 100644
index 0000000..f2fdc0a
--- /dev/null
+++ b/src/crepe/api/Engine.hpp
@@ -0,0 +1,12 @@
+#pragma once
+
+#include "Engine.h"
+
+namespace crepe {
+
+template <class T>
+void Engine::add_scene() {
+ this->scene_manager.add_scene<T>();
+}
+
+} // namespace crepe
diff --git a/src/crepe/api/Event.h b/src/crepe/api/Event.h
new file mode 100644
index 0000000..8e38280
--- /dev/null
+++ b/src/crepe/api/Event.h
@@ -0,0 +1,154 @@
+#pragma once
+// TODO discussing the location of these events
+
+#include <string>
+
+#include "types.h"
+
+#include "KeyCodes.h"
+
+namespace crepe {
+
+/**
+ * \brief Base class for all event types in the system.
+ */
+class Event {};
+
+/**
+ * \brief Event triggered when a key is pressed.
+ */
+class KeyPressEvent : public Event {
+public:
+ //! false if first time press, true if key is repeated
+ bool repeat = false;
+
+ //! The key that was pressed.
+ Keycode key = Keycode::NONE;
+};
+
+/**
+ * \brief Event triggered when a key is released.
+ */
+class KeyReleaseEvent : public Event {
+public:
+ //! The key that was released.
+ Keycode key = Keycode::NONE;
+};
+
+/**
+ * \brief Event triggered when a mouse button is pressed.
+ */
+class MousePressEvent : public Event {
+public:
+ //! mouse position in world coordinates (game units).
+ vec2 mouse_pos = {0, 0};
+
+ //! The mouse button that was pressed.
+ MouseButton button = MouseButton::NONE;
+};
+
+/**
+ * \brief Event triggered when a mouse button is clicked (press and release).
+ */
+class MouseClickEvent : public Event {
+public:
+ //! mouse position in world coordinates (game units).
+ vec2 mouse_pos = {0, 0};
+
+ //! The mouse button that was clicked.
+ MouseButton button = MouseButton::NONE;
+};
+
+/**
+ * \brief Event triggered when a mouse button is released.
+ */
+class MouseReleaseEvent : public Event {
+public:
+ //! mouse position in world coordinates (game units).
+ vec2 mouse_pos = {0, 0};
+
+ //! The mouse button that was released.
+ MouseButton button = MouseButton::NONE;
+};
+
+/**
+ * \brief Event triggered when the mouse is moved.
+ */
+class MouseMoveEvent : public Event {
+public:
+ //! mouse position in world coordinates (game units).
+ vec2 mouse_pos = {0, 0};
+ //! The change in mouse position relative to the last position (in pixels).
+ ivec2 mouse_delta = {0, 0};
+};
+
+/**
+ * \brief Event triggered when the mouse is moved.
+ */
+class MouseScrollEvent : public Event {
+public:
+ //! mouse position in world coordinates (game units) when the scroll happened.
+ vec2 mouse_pos = {0, 0};
+ //! scroll direction (-1 = down, 1 = up)
+ int scroll_direction = 0;
+ //! scroll amount in y axis (from and away from the person).
+ float scroll_delta = 0;
+};
+
+/**
+ * \brief Event triggered to indicate the application is shutting down.
+ */
+class ShutDownEvent : public Event {};
+
+/**
+ * \brief Event triggered to indicate the window is overlapped by another window.
+ *
+ * When two windows overlap the bottom window gets distorted and that window has to be redrawn.
+ */
+class WindowExposeEvent : public Event {};
+
+/**
+ * \brief Event triggered to indicate the window is resized.
+ */
+class WindowResizeEvent : public Event {
+public:
+ //! new window dimensions
+ ivec2 dimensions = {0, 0};
+};
+
+/**
+ * \brief Event triggered to indicate the window is moved.
+ */
+class WindowMoveEvent : public Event {
+public:
+ //! The change in position relative to the last position (in pixels).
+ ivec2 delta_move = {0, 0};
+};
+
+/**
+ * \brief Event triggered to indicate the window is minimized.
+ */
+class WindowMinimizeEvent : public Event {};
+
+/**
+ * \brief Event triggered to indicate the window is maximized
+ */
+class WindowMaximizeEvent : public Event {};
+
+/**
+ * \brief Event triggered to indicate the window gained focus
+ *
+ * This event is triggered when the window receives focus, meaning it becomes the active window
+ * for user interaction.
+ */
+class WindowFocusGainEvent : public Event {};
+
+/**
+ * \brief Event triggered to indicate the window lost focus
+ *
+ * This event is triggered when the window loses focus, meaning it is no longer the active window
+ * for user interaction.
+ */
+class WindowFocusLostEvent : public Event {};
+
+} // namespace crepe
diff --git a/src/crepe/api/EventHandler.cpp b/src/crepe/api/EventHandler.cpp
new file mode 100644
index 0000000..4dc232f
--- /dev/null
+++ b/src/crepe/api/EventHandler.cpp
@@ -0,0 +1,5 @@
+#include "EventHandler.h"
+
+using namespace crepe;
+
+bool IEventHandlerWrapper::exec(const Event & e) { return this->call(e); }
diff --git a/src/crepe/api/EventHandler.h b/src/crepe/api/EventHandler.h
new file mode 100644
index 0000000..7bb501b
--- /dev/null
+++ b/src/crepe/api/EventHandler.h
@@ -0,0 +1,96 @@
+#pragma once
+
+#include <functional>
+#include <string>
+
+#include "Event.h"
+
+namespace crepe {
+/**
+ * \brief A type alias for an event handler function.
+ *
+ * The EventHandler is a std::function that takes an EventType reference and returns a boolean value
+ * indicating whether the event is handled.
+ *
+ * \tparam EventType The type of event this handler will handle.
+ *
+ * Returning \c false from an event handler results in the event being propogated to other listeners for the same event type, while returning \c true stops propogation altogether.
+ */
+template <typename EventType>
+using EventHandler = std::function<bool(const EventType & e)>;
+
+/**
+ * \class IEventHandlerWrapper
+ * \brief An abstract base class for event handler wrappers.
+ *
+ * This class provides the interface for handling events. Derived classes must implement the
+ * `call()` method to process events
+ */
+class IEventHandlerWrapper {
+public:
+ /**
+ * \brief Virtual destructor for IEventHandlerWrapper.
+ */
+ virtual ~IEventHandlerWrapper() = default;
+
+ /**
+ * \brief Executes the handler with the given event.
+ *
+ * This method calls the `call()` method of the derived class, passing the event to the handler.
+ *
+ * \param e The event to be processed.
+ * \return A boolean value indicating whether the event is handled.
+ */
+ bool exec(const Event & e);
+
+private:
+ /**
+ * \brief The method responsible for handling the event.
+ *
+ * This method is implemented by derived classes to process the event.
+ *
+ * \param e The event to be processed.
+ * \return A boolean value indicating whether the event is handled.
+ */
+ virtual bool call(const Event & e) = 0;
+};
+
+/**
+ * \class EventHandlerWrapper
+ * \brief A wrapper for event handler functions.
+ *
+ * This class wraps an event handler function of a specific event type. It implements the
+ * `call()` and `get_type()` methods to allow the handler to be executed and its type to be
+ * queried.
+ *
+ * \tparam EventType The type of event this handler will handle.
+ */
+template <typename EventType>
+class EventHandlerWrapper : public IEventHandlerWrapper {
+public:
+ /**
+ * \brief Constructs an EventHandlerWrapper with a given handler.
+ *
+ * The constructor takes an event handler function and stores it in the wrapper.
+ *
+ * \param handler The event handler function.
+ */
+ explicit EventHandlerWrapper(const EventHandler<EventType> & handler);
+
+private:
+ /**
+ * \brief Calls the stored event handler with the event.
+ *
+ * This method casts the event to the appropriate type and calls the handler.
+ *
+ * \param e The event to be handled.
+ * \return A boolean value indicating whether the event is handled.
+ */
+ bool call(const Event & e) override;
+ //! The event handler function.
+ EventHandler<EventType> handler;
+};
+
+} // namespace crepe
+
+#include "EventHandler.hpp"
diff --git a/src/crepe/api/EventHandler.hpp b/src/crepe/api/EventHandler.hpp
new file mode 100644
index 0000000..050e57e
--- /dev/null
+++ b/src/crepe/api/EventHandler.hpp
@@ -0,0 +1,20 @@
+#pragma once
+
+#include <typeindex>
+
+#include "EventHandler.h"
+
+namespace crepe {
+
+// Implementation of EventHandlerWrapper constructor
+template <typename EventType>
+EventHandlerWrapper<EventType>::EventHandlerWrapper(const EventHandler<EventType> & handler)
+ : handler(handler) {}
+
+// Implementation of EventHandlerWrapper::call
+template <typename EventType>
+bool EventHandlerWrapper<EventType>::call(const Event & e) {
+ return this->handler(static_cast<const EventType &>(e));
+}
+
+} //namespace crepe
diff --git a/src/crepe/api/GameObject.cpp b/src/crepe/api/GameObject.cpp
new file mode 100644
index 0000000..9b94cad
--- /dev/null
+++ b/src/crepe/api/GameObject.cpp
@@ -0,0 +1,35 @@
+#include "api/Transform.h"
+
+#include "BehaviorScript.h"
+#include "GameObject.h"
+#include "Metadata.h"
+
+using namespace crepe;
+using namespace std;
+
+GameObject::GameObject(Mediator & mediator, game_object_id_t id, const std::string & name,
+ const std::string & tag, const vec2 & position, double rotation,
+ double scale)
+ : id(id),
+ mediator(mediator),
+ transform(mediator.component_manager->add_component<Transform>(this->id, position,
+ rotation, scale)),
+ metadata(mediator.component_manager->add_component<Metadata>(this->id, name, tag)) {}
+
+void GameObject::set_parent(const GameObject & parent) {
+ ComponentManager & mgr = this->mediator.component_manager;
+
+ // Set parent on own Metadata component
+ RefVector<Metadata> this_metadata = mgr.get_components_by_id<Metadata>(this->id);
+ this_metadata.at(0).get().parent = parent.id;
+
+ // Add own id to children list of parent's Metadata component
+ RefVector<Metadata> parent_metadata = mgr.get_components_by_id<Metadata>(parent.id);
+ parent_metadata.at(0).get().children.push_back(this->id);
+}
+
+void GameObject::set_persistent(bool persistent) {
+ ComponentManager & mgr = this->mediator.component_manager;
+
+ mgr.set_persistent(this->id, persistent);
+}
diff --git a/src/crepe/api/GameObject.h b/src/crepe/api/GameObject.h
new file mode 100644
index 0000000..572ce3a
--- /dev/null
+++ b/src/crepe/api/GameObject.h
@@ -0,0 +1,86 @@
+#pragma once
+
+#include <string>
+
+#include "types.h"
+
+namespace crepe {
+
+class Mediator;
+class Transform;
+class Metadata;
+
+/**
+ * \brief Represents a GameObject
+ *
+ * This class represents a GameObject. The GameObject class is only used as an interface for
+ * the game programmer. The actual implementation is done in the ComponentManager.
+ */
+class GameObject {
+private:
+ /**
+ * This constructor creates a new GameObject. It creates a new Transform and Metadata
+ * component and adds them to the ComponentManager.
+ *
+ * \param mediator Reference to mediator
+ * \param id The id of the GameObject
+ * \param name The name of the GameObject
+ * \param tag The tag of the GameObject
+ * \param position The position of the GameObject
+ * \param rotation The rotation of the GameObject
+ * \param scale The scale of the GameObject
+ */
+ GameObject(Mediator & mediator, game_object_id_t id, const std::string & name,
+ const std::string & tag, const vec2 & position, double rotation, double scale);
+ //! ComponentManager instances GameObject
+ friend class ComponentManager;
+
+public:
+ //! The id of the GameObject
+ const game_object_id_t id;
+ //! This entity's transform
+ Transform & transform;
+ //! This entity's metadata
+ Metadata & metadata;
+
+public:
+ /**
+ * \brief Set the parent of this GameObject
+ *
+ * This method sets the parent of this GameObject. It sets the parent in the Metadata
+ * component of this GameObject and adds this GameObject to the children list of the parent
+ * GameObject.
+ *
+ * \param parent The parent GameObject
+ */
+ void set_parent(const GameObject & parent);
+ /**
+ * \brief Add a component to the GameObject
+ *
+ * This method adds a component to the GameObject. It forwards the arguments to the
+ * ComponentManager.
+ *
+ * \tparam T The type of the component
+ * \tparam Args The types of the arguments
+ * \param args The arguments to create the component
+ * \return The created component
+ */
+ template <typename T, typename... Args>
+ T & add_component(Args &&... args);
+ /**
+ * \brief Components will not be deleted if this method is called
+ *
+ * This method sets the persistent flag of the GameObject to true. If the persistent
+ * flag is set to true, the GameObject will not be deleted when the scene is changed.
+ *
+ * \param persistent The persistent flag
+ */
+ void set_persistent(bool persistent = true);
+
+protected:
+ Mediator & mediator;
+};
+
+} // namespace crepe
+
+#include "GameObject.hpp"
diff --git a/src/crepe/api/GameObject.hpp b/src/crepe/api/GameObject.hpp
new file mode 100644
index 0000000..69f7d73
--- /dev/null
+++ b/src/crepe/api/GameObject.hpp
@@ -0,0 +1,15 @@
+#pragma once
+
+#include "../manager/ComponentManager.h"
+
+#include "GameObject.h"
+
+namespace crepe {
+
+template <typename T, typename... Args>
+T & GameObject::add_component(Args &&... args) {
+ ComponentManager & mgr = this->mediator.component_manager;
+ return mgr.add_component<T>(this->id, std::forward<Args>(args)...);
+}
+
+} // namespace crepe
diff --git a/src/crepe/api/KeyCodes.h b/src/crepe/api/KeyCodes.h
new file mode 100644
index 0000000..1b9573a
--- /dev/null
+++ b/src/crepe/api/KeyCodes.h
@@ -0,0 +1,160 @@
+#pragma once
+
+#include <unordered_map>
+
+namespace crepe {
+
+//! Enumeration for mouse button inputs, including standard and extended buttons.
+enum class MouseButton {
+ NONE = 0, //!< No mouse button input.
+ LEFT_MOUSE = 1, //!< Left mouse button.
+ RIGHT_MOUSE = 2, //!< Right mouse button.
+ MIDDLE_MOUSE = 3, //!< Middle mouse button (scroll wheel press).
+ X1_MOUSE = 4, //!< First extended mouse button.
+ X2_MOUSE = 5, //!< Second extended mouse button.
+ SCROLL_UP = 6, //!< Scroll wheel upward movement.
+ SCROLL_DOWN = 7, //!< Scroll wheel downward movement.
+};
+
+//! Enumeration for keyboard key inputs, including printable characters, function keys, and keypad keys.
+enum class Keycode {
+ NONE = 0, //!< No key input.
+ SPACE = 32, //!< Spacebar.
+ APOSTROPHE = 39, //!< Apostrophe (').
+ COMMA = 44, //!< Comma (,).
+ MINUS = 45, //!< Minus (-).
+ PERIOD = 46, //!< Period (.).
+ SLASH = 47, //!< Slash (/).
+ D0 = 48, //!< Digit 0.
+ D1 = 49, //!< Digit 1.
+ D2 = 50, //!< Digit 2.
+ D3 = 51, //!< Digit 3.
+ D4 = 52, //!< Digit 4.
+ D5 = 53, //!< Digit 5.
+ D6 = 54, //!< Digit 6.
+ D7 = 55, //!< Digit 7.
+ D8 = 56, //!< Digit 8.
+ D9 = 57, //!< Digit 9.
+ SEMICOLON = 59, //!< Semicolon (;).
+ EQUAL = 61, //!< Equal sign (=).
+ A = 65, //!< Key 'A'.
+ B = 66, //!< Key 'B'.
+ C = 67, //!< Key 'C'.
+ D = 68, //!< Key 'D'.
+ E = 69, //!< Key 'E'.
+ F = 70, //!< Key 'F'.
+ G = 71, //!< Key 'G'.
+ H = 72, //!< Key 'H'.
+ I = 73, //!< Key 'I'.
+ J = 74, //!< Key 'J'.
+ K = 75, //!< Key 'K'.
+ L = 76, //!< Key 'L'.
+ M = 77, //!< Key 'M'.
+ N = 78, //!< Key 'N'.
+ O = 79, //!< Key 'O'.
+ P = 80, //!< Key 'P'.
+ Q = 81, //!< Key 'Q'.
+ R = 82, //!< Key 'R'.
+ S = 83, //!< Key 'S'.
+ T = 84, //!< Key 'T'.
+ U = 85, //!< Key 'U'.
+ V = 86, //!< Key 'V'.
+ W = 87, //!< Key 'W'.
+ X = 88, //!< Key 'X'.
+ Y = 89, //!< Key 'Y'.
+ Z = 90, //!< Key 'Z'.
+ LEFT_BRACKET = 91, //!< Left bracket ([).
+ BACKSLASH = 92, //!< Backslash (\).
+ RIGHT_BRACKET = 93, //!< Right bracket (]).
+ GRAVE_ACCENT = 96, //!< Grave accent (`).
+ WORLD1 = 161, //!< Non-US key #1.
+ WORLD2 = 162, //!< Non-US key #2.
+ ESCAPE = 256, //!< Escape key.
+ ENTER = 257, //!< Enter key.
+ TAB = 258, //!< Tab key.
+ BACKSPACE = 259, //!< Backspace key.
+ INSERT = 260, //!< Insert key.
+ DELETE = 261, //!< Delete key.
+ RIGHT = 262, //!< Right arrow key.
+ LEFT = 263, //!< Left arrow key.
+ DOWN = 264, //!< Down arrow key.
+ UP = 265, //!< Up arrow key.
+ PAGE_UP = 266, //!< Page Up key.
+ PAGE_DOWN = 267, //!< Page Down key.
+ HOME = 268, //!< Home key.
+ END = 269, //!< End key.
+ CAPS_LOCK = 280, //!< Caps Lock key.
+ SCROLL_LOCK = 281, //!< Scroll Lock key.
+ NUM_LOCK = 282, //!< Num Lock key.
+ PRINT_SCREEN = 283, //!< Print Screen key.
+ PAUSE = 284, //!< Pause key.
+ /**
+ * \name Function keys (F1-F25).
+ * \{
+ */
+ F1 = 290,
+ F2 = 291,
+ F3 = 292,
+ F4 = 293,
+ F5 = 294,
+ F6 = 295,
+ F7 = 296,
+ F8 = 297,
+ F9 = 298,
+ F10 = 299,
+ F11 = 300,
+ F12 = 301,
+ F13 = 302,
+ F14 = 303,
+ F15 = 304,
+ F16 = 305,
+ F17 = 306,
+ F18 = 307,
+ F19 = 308,
+ F20 = 309,
+ F21 = 310,
+ F22 = 311,
+ F23 = 312,
+ F24 = 313,
+ F25 = 314,
+ /// \}
+ /**
+ * \name Keypad digits and operators.
+ * \{
+ */
+ KP0 = 320,
+ KP1 = 321,
+ KP2 = 322,
+ KP3 = 323,
+ KP4 = 324,
+ KP5 = 325,
+ KP6 = 326,
+ KP7 = 327,
+ KP8 = 328,
+ KP9 = 329,
+ KP_DECIMAL = 330,
+ KP_DIVIDE = 331,
+ KP_MULTIPLY = 332,
+ KP_SUBTRACT = 333,
+ KP_ADD = 334,
+ KP_ENTER = 335,
+ KP_EQUAL = 336,
+ /// \}
+ /**
+ * \name Modifier keys.
+ * \{
+ */
+ LEFT_SHIFT = 340,
+ LEFT_CONTROL = 341,
+ LEFT_ALT = 342,
+ LEFT_SUPER = 343,
+ RIGHT_SHIFT = 344,
+ RIGHT_CONTROL = 345,
+ RIGHT_ALT = 346,
+ RIGHT_SUPER = 347,
+ /// \}
+ MENU = 348, //!< Menu key.
+};
+//! Typedef for keyboard state.
+typedef std::unordered_map<Keycode, bool> keyboard_state_t;
+} // namespace crepe
diff --git a/src/crepe/api/Metadata.cpp b/src/crepe/api/Metadata.cpp
new file mode 100644
index 0000000..d421de5
--- /dev/null
+++ b/src/crepe/api/Metadata.cpp
@@ -0,0 +1,9 @@
+#include "Metadata.h"
+
+using namespace crepe;
+using namespace std;
+
+Metadata::Metadata(game_object_id_t id, const string & name, const string & tag)
+ : Component(id),
+ name(name),
+ tag(tag) {}
diff --git a/src/crepe/api/Metadata.h b/src/crepe/api/Metadata.h
new file mode 100644
index 0000000..f404703
--- /dev/null
+++ b/src/crepe/api/Metadata.h
@@ -0,0 +1,42 @@
+#pragma once
+
+#include <string>
+#include <vector>
+
+#include "../Component.h"
+
+namespace crepe {
+
+/**
+ * \brief Metadata component
+ *
+ * This class represents the Metadata component. It stores the name, tag, parent and children
+ * of a GameObject.
+ */
+class Metadata : public Component {
+public:
+ /**
+ * \param game_object_id The id of the GameObject this component belongs to
+ * \param name The name of the GameObject
+ * \param tag The tag of the GameObject
+ */
+ Metadata(game_object_id_t id, const std::string & name, const std::string & tag);
+ /**
+ * \brief Get the maximum number of instances for this component
+ *
+ * \return The maximum number of instances for this component
+ */
+ virtual int get_instances_max() const { return 1; }
+
+public:
+ //! The name of the GameObject
+ const std::string name;
+ //! The tag of the GameObject
+ const std::string tag;
+ //! The id of the parent GameObject (-1 if no parent)
+ game_object_id_t parent = -1;
+ //! The ids of the children GameObjects
+ std::vector<game_object_id_t> children;
+};
+
+} // namespace crepe
diff --git a/src/crepe/api/ParticleEmitter.cpp b/src/crepe/api/ParticleEmitter.cpp
new file mode 100644
index 0000000..9a70334
--- /dev/null
+++ b/src/crepe/api/ParticleEmitter.cpp
@@ -0,0 +1,28 @@
+#include "ParticleEmitter.h"
+#include "api/Sprite.h"
+
+using namespace crepe;
+using namespace std;
+
+ParticleEmitter::ParticleEmitter(game_object_id_t game_object_id, const Sprite & sprite,
+ const Data & data)
+ : Component(game_object_id),
+ sprite(sprite),
+ data(data) {
+ for (size_t i = 0; i < this->data.max_particles; i++) {
+ this->particles.emplace_back();
+ }
+}
+
+unique_ptr<Component> ParticleEmitter::save() const {
+ return unique_ptr<Component>{new ParticleEmitter(*this)};
+}
+
+void ParticleEmitter::restore(const Component & snapshot) {
+ *this = static_cast<const ParticleEmitter &>(snapshot);
+}
+
+ParticleEmitter & ParticleEmitter::operator=(const ParticleEmitter & other) {
+ this->particles = other.particles;
+ return *this;
+}
diff --git a/src/crepe/api/ParticleEmitter.h b/src/crepe/api/ParticleEmitter.h
new file mode 100644
index 0000000..1edd2b5
--- /dev/null
+++ b/src/crepe/api/ParticleEmitter.h
@@ -0,0 +1,104 @@
+#pragma once
+
+#include <cmath>
+#include <vector>
+
+#include "system/ParticleSystem.h"
+#include "system/RenderSystem.h"
+
+#include "Component.h"
+#include "Particle.h"
+#include "types.h"
+
+namespace crepe {
+
+class Sprite;
+
+/**
+ * \brief Data holder for particle emission parameters.
+ *
+ * The ParticleEmitter class stores configuration data for particle properties, defining the
+ * characteristics and boundaries of particle emissions.
+ */
+class ParticleEmitter : public Component {
+public:
+ /**
+ * \brief Defines the boundary within which particles are constrained.
+ *
+ * This structure specifies the boundary's size and offset, as well as the behavior of
+ * particles upon reaching the boundary limits.
+ */
+ struct Boundary {
+ //! boundary width (midpoint is emitter location)
+ float width = INFINITY;
+ //! boundary height (midpoint is emitter location)
+ float height = INFINITY;
+ //! boundary offset from particle emitter location
+ vec2 offset;
+ //! reset on exit or stop velocity and set max postion
+ bool reset_on_exit = false;
+ };
+
+ //! sprite reference of displayed sprite
+ const Sprite & sprite;
+
+ /**
+ * \brief Holds parameters that control particle emission.
+ *
+ * Contains settings for the emitter’s position, particle speed, angle, lifespan, boundary,
+ * and the sprite used for rendering particles.
+ */
+ struct Data {
+ //! offset of the emitter relative to transform
+ vec2 offset;
+ //! maximum number of particles
+ const unsigned int max_particles = 256;
+ //! rate of particle emission per second
+ float emission_rate = 50;
+ //! min speed of the particles
+ float min_speed = 100;
+ //! min speed of the particles
+ float max_speed = 100;
+ //! min angle of particle emission
+ float min_angle = 0;
+ //! max angle of particle emission
+ float max_angle = 0;
+ //! begin Lifespan of particle in seconds (only visual)
+ float begin_lifespan = 0.0;
+ //! end Lifespan of particle in seconds
+ float end_lifespan = 10.0;
+ //! force over time (physics)
+ vec2 force_over_time;
+ //! particle boundary
+ Boundary boundary;
+ };
+
+public:
+ /**
+ * \param game_object_id Identifier for the game object using this emitter.
+ * \param data Configuration data defining particle properties.
+ */
+ ParticleEmitter(game_object_id_t game_object_id, const Sprite & sprite, const Data & data);
+
+public:
+ //! Configuration data for particle emission settings.
+ Data data;
+
+protected:
+ virtual std::unique_ptr<Component> save() const;
+ ParticleEmitter(const ParticleEmitter &) = default;
+ virtual void restore(const Component & snapshot);
+ virtual ParticleEmitter & operator=(const ParticleEmitter &);
+
+private:
+ //! Only ParticleSystem can move and read particles
+ friend ParticleSystem;
+ //! Only RenderSystem can read particles
+ friend RenderSystem;
+ //! Saves time left over from last update event.
+ float spawn_accumulator = 0;
+ //! collection of particles
+ std::vector<Particle> particles;
+};
+
+} // namespace crepe
diff --git a/src/crepe/api/Rigidbody.cpp b/src/crepe/api/Rigidbody.cpp
new file mode 100644
index 0000000..8213afb
--- /dev/null
+++ b/src/crepe/api/Rigidbody.cpp
@@ -0,0 +1,13 @@
+#include "Rigidbody.h"
+
+using namespace crepe;
+
+crepe::Rigidbody::Rigidbody(game_object_id_t id, const Data & data)
+ : Component(id),
+ data(data) {}
+
+void crepe::Rigidbody::add_force_linear(const vec2 & force) {
+ this->data.linear_velocity += force;
+}
+
+void crepe::Rigidbody::add_force_angular(float force) { this->data.angular_velocity += force; }
diff --git a/src/crepe/api/Rigidbody.h b/src/crepe/api/Rigidbody.h
new file mode 100644
index 0000000..6900295
--- /dev/null
+++ b/src/crepe/api/Rigidbody.h
@@ -0,0 +1,178 @@
+#pragma once
+
+#include <cmath>
+#include <set>
+
+#include "../Component.h"
+
+#include "types.h"
+
+namespace crepe {
+
+/**
+ * \brief Rigidbody class
+ *
+ * This class is used by the physics sytem and collision system. It configures how to system
+ * interact with the gameobject for movement and collisions.
+ */
+class Rigidbody : public Component {
+public:
+ /**
+ * \brief BodyType enum
+ *
+ * This enum provides three bodytypes the physics sytem and collision system use.
+ */
+ enum class BodyType {
+ //! Does not move (e.g. walls, ground ...)
+ STATIC,
+ //! Moves and responds to forces (e.g. player, physics objects ...)
+ DYNAMIC,
+ //! Moves but does not respond to forces (e.g. moving platforms ...)
+ KINEMATIC,
+ };
+ /**
+ * \brief PhysicsConstraints to constrain movement
+ *
+ * This struct configures the movement constraint for this object. If a constraint is enabled
+ * the systems will not move the object.
+ */
+ struct PhysicsConstraints {
+ //! Prevent movement along X axis
+ bool x = false;
+ //! Prevent movement along Y axis
+ bool y = false;
+ //! Prevent rotation
+ bool rotation = false;
+ };
+
+public:
+ /**
+ * \brief struct for Rigidbody data
+ *
+ * This struct holds the data for the Rigidbody.
+ */
+ struct Data {
+ //! objects mass
+ float mass = 1;
+ /**
+ * \brief Gravity scale factor.
+ *
+ * The `gravity_scale` controls how much gravity affects the object. It is a multiplier applied to the default
+ * gravity force, allowing for fine-grained control over how the object responds to gravity.
+ *
+ */
+ float gravity_scale = 0;
+
+ //! Defines the type of the physics body, which determines how the physics system interacts with the object.
+ BodyType body_type = BodyType::DYNAMIC;
+
+ /**
+ * \name Linear (positional) motion
+ *
+ * These variables define the linear motion (movement along the position) of an object.
+ * The linear velocity is applied to the object's position in each update of the PhysicsSystem.
+ * The motion is affected by the object's linear velocity, its maximum velocity, and a coefficient
+ * that can scale the velocity over time.
+ *
+ * \{
+ */
+ //! Linear velocity of the object (speed and direction).
+ vec2 linear_velocity;
+ //! Maximum linear velocity of the object. This limits the object's speed.
+ float max_linear_velocity = INFINITY;
+ //! Linear velocity coefficient. This scales the object's velocity for adjustment or damping.
+ vec2 linear_velocity_coefficient = {1, 1};
+ //! \}
+
+ /**
+ * \name Angular (rotational) motion
+ *
+ * These variables define the angular motion (rotation) of an object.
+ * The angular velocity determines how quickly the object rotates, while the maximum angular velocity
+ * sets a limit on the rotation speed. The angular velocity coefficient applies damping or scaling
+ * to the angular velocity, which can be used to simulate friction or other effects that slow down rotation.
+ *
+ * \{
+ */
+ //! Angular velocity of the object, representing the rate of rotation (in degrees).
+ float angular_velocity = 0;
+ //! Maximum angular velocity of the object. This limits the maximum rate of rotation.
+ float max_angular_velocity = INFINITY;
+ //! Angular velocity coefficient. This scales the object's angular velocity, typically used for damping.
+ float angular_velocity_coefficient = 1;
+ //! \}
+
+ /**
+ * \brief Movement constraints for an object.
+ *
+ * The `PhysicsConstraints` struct defines the constraints that restrict an object's movement
+ * in certain directions or prevent rotation. These constraints effect only the physics system
+ * to prevent the object from moving or rotating in specified ways.
+ *
+ */
+ PhysicsConstraints constraints;
+
+ /**
+ * \brief Elasticity factor of the material (bounce factor).
+ *
+ * The `elasticity_coefficient` controls how much of the object's velocity is retained after a collision.
+ * It represents the material's ability to bounce or recover velocity upon impact. The coefficient is a value
+ * above 0.0.
+ *
+ */
+ float elastisity_coefficient = 0.0;
+
+ /**
+ * \brief Offset of all colliders relative to the object's transform position.
+ *
+ * The `offset` defines a positional shift applied to all colliders associated with the object, relative to the object's
+ * transform position. This allows for the colliders to be placed at a different position than the object's actual
+ * position, without modifying the object's transform itself.
+ *
+ */
+ vec2 offset;
+
+ /**
+ * \brief Defines the collision layers of a GameObject.
+ *
+ * The `collision_layers` specifies the layers that the GameObject will collide with.
+ * Each element represents a layer ID, and the GameObject will only detect
+ * collisions with other GameObjects that belong to these layers.
+ */
+ std::set<int> collision_layers = {0};
+ };
+
+public:
+ /**
+ * \param game_object_id id of the gameobject the rigibody is added to.
+ * \param data struct to configure the rigidbody.
+ */
+ Rigidbody(game_object_id_t id, const Data & data);
+ //! struct to hold data of rigidbody
+ Data data;
+
+public:
+ /**
+ * \brief add a linear force to the Rigidbody.
+ *
+ * \param force Vector2 that is added to the linear force.
+ */
+ void add_force_linear(const vec2 & force);
+ /**
+ * \brief add a angular force to the Rigidbody.
+ *
+ * \param force Vector2 that is added to the angular force.
+ */
+ void add_force_angular(float force);
+
+protected:
+ /**
+ * Ensures there is at most one Rigidbody component per entity.
+ * \return Always returns 1, indicating this constraint.
+ */
+ virtual int get_instances_max() const { return 1; }
+ //! ComponentManager instantiates all components
+ friend class ComponentManager;
+};
+
+} // namespace crepe
diff --git a/src/crepe/api/Scene.cpp b/src/crepe/api/Scene.cpp
new file mode 100644
index 0000000..ad729d2
--- /dev/null
+++ b/src/crepe/api/Scene.cpp
@@ -0,0 +1,15 @@
+#include "Scene.h"
+
+using namespace crepe;
+
+SaveManager & Scene::get_save_manager() const { return mediator->save_manager; }
+
+GameObject Scene::new_object(const std::string & name, const std::string & tag,
+ const vec2 & position, double rotation, double scale) {
+ // Forward the call to ComponentManager's new_object method
+ return mediator->component_manager->new_object(name, tag, position, rotation, scale);
+}
+
+void Scene::set_persistent(const Asset & asset, bool persistent) {
+ mediator->resource_manager->set_persistent(asset, persistent);
+}
diff --git a/src/crepe/api/Scene.h b/src/crepe/api/Scene.h
new file mode 100644
index 0000000..dcca9d4
--- /dev/null
+++ b/src/crepe/api/Scene.h
@@ -0,0 +1,94 @@
+#pragma once
+
+#include <string>
+
+#include "../manager/ComponentManager.h"
+#include "../manager/Mediator.h"
+#include "../manager/ResourceManager.h"
+#include "../util/Log.h"
+#include "../util/OptionalRef.h"
+
+#include "GameObject.h"
+
+namespace crepe {
+
+class SceneManager;
+class ComponentManager;
+class Asset;
+
+/**
+ * \brief Represents a Scene
+ *
+ * This class represents a Scene. The Scene class is only used as an interface for the game
+ * programmer.
+ */
+class Scene {
+protected:
+ // NOTE: This must be the only constructor on Scene, see "Late references" below
+ Scene() = default;
+ //! SceneManager instances Scene
+ friend class SceneManager;
+
+public:
+ virtual ~Scene() = default;
+
+public:
+ //! Load the scene
+ virtual void load_scene() = 0;
+ /**
+ * \brief Get the scene's name
+ * \return The scene's name
+ */
+ virtual std::string get_name() const = 0;
+
+ // TODO: Late references should ALWAYS be private! This is currently kept as-is so unit tests
+ // keep passing, but this reference should not be directly accessible by the user!!!
+
+private:
+ /**
+ * \name Late references
+ *
+ * These references are set by SceneManager immediately after calling the constructor of Scene.
+ *
+ * \note Scene must have a constructor without arguments so the game programmer doesn't need to
+ * manually add `using Scene::Scene` to their concrete scene class, if they want to add a
+ * constructor with arguments (e.g. for passing references to their own concrete Scene classes).
+ *
+ * \{
+ */
+ //! Mediator reference
+ OptionalRef<Mediator> mediator;
+ //! \}
+
+protected:
+ /**
+ * \brief Retrieve the reference to the SaveManager instance
+ *
+ * \returns A reference to the SaveManager instance held by the Mediator.
+ */
+ SaveManager & get_save_manager() const;
+
+ //! \copydoc ComponentManager::new_object
+ GameObject new_object(const std::string & name, const std::string & tag = "",
+ const vec2 & position = {0, 0}, double rotation = 0,
+ double scale = 1);
+
+ //! \copydoc ResourceManager::set_persistent
+ void set_persistent(const Asset & asset, bool persistent);
+ /**
+ * \name Logging functions
+ * \see Log
+ * \{
+ */
+ //! \copydoc Log::logf
+ template <class... Args>
+ void logf(const Log::Level & level, std::format_string<Args...> fmt, Args &&... args);
+ //! \copydoc Log::logf
+ template <class... Args>
+ void logf(std::format_string<Args...> fmt, Args &&... args);
+ //! \}
+};
+
+} // namespace crepe
+
+#include "Scene.hpp"
diff --git a/src/crepe/api/Scene.hpp b/src/crepe/api/Scene.hpp
new file mode 100644
index 0000000..14635df
--- /dev/null
+++ b/src/crepe/api/Scene.hpp
@@ -0,0 +1,19 @@
+#pragma once
+
+#include "../util/Log.h"
+
+#include "Scene.h"
+
+namespace crepe {
+
+template <class... Args>
+void Scene::logf(const Log::Level & level, std::format_string<Args...> fmt, Args &&... args) {
+ Log::logf(level, fmt, std::forward<Args>(args)...);
+}
+
+template <class... Args>
+void Scene::logf(std::format_string<Args...> fmt, Args &&... args) {
+ Log::logf(fmt, std::forward<Args>(args)...);
+}
+
+} // namespace crepe
diff --git a/src/crepe/api/Script.cpp b/src/crepe/api/Script.cpp
new file mode 100644
index 0000000..b147252
--- /dev/null
+++ b/src/crepe/api/Script.cpp
@@ -0,0 +1,63 @@
+#include <string>
+
+#include "../facade/SDLContext.h"
+#include "../manager/SceneManager.h"
+
+#include "Script.h"
+
+using namespace crepe;
+using namespace std;
+
+Script::~Script() {
+ EventManager & mgr = this->mediator->event_manager;
+ for (auto id : this->listeners) {
+ mgr.unsubscribe(id);
+ }
+}
+
+template <>
+void Script::subscribe(const EventHandler<CollisionEvent> & callback) {
+ this->subscribe_internal(callback, this->game_object_id);
+}
+
+void Script::set_next_scene(const string & name) {
+ SceneManager & mgr = this->mediator->scene_manager;
+ mgr.set_next_scene(name);
+}
+
+SaveManager & Script::get_save_manager() const { return this->mediator->save_manager; }
+
+LoopTimerManager & Script::get_loop_timer() const { return this->mediator->loop_timer; }
+
+void Script::replay::record_start() {
+ ReplayManager & mgr = this->mediator->replay_manager;
+ return mgr.record_start();
+}
+
+recording_t Script::replay::record_end() {
+ ReplayManager & mgr = this->mediator->replay_manager;
+ return mgr.record_end();
+}
+
+void Script::replay::play(recording_t recording) {
+ ReplayManager & mgr = this->mediator->replay_manager;
+ return mgr.play(recording);
+}
+
+void Script::replay::release(recording_t recording) {
+ ReplayManager & mgr = this->mediator->replay_manager;
+ return mgr.release(recording);
+}
+
+const keyboard_state_t & Script::get_keyboard_state() const {
+ SDLContext & sdl_context = this->mediator->sdl_context;
+ return sdl_context.get_keyboard_state();
+}
+
+bool Script::get_key_state(Keycode key) const noexcept {
+ try {
+ return this->get_keyboard_state().at(key);
+ } catch (...) {
+ return false;
+ }
+}
diff --git a/src/crepe/api/Script.h b/src/crepe/api/Script.h
new file mode 100644
index 0000000..5f68928
--- /dev/null
+++ b/src/crepe/api/Script.h
@@ -0,0 +1,276 @@
+#pragma once
+
+#include <vector>
+
+#include "../api/KeyCodes.h"
+#include "../manager/EventManager.h"
+#include "../manager/LoopTimerManager.h"
+#include "../manager/Mediator.h"
+#include "../manager/ReplayManager.h"
+#include "../system/CollisionSystem.h"
+#include "../types.h"
+#include "../util/Log.h"
+#include "../util/OptionalRef.h"
+
+namespace crepe {
+
+class ScriptSystem;
+class BehaviorScript;
+class ComponentManager;
+
+/**
+ * \brief Script interface
+ *
+ * This class is used as a base class for user-defined scripts that can be added to game
+ * objects using the \c BehaviorScript component.
+ *
+ * \note Additional *events* (like Unity's OnDisable and OnEnable) should be implemented as
+ * member or lambda methods in derivative user script classes and registered in \c init().
+ *
+ * \warning Concrete scripts are allowed do create a custom constructor, but the utility
+ * functions should not be called inside the constructor as they rely on late references that
+ * are only available after the constructor returns.
+ *
+ * \see feature_script
+ */
+class Script {
+protected:
+ /**
+ * \name Interface functions
+ * \{
+ */
+ /**
+ * \brief Script initialization function (empty by default)
+ *
+ * This function is called during the ScriptSystem::update() routine *before*
+ * Script::update() if it (a) has not yet been called and (b) the \c BehaviorScript component
+ * holding this script instance is active.
+ */
+ virtual void init() {}
+ /**
+ * \brief Script fixed update function (empty by default)
+ *
+ * \param delta_time Time since last fixed update
+ *
+ * \note This function is called during the ScriptSystem::update() routine if the \c
+ * BehaviorScript component holding this script instance is active.
+ */
+ virtual void fixed_update(duration_t delta_time) {}
+ /**
+ * \brief Script frame update function (empty by default)
+ *
+ * \param delta_time Time since last frame update
+ *
+ * \note This function is called during the ScriptSystem::update() routine if the \c
+ * BehaviorScript component holding this script instance is active.
+ */
+ virtual void frame_update(duration_t delta_time) {}
+ //! \}
+
+ //! ScriptSystem calls \c init() and \c update()
+ friend class crepe::ScriptSystem;
+
+protected:
+ /**
+ * \name Component query functions
+ * \see ComponentManager
+ * \{
+ */
+ /**
+ * \brief Get single component of type \c T on this game object
+ * \tparam T Type of component
+ * \returns Reference to component
+ * \throws std::runtime_error if this game object does not have a component with type \c T
+ */
+ template <typename T>
+ T & get_component() const;
+ /**
+ * \brief Get all components of type \c T on this game object
+ * \tparam T Type of component
+ * \returns List of component references
+ */
+ template <typename T>
+ RefVector<T> get_components() const;
+ //! \copydoc ComponentManager::get_components_by_id
+ template <typename T>
+ RefVector<T> get_components_by_id(game_object_id_t id) const;
+ //! \copydoc ComponentManager::get_components_by_name
+ template <typename T>
+ RefVector<T> get_components_by_name(const std::string & name) const;
+ //! \copydoc ComponentManager::get_components_by_tag
+ template <typename T>
+ RefVector<T> get_components_by_tag(const std::string & tag) const;
+ //! \}
+
+ /**
+ * \name Logging functions
+ * \see Log
+ * \{
+ */
+ //! \copydoc Log::logf
+ template <class... Args>
+ void logf(const Log::Level & level, std::format_string<Args...> fmt, Args &&... args);
+ //! \copydoc Log::logf
+ template <class... Args>
+ void logf(std::format_string<Args...> fmt, Args &&... args);
+ // \}
+
+ /**
+ * \name Event manager functions
+ * \see EventManager
+ * \{
+ */
+ //! \copydoc EventManager::subscribe
+ template <typename EventType>
+ void subscribe(const EventHandler<EventType> & callback, event_channel_t channel);
+ //! \copydoc EventManager::subscribe
+ template <typename EventType>
+ void subscribe(const EventHandler<EventType> & callback);
+ //! \copydoc EventManager::trigger_event
+ template <typename EventType>
+ void trigger_event(const EventType & event = {},
+ event_channel_t channel = EventManager::CHANNEL_ALL);
+ //! \copydoc EventManager::queue_event
+ template <typename EventType>
+ void queue_event(const EventType & event = {},
+ event_channel_t channel = EventManager::CHANNEL_ALL);
+ //! \}
+
+ /**
+ * \name Scene-related functions
+ * \see SceneManager
+ * \{
+ */
+ //! \copydoc SceneManager::set_next_scene
+ void set_next_scene(const std::string & name);
+ //! \}
+
+ /**
+ * \name Save data management functions
+ * \see SaveManager
+ * \{
+ */
+ //! Retrieve SaveManager reference
+ SaveManager & get_save_manager() const;
+ //! \}
+
+ /**
+ * \name Timing functions
+ * \see LoopTimerManager
+ * \{
+ */
+ //! Retrieve LoopTimerManager reference
+ LoopTimerManager & get_loop_timer() const;
+ //! \}
+
+ //! Replay management functions
+ struct replay { // NOLINT
+ //! \copydoc ReplayManager::record_start
+ void record_start();
+ //! \copydoc ReplayManager::record_end
+ recording_t record_end();
+ //! \copydoc ReplayManager::play
+ void play(recording_t);
+ //! \copydoc ReplayManager::release
+ void release(recording_t);
+
+ private:
+ OptionalRef<Mediator> & mediator;
+ replay(OptionalRef<Mediator> & mediator) : mediator(mediator) {}
+ friend class Script;
+ } replay{mediator};
+
+ /**
+ * \brief Utility function to retrieve the keyboard state
+ * \see SDLContext::get_keyboard_state
+ *
+ * \return current keyboard state map with Keycode as key and bool as value(true = pressed, false = not pressed)
+ */
+ const keyboard_state_t & get_keyboard_state() const;
+ /**
+ * \brief Utility function to retrieve a single key state.
+ * \see SDLContext::get_keyboard_state
+ *
+ * \return Keycode state (true if pressed, false if not pressed).
+ */
+ bool get_key_state(Keycode key) const noexcept;
+
+private:
+ /**
+ * \brief Internal subscribe function
+ *
+ * This function exists so certain template specializations of Script::subscribe can be
+ * explicitly deleted, and does the following:
+ * - Wrap the user-provided callback in a check that tests if the parent BehaviorScript
+ * component is still active
+ * - Store the subscriber handle returned by the event manager so this listener is
+ * automatically unsubscribed at the end of this Script instance's life
+ *
+ * \tparam EventType concrete Event class
+ * \param callback User-provided callback function
+ * \param channel Event channel (may have been overridden by template specializations)
+ */
+ template <typename EventType>
+ void subscribe_internal(const EventHandler<EventType> & callback, event_channel_t channel);
+
+protected:
+ // NOTE: This must be the only constructor on Script, see "Late references" below
+ Script() = default;
+ //! Only \c BehaviorScript instantiates Script
+ friend class BehaviorScript;
+
+public:
+ // std::unique_ptr destroys script
+ virtual ~Script();
+
+private:
+ Script(const Script &) = delete;
+ Script(Script &&) = delete;
+ Script & operator=(const Script &) = delete;
+ Script & operator=(Script &&) = delete;
+
+private:
+ /**
+ * \name Late references
+ *
+ * These references are set by BehaviorScript immediately after calling the constructor of
+ * Script.
+ *
+ * \note Script must have a constructor without arguments so the game programmer doesn't need
+ * to manually add `using Script::Script` to their concrete script class if they want to
+ * implement a non-default constructor (e.g. for passing references to their own concrete
+ * Script classes).
+ *
+ * \{
+ */
+ //! Game object ID of game object parent BehaviorScript is attached to
+ game_object_id_t game_object_id;
+ //! Reference to parent component
+ OptionalRef<bool> active;
+ //! Mediator reference
+ OptionalRef<Mediator> mediator;
+ //! \}
+
+private:
+ //! Flag to indicate if \c init() has been called already
+ bool initialized = false;
+ //! List of subscribed events
+ std::vector<subscription_t> listeners;
+};
+
+/**
+ * \brief Subscribe to CollisionEvent for the current GameObject
+ *
+ * This is a template specialization for Script::subscribe which automatically sets the event
+ * channel so the callback handler is only called for CollisionEvent events that apply to the
+ * current GameObject the parent BehaviorScript is attached to.
+ */
+template <>
+void Script::subscribe(const EventHandler<CollisionEvent> & callback);
+template <>
+void Script::subscribe(const EventHandler<CollisionEvent> & callback, event_channel_t)
+ = delete;
+
+} // namespace crepe
+
+#include "Script.hpp"
diff --git a/src/crepe/api/Script.hpp b/src/crepe/api/Script.hpp
new file mode 100644
index 0000000..4462a41
--- /dev/null
+++ b/src/crepe/api/Script.hpp
@@ -0,0 +1,105 @@
+#pragma once
+
+#include "../manager/ComponentManager.h"
+#include "../manager/ReplayManager.h"
+
+#include "BehaviorScript.h"
+#include "Script.h"
+
+namespace crepe {
+
+template <typename T>
+T & Script::get_component() const {
+ using namespace std;
+ RefVector<T> all_components = this->get_components<T>();
+ if (all_components.size() < 1)
+ throw runtime_error(
+ format("Script: no component found with type = {}", typeid(T).name()));
+
+ return all_components.back().get();
+}
+
+template <typename T>
+RefVector<T> Script::get_components() const {
+ return this->get_components_by_id<T>(this->game_object_id);
+}
+
+template <class... Args>
+void Script::logf(const Log::Level & level, std::format_string<Args...> fmt, Args &&... args) {
+ Log::logf(level, fmt, std::forward<Args>(args)...);
+}
+
+template <class... Args>
+void Script::logf(std::format_string<Args...> fmt, Args &&... args) {
+ Log::logf(fmt, std::forward<Args>(args)...);
+}
+
+template <typename EventType>
+void Script::subscribe_internal(const EventHandler<EventType> & callback,
+ event_channel_t channel) {
+ EventManager & mgr = this->mediator->event_manager;
+ subscription_t listener = mgr.subscribe<EventType>(
+ [this, callback](const EventType & data) -> bool {
+ // check if (parent) BehaviorScript component is active
+ bool & active = this->active;
+ if (!active) return false;
+
+ // check if replay manager is playing (if initialized)
+ try {
+ ReplayManager & replay = this->mediator->replay_manager;
+ if (replay.get_state() == ReplayManager::PLAYING) return false;
+ } catch (const std::runtime_error &) {
+ }
+
+ // call user-provided callback
+ return callback(data);
+ },
+ channel);
+ this->listeners.push_back(listener);
+}
+
+template <typename EventType>
+void Script::subscribe(const EventHandler<EventType> & callback, event_channel_t channel) {
+ this->subscribe_internal(callback, channel);
+}
+
+template <typename EventType>
+void Script::subscribe(const EventHandler<EventType> & callback) {
+ this->subscribe_internal(callback, EventManager::CHANNEL_ALL);
+}
+
+template <typename EventType>
+void Script::trigger_event(const EventType & event, event_channel_t channel) {
+ EventManager & mgr = this->mediator->event_manager;
+ mgr.trigger_event(event, channel);
+}
+
+template <typename EventType>
+void Script::queue_event(const EventType & event, event_channel_t channel) {
+ EventManager & mgr = this->mediator->event_manager;
+ mgr.queue_event(event, channel);
+}
+
+template <typename T>
+RefVector<T> Script::get_components_by_id(game_object_id_t id) const {
+ Mediator & mediator = this->mediator;
+ ComponentManager & mgr = mediator.component_manager;
+
+ return mgr.get_components_by_id<T>(id);
+}
+template <typename T>
+RefVector<T> Script::get_components_by_name(const std::string & name) const {
+ Mediator & mediator = this->mediator;
+ ComponentManager & mgr = mediator.component_manager;
+
+ return mgr.get_components_by_name<T>(name);
+}
+template <typename T>
+RefVector<T> Script::get_components_by_tag(const std::string & tag) const {
+ Mediator & mediator = this->mediator;
+ ComponentManager & mgr = mediator.component_manager;
+
+ return mgr.get_components_by_tag<T>(tag);
+}
+
+} // namespace crepe
diff --git a/src/crepe/api/Sprite.cpp b/src/crepe/api/Sprite.cpp
new file mode 100644
index 0000000..0107c7b
--- /dev/null
+++ b/src/crepe/api/Sprite.cpp
@@ -0,0 +1,21 @@
+#include <cmath>
+
+#include "../util/dbg.h"
+#include "api/Asset.h"
+
+#include "Component.h"
+#include "Sprite.h"
+#include "types.h"
+
+using namespace std;
+using namespace crepe;
+
+Sprite::Sprite(game_object_id_t id, const Asset & texture, const Sprite::Data & data)
+ : Component(id),
+ source(texture),
+ data(data) {
+
+ dbg_trace();
+}
+
+Sprite::~Sprite() { dbg_trace(); }
diff --git a/src/crepe/api/Sprite.h b/src/crepe/api/Sprite.h
new file mode 100644
index 0000000..a2409c2
--- /dev/null
+++ b/src/crepe/api/Sprite.h
@@ -0,0 +1,114 @@
+#pragma once
+
+#include "../Component.h"
+#include "api/Asset.h"
+
+#include "Color.h"
+#include "types.h"
+
+namespace crepe {
+
+class SDLContext;
+class Animator;
+class AnimatorSystem;
+
+/**
+ * \brief Represents a renderable sprite component.
+ *
+ * A renderable sprite that can be displayed in the game. It includes a texture, color, and
+ * flip settings, and is managed in layers with defined sorting orders.
+ */
+class Sprite : public Component {
+public:
+ //! settings to flip the image
+ struct FlipSettings {
+ //! horizantal flip
+ bool flip_x = false;
+ //! vertical flip
+ bool flip_y = false;
+ };
+
+ //! Sprite data that does not have to be set in the constructor
+ struct Data {
+ /**
+ * \brief Sprite tint (multiplied)
+ *
+ * The sprite texture's pixels are multiplied by this color before being displayed
+ * (including alpha channel for transparency).
+ */
+ Color color = Color::WHITE;
+
+ //! Flip settings for the sprite
+ FlipSettings flip;
+
+ //! Layer sorting level of the sprite
+ const int sorting_in_layer = 0;
+
+ //! Order within the sorting layer
+ const int order_in_layer = 0;
+
+ /**
+ * \brief width and height of the sprite in game units
+ *
+ * - if exclusively width is specified, the height is calculated using the texture's aspect
+ * ratio
+ * - if exclusively height is specified, the width is calculated using the texture's aspect
+ * ratio
+ * - if both are specified the texture is streched to fit the specified size
+ */
+ vec2 size = {0, 0};
+
+ //! independent sprite angle. rotating clockwise direction in degrees
+ float angle_offset = 0;
+
+ //! independent sprite scale multiplier
+ float scale_offset = 1;
+
+ //! independent sprite offset position
+ vec2 position_offset;
+ };
+
+public:
+ /**
+ * \param game_id Unique identifier for the game object this sprite belongs to.
+ * \param texture asset of the image
+ * \param ctx all the sprite data
+ */
+ Sprite(game_object_id_t id, const Asset & texture, const Data & data);
+ ~Sprite();
+
+ //! Texture used for the sprite
+ const Asset source;
+
+ Data data;
+
+private:
+ //! Reads the mask of sprite
+ friend class SDLContext;
+
+ //! Reads the all the variables plus the mask
+ friend class Animator;
+
+ //! Reads the all the variables plus the mask
+ friend class AnimatorSystem;
+
+ /**
+ * \aspect_ratio the ratio of the sprite image
+ *
+ * - this value will only be set by the \c Animator component for the ratio of the Animation
+ * - if \c Animator component is not added it will not use this ratio (because 0) and will use aspect_ratio of the Asset.
+ */
+ float aspect_ratio = 0;
+
+ struct Rect {
+ int w = 0;
+ int h = 0;
+ int x = 0;
+ int y = 0;
+ };
+ //! Render area of the sprite this will also be adjusted by the AnimatorSystem if an Animator
+ // object is present in GameObject. this is in sprite pixels
+ Rect mask;
+};
+
+} // namespace crepe
diff --git a/src/crepe/api/Text.cpp b/src/crepe/api/Text.cpp
new file mode 100644
index 0000000..54a4370
--- /dev/null
+++ b/src/crepe/api/Text.cpp
@@ -0,0 +1,12 @@
+#include "../facade/FontFacade.h"
+
+#include "Text.h"
+
+using namespace crepe;
+
+Text::Text(game_object_id_t id, const vec2 & dimensions, const vec2 & offset,
+ const std::string & font_family, const Data & data, const std::string & text)
+ : UIObject(id, dimensions, offset),
+ text(text),
+ data(data),
+ font_family(font_family) {}
diff --git a/src/crepe/api/Text.h b/src/crepe/api/Text.h
new file mode 100644
index 0000000..c30dc80
--- /dev/null
+++ b/src/crepe/api/Text.h
@@ -0,0 +1,66 @@
+#pragma once
+
+#include <optional>
+#include <string>
+
+#include "../Component.h"
+
+#include "Asset.h"
+#include "Color.h"
+#include "UIObject.h"
+
+namespace crepe {
+/**
+ * \brief Text UIObject component for displaying text
+ *
+ * This class can be used to display text on screen. By setting the font_family to a font already stored on the current device it will automatically be loaded in.
+ */
+class Text : public UIObject {
+public:
+ //! Text data that does not have to be set in the constructor
+ struct Data {
+ /**
+ * \brief fontsize for text rendering
+ *
+ * \note this is not the actual font size that is loaded in.
+ *
+ * Since SDL_TTF requires the font size when loading in the font it is not possible to switch the font size.
+ * The default font size that is loaded is set in the Config.
+ * Instead this value is used to upscale the font texture which can cause blurring or distorted text when upscaling or downscaling too much.
+ */
+ unsigned int font_size = 16;
+
+ //! Layer sorting level of the text
+ const int sorting_in_layer = 0;
+
+ //! Order within the sorting text
+ const int order_in_layer = 0;
+
+ //! Label text color.
+ Color text_color = Color::BLACK;
+ };
+
+public:
+ /**
+ *
+ * \param dimensions Width and height of the UIObject.
+ * \param offset Offset of the UIObject relative to its transform
+ * \param text The text to be displayed.
+ * \param font_family The font style name to be displayed.
+ * \param data Data struct containing extra text parameters.
+ * \param font Optional font asset that can be passed or left empty.
+ */
+ Text(game_object_id_t id, const vec2 & dimensions, const vec2 & offset,
+ const std::string & font_family, const Data & data, const std::string & text = "");
+
+ //! Label text.
+ std::string text = "";
+ //! font family name
+ std::string font_family = "";
+ //! Font asset variable if this is not set, it will use the font_family to create an asset.
+ std::optional<Asset> font;
+ //! Data instance
+ Data data;
+};
+
+} // namespace crepe
diff --git a/src/crepe/api/Transform.cpp b/src/crepe/api/Transform.cpp
new file mode 100644
index 0000000..fcfce14
--- /dev/null
+++ b/src/crepe/api/Transform.cpp
@@ -0,0 +1,22 @@
+#include "../util/dbg.h"
+
+#include "Transform.h"
+
+using namespace crepe;
+using namespace std;
+
+Transform::Transform(game_object_id_t id, const vec2 & point, double rotation, double scale)
+ : Component(id),
+ position(point),
+ rotation(rotation),
+ scale(scale) {
+ dbg_trace();
+}
+
+unique_ptr<Component> Transform::save() const {
+ return unique_ptr<Component>{new Transform(*this)};
+}
+
+void Transform::restore(const Component & snapshot) {
+ *this = static_cast<const Transform &>(snapshot);
+}
diff --git a/src/crepe/api/Transform.h b/src/crepe/api/Transform.h
new file mode 100644
index 0000000..a6f3486
--- /dev/null
+++ b/src/crepe/api/Transform.h
@@ -0,0 +1,46 @@
+#pragma once
+
+#include "Component.h"
+#include "types.h"
+
+namespace crepe {
+
+/**
+ * \brief Transform component
+ *
+ * This class represents the Transform component. It stores the position, rotation and scale of
+ * a GameObject.
+ */
+class Transform : public Component {
+public:
+ //! Translation (shift)
+ vec2 position = {0, 0};
+ //! Rotation, in degrees clockwise
+ float rotation = 0;
+ //! Multiplication factor
+ float scale = 0;
+
+protected:
+ /**
+ * \param id The id of the GameObject this component belongs to
+ * \param point The position of the GameObject
+ * \param rotation The rotation of the GameObject
+ * \param scale The scale of the GameObject
+ */
+ Transform(game_object_id_t id, const vec2 & point, double rotation, double scale);
+ /**
+ * There is always exactly one transform component per entity
+ * \return 1
+ */
+ virtual int get_instances_max() const { return 1; }
+ //! ComponentManager instantiates all components
+ friend class ComponentManager;
+
+protected:
+ virtual std::unique_ptr<Component> save() const;
+ Transform(const Transform &) = default;
+ virtual void restore(const Component & snapshot);
+ virtual Transform & operator=(const Transform &) = default;
+};
+
+} // namespace crepe
diff --git a/src/crepe/api/UIObject.cpp b/src/crepe/api/UIObject.cpp
new file mode 100644
index 0000000..d239b89
--- /dev/null
+++ b/src/crepe/api/UIObject.cpp
@@ -0,0 +1,8 @@
+#include "UIObject.h"
+
+using namespace crepe;
+
+UIObject::UIObject(game_object_id_t id, const vec2 & dimensions, const vec2 & offset)
+ : Component(id),
+ dimensions(dimensions),
+ offset(offset) {}
diff --git a/src/crepe/api/UIObject.h b/src/crepe/api/UIObject.h
new file mode 100644
index 0000000..f7f4fba
--- /dev/null
+++ b/src/crepe/api/UIObject.h
@@ -0,0 +1,25 @@
+#pragma once
+
+#include "../Component.h"
+
+namespace crepe {
+
+/**
+ * \brief Represents a UI object in the game, derived from the Component class.
+ */
+class UIObject : public Component {
+public:
+ /**
+ * \brief Constructs a UiObject with the specified game object ID.
+ * \param id The unique ID of the game object associated with this UI object.
+ * \param dimensions width and height of the UIObject
+ * \param offset Offset relative to the GameObject Transform
+ */
+ UIObject(game_object_id_t id, const vec2 & dimensions, const vec2 & offset);
+ //! Width and height of the UIObject
+ vec2 dimensions;
+ //! Position offset relative to this GameObjects Transform
+ vec2 offset;
+};
+
+} // namespace crepe
diff --git a/src/crepe/api/Vector2.h b/src/crepe/api/Vector2.h
new file mode 100644
index 0000000..bf9d124
--- /dev/null
+++ b/src/crepe/api/Vector2.h
@@ -0,0 +1,97 @@
+#pragma once
+
+namespace crepe {
+
+//! 2D vector
+template <class T>
+struct Vector2 {
+ //! X component of the vector
+ T x = 0;
+ //! Y component of the vector
+ T y = 0;
+
+ //! Subtracts another vector from this vector and returns the result.
+ Vector2 operator-(const Vector2<T> & other) const;
+
+ //! Subtracts a scalar value from both components of this vector and returns the result.
+ Vector2 operator-(T scalar) const;
+
+ //! Adds another vector to this vector and returns the result.
+ Vector2 operator+(const Vector2<T> & other) const;
+
+ //! Adds a scalar value to both components of this vector and returns the result.
+ Vector2 operator+(T scalar) const;
+
+ //! Multiplies this vector by another vector element-wise and returns the result.
+ Vector2 operator*(const Vector2<T> & other) const;
+
+ //! Multiplies this vector by a scalar and returns the result.
+ Vector2 operator*(T scalar) const;
+
+ //! Divides this vector by another vector element-wise and returns the result.
+ Vector2 operator/(const Vector2<T> & other) const;
+
+ //! Divides this vector by a scalar and returns the result.
+ Vector2 operator/(T scalar) const;
+
+ //! Adds another vector to this vector and updates this vector.
+ Vector2 & operator+=(const Vector2<T> & other);
+
+ //! Adds a scalar value to both components of this vector and updates this vector.
+ Vector2 & operator+=(T other);
+
+ //! Subtracts another vector from this vector and updates this vector.
+ Vector2 & operator-=(const Vector2<T> & other);
+
+ //! Subtracts a scalar value from both components of this vector and updates this vector.
+ Vector2 & operator-=(T other);
+
+ //! Multiplies this vector by another vector element-wise and updates this vector.
+ Vector2 & operator*=(const Vector2<T> & other);
+
+ //! Multiplies this vector by a scalar and updates this vector.
+ Vector2 & operator*=(T other);
+
+ //! Divides this vector by another vector element-wise and updates this vector.
+ Vector2 & operator/=(const Vector2<T> & other);
+
+ //! Divides this vector by a scalar and updates this vector.
+ Vector2 & operator/=(T other);
+
+ //! Returns the negation of this vector.
+ Vector2 operator-() const;
+
+ //! Checks if this vector is equal to another vector.
+ bool operator==(const Vector2<T> & other) const;
+
+ //! Checks if this vector is not equal to another vector.
+ bool operator!=(const Vector2<T> & other) const;
+
+ //! Truncates the vector to a maximum length.
+ void truncate(T max);
+
+ //! Normalizes the vector (resulting in vector with a length of 1).
+ void normalize();
+
+ //! Returns the length of the vector.
+ T length() const;
+
+ //! Returns the squared length of the vector.
+ T length_squared() const;
+
+ //! Returns the dot product (inwendig product) of this vector and another vector.
+ T dot(const Vector2<T> & other) const;
+
+ //! Returns the distance between this vector and another vector.
+ T distance(const Vector2<T> & other) const;
+
+ //! Returns the squared distance between this vector and another vector.
+ T distance_squared(const Vector2<T> & other) const;
+
+ //! Returns the perpendicular vector to this vector.
+ Vector2 perpendicular() const;
+};
+
+} // namespace crepe
+
+#include "Vector2.hpp"
diff --git a/src/crepe/api/Vector2.hpp b/src/crepe/api/Vector2.hpp
new file mode 100644
index 0000000..ff53cb0
--- /dev/null
+++ b/src/crepe/api/Vector2.hpp
@@ -0,0 +1,166 @@
+#pragma once
+
+#include <cmath>
+
+#include "Vector2.h"
+
+namespace crepe {
+
+template <class T>
+Vector2<T> Vector2<T>::operator-(const Vector2<T> & other) const {
+ return {x - other.x, y - other.y};
+}
+
+template <class T>
+Vector2<T> Vector2<T>::operator-(T scalar) const {
+ return {x - scalar, y - scalar};
+}
+
+template <class T>
+Vector2<T> Vector2<T>::operator+(const Vector2<T> & other) const {
+ return {x + other.x, y + other.y};
+}
+
+template <class T>
+Vector2<T> Vector2<T>::operator+(T scalar) const {
+ return {x + scalar, y + scalar};
+}
+
+template <class T>
+Vector2<T> Vector2<T>::operator*(const Vector2<T> & other) const {
+ return {x * other.x, y * other.y};
+}
+
+template <class T>
+Vector2<T> Vector2<T>::operator*(T scalar) const {
+ return {x * scalar, y * scalar};
+}
+
+template <class T>
+Vector2<T> Vector2<T>::operator/(const Vector2<T> & other) const {
+ return {x / other.x, y / other.y};
+}
+
+template <class T>
+Vector2<T> Vector2<T>::operator/(T scalar) const {
+ return {x / scalar, y / scalar};
+}
+
+template <class T>
+Vector2<T> & Vector2<T>::operator+=(const Vector2<T> & other) {
+ x += other.x;
+ y += other.y;
+ return *this;
+}
+
+template <class T>
+Vector2<T> & Vector2<T>::operator+=(T other) {
+ x += other;
+ y += other;
+ return *this;
+}
+
+template <class T>
+Vector2<T> & Vector2<T>::operator-=(const Vector2<T> & other) {
+ x -= other.x;
+ y -= other.y;
+ return *this;
+}
+
+template <class T>
+Vector2<T> & Vector2<T>::operator-=(T other) {
+ x -= other;
+ y -= other;
+ return *this;
+}
+
+template <class T>
+Vector2<T> & Vector2<T>::operator*=(const Vector2<T> & other) {
+ x *= other.x;
+ y *= other.y;
+ return *this;
+}
+
+template <class T>
+Vector2<T> & Vector2<T>::operator*=(T other) {
+ x *= other;
+ y *= other;
+ return *this;
+}
+
+template <class T>
+Vector2<T> & Vector2<T>::operator/=(const Vector2<T> & other) {
+ x /= other.x;
+ y /= other.y;
+ return *this;
+}
+
+template <class T>
+Vector2<T> & Vector2<T>::operator/=(T other) {
+ x /= other;
+ y /= other;
+ return *this;
+}
+
+template <class T>
+Vector2<T> Vector2<T>::operator-() const {
+ return {-x, -y};
+}
+
+template <class T>
+bool Vector2<T>::operator==(const Vector2<T> & other) const {
+ return x == other.x && y == other.y;
+}
+
+template <class T>
+bool Vector2<T>::operator!=(const Vector2<T> & other) const {
+ return !(*this == other);
+}
+
+template <class T>
+void Vector2<T>::truncate(T max) {
+ if (length() > max) {
+ normalize();
+ *this *= max;
+ }
+}
+
+template <class T>
+void Vector2<T>::normalize() {
+ T len = length();
+ if (len > 0) {
+ *this /= len;
+ }
+}
+
+template <class T>
+T Vector2<T>::length() const {
+ return std::sqrt(x * x + y * y);
+}
+
+template <class T>
+T Vector2<T>::length_squared() const {
+ return x * x + y * y;
+}
+
+template <class T>
+T Vector2<T>::dot(const Vector2<T> & other) const {
+ return x * other.x + y * other.y;
+}
+
+template <class T>
+T Vector2<T>::distance(const Vector2<T> & other) const {
+ return (*this - other).length();
+}
+
+template <class T>
+T Vector2<T>::distance_squared(const Vector2<T> & other) const {
+ return (*this - other).length_squared();
+}
+
+template <class T>
+Vector2<T> Vector2<T>::perpendicular() const {
+ return {-y, x};
+}
+
+} // namespace crepe
diff --git a/src/crepe/facade/CMakeLists.txt b/src/crepe/facade/CMakeLists.txt
new file mode 100644
index 0000000..243ae46
--- /dev/null
+++ b/src/crepe/facade/CMakeLists.txt
@@ -0,0 +1,20 @@
+target_sources(crepe PUBLIC
+ Sound.cpp
+ Texture.cpp
+ SoundContext.cpp
+ SDLContext.cpp
+ DB.cpp
+ FontFacade.cpp
+ Font.cpp
+)
+
+target_sources(crepe PUBLIC FILE_SET HEADERS FILES
+ Sound.h
+ Texture.h
+ SoundContext.h
+ SDLContext.h
+ DB.h
+ FontFacade.h
+ Font.h
+)
+
diff --git a/src/crepe/facade/DB.cpp b/src/crepe/facade/DB.cpp
new file mode 100644
index 0000000..7a3e473
--- /dev/null
+++ b/src/crepe/facade/DB.cpp
@@ -0,0 +1,61 @@
+#include <cstring>
+
+#include "util/dbg.h"
+
+#include "DB.h"
+
+using namespace std;
+using namespace crepe;
+
+DB::DB(const string & path) {
+ dbg_trace();
+ int ret;
+
+ // init database struct
+ libdb::DB * db;
+ if ((ret = libdb::db_create(&db, NULL, 0)) != 0)
+ throw runtime_error(format("db_create: {}", libdb::db_strerror(ret)));
+ this->db = {db, [](libdb::DB * db) { db->close(db, 0); }};
+
+ // load or create database file
+ const char * file = path.empty() ? NULL : path.c_str();
+ ret = this->db->open(this->db.get(), NULL, file, NULL, libdb::DB_BTREE, DB_CREATE, 0);
+ if (ret != 0) throw runtime_error(format("db->open: {}", libdb::db_strerror(ret)));
+}
+
+libdb::DBT DB::to_thing(const string & thing) const noexcept {
+ libdb::DBT thang;
+ memset(&thang, 0, sizeof(libdb::DBT));
+ thang.data = (void *) thing.data();
+ thang.size = thing.size();
+ return thang;
+}
+
+string DB::get(const string & key) {
+ libdb::DBT db_key = this->to_thing(key);
+ libdb::DBT db_val;
+ memset(&db_val, 0, sizeof(libdb::DBT));
+
+ int ret = this->db->get(this->db.get(), NULL, &db_key, &db_val, 0);
+ if (ret == 0) return {static_cast<char *>(db_val.data), db_val.size};
+
+ string err = format("db->get: {}", libdb::db_strerror(ret));
+ if (ret == DB_NOTFOUND) throw out_of_range(err);
+ else throw runtime_error(err);
+}
+
+void DB::set(const string & key, const string & value) {
+ libdb::DBT db_key = this->to_thing(key);
+ libdb::DBT db_val = this->to_thing(value);
+ int ret = this->db->put(this->db.get(), NULL, &db_key, &db_val, 0);
+ if (ret != 0) throw runtime_error(format("db->get: {}", libdb::db_strerror(ret)));
+}
+
+bool DB::has(const std::string & key) {
+ try {
+ this->get(key);
+ } catch (std::out_of_range &) {
+ return false;
+ }
+ return true;
+}
diff --git a/src/crepe/facade/DB.h b/src/crepe/facade/DB.h
new file mode 100644
index 0000000..84cdf19
--- /dev/null
+++ b/src/crepe/facade/DB.h
@@ -0,0 +1,75 @@
+#pragma once
+
+#include <functional>
+#include <memory>
+#include <string>
+
+namespace libdb {
+extern "C" {
+#include <db.h>
+}
+} // namespace libdb
+
+namespace crepe {
+
+/**
+ * \brief Berkeley DB facade
+ *
+ * Berkeley DB is a simple key-value database that stores arbitrary data as both key and value.
+ * This facade uses STL strings as keys/values.
+ */
+class DB {
+public:
+ /**
+ * \param path The path of the database (created if nonexistant)
+ *
+ * \note If \p path is empty, the database is entirely in-memory
+ */
+ DB(const std::string & path = "");
+ virtual ~DB() = default;
+
+public:
+ /**
+ * \brief Get a value from the database, or throw an exception
+ *
+ * \param key The value key
+ *
+ * \return The value
+ *
+ * \throws std::out_of_range if value is not found in DB
+ * \throws std::runtime_error if other error occurs
+ */
+ std::string get(const std::string & key);
+ /**
+ * \brief Set (create or overwrite) a value in the database
+ *
+ * \param key The value key
+ * \param value The value to store
+ *
+ * \throws std::runtime_error if an error occurs
+ */
+ void set(const std::string & key, const std::string & value);
+ /**
+ * \brief Check if a key exists in the database
+ *
+ * \param key The value key
+ *
+ * \returns True if the key exists, or false if it does not
+ */
+ bool has(const std::string & key);
+
+private:
+ //! RAII wrapper around \c DB struct
+ std::unique_ptr<libdb::DB, std::function<void(libdb::DB *)>> db;
+
+private:
+ /**
+ * \brief Convert an STL string to DBT (data base thang)
+ *
+ * \param thing Input data
+ * \return \c DBT with the same data as input \c thing
+ */
+ libdb::DBT to_thing(const std::string & thing) const noexcept;
+};
+
+} // namespace crepe
diff --git a/src/crepe/facade/EventData.h b/src/crepe/facade/EventData.h
new file mode 100644
index 0000000..a7526b4
--- /dev/null
+++ b/src/crepe/facade/EventData.h
@@ -0,0 +1,54 @@
+#pragma once
+#include "../api/KeyCodes.h"
+#include "../types.h"
+namespace crepe {
+//! EventType enum for passing eventType
+enum EventType {
+ NONE = 0,
+ MOUSE_DOWN,
+ MOUSE_UP,
+ MOUSE_MOVE,
+ MOUSE_WHEEL,
+ KEY_UP,
+ KEY_DOWN,
+ SHUTDOWN,
+ WINDOW_MINIMIZE,
+ WINDOW_MAXIMIZE,
+ WINDOW_FOCUS_GAIN,
+ WINDOW_FOCUS_LOST,
+ WINDOW_MOVE,
+ WINDOW_RESIZE,
+ WINDOW_EXPOSE,
+};
+
+//! Struct for storing key data.
+struct KeyData {
+ Keycode key = Keycode::NONE;
+ bool key_repeat = false;
+};
+
+//! Struct for storing mouse data.
+struct MouseData {
+ MouseButton mouse_button = MouseButton::NONE;
+ ivec2 mouse_position = {-1, -1};
+ int scroll_direction = -1;
+ float scroll_delta = INFINITY;
+ ivec2 rel_mouse_move = {-1, -1};
+};
+
+//! Struct for storing window data.
+struct WindowData {
+ ivec2 move_delta;
+ ivec2 resize_dimension;
+};
+
+//! EventData struct for passing event data from facade
+struct EventData {
+ EventType event_type = EventType::NONE;
+ union {
+ KeyData key_data;
+ MouseData mouse_data;
+ WindowData window_data;
+ } data;
+};
+} // namespace crepe
diff --git a/src/crepe/facade/Font.cpp b/src/crepe/facade/Font.cpp
new file mode 100644
index 0000000..771002f
--- /dev/null
+++ b/src/crepe/facade/Font.cpp
@@ -0,0 +1,21 @@
+#include <SDL2/SDL_ttf.h>
+
+#include "../api/Asset.h"
+#include "../api/Config.h"
+
+#include "Font.h"
+
+using namespace std;
+using namespace crepe;
+
+Font::Font(const Asset & src, Mediator & mediator) : Resource(src, mediator) {
+ const Config & config = Config::get_instance();
+ const std::string FONT_PATH = src.get_path();
+ TTF_Font * loaded_font = TTF_OpenFont(FONT_PATH.c_str(), config.font.size);
+ if (loaded_font == NULL) {
+ throw runtime_error(format("Font: {} (path: {})", TTF_GetError(), FONT_PATH));
+ }
+ this->font = {loaded_font, [](TTF_Font * close_font) { TTF_CloseFont(close_font); }};
+}
+
+TTF_Font * Font::get_font() const { return this->font.get(); }
diff --git a/src/crepe/facade/Font.h b/src/crepe/facade/Font.h
new file mode 100644
index 0000000..b208d96
--- /dev/null
+++ b/src/crepe/facade/Font.h
@@ -0,0 +1,42 @@
+#pragma once
+
+#include <SDL2/SDL_ttf.h>
+#include <memory>
+
+#include "../Resource.h"
+#include "../api/Config.h"
+
+namespace crepe {
+
+class Asset;
+/**
+ * \brief Resource for managing font creation and destruction
+ *
+ * This class is a wrapper around an SDL_ttf font instance, encapsulating font loading and usage.
+ * It loads a font from an Asset and manages its lifecycle. The font is automatically unloaded
+ * when this object is destroyed.
+ */
+class Font : public Resource {
+
+public:
+ /**
+ * \param src The Asset containing the font file path and metadata to load the font.
+ * \param mediator The Mediator object used for managing the SDL context or related systems.
+ */
+ Font(const Asset & src, Mediator & mediator);
+ /**
+ * \brief Gets the underlying TTF_Font resource.
+ *
+ * This function returns the raw pointer to the SDL_ttf TTF_Font object that represents
+ * the loaded font. This can be used with SDL_ttf functions to render text.
+ *
+ * \return The raw TTF_Font object wrapped in a unique pointer.
+ */
+ TTF_Font * get_font() const;
+
+private:
+ //! The SDL_ttf font object with custom deleter.
+ std::unique_ptr<TTF_Font, std::function<void(TTF_Font *)>> font = nullptr;
+};
+
+} // namespace crepe
diff --git a/src/crepe/facade/FontFacade.cpp b/src/crepe/facade/FontFacade.cpp
new file mode 100644
index 0000000..87f95ab
--- /dev/null
+++ b/src/crepe/facade/FontFacade.cpp
@@ -0,0 +1,43 @@
+#include <fontconfig/fontconfig.h>
+#include <functional>
+#include <memory>
+#include <stdexcept>
+#include <string>
+
+#include "FontFacade.h"
+
+using namespace std;
+using namespace crepe;
+
+FontFacade::FontFacade() {
+ if (!FcInit()) throw runtime_error("Failed to initialize Fontconfig.");
+}
+
+FontFacade::~FontFacade() { FcFini(); }
+
+Asset FontFacade::get_font_asset(const string & font_family) {
+ FcPattern * raw_pattern
+ = FcNameParse(reinterpret_cast<const FcChar8 *>(font_family.c_str()));
+ if (raw_pattern == NULL) throw runtime_error("Failed to create font pattern.");
+
+ unique_ptr<FcPattern, function<void(FcPattern *)>> pattern{
+ raw_pattern, [](FcPattern * p) { FcPatternDestroy(p); }};
+
+ FcConfig * config = FcConfigGetCurrent();
+ if (config == NULL) throw runtime_error("Failed to get current Fontconfig configuration.");
+
+ FcResult result;
+ FcPattern * raw_matched_pattern = FcFontMatch(config, pattern.get(), &result);
+ if (raw_matched_pattern == NULL) throw runtime_error("No matching font found.");
+
+ unique_ptr<FcPattern, function<void(FcPattern *)>> matched_pattern
+ = {raw_matched_pattern, [](FcPattern * p) { FcPatternDestroy(p); }};
+
+ FcChar8 * file_path = nullptr;
+ FcResult res = FcPatternGetString(matched_pattern.get(), FC_FILE, 0, &file_path);
+ if (res != FcResultMatch || file_path == NULL)
+ throw runtime_error("Failed to get font file path.");
+
+ string font_file_path = reinterpret_cast<const char *>(file_path);
+ return Asset(font_file_path);
+}
diff --git a/src/crepe/facade/FontFacade.h b/src/crepe/facade/FontFacade.h
new file mode 100644
index 0000000..9761070
--- /dev/null
+++ b/src/crepe/facade/FontFacade.h
@@ -0,0 +1,34 @@
+#pragma once
+
+#include <memory>
+
+#include "../api/Asset.h"
+
+namespace crepe {
+
+/**
+ *
+ * \brief Font facade class for converting font family names to absolute file paths
+ *
+ */
+class FontFacade {
+public:
+ FontFacade();
+ ~FontFacade();
+ FontFacade(const FontFacade & other) = delete;
+ FontFacade & operator=(const FontFacade & other) = delete;
+ FontFacade(FontFacade && other) noexcept = delete;
+ FontFacade & operator=(FontFacade && other) noexcept = delete;
+ /**
+ *
+ * \brief Facade function to convert a font_family into an asset.
+ *
+ * This function uses the FontConfig library to convert a font family name (Arial, Inter, Helvetica) and converts it to the font source path.
+ * This function returns a default font path if the font_family name doesnt exist or cant be found
+ * \param font_family Name of the font family name.
+ * \return Asset with filepath to the corresponding font.
+ */
+ Asset get_font_asset(const std::string & font_family);
+};
+
+} // namespace crepe
diff --git a/src/crepe/facade/SDLContext.cpp b/src/crepe/facade/SDLContext.cpp
new file mode 100644
index 0000000..9486ccd
--- /dev/null
+++ b/src/crepe/facade/SDLContext.cpp
@@ -0,0 +1,419 @@
+#include <SDL2/SDL.h>
+#include <SDL2/SDL_blendmode.h>
+#include <SDL2/SDL_image.h>
+#include <SDL2/SDL_keycode.h>
+#include <SDL2/SDL_pixels.h>
+#include <SDL2/SDL_rect.h>
+#include <SDL2/SDL_render.h>
+#include <SDL2/SDL_surface.h>
+#include <SDL2/SDL_ttf.h>
+#include <SDL2/SDL_video.h>
+#include <array>
+#include <cmath>
+#include <cstddef>
+#include <cstdint>
+#include <functional>
+#include <memory>
+#include <stdexcept>
+
+#include "../api/Camera.h"
+#include "../api/Color.h"
+#include "../api/Config.h"
+#include "../api/Sprite.h"
+#include "../util/dbg.h"
+#include "manager/Mediator.h"
+
+#include "SDLContext.h"
+#include "Texture.h"
+#include "types.h"
+
+using namespace crepe;
+using namespace std;
+
+SDLContext::SDLContext(Mediator & mediator) {
+ dbg_trace();
+ if (TTF_Init() == -1) {
+ throw runtime_error(format("SDL_ttf initialization failed: {}", TTF_GetError()));
+ }
+ if (SDL_Init(SDL_INIT_VIDEO) != 0) {
+ throw runtime_error(format("SDLContext: SDL_Init error: {}", SDL_GetError()));
+ }
+
+ auto & cfg = Config::get_instance().window_settings;
+ SDL_Window * tmp_window
+ = SDL_CreateWindow(cfg.window_title.c_str(), SDL_WINDOWPOS_CENTERED,
+ SDL_WINDOWPOS_CENTERED, cfg.default_size.x, cfg.default_size.y, 0);
+ if (!tmp_window) {
+ throw runtime_error(format("SDLContext: SDL_Window error: {}", SDL_GetError()));
+ }
+ this->game_window = {tmp_window, [](SDL_Window * window) { SDL_DestroyWindow(window); }};
+
+ SDL_Renderer * tmp_renderer
+ = SDL_CreateRenderer(this->game_window.get(), -1, SDL_RENDERER_ACCELERATED);
+ if (!tmp_renderer) {
+ throw runtime_error(
+ format("SDLContext: SDL_CreateRenderer error: {}", SDL_GetError()));
+ }
+
+ this->game_renderer
+ = {tmp_renderer, [](SDL_Renderer * renderer) { SDL_DestroyRenderer(renderer); }};
+
+ int img_flags = IMG_INIT_PNG;
+ if (!(IMG_Init(img_flags) & img_flags)) {
+ throw runtime_error("SDLContext: SDL_image could not initialize!");
+ }
+
+ mediator.sdl_context = *this;
+}
+
+SDLContext::~SDLContext() {
+ dbg_trace();
+
+ this->game_renderer.reset();
+ this->game_window.reset();
+
+ // TODO: how are we going to ensure that these are called from the same
+ // thread that SDL_Init() was called on? This has caused problems for me
+ // before.
+ IMG_Quit();
+ TTF_Quit();
+ SDL_Quit();
+}
+
+Keycode SDLContext::sdl_to_keycode(SDL_Scancode sdl_key) {
+ if (!lookup_table.contains(sdl_key)) return Keycode::NONE;
+ return lookup_table.at(sdl_key);
+}
+
+const keyboard_state_t & SDLContext::get_keyboard_state() {
+ SDL_PumpEvents();
+ const Uint8 * current_state = SDL_GetKeyboardState(nullptr);
+
+ for (int i = 0; i < SDL_NUM_SCANCODES; ++i) {
+
+ Keycode key = sdl_to_keycode(static_cast<SDL_Scancode>(i));
+ if (key != Keycode::NONE) {
+ this->keyboard_state[key] = current_state[i] != 0;
+ }
+ }
+ return this->keyboard_state;
+}
+
+MouseButton SDLContext::sdl_to_mousebutton(Uint8 sdl_button) {
+ static const std::array<MouseButton, 5> MOUSE_BUTTON_LOOKUP_TABLE = [] {
+ std::array<MouseButton, 5> table{};
+ table.fill(MouseButton::NONE);
+
+ table[SDL_BUTTON_LEFT] = MouseButton::LEFT_MOUSE;
+ table[SDL_BUTTON_RIGHT] = MouseButton::RIGHT_MOUSE;
+ table[SDL_BUTTON_MIDDLE] = MouseButton::MIDDLE_MOUSE;
+ table[SDL_BUTTON_X1] = MouseButton::X1_MOUSE;
+ table[SDL_BUTTON_X2] = MouseButton::X2_MOUSE;
+
+ return table;
+ }();
+
+ if (sdl_button >= MOUSE_BUTTON_LOOKUP_TABLE.size()) {
+ // Return NONE for invalid or unmapped button
+ return MouseButton::NONE;
+ }
+
+ return MOUSE_BUTTON_LOOKUP_TABLE[sdl_button];
+}
+
+void SDLContext::clear_screen() { SDL_RenderClear(this->game_renderer.get()); }
+void SDLContext::present_screen() {
+ SDL_SetRenderDrawColor(this->game_renderer.get(), 0, 0, 0, 255);
+ SDL_RenderFillRectF(this->game_renderer.get(), &black_bars[0]);
+ SDL_RenderFillRectF(this->game_renderer.get(), &black_bars[1]);
+ SDL_RenderPresent(this->game_renderer.get());
+}
+
+SDL_FRect SDLContext::get_dst_rect(const DestinationRectangleData & ctx) const {
+
+ const Sprite::Data & data = ctx.sprite.data;
+
+ float aspect_ratio
+ = (ctx.sprite.aspect_ratio == 0) ? ctx.texture.get_ratio() : ctx.sprite.aspect_ratio;
+
+ vec2 size = data.size;
+ if (data.size.x == 0 && data.size.y != 0) {
+ size.x = data.size.y * aspect_ratio;
+ }
+ if (data.size.y == 0 && data.size.x != 0) {
+ size.y = data.size.x / aspect_ratio;
+ }
+ size *= cam_aux_data.render_scale * ctx.img_scale * data.scale_offset;
+
+ vec2 screen_pos = (ctx.pos + data.position_offset - cam_aux_data.cam_pos
+ + (cam_aux_data.zoomed_viewport) / 2)
+ * cam_aux_data.render_scale
+ - size / 2 + cam_aux_data.bar_size;
+
+ return SDL_FRect{
+ .x = screen_pos.x,
+ .y = screen_pos.y,
+ .w = size.x,
+ .h = size.y,
+ };
+}
+
+void SDLContext::draw(const RenderContext & ctx) {
+ const Sprite::Data & data = ctx.sprite.data;
+ SDL_RendererFlip render_flip
+ = (SDL_RendererFlip) ((SDL_FLIP_HORIZONTAL * data.flip.flip_x)
+ | (SDL_FLIP_VERTICAL * data.flip.flip_y));
+
+ SDL_Rect srcrect;
+ SDL_Rect * srcrect_ptr = NULL;
+ if (ctx.sprite.mask.w != 0 || ctx.sprite.mask.h != 0) {
+ srcrect.w = ctx.sprite.mask.w;
+ srcrect.h = ctx.sprite.mask.h;
+ srcrect.x = ctx.sprite.mask.x;
+ srcrect.y = ctx.sprite.mask.y;
+ srcrect_ptr = &srcrect;
+ }
+
+ SDL_FRect dstrect = this->get_dst_rect(SDLContext::DestinationRectangleData{
+ .sprite = ctx.sprite,
+ .texture = ctx.texture,
+ .pos = ctx.pos,
+ .img_scale = ctx.scale,
+ });
+
+ double angle = ctx.angle + data.angle_offset;
+
+ this->set_color_texture(ctx.texture, ctx.sprite.data.color);
+ SDL_RenderCopyExF(this->game_renderer.get(), ctx.texture.get_img(), srcrect_ptr, &dstrect,
+ angle, NULL, render_flip);
+}
+
+void SDLContext::update_camera_view(const Camera & cam, const vec2 & new_pos) {
+
+ const Camera::Data & cam_data = cam.data;
+ // resize window
+ int w, h;
+ SDL_GetWindowSize(this->game_window.get(), &w, &h);
+ if (w != cam.screen.x || h != cam.screen.y) {
+ SDL_SetWindowSize(this->game_window.get(), cam.screen.x, cam.screen.y);
+ }
+
+ vec2 & zoomed_viewport = this->cam_aux_data.zoomed_viewport;
+ vec2 & bar_size = this->cam_aux_data.bar_size;
+ vec2 & render_scale = this->cam_aux_data.render_scale;
+ this->cam_aux_data.cam_pos = new_pos;
+
+ zoomed_viewport = cam.viewport_size * cam_data.zoom;
+ float screen_aspect = static_cast<float>(cam.screen.x) / cam.screen.y;
+ float viewport_aspect = zoomed_viewport.x / zoomed_viewport.y;
+
+ // calculate black bars
+ if (screen_aspect > viewport_aspect) {
+ // pillarboxing
+ float scale = cam.screen.y / zoomed_viewport.y;
+ float adj_width = zoomed_viewport.x * scale;
+ float bar_width = (cam.screen.x - adj_width) / 2;
+ this->black_bars[0] = {0, 0, bar_width, (float) cam.screen.y};
+ this->black_bars[1] = {(cam.screen.x - bar_width), 0, bar_width, (float) cam.screen.y};
+
+ bar_size = {bar_width, 0};
+ render_scale.x = render_scale.y = scale;
+ } else {
+ // letterboxing
+ float scale = cam.screen.x / (cam.viewport_size.x * cam_data.zoom);
+ float adj_height = cam.viewport_size.y * scale;
+ float bar_height = (cam.screen.y - adj_height) / 2;
+ this->black_bars[0] = {0, 0, (float) cam.screen.x, bar_height};
+ this->black_bars[1]
+ = {0, (cam.screen.y - bar_height), (float) cam.screen.x, bar_height};
+
+ bar_size = {0, bar_height};
+ render_scale.x = render_scale.y = scale;
+ }
+
+ SDL_SetRenderDrawColor(this->game_renderer.get(), cam_data.bg_color.r, cam_data.bg_color.g,
+ cam_data.bg_color.b, cam_data.bg_color.a);
+
+ SDL_Rect bg = {
+ .x = 0,
+ .y = 0,
+ .w = cam.screen.x,
+ .h = cam.screen.y,
+ };
+
+ // fill bg color
+ SDL_RenderFillRect(this->game_renderer.get(), &bg);
+}
+
+std::unique_ptr<SDL_Texture, std::function<void(SDL_Texture *)>>
+SDLContext::texture_from_path(const std::string & path) {
+
+ SDL_Surface * tmp = IMG_Load(path.c_str());
+ if (tmp == nullptr)
+ throw runtime_error(format("SDLContext: IMG_Load error: {}", SDL_GetError()));
+
+ std::unique_ptr<SDL_Surface, std::function<void(SDL_Surface *)>> img_surface;
+ img_surface = {tmp, [](SDL_Surface * surface) { SDL_FreeSurface(surface); }};
+
+ SDL_Texture * tmp_texture
+ = SDL_CreateTextureFromSurface(this->game_renderer.get(), img_surface.get());
+
+ if (tmp_texture == nullptr) {
+ throw runtime_error(format("SDLContext: Texture cannot be load from {}", path));
+ }
+
+ std::unique_ptr<SDL_Texture, std::function<void(SDL_Texture *)>> img_texture;
+ img_texture = {tmp_texture, [](SDL_Texture * texture) { SDL_DestroyTexture(texture); }};
+
+ SDL_SetTextureBlendMode(img_texture.get(), SDL_BLENDMODE_BLEND);
+ return img_texture;
+}
+
+ivec2 SDLContext::get_size(const Texture & ctx) {
+ ivec2 size;
+ SDL_QueryTexture(ctx.get_img(), NULL, NULL, &size.x, &size.y);
+ return size;
+}
+
+std::vector<EventData> SDLContext::get_events() {
+ std::vector<EventData> event_list;
+ SDL_Event event;
+ const CameraAuxiliaryData & cam = this->cam_aux_data;
+ while (SDL_PollEvent(&event)) {
+ ivec2 mouse_pos;
+ mouse_pos.x = (event.button.x - cam.bar_size.x) / cam.render_scale.x;
+ mouse_pos.y = (event.button.y - cam.bar_size.y) / cam.render_scale.y;
+ switch (event.type) {
+ case SDL_QUIT:
+ event_list.push_back({.event_type = EventType::SHUTDOWN});
+ break;
+ case SDL_KEYDOWN:
+ event_list.push_back(EventData{
+ .event_type = EventType::KEY_DOWN,
+ .data = {
+ .key_data = {
+ .key = this->sdl_to_keycode(event.key.keysym.scancode),
+ .key_repeat = event.key.repeat != 0,
+ },
+ },
+ });
+ break;
+
+ case SDL_KEYUP:
+ event_list.push_back(EventData{
+ .event_type = EventType::KEY_UP,
+ .data = {
+ .key_data = {
+ .key = this->sdl_to_keycode(event.key.keysym.scancode),
+ .key_repeat = event.key.repeat != 0,
+ },
+ },
+ });
+ break;
+
+ case SDL_MOUSEBUTTONDOWN:
+ event_list.push_back(EventData{
+ .event_type = EventType::MOUSE_DOWN,
+ .data = {
+ .mouse_data = {
+ .mouse_button = this->sdl_to_mousebutton(event.button.button),
+ .mouse_position = mouse_pos,
+ },
+ },
+ });
+ break;
+ case SDL_MOUSEBUTTONUP:
+ event_list.push_back(EventData{
+ .event_type = EventType::MOUSE_UP,
+ .data = {
+ .mouse_data = {
+ .mouse_button = this->sdl_to_mousebutton(event.button.button),
+ .mouse_position = mouse_pos,
+ },
+ },
+ });
+ break;
+
+ case SDL_MOUSEMOTION:
+ event_list.push_back(EventData{
+ .event_type = EventType::MOUSE_MOVE,
+ .data = {
+ .mouse_data = {
+ .mouse_position = mouse_pos,
+ .rel_mouse_move = {event.motion.xrel, event.motion.yrel},
+ },
+ },
+ });
+ break;
+
+ case SDL_MOUSEWHEEL:
+ event_list.push_back(EventData{
+ .event_type = EventType::MOUSE_WHEEL,
+ .data = {
+ .mouse_data = {
+ .mouse_position = mouse_pos,
+ .scroll_direction = event.wheel.y < 0 ? -1 : 1,
+ .scroll_delta = event.wheel.preciseY,
+ },
+ },
+ });
+ break;
+ case SDL_WINDOWEVENT:
+ this->handle_window_event(event.window, event_list);
+ break;
+ }
+ }
+
+ return event_list;
+}
+
+void SDLContext::handle_window_event(const SDL_WindowEvent & window_event,
+ std::vector<EventData> & event_list) {
+ switch (window_event.event) {
+ case SDL_WINDOWEVENT_EXPOSED:
+ event_list.push_back(EventData{EventType::WINDOW_EXPOSE});
+ break;
+ case SDL_WINDOWEVENT_RESIZED:
+ event_list.push_back(EventData{
+ .event_type = EventType::WINDOW_RESIZE,
+ .data = {
+ .window_data = {
+ .resize_dimension = {window_event.data1, window_event.data2}
+ },
+ },
+ });
+ break;
+ case SDL_WINDOWEVENT_MOVED:
+ event_list.push_back(EventData{
+ .event_type = EventType::WINDOW_MOVE,
+ .data = {
+ .window_data = {
+ .move_delta = {window_event.data1, window_event.data2}
+ },
+ },
+ });
+ break;
+
+ case SDL_WINDOWEVENT_MINIMIZED:
+ event_list.push_back(EventData{EventType::WINDOW_MINIMIZE});
+ break;
+ case SDL_WINDOWEVENT_MAXIMIZED:
+ event_list.push_back(EventData{EventType::WINDOW_MAXIMIZE});
+ break;
+ case SDL_WINDOWEVENT_FOCUS_GAINED:
+ event_list.push_back(EventData{EventType::WINDOW_FOCUS_GAIN});
+ break;
+ case SDL_WINDOWEVENT_FOCUS_LOST:
+ event_list.push_back(EventData{EventType::WINDOW_FOCUS_LOST});
+ break;
+ }
+}
+
+void SDLContext::set_color_texture(const Texture & texture, const Color & color) {
+ SDL_SetTextureColorMod(texture.get_img(), color.r, color.g, color.b);
+ SDL_SetTextureAlphaMod(texture.get_img(), color.a);
+}
+
+Asset SDLContext::get_font_from_name(const std::string & font_family) {
+ return this->font_facade.get_font_asset(font_family);
+}
diff --git a/src/crepe/facade/SDLContext.h b/src/crepe/facade/SDLContext.h
new file mode 100644
index 0000000..b687f87
--- /dev/null
+++ b/src/crepe/facade/SDLContext.h
@@ -0,0 +1,365 @@
+#pragma once
+
+#include <SDL2/SDL.h>
+#include <SDL2/SDL_keycode.h>
+#include <SDL2/SDL_rect.h>
+#include <SDL2/SDL_render.h>
+#include <SDL2/SDL_video.h>
+#include <cmath>
+#include <functional>
+#include <memory>
+#include <string>
+#include <unordered_map>
+
+#include "../types.h"
+#include "api/Camera.h"
+#include "api/Color.h"
+#include "api/KeyCodes.h"
+#include "api/Sprite.h"
+#include "api/Transform.h"
+#include "types.h"
+
+#include "EventData.h"
+#include "FontFacade.h"
+
+namespace crepe {
+class Texture;
+class Mediator;
+
+/**
+ * \brief Facade for the SDL library
+ *
+ * SDLContext is a singleton that handles the SDL window and renderer, provides methods for
+ * event handling, and rendering to the screen. It is never used directly by the user
+ */
+class SDLContext {
+public:
+ //! data that the camera component cannot hold
+ struct CameraAuxiliaryData {
+
+ //! zoomed in viewport in game_units
+ vec2 zoomed_viewport;
+
+ /**
+ * \brief scaling factor
+ *
+ * depending on the black bars type will the scaling be different.
+ * - letterboxing --> scaling on the y-as
+ * - pillarboxing --> scaling on the x-as
+ */
+ vec2 render_scale;
+
+ /**
+ * \brief size of calculated black bars
+ *
+ * depending on the black bars type will the size be different
+ * - lettorboxing --> {0, bar_height}
+ * - pillarboxing --> {bar_width , 0}
+ */
+ vec2 bar_size;
+
+ //! Calculated camera position
+ vec2 cam_pos;
+ };
+
+ //! rendering data needed to render on screen
+ struct RenderContext {
+ const Sprite & sprite;
+ const Texture & texture;
+ const vec2 & pos;
+ const double & angle;
+ const double & scale;
+ };
+
+public:
+ /**
+ * \brief Gets the singleton instance of SDLContext.
+ * \return Reference to the SDLContext instance.
+ */
+ static SDLContext & get_instance();
+
+public:
+ SDLContext(const SDLContext &) = delete;
+ SDLContext(SDLContext &&) = delete;
+ SDLContext & operator=(const SDLContext &) = delete;
+ SDLContext & operator=(SDLContext &&) = delete;
+
+public:
+ /**
+ * \brief Constructs an SDLContext instance.
+ * Initializes SDL, creates a window and renderer.
+ */
+ SDLContext(Mediator & mediator);
+
+ /**
+ * \brief Destroys the SDLContext instance.
+ * Cleans up SDL resources, including the window and renderer.
+ */
+ ~SDLContext();
+
+public:
+ /**
+ * \brief Retrieves a list of all events from the SDL context.
+ *
+ * This method retrieves all the events from the SDL context that are currently
+ * available. It is primarily used by the InputSystem to process various
+ * input events such as mouse clicks, mouse movements, and keyboard presses.
+ *
+ * \return Events that occurred since last call to `get_events()`
+ */
+ std::vector<EventData> get_events();
+ /**
+ * \brief Fills event_list with triggered window events
+ *
+ * This method checks if any window events are triggered and adds them to the event_list.
+ *
+ */
+ void handle_window_event(const SDL_WindowEvent & window_event,
+ std::vector<EventData> & event_list);
+ /**
+ * \brief Converts an SDL scan code to the custom Keycode type.
+ *
+ * This method maps an SDL scan code to the corresponding `Keycode` enum value,
+ * which is used internally by the system to identify the keys.
+ *
+ * \param sdl_key The SDL scan code to convert.
+ * \return The corresponding `Keycode` value or `Keycode::NONE` if the key is unrecognized.
+ */
+ Keycode sdl_to_keycode(SDL_Scancode sdl_key);
+
+ /**
+ * \brief Converts an SDL mouse button code to the custom MouseButton type.
+ *
+ * This method maps an SDL mouse button code to the corresponding `MouseButton`
+ * enum value, which is used internally by the system to identify mouse buttons.
+ *
+ * \param sdl_button The SDL mouse button code to convert.
+ * \return The corresponding `MouseButton` value or `MouseButton::NONE` if the key is unrecognized
+ */
+ MouseButton sdl_to_mousebutton(Uint8 sdl_button);
+ /**
+ * \brief Gets the current state of the keyboard.
+ *
+ * Updates the internal keyboard state by checking the current key states using
+ * SDL's `SDL_GetKeyboardState()`, and returns a reference to the `keyboard_state_t`.
+ *
+ * \return A constant reference to the `keyboard_state_t`, which holds the state
+ * of each key (true = pressed, false = not pressed).
+ */
+ const keyboard_state_t & get_keyboard_state();
+
+public:
+ /**
+ * \brief Gets the current SDL ticks since the program started.
+ * \return Current ticks in milliseconds as a constant uint64_t.
+ */
+ uint64_t get_ticks() const;
+ /**
+ * \brief Pauses the execution for a specified duration.
+ *
+ * This function uses SDL's delay function to halt the program execution for a given number
+ * of milliseconds, allowing for frame rate control or other timing-related functionality.
+ *
+ * \param ms Duration of the delay in milliseconds.
+ */
+ void delay(int ms) const;
+
+public:
+ /**
+ * \brief Loads a texture from a file path.
+ * \param path Path to the image file.
+ * \return Pointer to the created SDL_Texture.
+ */
+ std::unique_ptr<SDL_Texture, std::function<void(SDL_Texture *)>>
+ texture_from_path(const std::string & path);
+ /**
+ * \brief Gets the size of a texture.
+ * \param texture Reference to the Texture object.
+ * \return Width and height of the texture as an integer in pixels.
+ */
+ ivec2 get_size(const Texture & ctx);
+
+public:
+ /**
+ * \brief Draws a sprite to the screen using the specified transform and camera.
+ * \param RenderContext Reference to rendering data to draw
+ */
+ void draw(const RenderContext & ctx);
+
+ //! Clears the screen, preparing for a new frame.
+ void clear_screen();
+
+ //! Presents the rendered frame to the screen.
+ void present_screen();
+
+ /**
+ * \brief calculates camera view settings. such as black_bars, zoomed_viewport, scaling and
+ * adjusting window size.
+ *
+ * \note only supports windowed mode.
+ * \param camera Reference to the current Camera object in the scene.
+ * \param new_pos new camera position from transform and offset
+ */
+ void update_camera_view(const Camera & camera, const vec2 & new_pos);
+
+public:
+ //! the data needed to construct a sdl dst rectangle
+ struct DestinationRectangleData {
+ const Sprite & sprite;
+ const Texture & texture;
+ const vec2 & pos;
+ const double & img_scale;
+ };
+
+ /**
+ * \brief calculates the sqaure size of the image for destination
+ *
+ * \param data needed to calculate a destination rectangle
+ * \return sdl rectangle to draw a dst image to draw on the screen
+ */
+ SDL_FRect get_dst_rect(const DestinationRectangleData & data) const;
+ /**
+ * \brief Set an additional color value multiplied into render copy operations.
+ *
+ * \param texture the given texture to adjust
+ * \param color the color data for the texture
+ */
+ void set_color_texture(const Texture & texture, const Color & color);
+
+private:
+ //! sdl Window
+ std::unique_ptr<SDL_Window, std::function<void(SDL_Window *)>> game_window;
+
+ //! renderer for the crepe engine
+ std::unique_ptr<SDL_Renderer, std::function<void(SDL_Renderer *)>> game_renderer;
+
+ //! black bars rectangle to draw
+ SDL_FRect black_bars[2] = {};
+
+ /**
+ * \cam_aux_data extra data that the component cannot hold.
+ *
+ * - this is defined in this class because get_events() needs this information aswell
+ */
+ CameraAuxiliaryData cam_aux_data;
+
+private:
+ //! instance of the font_facade
+ FontFacade font_facade{};
+
+public:
+ /**
+ * \brief Function to Get asset from font_family
+ *
+ * This function uses the FontFacade function to convert a font_family to an asset.
+ *
+ * \param font_family name of the font style that needs to be used (will return an asset with default font path of the font_family doesnt exist)
+ *
+ * \return asset with the font style absolute path
+ */
+ Asset get_font_from_name(const std::string & font_family);
+ //! variable to store the state of each key (true = pressed, false = not pressed)
+ keyboard_state_t keyboard_state;
+ //! lookup table for converting SDL_SCANCODES to Keycodes
+ const std::unordered_map<SDL_Scancode, Keycode> lookup_table
+ = {{SDL_SCANCODE_SPACE, Keycode::SPACE},
+ {SDL_SCANCODE_APOSTROPHE, Keycode::APOSTROPHE},
+ {SDL_SCANCODE_COMMA, Keycode::COMMA},
+ {SDL_SCANCODE_MINUS, Keycode::MINUS},
+ {SDL_SCANCODE_PERIOD, Keycode::PERIOD},
+ {SDL_SCANCODE_SLASH, Keycode::SLASH},
+ {SDL_SCANCODE_0, Keycode::D0},
+ {SDL_SCANCODE_1, Keycode::D1},
+ {SDL_SCANCODE_2, Keycode::D2},
+ {SDL_SCANCODE_3, Keycode::D3},
+ {SDL_SCANCODE_4, Keycode::D4},
+ {SDL_SCANCODE_5, Keycode::D5},
+ {SDL_SCANCODE_6, Keycode::D6},
+ {SDL_SCANCODE_7, Keycode::D7},
+ {SDL_SCANCODE_8, Keycode::D8},
+ {SDL_SCANCODE_9, Keycode::D9},
+ {SDL_SCANCODE_SEMICOLON, Keycode::SEMICOLON},
+ {SDL_SCANCODE_EQUALS, Keycode::EQUAL},
+ {SDL_SCANCODE_A, Keycode::A},
+ {SDL_SCANCODE_B, Keycode::B},
+ {SDL_SCANCODE_C, Keycode::C},
+ {SDL_SCANCODE_D, Keycode::D},
+ {SDL_SCANCODE_E, Keycode::E},
+ {SDL_SCANCODE_F, Keycode::F},
+ {SDL_SCANCODE_G, Keycode::G},
+ {SDL_SCANCODE_H, Keycode::H},
+ {SDL_SCANCODE_I, Keycode::I},
+ {SDL_SCANCODE_J, Keycode::J},
+ {SDL_SCANCODE_K, Keycode::K},
+ {SDL_SCANCODE_L, Keycode::L},
+ {SDL_SCANCODE_M, Keycode::M},
+ {SDL_SCANCODE_N, Keycode::N},
+ {SDL_SCANCODE_O, Keycode::O},
+ {SDL_SCANCODE_P, Keycode::P},
+ {SDL_SCANCODE_Q, Keycode::Q},
+ {SDL_SCANCODE_R, Keycode::R},
+ {SDL_SCANCODE_S, Keycode::S},
+ {SDL_SCANCODE_T, Keycode::T},
+ {SDL_SCANCODE_U, Keycode::U},
+ {SDL_SCANCODE_V, Keycode::V},
+ {SDL_SCANCODE_W, Keycode::W},
+ {SDL_SCANCODE_X, Keycode::X},
+ {SDL_SCANCODE_Y, Keycode::Y},
+ {SDL_SCANCODE_Z, Keycode::Z},
+ {SDL_SCANCODE_LEFTBRACKET, Keycode::LEFT_BRACKET},
+ {SDL_SCANCODE_BACKSLASH, Keycode::BACKSLASH},
+ {SDL_SCANCODE_RIGHTBRACKET, Keycode::RIGHT_BRACKET},
+ {SDL_SCANCODE_GRAVE, Keycode::GRAVE_ACCENT},
+ {SDL_SCANCODE_ESCAPE, Keycode::ESCAPE},
+ {SDL_SCANCODE_RETURN, Keycode::ENTER},
+ {SDL_SCANCODE_TAB, Keycode::TAB},
+ {SDL_SCANCODE_BACKSPACE, Keycode::BACKSPACE},
+ {SDL_SCANCODE_INSERT, Keycode::INSERT},
+ {SDL_SCANCODE_DELETE, Keycode::DELETE},
+ {SDL_SCANCODE_RIGHT, Keycode::RIGHT},
+ {SDL_SCANCODE_LEFT, Keycode::LEFT},
+ {SDL_SCANCODE_DOWN, Keycode::DOWN},
+ {SDL_SCANCODE_UP, Keycode::UP},
+ {SDL_SCANCODE_PAGEUP, Keycode::PAGE_UP},
+ {SDL_SCANCODE_PAGEDOWN, Keycode::PAGE_DOWN},
+ {SDL_SCANCODE_HOME, Keycode::HOME},
+ {SDL_SCANCODE_END, Keycode::END},
+ {SDL_SCANCODE_CAPSLOCK, Keycode::CAPS_LOCK},
+ {SDL_SCANCODE_SCROLLLOCK, Keycode::SCROLL_LOCK},
+ {SDL_SCANCODE_NUMLOCKCLEAR, Keycode::NUM_LOCK},
+ {SDL_SCANCODE_PRINTSCREEN, Keycode::PRINT_SCREEN},
+ {SDL_SCANCODE_PAUSE, Keycode::PAUSE},
+ {SDL_SCANCODE_F1, Keycode::F1},
+ {SDL_SCANCODE_F2, Keycode::F2},
+ {SDL_SCANCODE_F3, Keycode::F3},
+ {SDL_SCANCODE_F4, Keycode::F4},
+ {SDL_SCANCODE_F5, Keycode::F5},
+ {SDL_SCANCODE_F6, Keycode::F6},
+ {SDL_SCANCODE_F7, Keycode::F7},
+ {SDL_SCANCODE_F8, Keycode::F8},
+ {SDL_SCANCODE_F9, Keycode::F9},
+ {SDL_SCANCODE_F10, Keycode::F10},
+ {SDL_SCANCODE_F11, Keycode::F11},
+ {SDL_SCANCODE_F12, Keycode::F12},
+ {SDL_SCANCODE_KP_0, Keycode::KP0},
+ {SDL_SCANCODE_KP_1, Keycode::KP1},
+ {SDL_SCANCODE_KP_2, Keycode::KP2},
+ {SDL_SCANCODE_KP_3, Keycode::KP3},
+ {SDL_SCANCODE_KP_4, Keycode::KP4},
+ {SDL_SCANCODE_KP_5, Keycode::KP5},
+ {SDL_SCANCODE_KP_6, Keycode::KP6},
+ {SDL_SCANCODE_KP_7, Keycode::KP7},
+ {SDL_SCANCODE_KP_8, Keycode::KP8},
+ {SDL_SCANCODE_KP_9, Keycode::KP9},
+ {SDL_SCANCODE_LSHIFT, Keycode::LEFT_SHIFT},
+ {SDL_SCANCODE_LCTRL, Keycode::LEFT_CONTROL},
+ {SDL_SCANCODE_LALT, Keycode::LEFT_ALT},
+ {SDL_SCANCODE_LGUI, Keycode::LEFT_SUPER},
+ {SDL_SCANCODE_RSHIFT, Keycode::RIGHT_SHIFT},
+ {SDL_SCANCODE_RCTRL, Keycode::RIGHT_CONTROL},
+ {SDL_SCANCODE_RALT, Keycode::RIGHT_ALT},
+ {SDL_SCANCODE_RGUI, Keycode::RIGHT_SUPER},
+ {SDL_SCANCODE_MENU, Keycode::MENU}};
+};
+
+} // namespace crepe
diff --git a/src/crepe/facade/Sound.cpp b/src/crepe/facade/Sound.cpp
new file mode 100644
index 0000000..b1e6463
--- /dev/null
+++ b/src/crepe/facade/Sound.cpp
@@ -0,0 +1,13 @@
+#include "../api/Asset.h"
+#include "../util/dbg.h"
+
+#include "Sound.h"
+
+using namespace crepe;
+using namespace std;
+
+Sound::Sound(const Asset & src, Mediator & mediator) : Resource(src, mediator) {
+ this->sample.load(src.get_path().c_str());
+ dbg_trace();
+}
+Sound::~Sound() { dbg_trace(); }
diff --git a/src/crepe/facade/Sound.h b/src/crepe/facade/Sound.h
new file mode 100644
index 0000000..4a5d692
--- /dev/null
+++ b/src/crepe/facade/Sound.h
@@ -0,0 +1,31 @@
+#pragma once
+
+#include <soloud/soloud.h>
+#include <soloud/soloud_wav.h>
+
+#include "../Resource.h"
+
+namespace crepe {
+
+class SoundContext;
+class Mediator;
+
+/**
+ * \brief Sound resource facade
+ *
+ * This class is a wrapper around a \c SoLoud::Wav instance, which holds a single sample. It is
+ * part of the sound facade.
+ */
+class Sound : public Resource {
+public:
+ Sound(const Asset & src, Mediator & mediator);
+ ~Sound(); // dbg_trace
+
+private:
+ //! Deserialized resource (soloud)
+ SoLoud::Wav sample;
+ //! SoundContext uses \c sample
+ friend class SoundContext;
+};
+
+} // namespace crepe
diff --git a/src/crepe/facade/SoundContext.cpp b/src/crepe/facade/SoundContext.cpp
new file mode 100644
index 0000000..5091e07
--- /dev/null
+++ b/src/crepe/facade/SoundContext.cpp
@@ -0,0 +1,36 @@
+#include "../util/dbg.h"
+
+#include "SoundContext.h"
+
+using namespace crepe;
+
+SoundContext::SoundContext() {
+ dbg_trace();
+ this->engine.init();
+ this->engine.setMaxActiveVoiceCount(this->config.audio.voices);
+}
+
+SoundContext::~SoundContext() {
+ dbg_trace();
+ this->engine.deinit();
+}
+
+SoundHandle SoundContext::play(Sound & resource) {
+ SoLoud::handle real_handle = this->engine.play(resource.sample, 1.0f);
+ SoundHandle handle = this->next_handle;
+ this->registry[handle] = real_handle;
+ this->next_handle++;
+ return handle;
+}
+
+void SoundContext::stop(const SoundHandle & handle) {
+ this->engine.stop(this->registry[handle]);
+}
+
+void SoundContext::set_volume(const SoundHandle & handle, float volume) {
+ this->engine.setVolume(this->registry[handle], volume);
+}
+
+void SoundContext::set_loop(const SoundHandle & handle, bool loop) {
+ this->engine.setLooping(this->registry[handle], loop);
+}
diff --git a/src/crepe/facade/SoundContext.h b/src/crepe/facade/SoundContext.h
new file mode 100644
index 0000000..d986c59
--- /dev/null
+++ b/src/crepe/facade/SoundContext.h
@@ -0,0 +1,81 @@
+#pragma once
+
+#include <soloud/soloud.h>
+
+#include "../api/Config.h"
+
+#include "Sound.h"
+#include "SoundHandle.h"
+
+namespace crepe {
+
+/**
+ * \brief Sound engine facade
+ *
+ * This class is a wrapper around a \c SoLoud::Soloud instance, which provides the methods for
+ * playing \c Sound instances. It is part of the sound facade.
+ */
+class SoundContext {
+public:
+ SoundContext();
+ virtual ~SoundContext();
+
+ SoundContext(const SoundContext &) = delete;
+ SoundContext(SoundContext &&) = delete;
+ SoundContext & operator=(const SoundContext &) = delete;
+ SoundContext & operator=(SoundContext &&) = delete;
+
+ /**
+ * \brief Play a sample
+ *
+ * Plays a Sound from the beginning of the sample and returns a handle to control it later.
+ *
+ * \param resource Sound instance to play
+ *
+ * \returns Handle to control this voice
+ */
+ virtual SoundHandle play(Sound & resource);
+ /**
+ * \brief Stop a voice immediately if it is still playing
+ *
+ * \note This function does nothing if the handle is invalid or if the sound is already
+ * stopped / finished playing.
+ *
+ * \param handle Voice handle returned by SoundContext::play
+ */
+ virtual void stop(const SoundHandle & handle);
+ /**
+ * \brief Change the volume of a voice
+ *
+ * \note This function does nothing if the handle is invalid or if the sound is already
+ * stopped / finished playing.
+ *
+ * \param handle Voice handle returned by SoundContext::play
+ * \param volume New gain value (0=silent, 1=default)
+ */
+ virtual void set_volume(const SoundHandle & handle, float volume);
+ /**
+ * \brief Set the looping behavior of a voice
+ *
+ * \note This function does nothing if the handle is invalid or if the sound is already
+ * stopped / finished playing.
+ *
+ * \param handle Voice handle returned by SoundContext::play
+ * \param loop Looping behavior (false=oneshot, true=loop)
+ */
+ virtual void set_loop(const SoundHandle & handle, bool loop);
+
+private:
+ //! Abstracted class
+ SoLoud::Soloud engine;
+
+ //! Config reference
+ Config & config = Config::get_instance();
+
+ //! Sound handle registry
+ std::unordered_map<SoundHandle, SoLoud::handle> registry;
+ //! Unique handle counter
+ SoundHandle next_handle = 0;
+};
+
+} // namespace crepe
diff --git a/src/crepe/facade/SoundHandle.h b/src/crepe/facade/SoundHandle.h
new file mode 100644
index 0000000..b7925fc
--- /dev/null
+++ b/src/crepe/facade/SoundHandle.h
@@ -0,0 +1,12 @@
+#pragma once
+
+#include <cstddef>
+
+namespace crepe {
+
+/**
+ * \brief Voice handle returned by
+ */
+typedef size_t SoundHandle;
+
+} // namespace crepe
diff --git a/src/crepe/facade/Texture.cpp b/src/crepe/facade/Texture.cpp
new file mode 100644
index 0000000..6fb22e1
--- /dev/null
+++ b/src/crepe/facade/Texture.cpp
@@ -0,0 +1,29 @@
+#include "../Resource.h"
+#include "../facade/SDLContext.h"
+#include "../manager/Mediator.h"
+#include "../types.h"
+#include "../util/dbg.h"
+
+#include "Texture.h"
+
+using namespace crepe;
+using namespace std;
+
+Texture::Texture(const Asset & src, Mediator & mediator) : Resource(src, mediator) {
+ dbg_trace();
+ SDLContext & ctx = mediator.sdl_context;
+ this->texture = ctx.texture_from_path(src.get_path());
+ this->size = ctx.get_size(*this);
+ this->aspect_ratio = static_cast<float>(this->size.x) / this->size.y;
+}
+
+Texture::~Texture() {
+ dbg_trace();
+ this->texture.reset();
+}
+
+const ivec2 & Texture::get_size() const noexcept { return this->size; }
+
+const float & Texture::get_ratio() const noexcept { return this->aspect_ratio; }
+
+SDL_Texture * Texture::get_img() const noexcept { return this->texture.get(); }
diff --git a/src/crepe/facade/Texture.h b/src/crepe/facade/Texture.h
new file mode 100644
index 0000000..cdacac4
--- /dev/null
+++ b/src/crepe/facade/Texture.h
@@ -0,0 +1,69 @@
+#pragma once
+
+#include <SDL2/SDL_render.h>
+#include <memory>
+
+#include "../Resource.h"
+
+#include "types.h"
+
+namespace crepe {
+
+class Mediator;
+class Asset;
+
+/**
+ * \class Texture
+ * \brief Manages texture loading and properties.
+ *
+ * The Texture class is responsible for loading an image from a source and providing access to
+ * its dimensions. Textures can be used for rendering.
+ */
+class Texture : public Resource {
+
+public:
+ /**
+ * \brief Constructs a Texture from an Asset resource.
+ * \param src Asset with texture data to load.
+ * \param mediator use the SDLContext reference to load the image
+ */
+ Texture(const Asset & src, Mediator & mediator);
+
+ /**
+ * \brief Destroys the Texture instance
+ */
+ ~Texture();
+
+ /**
+ * \brief get width and height of image in pixels
+ * \return pixel size width and height
+ *
+ */
+ const ivec2 & get_size() const noexcept;
+
+ /**
+ * \brief aspect_ratio of image
+ * \return ratio
+ *
+ */
+ const float & get_ratio() const noexcept;
+
+ /**
+ * \brief get the image texture
+ * \return SDL_Texture
+ *
+ */
+ SDL_Texture * get_img() const noexcept;
+
+private:
+ //! The texture of the class from the library
+ std::unique_ptr<SDL_Texture, std::function<void(SDL_Texture *)>> texture;
+
+ // texture size in pixel
+ ivec2 size;
+
+ //! ratio of image
+ float aspect_ratio;
+};
+
+} // namespace crepe
diff --git a/src/crepe/manager/CMakeLists.txt b/src/crepe/manager/CMakeLists.txt
new file mode 100644
index 0000000..48e444f
--- /dev/null
+++ b/src/crepe/manager/CMakeLists.txt
@@ -0,0 +1,30 @@
+target_sources(crepe PUBLIC
+ ComponentManager.cpp
+ EventManager.cpp
+ Manager.cpp
+ SaveManager.cpp
+ SceneManager.cpp
+ LoopTimerManager.cpp
+ ResourceManager.cpp
+ ReplayManager.cpp
+ SystemManager.cpp
+)
+
+target_sources(crepe PUBLIC FILE_SET HEADERS FILES
+ ComponentManager.h
+ ComponentManager.hpp
+ EventManager.h
+ EventManager.hpp
+ Manager.h
+ Mediator.h
+ SaveManager.h
+ SceneManager.h
+ SceneManager.hpp
+ LoopTimerManager.h
+ ResourceManager.h
+ ResourceManager.hpp
+ ReplayManager.h
+ SystemManager.h
+ SystemManager.hpp
+)
+
diff --git a/src/crepe/manager/ComponentManager.cpp b/src/crepe/manager/ComponentManager.cpp
new file mode 100644
index 0000000..745ddae
--- /dev/null
+++ b/src/crepe/manager/ComponentManager.cpp
@@ -0,0 +1,99 @@
+#include "../api/GameObject.h"
+#include "../api/Metadata.h"
+#include "../types.h"
+#include "../util/dbg.h"
+
+#include "ComponentManager.h"
+
+using namespace crepe;
+using namespace std;
+
+ComponentManager::ComponentManager(Mediator & mediator) : Manager(mediator) {
+ mediator.component_manager = *this;
+ dbg_trace();
+}
+ComponentManager::~ComponentManager() { dbg_trace(); }
+
+void ComponentManager::delete_all_components_of_id(game_object_id_t id) {
+ // Do not delete persistent objects
+ if (this->persistent[id]) {
+ return;
+ }
+
+ // Loop through all the types (in the unordered_map<>)
+ for (auto & [type, component_array] : this->components) {
+ // Make sure that the id (that we are looking for) is within the boundaries of the vector<>
+ if (id < component_array.size()) {
+ // Clear the components at this specific id
+ component_array[id].clear();
+ }
+ }
+}
+
+void ComponentManager::delete_all_components() {
+ // Loop through all the types (in the unordered_map<>)
+ for (auto & [type, component_array] : this->components) {
+ // Loop through all the ids (in the vector<>)
+ for (game_object_id_t id = 0; id < component_array.size(); id++) {
+ // Do not delete persistent objects
+ if (!this->persistent[id]) {
+ // Clear the components at this specific id
+ component_array[id].clear();
+ }
+ }
+ }
+
+ this->next_id = 0;
+}
+
+GameObject ComponentManager::new_object(const string & name, const string & tag,
+ const vec2 & position, double rotation, double scale) {
+ // Find the first available id (taking persistent objects into account)
+ while (this->persistent[this->next_id]) {
+ this->next_id++;
+ }
+
+ GameObject object{this->mediator, this->next_id, name, tag, position, rotation, scale};
+ this->next_id++;
+
+ return object;
+}
+
+void ComponentManager::set_persistent(game_object_id_t id, bool persistent) {
+ this->persistent[id] = persistent;
+}
+
+set<game_object_id_t> ComponentManager::get_objects_by_name(const string & name) const {
+ return this->get_objects_by_predicate<Metadata>(
+ [name](const Metadata & data) { return data.name == name; });
+}
+
+set<game_object_id_t> ComponentManager::get_objects_by_tag(const string & tag) const {
+ return this->get_objects_by_predicate<Metadata>(
+ [tag](const Metadata & data) { return data.tag == tag; });
+}
+
+ComponentManager::Snapshot ComponentManager::save() {
+ Snapshot snapshot{};
+ for (const auto & [type, by_id_index] : this->components) {
+ for (game_object_id_t id = 0; id < by_id_index.size(); id++) {
+ const auto & components = by_id_index[id];
+ for (size_t index = 0; index < components.size(); index++) {
+ const Component & component = *components[index];
+ snapshot.components.push_back(SnapshotComponent{
+ .type = type,
+ .id = id,
+ .index = index,
+ .component = component.save(),
+ });
+ }
+ }
+ }
+ return snapshot;
+}
+
+void ComponentManager::restore(const Snapshot & snapshot) {
+ for (const SnapshotComponent & info : snapshot.components) {
+ this->components[info.type][info.id][info.index]->restore(*info.component);
+ }
+}
diff --git a/src/crepe/manager/ComponentManager.h b/src/crepe/manager/ComponentManager.h
new file mode 100644
index 0000000..c3a5b4a
--- /dev/null
+++ b/src/crepe/manager/ComponentManager.h
@@ -0,0 +1,252 @@
+#pragma once
+
+#include <memory>
+#include <set>
+#include <typeindex>
+#include <unordered_map>
+#include <vector>
+
+#include "../Component.h"
+#include "../types.h"
+
+#include "Manager.h"
+
+namespace crepe {
+
+class GameObject;
+
+/**
+ * \brief Manages all components
+ *
+ * This class manages all components. It provides methods to add, delete and get components.
+ */
+class ComponentManager : public Manager {
+public:
+ ComponentManager(Mediator & mediator);
+ ~ComponentManager(); // dbg_trace
+
+ /**
+ * \brief Create a new game object using the component manager
+ *
+ * \param name Metadata::name (required)
+ * \param tag Metadata::tag (optional, empty by default)
+ * \param position Transform::position (optional, origin by default)
+ * \param rotation Transform::rotation (optional, 0 by default)
+ * \param scale Transform::scale (optional, 1 by default)
+ *
+ * \returns GameObject interface
+ *
+ * \note This method automatically assigns a new entity ID
+ */
+ GameObject new_object(const std::string & name, const std::string & tag = "",
+ const vec2 & position = {0, 0}, double rotation = 0,
+ double scale = 1);
+
+public:
+ /**
+ * \brief Add a component to the ComponentManager
+ *
+ * This method adds a component to the ComponentManager. The component is created with the
+ * given arguments and added to the ComponentManager.
+ *
+ * \tparam T The type of the component
+ * \tparam Args The types of the arguments
+ * \param id The id of the GameObject this component belongs to
+ * \param args The arguments to create the component
+ * \return The created component
+ */
+ template <typename T, typename... Args>
+ T & add_component(game_object_id_t id, Args &&... args);
+ /**
+ * \brief Delete all components of a specific type and id
+ *
+ * This method deletes all components of a specific type and id.
+ *
+ * \tparam T The type of the component
+ * \param id The id of the GameObject this component belongs to
+ */
+ template <typename T>
+ void delete_components_by_id(game_object_id_t id);
+ /**
+ * \brief Delete all components of a specific type
+ *
+ * This method deletes all components of a specific type.
+ *
+ * \tparam T The type of the component
+ */
+ template <typename T>
+ void delete_components();
+ /**
+ * \brief Delete all components of a specific id
+ *
+ * This method deletes all components of a specific id.
+ *
+ * \param id The id of the GameObject this component belongs to
+ */
+ void delete_all_components_of_id(game_object_id_t id);
+ /**
+ * \brief Delete all components
+ *
+ * This method deletes all components.
+ */
+ void delete_all_components();
+ /**
+ * \brief Set a GameObject as persistent
+ *
+ * This method sets a GameObject as persistent. If a GameObject is persistent, its
+ * components will not be deleted.
+ *
+ * \param id The id of the GameObject to set as persistent
+ * \param persistent The persistent flag
+ */
+ void set_persistent(game_object_id_t id, bool persistent);
+
+public:
+ /**
+ * \brief Get all components of a specific type and id
+ *
+ * This method gets all components of a specific type and id.
+ *
+ * \tparam T The type of the component
+ * \param id The id of the GameObject this component belongs to
+ * \return A vector of all components of the specific type and id
+ */
+ template <typename T>
+ RefVector<T> get_components_by_id(game_object_id_t id) const;
+ /**
+ * \brief Get all components of a specific type
+ *
+ * This method gets all components of a specific type.
+ *
+ * \tparam T The type of the component
+ * \return A vector of all components of the specific type
+ */
+ template <typename T>
+ RefVector<T> get_components_by_type() const;
+ /**
+ * \brief Get all components of a specific type on a GameObject with name \c name
+ *
+ * \tparam T The type of the component
+ * \param name Metadata::name for the same game_object_id as the returned components
+ * \return Components matching criteria
+ */
+ template <typename T>
+ RefVector<T> get_components_by_name(const std::string & name) const;
+ /**
+ * \brief Get all components of a specific type on a GameObject with tag \c tag
+ *
+ * \tparam T The type of the component
+ * \param name Metadata::tag for the same game_object_id as the returned components
+ * \return Components matching criteria
+ */
+ template <typename T>
+ RefVector<T> get_components_by_tag(const std::string & tag) const;
+
+ //! Snapshot of single component (including path in \c components)
+ struct SnapshotComponent {
+ //! \c components path
+ std::type_index type;
+ //! \c components path
+ game_object_id_t id;
+ //! \c components path
+ size_t index;
+ //! Actual component snapshot
+ std::unique_ptr<Component> component;
+ };
+ //! Snapshot of the entire component manager state
+ struct Snapshot {
+ //! All components
+ std::vector<SnapshotComponent> components;
+ // TODO: some kind of hash code that ensures components exist in all the same places as
+ // this snapshot
+ };
+ /**
+ * \name ReplayManager (Memento) functions
+ * \{
+ */
+ /**
+ * \brief Save a snapshot of the component manager state
+ * \returns Deep copy of the component manager's internal state
+ */
+ Snapshot save();
+ /**
+ * \brief Restore component manager from a snapshot
+ * \param snapshot Snapshot to restore from (as returned by \c save())
+ */
+ void restore(const Snapshot & snapshot);
+ //! \}
+
+private:
+ /**
+ * \brief Get object IDs by predicate function
+ *
+ * This function calls the predicate function \c pred for all components matching type \c T,
+ * and adds their parent game_object_id to a \c std::set if the predicate returns true.
+ *
+ * \tparam T The type of the component to check the predicate against
+ * \param pred Predicate function
+ *
+ * \note The predicate function may be called for multiple components with the same \c
+ * game_object_id. In this case, the ID is added if *any* call returns \c true.
+ *
+ * \returns game_object_id for all components where the predicate returned true
+ */
+ template <typename T>
+ std::set<game_object_id_t>
+ get_objects_by_predicate(const std::function<bool(const T &)> & pred) const;
+
+ /**
+ * \brief Get components of type \c T for multiple game object IDs
+ *
+ * \tparam T The type of the components to return
+ * \param ids The object IDs
+ *
+ * \return All components matching type \c T and one of the IDs in \c ids
+ */
+ template <typename T>
+ RefVector<T> get_components_by_ids(const std::set<game_object_id_t> & ids) const;
+
+ /**
+ * \brief Get object IDs for objects with name \c name
+ *
+ * \param name Object name to match
+ * \returns Object IDs where Metadata::name is equal to \c name
+ */
+ std::set<game_object_id_t> get_objects_by_name(const std::string & name) const;
+ /**
+ * \brief Get object IDs for objects with tag \c tag
+ *
+ * \param tag Object tag to match
+ * \returns Object IDs where Metadata::tag is equal to \c tag
+ */
+ std::set<game_object_id_t> get_objects_by_tag(const std::string & tag) const;
+
+private:
+ //! By Component \c std::type_index (readability helper type)
+ template <typename T>
+ using by_type = std::unordered_map<std::type_index, T>;
+ //! By \c game_object_id index (readability helper type)
+ template <typename T>
+ using by_id_index = std::vector<T>;
+ /**
+ * \brief The components
+ *
+ * This unordered_map stores all components. The key is the type of the component and the
+ * value is a vector of vectors of unique pointers to the components.
+ *
+ * Every component type has its own vector of vectors of unique pointers to the components.
+ * The first vector is for the ids of the GameObjects and the second vector is for the
+ * components (because a GameObject might have multiple components).
+ */
+ by_type<by_id_index<std::vector<std::unique_ptr<Component>>>> components;
+
+ //! Persistent flag for each GameObject
+ std::unordered_map<game_object_id_t, bool> persistent;
+
+ //! ID of next GameObject allocated by \c ComponentManager::new_object
+ game_object_id_t next_id = 0;
+};
+
+} // namespace crepe
+
+#include "ComponentManager.hpp"
diff --git a/src/crepe/manager/ComponentManager.hpp b/src/crepe/manager/ComponentManager.hpp
new file mode 100644
index 0000000..9e70865
--- /dev/null
+++ b/src/crepe/manager/ComponentManager.hpp
@@ -0,0 +1,196 @@
+#pragma once
+
+#include <type_traits>
+
+#include "ComponentManager.h"
+#include "types.h"
+
+namespace crepe {
+
+template <class T, typename... Args>
+T & ComponentManager::add_component(game_object_id_t id, Args &&... args) {
+ using namespace std;
+
+ static_assert(is_base_of<Component, T>::value,
+ "add_component must recieve a derivative class of Component");
+
+ // Determine the type of T (this is used as the key of the unordered_map<>)
+ type_index type = typeid(T);
+
+ // Check if this component type is already in the unordered_map<>
+ if (this->components.find(type) == this->components.end()) {
+ //If not, create a new (empty) vector<> of vector<unique_ptr<Component>>
+ this->components[type] = vector<vector<unique_ptr<Component>>>();
+ }
+
+ // Resize the vector<> if the id is greater than the current size
+ if (id >= this->components[type].size()) {
+ // Initialize new slots to nullptr (resize does automatically init to nullptr)
+ this->components[type].resize(id + 1);
+ }
+
+ // Create a new component of type T (arguments directly forwarded). The
+ // constructor must be called by ComponentManager.
+ T * instance_ptr = new T(id, forward<Args>(args)...);
+ if (instance_ptr == nullptr) throw std::bad_alloc();
+
+ T & instance_ref = *instance_ptr;
+ unique_ptr<T> instance = unique_ptr<T>(instance_ptr);
+
+ // Check if the vector size is not greater than get_instances_max
+ int max_instances = instance->get_instances_max();
+ if (max_instances != -1 && components[type][id].size() >= max_instances) {
+ throw std::runtime_error(
+ "Exceeded maximum number of instances for this component type");
+ }
+
+ // store its unique_ptr in the vector<>
+ this->components[type][id].push_back(std::move(instance));
+
+ return instance_ref;
+}
+
+template <typename T>
+void ComponentManager::delete_components_by_id(game_object_id_t id) {
+ using namespace std;
+
+ // Do not delete persistent objects
+ if (this->persistent[id]) {
+ return;
+ }
+
+ // Determine the type of T (this is used as the key of the unordered_map<>)
+ type_index type = typeid(T);
+
+ // Find the type (in the unordered_map<>)
+ if (this->components.find(type) != this->components.end()) {
+ // Get the correct vector<>
+ vector<vector<unique_ptr<Component>>> & component_array = this->components[type];
+
+ // Make sure that the id (that we are looking for) is within the boundaries of the vector<>
+ if (id < component_array.size()) {
+ // Clear the whole vector<> of this specific type and id
+ component_array[id].clear();
+ }
+ }
+}
+
+template <typename T>
+void ComponentManager::delete_components() {
+ // Determine the type of T (this is used as the key of the unordered_map<>)
+ std::type_index type = typeid(T);
+
+ if (this->components.find(type) == this->components.end()) return;
+
+ // Loop through the whole vector<> of this specific type
+ for (game_object_id_t i = 0; i < this->components[type].size(); ++i) {
+ // Do not delete persistent objects
+ if (!this->persistent[i]) {
+ this->components[type][i].clear();
+ }
+ }
+}
+
+template <typename T>
+RefVector<T> ComponentManager::get_components_by_id(game_object_id_t id) const {
+ using namespace std;
+
+ static_assert(is_base_of<Component, T>::value,
+ "get_components_by_id must recieve a derivative class of Component");
+
+ type_index type = typeid(T);
+ if (!this->components.contains(type)) return {};
+
+ const by_id_index<vector<unique_ptr<Component>>> & components_by_id
+ = this->components.at(type);
+ if (id >= components_by_id.size()) return {};
+
+ RefVector<T> out = {};
+ const vector<unique_ptr<Component>> & components = components_by_id.at(id);
+ for (auto & component_ptr : components) {
+ if (component_ptr == nullptr) continue;
+ Component & component = *component_ptr.get();
+ out.push_back(static_cast<T &>(component));
+ }
+
+ return out;
+}
+
+template <typename T>
+RefVector<T> ComponentManager::get_components_by_type() const {
+ using namespace std;
+
+ // Determine the type of T (this is used as the key of the unordered_map<>)
+ type_index type = typeid(T);
+
+ // Create an empty vector<>
+ RefVector<T> component_vector;
+
+ // Find the type (in the unordered_map<>)
+ if (this->components.find(type) == this->components.end()) return component_vector;
+
+ // Get the correct vector<>
+ const vector<vector<unique_ptr<Component>>> & component_array = this->components.at(type);
+
+ // Loop through the whole vector<>
+ for (const vector<unique_ptr<Component>> & component : component_array) {
+ // Loop trough the whole vector<>
+ for (const unique_ptr<Component> & component_ptr : component) {
+ // Cast the unique_ptr to a raw pointer
+ T * casted_component = static_cast<T *>(component_ptr.get());
+
+ // Ensure that the cast was successful
+ if (casted_component == nullptr) continue;
+
+ // Add the dereferenced raw pointer to the vector<>
+ component_vector.emplace_back(ref(*casted_component));
+ }
+ }
+
+ // Return the vector<>
+ return component_vector;
+}
+
+template <typename T>
+std::set<game_object_id_t>
+ComponentManager::get_objects_by_predicate(const std::function<bool(const T &)> & pred) const {
+ using namespace std;
+
+ set<game_object_id_t> objects = {};
+ RefVector<T> components = this->get_components_by_type<T>();
+
+ for (const T & component : components) {
+ game_object_id_t id = dynamic_cast<const Component &>(component).game_object_id;
+ if (objects.contains(id)) continue;
+ if (!pred(component)) continue;
+ objects.insert(id);
+ }
+
+ return objects;
+}
+
+template <typename T>
+RefVector<T>
+ComponentManager::get_components_by_ids(const std::set<game_object_id_t> & ids) const {
+ using namespace std;
+
+ RefVector<T> out = {};
+ for (game_object_id_t id : ids) {
+ RefVector<T> components = get_components_by_id<T>(id);
+ out.insert(out.end(), components.begin(), components.end());
+ }
+
+ return out;
+}
+
+template <typename T>
+RefVector<T> ComponentManager::get_components_by_name(const std::string & name) const {
+ return this->get_components_by_ids<T>(this->get_objects_by_name(name));
+}
+
+template <typename T>
+RefVector<T> ComponentManager::get_components_by_tag(const std::string & tag) const {
+ return this->get_components_by_ids<T>(this->get_objects_by_tag(tag));
+}
+
+} // namespace crepe
diff --git a/src/crepe/manager/EventManager.cpp b/src/crepe/manager/EventManager.cpp
new file mode 100644
index 0000000..6aa49ee
--- /dev/null
+++ b/src/crepe/manager/EventManager.cpp
@@ -0,0 +1,44 @@
+#include "EventManager.h"
+
+using namespace crepe;
+using namespace std;
+
+EventManager::EventManager(Mediator & mediator) : Manager(mediator) {
+ this->mediator.event_manager = *this;
+}
+void EventManager::dispatch_events() {
+ for (auto & event : this->events_queue) {
+ this->handle_event(event.type, event.channel, *event.event.get());
+ }
+ this->events_queue.clear();
+}
+
+void EventManager::handle_event(type_index type, event_channel_t channel, const Event & data) {
+ auto handlers_it = this->subscribers.find(type);
+ if (handlers_it == this->subscribers.end()) return;
+
+ vector<CallbackEntry> & handlers = handlers_it->second;
+ for (auto & handler : handlers) {
+ bool check_channel = handler.channel != CHANNEL_ALL || channel != CHANNEL_ALL;
+ if (check_channel && handler.channel != channel) continue;
+
+ bool handled = handler.callback->exec(data);
+ if (handled) return;
+ }
+}
+
+void EventManager::clear() {
+ this->subscribers.clear();
+ this->events_queue.clear();
+}
+
+void EventManager::unsubscribe(subscription_t id) {
+ for (auto & [event_type, handlers] : this->subscribers) {
+ for (auto it = handlers.begin(); it != handlers.end(); it++) {
+ // find listener with subscription id
+ if ((*it).id != id) continue;
+ it = handlers.erase(it);
+ return;
+ }
+ }
+}
diff --git a/src/crepe/manager/EventManager.h b/src/crepe/manager/EventManager.h
new file mode 100644
index 0000000..639e37f
--- /dev/null
+++ b/src/crepe/manager/EventManager.h
@@ -0,0 +1,148 @@
+#pragma once
+
+#include <memory>
+#include <typeindex>
+#include <unordered_map>
+#include <vector>
+
+#include "../api/Event.h"
+#include "../api/EventHandler.h"
+
+#include "Manager.h"
+
+namespace crepe {
+
+//! Event listener unique ID
+typedef size_t subscription_t;
+
+/**
+ * \brief Event channel
+ *
+ * Events can be sent to a specific channel, which prevents listeners on other channels from
+ * being called. The default channel is EventManager::CHANNEL_ALL, which calls all listeners.
+ */
+typedef size_t event_channel_t;
+
+/**
+ * \brief Manages event subscriptions, triggers, and queues, enabling decoupled event handling.
+ *
+ * The `EventManager` acts as a centralized event system. It allows for registering callbacks
+ * for specific event types, triggering events synchronously, queueing events for later
+ * processing, and managing subscriptions via unique identifiers.
+ */
+class EventManager : public Manager {
+public:
+ static constexpr const event_channel_t CHANNEL_ALL = -1;
+ /**
+ * \param mediator A reference to a Mediator object used for transfering managers.
+ */
+ EventManager(Mediator & mediator);
+ /**
+ * \brief Subscribe to a specific event type.
+ *
+ * Registers a callback for a given event type and optional channel. Each callback
+ * is assigned a unique subscription ID that can be used for later unsubscription.
+ *
+ * \tparam EventType The type of the event to subscribe to.
+ * \param callback The callback function to be invoked when the event is triggered.
+ * \param channel The channel number to subscribe to (default is CHANNEL_ALL, which listens to all channels).
+ * \return A unique subscription ID associated with the registered callback.
+ */
+ template <typename EventType>
+ subscription_t subscribe(const EventHandler<EventType> & callback,
+ event_channel_t channel = CHANNEL_ALL);
+
+ /**
+ * \brief Unsubscribe a previously registered callback.
+ *
+ * Removes a callback from the subscription list based on its unique subscription ID.
+ *
+ * \param event_id The unique subscription ID of the callback to remove.
+ */
+ void unsubscribe(subscription_t event_id);
+
+ /**
+ * \brief Trigger an event immediately.
+ *
+ * Synchronously invokes all registered callbacks for the given event type on the specified channel.
+ *
+ * \tparam EventType The type of the event to trigger.
+ * \param event The event instance to pass to the callbacks.
+ * \param channel The channel to trigger the event on (default is CHANNEL_ALL, which triggers on all channels).
+ */
+ template <typename EventType>
+ void trigger_event(const EventType & event = {}, event_channel_t channel = CHANNEL_ALL);
+
+ /**
+ * \brief Queue an event for later processing.
+ *
+ * Adds an event to the event queue to be processed during the next call to `dispatch_events`.
+ *
+ * \tparam EventType The type of the event to queue.
+ * \param event The event instance to queue.
+ * \param channel The channel to associate with the event (default is CHANNEL_ALL).
+ */
+ template <typename EventType>
+ void queue_event(const EventType & event = {}, event_channel_t channel = CHANNEL_ALL);
+
+ /**
+ * \brief Process all queued events.
+ *
+ * Iterates through the event queue and triggers callbacks for each queued event.
+ * Events are removed from the queue once processed.
+ */
+ void dispatch_events();
+
+ /**
+ * \brief Clear all subscriptions.
+ *
+ * Removes all registered event handlers and clears the subscription list.
+ */
+ void clear();
+
+private:
+ /**
+ * \struct QueueEntry
+ * \brief Represents an entry in the event queue.
+ */
+ struct QueueEntry {
+ std::unique_ptr<Event> event; ///< The event instance.
+ event_channel_t channel = CHANNEL_ALL; ///< The channel associated with the event.
+ std::type_index type; ///< The type of the event.
+ };
+
+ /**
+ * \brief Internal event handler
+ *
+ * This function processes a single event, and is used to process events both during
+ * EventManager::dispatch_events and inside EventManager::trigger_event
+ *
+ * \param type \c typeid of concrete Event class
+ * \param channel Event channel
+ * \param data Event data
+ */
+ void handle_event(std::type_index type, event_channel_t channel, const Event & data);
+
+ /**
+ * \struct CallbackEntry
+ * \brief Represents a registered event handler callback.
+ */
+ struct CallbackEntry {
+ std::unique_ptr<IEventHandlerWrapper> callback; ///< The callback function wrapper.
+ event_channel_t channel = CHANNEL_ALL; ///< The channel this callback listens to.
+ subscription_t id = -1; ///< Unique subscription ID.
+ };
+
+ //! The queue of events to be processed during dispatch.
+ std::vector<QueueEntry> events_queue;
+
+ //! A map of event type to registered callbacks.
+ std::unordered_map<std::type_index, std::vector<CallbackEntry>> subscribers;
+
+ //! Counter to generate unique subscription IDs.
+ subscription_t subscription_counter = 0;
+};
+
+} // namespace crepe
+
+#include "EventManager.hpp"
diff --git a/src/crepe/manager/EventManager.hpp b/src/crepe/manager/EventManager.hpp
new file mode 100644
index 0000000..a5f4556
--- /dev/null
+++ b/src/crepe/manager/EventManager.hpp
@@ -0,0 +1,36 @@
+#pragma once
+
+#include "EventManager.h"
+
+namespace crepe {
+
+template <typename EventType>
+subscription_t EventManager::subscribe(const EventHandler<EventType> & callback,
+ event_channel_t channel) {
+ subscription_counter++;
+ std::type_index event_type = typeid(EventType);
+ std::unique_ptr<EventHandlerWrapper<EventType>> handler
+ = std::make_unique<EventHandlerWrapper<EventType>>(callback);
+ std::vector<CallbackEntry> & handlers = this->subscribers[event_type];
+ handlers.emplace_back(CallbackEntry{
+ .callback = std::move(handler), .channel = channel, .id = subscription_counter});
+ return subscription_counter;
+}
+
+template <typename EventType>
+void EventManager::queue_event(const EventType & event, event_channel_t channel) {
+ static_assert(std::is_base_of<Event, EventType>::value,
+ "EventType must derive from Event");
+ this->events_queue.push_back(QueueEntry{
+ .event = std::make_unique<EventType>(event),
+ .channel = channel,
+ .type = typeid(EventType),
+ });
+}
+
+template <typename EventType>
+void EventManager::trigger_event(const EventType & event, event_channel_t channel) {
+ this->handle_event(typeid(EventType), channel, event);
+}
+
+} // namespace crepe
diff --git a/src/crepe/manager/LoopTimerManager.cpp b/src/crepe/manager/LoopTimerManager.cpp
new file mode 100644
index 0000000..e78f92f
--- /dev/null
+++ b/src/crepe/manager/LoopTimerManager.cpp
@@ -0,0 +1,91 @@
+#include <chrono>
+#include <thread>
+
+#include "../util/dbg.h"
+
+#include "LoopTimerManager.h"
+
+using namespace crepe;
+using namespace std::chrono;
+using namespace std::chrono_literals;
+
+LoopTimerManager::LoopTimerManager(Mediator & mediator) : Manager(mediator) {
+ this->mediator.loop_timer = *this;
+ dbg_trace();
+}
+
+void LoopTimerManager::start() {
+ this->last_frame_time = std::chrono::steady_clock::now();
+
+ this->elapsed_time = elapsed_time_t{0};
+ this->elapsed_fixed_time = elapsed_time_t{0};
+ this->delta_time = duration_t{0};
+}
+
+void LoopTimerManager::update() {
+ time_point_t current_frame_time = std::chrono::steady_clock::now();
+ // Convert to duration in seconds for delta time
+ this->delta_time = current_frame_time - last_frame_time;
+
+ if (this->delta_time > this->maximum_delta_time) {
+ this->delta_time = this->maximum_delta_time;
+ }
+ if (this->delta_time > 0s) {
+ this->actual_fps = static_cast<unsigned>(1.0 / this->delta_time.count());
+ } else {
+ this->actual_fps = 0;
+ }
+ this->elapsed_time += duration_cast<elapsed_time_t>(this->delta_time);
+ this->last_frame_time = current_frame_time;
+}
+
+duration_t LoopTimerManager::get_delta_time() const {
+ return this->delta_time * this->time_scale;
+}
+
+elapsed_time_t LoopTimerManager::get_elapsed_time() const { return this->elapsed_time; }
+
+void LoopTimerManager::advance_fixed_elapsed_time() {
+ this->elapsed_fixed_time
+ += std::chrono::duration_cast<elapsed_time_t>(this->fixed_delta_time);
+}
+
+void LoopTimerManager::set_target_framerate(unsigned fps) {
+ this->target_fps = fps;
+ //check if fps is lower or equals 0
+ if (fps <= 0) return;
+ // target time per frame in seconds
+ this->frame_target_time = duration_t(1s) / this->target_fps;
+}
+
+unsigned LoopTimerManager::get_fps() const { return this->actual_fps; }
+
+void LoopTimerManager::set_time_scale(double value) { this->time_scale = value; }
+
+float LoopTimerManager::get_time_scale() const { return this->time_scale; }
+
+void LoopTimerManager::enforce_frame_rate() {
+ time_point_t current_frame_time = std::chrono::steady_clock::now();
+ duration_t frame_duration = current_frame_time - this->last_frame_time;
+ // Check if frame duration is less than the target frame time
+ if (frame_duration < this->frame_target_time) {
+ duration_t delay_time = this->frame_target_time - frame_duration;
+ if (delay_time > 0s) {
+ std::this_thread::sleep_for(delay_time);
+ }
+ }
+}
+
+duration_t LoopTimerManager::get_lag() const {
+ return this->elapsed_time - this->elapsed_fixed_time;
+}
+
+duration_t LoopTimerManager::get_scaled_fixed_delta_time() const {
+ return this->fixed_delta_time * this->time_scale;
+}
+
+void LoopTimerManager::set_fixed_delta_time(float seconds) {
+ this->fixed_delta_time = duration_t(seconds);
+}
+
+duration_t LoopTimerManager::get_fixed_delta_time() const { return this->fixed_delta_time; }
diff --git a/src/crepe/manager/LoopTimerManager.h b/src/crepe/manager/LoopTimerManager.h
new file mode 100644
index 0000000..2f1e6b6
--- /dev/null
+++ b/src/crepe/manager/LoopTimerManager.h
@@ -0,0 +1,177 @@
+#pragma once
+
+#include <chrono>
+
+#include "Manager.h"
+
+namespace crepe {
+
+class Engine;
+
+typedef std::chrono::duration<float> duration_t;
+typedef std::chrono::duration<unsigned long long, std::micro> elapsed_time_t;
+
+/**
+ * \brief Manages timing and frame rate for the game loop.
+ *
+ * The LoopTimerManager class is responsible for calculating and managing timing functions
+ * such as delta time, frames per second (FPS), fixed time steps, and time scaling. It ensures
+ * consistent frame updates and supports game loop operations, such as handling fixed updates
+ * for physics and other time-sensitive operations.
+ */
+class LoopTimerManager : public Manager {
+public:
+ /**
+ * \param mediator A reference to a Mediator object used for transfering managers.
+ */
+ LoopTimerManager(Mediator & mediator);
+ /**
+ * \brief Get the current delta time for the current frame.
+ *
+ * This value represents the estimated frame duration of the current frame.
+ * This value can be used in the frame_update to convert pixel based values to time based values.
+ *
+ * \return Delta time in seconds since the last frame.
+ */
+ duration_t get_delta_time() const;
+
+ /**
+ * \brief Get the current elapsed time (total time passed )
+ *
+ * \note The current game time may vary from real-world elapsed time. It is the cumulative
+ * sum of each frame's delta time.
+ *
+ * \return Elapsed game time in seconds.
+ */
+ elapsed_time_t get_elapsed_time() const;
+
+ /**
+ * \brief Set the target frames per second (FPS).
+ *
+ * \param fps The desired frames rendered per second.
+ */
+ void set_target_framerate(unsigned fps);
+
+ /**
+ * \brief Get the current frames per second (FPS).
+ *
+ * \return Current FPS.
+ */
+ unsigned int get_fps() const;
+
+ /**
+ * \brief Get the current time scale.
+ *
+ * \return The current time scale, where (0 = pause, < 1 = slow down, 1 = normal speed, > 1 = speed up).
+ * up the game.
+ */
+ float get_time_scale() const;
+
+ /**
+ * \brief Set the time scale.
+ *
+ * time_scale is a value that changes the delta time that can be retrieved using get_delta_time function.
+ *
+ * \param time_scale The desired time scale (0 = pause, < 1 = slow down, 1 = normal speed, > 1 = speed up).
+ */
+ void set_time_scale(double time_scale);
+
+ /**
+ * \brief Get the fixed delta time in seconds without scaling by the time scale.
+ *
+ * This value is used in the LoopManager to determine how many times
+ * the fixed_update should be called within a given interval.
+ *
+ * \return The unscaled fixed delta time in seconds.
+ */
+ duration_t get_fixed_delta_time() const;
+
+ /**
+ * \brief Set the fixed_delta_time in seconds.
+ *
+ * \param seconds fixed_delta_time in seconds.
+ *
+ * The fixed_delta_time value is used to determine how many times per second the fixed_update and process_input functions are called.
+ *
+ */
+ void set_fixed_delta_time(float seconds);
+
+ /**
+ * \brief Retrieves the scaled fixed delta time in seconds.
+ *
+ * The scaled fixed delta time is the timing value used within the `fixed_update` function.
+ * It is adjusted by the time_scale to account for any changes in the simulation's
+ * speed.
+ *
+ * \return The fixed delta time, scaled by the current time scale, in seconds.
+ */
+ duration_t get_scaled_fixed_delta_time() const;
+
+private:
+ //! Friend relation to use start,enforce_frame_rate,get_lag,update,advance_fixed_update.
+ friend class Engine;
+ /**
+ * \brief Start the loop timer.
+ *
+ * Initializes the timer to begin tracking frame times.
+ */
+ void start();
+ /**
+ * \brief Enforce the frame rate limit.
+ *
+ * Ensures that the game loop does not exceed the target FPS by delaying frame updates as
+ * necessary.
+ */
+ void enforce_frame_rate();
+ /**
+ * \brief Get the accumulated lag in the game loop.
+ *
+ * Lag represents the difference between the target frame time and the actual frame time,
+ * useful for managing fixed update intervals.
+ *
+ * \return Accumulated lag in seconds.
+ */
+ duration_t get_lag() const;
+
+ /**
+ * \brief Update the timer to the current frame.
+ *
+ * Calculates and updates the delta time for the current frame and adds it to the cumulative
+ * game time.
+ */
+ void update();
+
+ /**
+ * \brief Progress the elapsed fixed time by the fixed delta time interval.
+ *
+ * This method advances the game's fixed update loop by adding the fixed_delta_time
+ * to elapsed_fixed_time, ensuring the fixed update catches up with the elapsed time.
+ */
+ void advance_fixed_elapsed_time();
+
+private:
+ //! Target frames per second.
+ unsigned int target_fps = 60;
+ //! Actual frames per second.
+ unsigned int actual_fps = 0;
+ //! Time scale for speeding up or slowing down the game (0 = pause, < 1 = slow down, 1 = normal speed, > 1 = speed up).
+ float time_scale = 1;
+ //! Maximum delta time in seconds to avoid large jumps.
+ duration_t maximum_delta_time{0.25};
+ //! Delta time for the current frame in seconds.
+ duration_t delta_time{0.0};
+ //! Target time per frame in seconds
+ duration_t frame_target_time{1.0 / target_fps};
+ //! Fixed delta time for fixed updates in seconds.
+ duration_t fixed_delta_time{1.0 / 50.0};
+ //! Total elapsed game time in microseconds.
+ elapsed_time_t elapsed_time{0};
+ //! Total elapsed time for fixed updates in microseconds.
+ elapsed_time_t elapsed_fixed_time{0};
+
+ typedef std::chrono::steady_clock::time_point time_point_t;
+ //! Time of the last frame.
+ time_point_t last_frame_time;
+};
+
+} // namespace crepe
diff --git a/src/crepe/manager/Manager.cpp b/src/crepe/manager/Manager.cpp
new file mode 100644
index 0000000..1182785
--- /dev/null
+++ b/src/crepe/manager/Manager.cpp
@@ -0,0 +1,5 @@
+#include "Manager.h"
+
+using namespace crepe;
+
+Manager::Manager(Mediator & mediator) : mediator(mediator) {}
diff --git a/src/crepe/manager/Manager.h b/src/crepe/manager/Manager.h
new file mode 100644
index 0000000..84d80fe
--- /dev/null
+++ b/src/crepe/manager/Manager.h
@@ -0,0 +1,24 @@
+#pragma once
+
+#include "Mediator.h"
+
+namespace crepe {
+
+/**
+ * \brief Base manager class
+ *
+ * Managers are used for various tasks that fall outside the ECS system category. All managers
+ * are required to register themselves to the mediator passed to the constructor, and this
+ * mutable reference is saved for convenience, even though not all managers use the mediator
+ * directly.
+ */
+class Manager {
+public:
+ Manager(Mediator & mediator);
+ virtual ~Manager() = default;
+
+protected:
+ Mediator & mediator;
+};
+
+} // namespace crepe
diff --git a/src/crepe/manager/Mediator.h b/src/crepe/manager/Mediator.h
new file mode 100644
index 0000000..842f1de
--- /dev/null
+++ b/src/crepe/manager/Mediator.h
@@ -0,0 +1,41 @@
+#pragma once
+
+#include "../util/OptionalRef.h"
+
+namespace crepe {
+
+class ComponentManager;
+class SceneManager;
+class EventManager;
+class LoopTimerManager;
+class SaveManager;
+class ResourceManager;
+class SDLContext;
+class ReplayManager;
+class SystemManager;
+
+/**
+ * Struct to pass references to classes that would otherwise need to be singletons down to
+ * other classes within the engine hierarchy. Made to prevent constant changes to subclasses to
+ * pass specific references through dependency injection. All references on this struct
+ * *should* be explicitly checked for availability as this struct does not guarantee anything.
+ *
+ * \note Dereferencing members of this struct should be deferred. If you are a user of this
+ * class, keep a reference to this mediator instead of just picking references from it when you
+ * receive an instance.
+ *
+ * \warning This class should never be directly accessible from the API
+ */
+struct Mediator {
+ OptionalRef<SDLContext> sdl_context;
+ OptionalRef<ComponentManager> component_manager;
+ OptionalRef<SceneManager> scene_manager;
+ OptionalRef<EventManager> event_manager;
+ OptionalRef<LoopTimerManager> loop_timer;
+ OptionalRef<SaveManager> save_manager;
+ OptionalRef<ResourceManager> resource_manager;
+ OptionalRef<ReplayManager> replay_manager;
+ OptionalRef<SystemManager> system_manager;
+};
+
+} // namespace crepe
diff --git a/src/crepe/manager/ReplayManager.cpp b/src/crepe/manager/ReplayManager.cpp
new file mode 100644
index 0000000..090a94e
--- /dev/null
+++ b/src/crepe/manager/ReplayManager.cpp
@@ -0,0 +1,70 @@
+#include <format>
+
+#include "Manager.h"
+#include "ReplayManager.h"
+
+using namespace crepe;
+using namespace std;
+
+ReplayManager::ReplayManager(Mediator & mediator) : Manager(mediator) {
+ mediator.replay_manager = *this;
+}
+
+void ReplayManager::record_start() {
+ if (this->state == RECORDING) this->release(this->id);
+ this->id++;
+ this->memory[this->id] = make_unique<Recording>();
+ this->recording = *this->memory.at(this->id);
+ this->state = RECORDING;
+}
+
+recording_t ReplayManager::record_end() {
+ this->state = IDLE;
+ return this->id;
+}
+
+void ReplayManager::play(recording_t handle) {
+ if (!this->memory.contains(handle))
+ throw out_of_range(format("ReplayManager: no recording for handle {}", handle));
+ this->recording = *this->memory.at(handle);
+ this->recording->frame = 0;
+ this->state = PLAYING;
+}
+
+void ReplayManager::release(recording_t handle) {
+ if (!this->memory.contains(handle)) return;
+ this->memory.erase(handle);
+}
+
+void ReplayManager::frame_record() {
+ if (this->state != RECORDING)
+ throw runtime_error("ReplayManager: frame_step called while not playing");
+
+ ComponentManager & components = this->mediator.component_manager;
+ Recording & recording = this->recording;
+
+ recording.frames.push_back(components.save());
+ recording.frame++;
+}
+
+bool ReplayManager::frame_step() {
+ if (this->state != PLAYING)
+ throw runtime_error("ReplayManager: frame_step called while not playing");
+
+ ComponentManager & components = this->mediator.component_manager;
+ Recording & recording = this->recording;
+
+ ComponentManager::Snapshot & frame = recording.frames.at(recording.frame);
+
+ components.restore(frame);
+ recording.frame++;
+
+ if (recording.frame < recording.frames.size()) return false;
+ // end of recording
+ recording.frame = 0;
+ this->state = IDLE;
+ this->recording.clear();
+ return true;
+}
+
+ReplayManager::State ReplayManager::get_state() const { return this->state; }
diff --git a/src/crepe/manager/ReplayManager.h b/src/crepe/manager/ReplayManager.h
new file mode 100644
index 0000000..f06a58b
--- /dev/null
+++ b/src/crepe/manager/ReplayManager.h
@@ -0,0 +1,96 @@
+#pragma once
+
+#include <unordered_map>
+
+#include "../util/OptionalRef.h"
+
+#include "ComponentManager.h"
+#include "Manager.h"
+
+namespace crepe {
+
+//! Handle to recording held by ReplayManager
+typedef size_t recording_t;
+
+/**
+ * \brief Replay manager
+ *
+ * The replay manager is responsible for creating, storing and restoring ComponentManager
+ * snapshots. Sequential snapshots can be recorded and replayed in combination with
+ * ReplaySystem.
+ */
+class ReplayManager : public Manager {
+ // TODO: Delete recordings at end of scene
+
+public:
+ ReplayManager(Mediator & mediator);
+
+public:
+ //! Start a new recording
+ void record_start();
+ /**
+ * \brief End the latest recording started by \c record_start()
+ * \returns Handle to recording
+ */
+ recording_t record_end();
+ /**
+ * \brief Play a recording
+ * \param handle Handle to recording (as returned by \c record_end())
+ */
+ void play(recording_t handle);
+ /**
+ * \brief Delete a recording from memory
+ * \param handle Handle to recording (as returned by \c record_end())
+ */
+ void release(recording_t handle);
+
+public:
+ //! Internal state
+ enum State {
+ IDLE, //!< Not doing anything
+ RECORDING, //!< Currently recording
+ PLAYING, //!< Currently playing back a recording
+ };
+ //! Get current internal state
+ State get_state() const;
+
+public:
+ /**
+ * \brief Record a single frame to the current recording
+ *
+ * This function is called by ReplaySystem after the game programmer has called \c
+ * record_start()
+ */
+ void frame_record();
+ /**
+ * \brief Play the next frame of the current recording
+ *
+ * \returns `true` if the recording is finished playing
+ * \returns `false` if there are more frames
+ *
+ * This function also automatically resets the internal state from PLAYING to IDLE at the end
+ * of a recording.
+ */
+ bool frame_step();
+
+private:
+ /**
+ * \brief Recording data
+ */
+ struct Recording {
+ //! Current frame being shown
+ size_t frame = 0;
+ //! All frames in recording
+ std::vector<ComponentManager::Snapshot> frames;
+ };
+ //! Internal state
+ State state = IDLE;
+ //! Current recording handle
+ recording_t id = -1;
+ //! Current recording data
+ OptionalRef<Recording> recording;
+ //! Recording storage
+ std::unordered_map<recording_t, std::unique_ptr<Recording>> memory;
+};
+
+} // namespace crepe
diff --git a/src/crepe/manager/ResourceManager.cpp b/src/crepe/manager/ResourceManager.cpp
new file mode 100644
index 0000000..5713183
--- /dev/null
+++ b/src/crepe/manager/ResourceManager.cpp
@@ -0,0 +1,30 @@
+#include "util/dbg.h"
+
+#include "ResourceManager.h"
+
+using namespace crepe;
+using namespace std;
+
+ResourceManager::ResourceManager(Mediator & mediator) : Manager(mediator) {
+ dbg_trace();
+ mediator.resource_manager = *this;
+}
+ResourceManager::~ResourceManager() { dbg_trace(); }
+
+void ResourceManager::clear() {
+ std::erase_if(this->resources, [](const pair<const Asset, CacheEntry> & pair) {
+ const CacheEntry & entry = pair.second;
+ return entry.persistent == false;
+ });
+}
+
+void ResourceManager::clear_all() { this->resources.clear(); }
+
+void ResourceManager::set_persistent(const Asset & asset, bool persistent) {
+ this->get_entry(asset).persistent = persistent;
+}
+
+ResourceManager::CacheEntry & ResourceManager::get_entry(const Asset & asset) {
+ if (!this->resources.contains(asset)) this->resources[asset] = {};
+ return this->resources.at(asset);
+}
diff --git a/src/crepe/manager/ResourceManager.h b/src/crepe/manager/ResourceManager.h
new file mode 100644
index 0000000..84b275d
--- /dev/null
+++ b/src/crepe/manager/ResourceManager.h
@@ -0,0 +1,78 @@
+#pragma once
+
+#include <memory>
+#include <unordered_map>
+
+#include "../Resource.h"
+#include "../api/Asset.h"
+
+#include "Manager.h"
+
+namespace crepe {
+
+/**
+ * \brief Owner of concrete Resource instances
+ *
+ * ResourceManager caches concrete Resource instances per Asset. Concrete resources are
+ * destroyed at the end of scenes by default, unless the game programmer marks them as
+ * persistent.
+ */
+class ResourceManager : public Manager {
+public:
+ ResourceManager(Mediator & mediator);
+ virtual ~ResourceManager(); // dbg_trace
+
+private:
+ //! Cache entry
+ struct CacheEntry {
+ //! Concrete resource instance
+ std::unique_ptr<Resource> resource = nullptr;
+ //! Prevent ResourceManager::clear from removing this entry
+ bool persistent = false;
+ };
+ //! Internal cache
+ std::unordered_map<const Asset, CacheEntry> resources;
+ /**
+ * \brief Ensure a cache entry exists for this asset and return a mutable reference to it
+ *
+ * \param asset Asset the concrete resource is instantiated from
+ *
+ * \returns Mutable reference to cache entry
+ */
+ CacheEntry & get_entry(const Asset & asset);
+
+public:
+ /**
+ * \brief Mark a resource as persistent (i.e. used across multiple scenes)
+ *
+ * \param asset Asset the concrete resource is instantiated from
+ * \param persistent Whether this resource is persistent (true=keep, false=destroy)
+ */
+ void set_persistent(const Asset & asset, bool persistent);
+
+ /**
+ * \brief Retrieve reference to concrete Resource by Asset
+ *
+ * \param asset Asset the concrete resource is instantiated from
+ * \tparam Resource Concrete derivative of Resource
+ *
+ * This class instantiates the concrete resource if it is not yet stored in the internal
+ * cache, or returns a reference to the cached resource if it already exists.
+ *
+ * \returns Reference to concrete resource
+ *
+ * \throws std::runtime_error if the \c Resource parameter does not match with the actual
+ * type of the resource stored in the cache for this Asset
+ */
+ template <typename Resource>
+ Resource & get(const Asset & asset);
+
+ //! Clear non-persistent resources from cache
+ void clear();
+ //! Clear all resources from cache regardless of persistence
+ void clear_all();
+};
+
+} // namespace crepe
+
+#include "ResourceManager.hpp"
diff --git a/src/crepe/manager/ResourceManager.hpp b/src/crepe/manager/ResourceManager.hpp
new file mode 100644
index 0000000..cf5c949
--- /dev/null
+++ b/src/crepe/manager/ResourceManager.hpp
@@ -0,0 +1,27 @@
+#pragma once
+
+#include <format>
+
+#include "ResourceManager.h"
+
+namespace crepe {
+
+template <typename T>
+T & ResourceManager::get(const Asset & asset) {
+ using namespace std;
+ static_assert(is_base_of<Resource, T>::value,
+ "cache must recieve a derivative class of Resource");
+
+ CacheEntry & entry = this->get_entry(asset);
+ if (entry.resource == nullptr) entry.resource = make_unique<T>(asset, this->mediator);
+
+ T * concrete_resource = dynamic_cast<T *>(entry.resource.get());
+ if (concrete_resource == nullptr)
+ throw runtime_error(format("ResourceManager: mismatch between requested type and "
+ "actual type of resource ({})",
+ asset.get_path()));
+
+ return *concrete_resource;
+}
+
+} // namespace crepe
diff --git a/src/crepe/manager/SaveManager.cpp b/src/crepe/manager/SaveManager.cpp
new file mode 100644
index 0000000..f313ed2
--- /dev/null
+++ b/src/crepe/manager/SaveManager.cpp
@@ -0,0 +1,169 @@
+#include "../ValueBroker.h"
+#include "../api/Config.h"
+#include "../facade/DB.h"
+
+#include "SaveManager.h"
+
+using namespace std;
+using namespace crepe;
+
+SaveManager::SaveManager(Mediator & mediator) : Manager(mediator) {
+ mediator.save_manager = *this;
+}
+
+DB & SaveManager::get_db() {
+ if (this->db == nullptr) {
+ Config & cfg = Config::get_instance();
+ this->db
+ = {new DB(cfg.savemgr.location), [](void * db) { delete static_cast<DB *>(db); }};
+ }
+ return *static_cast<DB *>(this->db.get());
+}
+
+template <>
+string SaveManager::serialize(const string & value) const noexcept {
+ return value;
+}
+template <typename T>
+string SaveManager::serialize(const T & value) const noexcept {
+ return to_string(value);
+}
+template string SaveManager::serialize(const uint8_t &) const noexcept;
+template string SaveManager::serialize(const int8_t &) const noexcept;
+template string SaveManager::serialize(const uint16_t &) const noexcept;
+template string SaveManager::serialize(const int16_t &) const noexcept;
+template string SaveManager::serialize(const uint32_t &) const noexcept;
+template string SaveManager::serialize(const int32_t &) const noexcept;
+template string SaveManager::serialize(const uint64_t &) const noexcept;
+template string SaveManager::serialize(const int64_t &) const noexcept;
+template string SaveManager::serialize(const float &) const noexcept;
+template string SaveManager::serialize(const double &) const noexcept;
+
+template <>
+uint64_t SaveManager::deserialize(const string & value) const noexcept {
+ try {
+ return stoul(value);
+ } catch (std::invalid_argument &) {
+ return 0;
+ }
+}
+template <>
+int64_t SaveManager::deserialize(const string & value) const noexcept {
+ try {
+ return stol(value);
+ } catch (std::invalid_argument &) {
+ return 0;
+ }
+}
+template <>
+float SaveManager::deserialize(const string & value) const noexcept {
+ try {
+ return stof(value);
+ } catch (std::invalid_argument &) {
+ return 0;
+ }
+ return stof(value);
+}
+template <>
+double SaveManager::deserialize(const string & value) const noexcept {
+ try {
+ return stod(value);
+ } catch (std::invalid_argument &) {
+ return 0;
+ }
+}
+template <>
+string SaveManager::deserialize(const string & value) const noexcept {
+ return value;
+}
+
+template <>
+uint8_t SaveManager::deserialize(const string & value) const noexcept {
+ return deserialize<uint64_t>(value);
+}
+template <>
+int8_t SaveManager::deserialize(const string & value) const noexcept {
+ return deserialize<int64_t>(value);
+}
+template <>
+uint16_t SaveManager::deserialize(const string & value) const noexcept {
+ return deserialize<uint64_t>(value);
+}
+template <>
+int16_t SaveManager::deserialize(const string & value) const noexcept {
+ return deserialize<int64_t>(value);
+}
+template <>
+uint32_t SaveManager::deserialize(const string & value) const noexcept {
+ return deserialize<uint64_t>(value);
+}
+template <>
+int32_t SaveManager::deserialize(const string & value) const noexcept {
+ return deserialize<int64_t>(value);
+}
+
+bool SaveManager::has(const string & key) {
+ DB & db = this->get_db();
+ return db.has(key);
+}
+
+template <>
+void SaveManager::set(const string & key, const string & value) {
+ DB & db = this->get_db();
+ db.set(key, value);
+}
+template <typename T>
+void SaveManager::set(const string & key, const T & value) {
+ DB & db = this->get_db();
+ db.set(key, std::to_string(value));
+}
+template void SaveManager::set(const string &, const uint8_t &);
+template void SaveManager::set(const string &, const int8_t &);
+template void SaveManager::set(const string &, const uint16_t &);
+template void SaveManager::set(const string &, const int16_t &);
+template void SaveManager::set(const string &, const uint32_t &);
+template void SaveManager::set(const string &, const int32_t &);
+template void SaveManager::set(const string &, const uint64_t &);
+template void SaveManager::set(const string &, const int64_t &);
+template void SaveManager::set(const string &, const float &);
+template void SaveManager::set(const string &, const double &);
+
+template <typename T>
+T SaveManager::get(const string & key) {
+ return this->deserialize<T>(this->get_db().get(key));
+}
+template uint8_t SaveManager::get(const string &);
+template int8_t SaveManager::get(const string &);
+template uint16_t SaveManager::get(const string &);
+template int16_t SaveManager::get(const string &);
+template uint32_t SaveManager::get(const string &);
+template int32_t SaveManager::get(const string &);
+template uint64_t SaveManager::get(const string &);
+template int64_t SaveManager::get(const string &);
+template float SaveManager::get(const string &);
+template double SaveManager::get(const string &);
+template string SaveManager::get(const string &);
+
+template <typename T>
+ValueBroker<T> SaveManager::get(const string & key, const T & default_value) {
+ if (!this->has(key)) this->set<T>(key, default_value);
+ T value;
+ return {
+ [this, key](const T & target) { this->set<T>(key, target); },
+ [this, key, value]() mutable -> const T & {
+ value = this->get<T>(key);
+ return value;
+ },
+ };
+}
+template ValueBroker<uint8_t> SaveManager::get(const string &, const uint8_t &);
+template ValueBroker<int8_t> SaveManager::get(const string &, const int8_t &);
+template ValueBroker<uint16_t> SaveManager::get(const string &, const uint16_t &);
+template ValueBroker<int16_t> SaveManager::get(const string &, const int16_t &);
+template ValueBroker<uint32_t> SaveManager::get(const string &, const uint32_t &);
+template ValueBroker<int32_t> SaveManager::get(const string &, const int32_t &);
+template ValueBroker<uint64_t> SaveManager::get(const string &, const uint64_t &);
+template ValueBroker<int64_t> SaveManager::get(const string &, const int64_t &);
+template ValueBroker<float> SaveManager::get(const string &, const float &);
+template ValueBroker<double> SaveManager::get(const string &, const double &);
+template ValueBroker<string> SaveManager::get(const string &, const string &);
diff --git a/src/crepe/manager/SaveManager.h b/src/crepe/manager/SaveManager.h
new file mode 100644
index 0000000..1e34bc0
--- /dev/null
+++ b/src/crepe/manager/SaveManager.h
@@ -0,0 +1,104 @@
+#pragma once
+
+#include <functional>
+#include <memory>
+
+#include "../ValueBroker.h"
+
+#include "Manager.h"
+
+namespace crepe {
+
+class DB;
+
+/**
+ * \brief Save data manager
+ *
+ * This class provides access to a simple key-value store that stores
+ * - integers (8-64 bit, signed or unsigned)
+ * - real numbers (float or double)
+ * - string (std::string)
+ *
+ * The underlying database is a key-value store.
+ */
+class SaveManager : public Manager {
+public:
+ /**
+ * \brief Get a read/write reference to a value and initialize it if it does not yet exist
+ *
+ * \param key The value key
+ * \param default_value Value to initialize \c key with if it does not already exist in the
+ * database
+ *
+ * \return Read/write reference to the value
+ */
+ template <typename T>
+ ValueBroker<T> get(const std::string & key, const T & default_value);
+
+ /**
+ * \brief Get a value directly
+ *
+ * \param key The value key
+ *
+ * \return The value
+ *
+ * \note Attempting to read this value before it is initialized (i.e. set) will result in an
+ * exception
+ */
+ template <typename T>
+ T get(const std::string & key);
+
+ /**
+ * \brief Set a value directly
+ *
+ * \param key The value key
+ * \param value The value to store
+ */
+ template <typename T>
+ void set(const std::string & key, const T & value);
+
+ /**
+ * \brief Check if the save file has a value for this \c key
+ *
+ * \param key The value key
+ *
+ * \returns True if the key exists, or false if it does not
+ */
+ bool has(const std::string & key);
+
+public:
+ SaveManager(Mediator & mediator);
+ virtual ~SaveManager() = default;
+
+private:
+ /**
+ * \brief Serialize an arbitrary value to STL string
+ *
+ * \tparam T Type of arbitrary value
+ *
+ * \returns String representation of value
+ */
+ template <typename T>
+ std::string serialize(const T &) const noexcept;
+
+ /**
+ * \brief Deserialize an STL string back to type \c T
+ *
+ * \tparam T Type of value
+ * \param value Serialized value
+ *
+ * \returns Deserialized value
+ */
+ template <typename T>
+ T deserialize(const std::string & value) const noexcept;
+
+protected:
+ //! Create or return DB
+ virtual DB & get_db();
+
+private:
+ //! Database
+ std::unique_ptr<void, std::function<void(void *)>> db = nullptr;
+};
+
+} // namespace crepe
diff --git a/src/crepe/manager/SceneManager.cpp b/src/crepe/manager/SceneManager.cpp
new file mode 100644
index 0000000..d4ca90b
--- /dev/null
+++ b/src/crepe/manager/SceneManager.cpp
@@ -0,0 +1,38 @@
+#include <algorithm>
+#include <memory>
+
+#include "ComponentManager.h"
+#include "SceneManager.h"
+
+using namespace crepe;
+using namespace std;
+
+SceneManager::SceneManager(Mediator & mediator) : Manager(mediator) {
+ mediator.scene_manager = *this;
+}
+
+void SceneManager::set_next_scene(const string & name) { next_scene = name; }
+
+void SceneManager::load_next_scene() {
+ // next scene not set
+ if (this->next_scene.empty()) return;
+
+ auto it = find_if(this->scenes.begin(), this->scenes.end(),
+ [&next_scene = this->next_scene](unique_ptr<Scene> & scene) {
+ return scene.get()->get_name() == next_scene;
+ });
+
+ // next scene not found
+ if (it == this->scenes.end()) return;
+ unique_ptr<Scene> & scene = *it;
+
+ // Delete all components of the current scene
+ ComponentManager & mgr = this->mediator.component_manager;
+ mgr.delete_all_components();
+
+ // Load the new scene
+ scene->load_scene();
+
+ //clear the next scene
+ next_scene.clear();
+}
diff --git a/src/crepe/manager/SceneManager.h b/src/crepe/manager/SceneManager.h
new file mode 100644
index 0000000..e0955c2
--- /dev/null
+++ b/src/crepe/manager/SceneManager.h
@@ -0,0 +1,52 @@
+#pragma once
+
+#include <memory>
+#include <vector>
+
+#include "../api/Scene.h"
+
+#include "Manager.h"
+
+namespace crepe {
+
+class ComponentManager;
+
+/**
+ * \brief Manages scenes
+ *
+ * This class manages scenes. It can add new scenes and load them. It also manages the current scene
+ * and the next scene.
+ */
+class SceneManager : public Manager {
+public:
+ SceneManager(Mediator & mediator);
+
+public:
+ /**
+ * \brief Add a new concrete scene to the scene manager
+ *
+ * \tparam T Type of concrete scene
+ */
+ template <typename T, typename... Args>
+ void add_scene(Args &&... args);
+ /**
+ * \brief Set the next scene
+ *
+ * This scene will be loaded at the end of the frame
+ *
+ * \param name Name of the next scene
+ */
+ void set_next_scene(const std::string & name);
+ //! Load a new scene (if there is one)
+ void load_next_scene();
+
+private:
+ //! Vector of concrete scenes (added by add_scene())
+ std::vector<std::unique_ptr<Scene>> scenes;
+ //! Next scene to load
+ std::string next_scene;
+};
+
+} // namespace crepe
+
+#include "SceneManager.hpp"
diff --git a/src/crepe/manager/SceneManager.hpp b/src/crepe/manager/SceneManager.hpp
new file mode 100644
index 0000000..dff4e51
--- /dev/null
+++ b/src/crepe/manager/SceneManager.hpp
@@ -0,0 +1,25 @@
+#pragma once
+
+#include "SceneManager.h"
+
+namespace crepe {
+
+template <typename T, typename... Args>
+void SceneManager::add_scene(Args &&... args) {
+ using namespace std;
+ static_assert(is_base_of<Scene, T>::value, "T must be derived from Scene");
+
+ Scene * scene = new T(std::forward<Args>(args)...);
+ unique_ptr<Scene> unique_scene(scene);
+
+ unique_scene->mediator = this->mediator;
+
+ this->scenes.emplace_back(std::move(unique_scene));
+
+ // The first scene added, is the one that will be loaded at the beginning
+ if (next_scene.empty()) {
+ next_scene = scene->get_name();
+ }
+}
+
+} // namespace crepe
diff --git a/src/crepe/manager/SystemManager.cpp b/src/crepe/manager/SystemManager.cpp
new file mode 100644
index 0000000..5ada30f
--- /dev/null
+++ b/src/crepe/manager/SystemManager.cpp
@@ -0,0 +1,66 @@
+#include "../system/AISystem.h"
+#include "../system/AnimatorSystem.h"
+#include "../system/AudioSystem.h"
+#include "../system/CollisionSystem.h"
+#include "../system/EventSystem.h"
+#include "../system/InputSystem.h"
+#include "../system/ParticleSystem.h"
+#include "../system/PhysicsSystem.h"
+#include "../system/RenderSystem.h"
+#include "../system/ReplaySystem.h"
+#include "../system/ScriptSystem.h"
+
+#include "SystemManager.h"
+
+using namespace crepe;
+using namespace std;
+
+SystemManager::SystemManager(Mediator & mediator) : Manager(mediator) {
+ this->load_system<InputSystem>();
+ this->load_system<EventSystem>();
+ this->load_system<ScriptSystem>();
+ this->load_system<AISystem>();
+ this->load_system<PhysicsSystem>();
+ this->load_system<CollisionSystem>();
+ this->load_system<AudioSystem>();
+ this->load_system<AnimatorSystem>();
+ this->load_system<ParticleSystem>();
+ this->load_system<RenderSystem>();
+ this->load_system<ReplaySystem>();
+
+ this->mediator.system_manager = *this;
+}
+
+void SystemManager::fixed_update() {
+ for (auto & [type, system] : this->systems) {
+ if (!system->active) continue;
+ system->fixed_update();
+ }
+}
+
+void SystemManager::frame_update() {
+ for (auto & [type, system] : this->systems) {
+ if (!system->active) continue;
+ system->frame_update();
+ }
+}
+
+SystemManager::Snapshot SystemManager::save() {
+ Snapshot snapshot;
+ for (auto & [type, system] : this->systems) {
+ snapshot[type] = system->active;
+ }
+ return snapshot;
+}
+
+void SystemManager::restore(const Snapshot & snapshot) {
+ for (auto & [type, active] : snapshot) {
+ this->systems[type]->active = active;
+ }
+}
+
+void SystemManager::disable_all() {
+ for (auto & [type, system] : this->systems) {
+ system->active = false;
+ }
+}
diff --git a/src/crepe/manager/SystemManager.h b/src/crepe/manager/SystemManager.h
new file mode 100644
index 0000000..50acf77
--- /dev/null
+++ b/src/crepe/manager/SystemManager.h
@@ -0,0 +1,85 @@
+#pragma once
+
+#include <memory>
+#include <typeindex>
+#include <unordered_map>
+
+#include "../system/System.h"
+
+#include "Manager.h"
+
+namespace crepe {
+
+/**
+ * \brief Collection of all systems
+ *
+ * This manager aggregates all systems and provides utility functions to retrieve references to
+ * and update systems.
+ */
+class SystemManager : public Manager {
+public:
+ SystemManager(Mediator &);
+
+ /**
+ * \brief Per-frame update.
+ *
+ * Updates the game state based on the elapsed time since the last frame.
+ */
+ void frame_update();
+
+ /**
+ * \brief Fixed update executed at a fixed rate.
+ *
+ * This function updates physics and game logic based on LoopTimer's fixed_delta_time.
+ */
+ void fixed_update();
+
+private:
+ /**
+ * \brief Collection of System instances
+ *
+ * This map holds System instances indexed by the system's class typeid. It is filled in the
+ * constructor of \c SystemManager using SystemManager::load_system.
+ */
+ std::unordered_map<std::type_index, std::unique_ptr<System>> systems;
+ /**
+ * \brief Initialize a system
+ * \tparam T System type (must be derivative of \c System)
+ */
+ template <class T>
+ void load_system();
+
+public:
+ /**
+ * \brief Retrieve a reference to ECS system
+ * \tparam T System type
+ * \returns Reference to system instance
+ * \throws std::runtime_error if the System is not initialized
+ */
+ template <class T>
+ T & get_system();
+
+public:
+ /**
+ * \brief SystemManager snapshot
+ *
+ * The SystemManager snapshot only stores which systems are active
+ */
+ typedef std::unordered_map<std::type_index, bool> Snapshot;
+ /**
+ * \brief Save a snapshot of the systems' state
+ * \returns Copy of each system's active property
+ */
+ Snapshot save();
+ /**
+ * \brief Restore system active state from a snapshot
+ * \param snapshot Snapshot to restore from (as returned by \c save())
+ */
+ void restore(const Snapshot & snapshot);
+ //! Disable all systems
+ void disable_all();
+};
+
+} // namespace crepe
+
+#include "SystemManager.hpp"
diff --git a/src/crepe/manager/SystemManager.hpp b/src/crepe/manager/SystemManager.hpp
new file mode 100644
index 0000000..3d26e4c
--- /dev/null
+++ b/src/crepe/manager/SystemManager.hpp
@@ -0,0 +1,41 @@
+#pragma once
+
+#include <cassert>
+#include <format>
+#include <memory>
+
+#include "SystemManager.h"
+
+namespace crepe {
+
+template <class T>
+T & SystemManager::get_system() {
+ using namespace std;
+ static_assert(is_base_of<System, T>::value,
+ "get_system must recieve a derivative class of System");
+
+ const type_info & type = typeid(T);
+ if (!this->systems.contains(type))
+ throw runtime_error(format("SystemManager: {} is not initialized", type.name()));
+
+ System * system = this->systems.at(type).get();
+ T * concrete_system = dynamic_cast<T *>(system);
+ assert(concrete_system != nullptr);
+
+ return *concrete_system;
+}
+
+template <class T>
+void SystemManager::load_system() {
+ using namespace std;
+ static_assert(is_base_of<System, T>::value,
+ "load_system must recieve a derivative class of System");
+
+ const type_info & type = typeid(T);
+ if (this->systems.contains(type))
+ throw runtime_error(format("SystemManager: {} is already initialized", type.name()));
+ System * system = new T(this->mediator);
+ this->systems[type] = unique_ptr<System>(system);
+}
+
+} // namespace crepe
diff --git a/src/crepe/system/AISystem.cpp b/src/crepe/system/AISystem.cpp
new file mode 100644
index 0000000..0f35010
--- /dev/null
+++ b/src/crepe/system/AISystem.cpp
@@ -0,0 +1,186 @@
+#include <algorithm>
+#include <cmath>
+
+#include "manager/ComponentManager.h"
+#include "manager/LoopTimerManager.h"
+#include "manager/Mediator.h"
+
+#include "AISystem.h"
+
+using namespace crepe;
+using namespace std::chrono;
+
+void AISystem::fixed_update() {
+ const Mediator & mediator = this->mediator;
+ ComponentManager & mgr = mediator.component_manager;
+ LoopTimerManager & loop_timer = mediator.loop_timer;
+ RefVector<AI> ai_components = mgr.get_components_by_type<AI>();
+
+ float dt = loop_timer.get_scaled_fixed_delta_time().count();
+
+ // Loop through all AI components
+ for (AI & ai : ai_components) {
+ if (!ai.active) {
+ continue;
+ }
+
+ RefVector<Rigidbody> rigidbodies
+ = mgr.get_components_by_id<Rigidbody>(ai.game_object_id);
+ if (rigidbodies.empty()) {
+ throw std::runtime_error(
+ "AI component must be attached to a GameObject with a Rigidbody component");
+ }
+ Rigidbody & rigidbody = rigidbodies.front().get();
+ if (!rigidbody.active) {
+ continue;
+ }
+ if (rigidbody.data.mass <= 0) {
+ throw std::runtime_error("Mass must be greater than 0");
+ }
+
+ // Calculate the force to apply to the entity
+ vec2 force = this->calculate(ai, rigidbody);
+ // Calculate the acceleration (using the above calculated force)
+ vec2 acceleration = force / rigidbody.data.mass;
+ // Finally, update Rigidbody's velocity
+ rigidbody.data.linear_velocity += acceleration * dt;
+ }
+}
+
+vec2 AISystem::calculate(AI & ai, const Rigidbody & rigidbody) {
+ const Mediator & mediator = this->mediator;
+ ComponentManager & mgr = mediator.component_manager;
+ RefVector<Transform> transforms = mgr.get_components_by_id<Transform>(ai.game_object_id);
+ Transform & transform = transforms.front().get();
+
+ vec2 force;
+
+ // Run all the behaviors that are on, and stop if the force gets too high
+ if (ai.on(AI::BehaviorTypeMask::FLEE)) {
+ vec2 force_to_add = this->flee(ai, rigidbody, transform);
+
+ if (!this->accumulate_force(ai, force, force_to_add)) {
+ return force;
+ }
+ }
+ if (ai.on(AI::BehaviorTypeMask::ARRIVE)) {
+ vec2 force_to_add = this->arrive(ai, rigidbody, transform);
+
+ if (!this->accumulate_force(ai, force, force_to_add)) {
+ return force;
+ }
+ }
+ if (ai.on(AI::BehaviorTypeMask::SEEK)) {
+ vec2 force_to_add = this->seek(ai, rigidbody, transform);
+
+ if (!this->accumulate_force(ai, force, force_to_add)) {
+ return force;
+ }
+ }
+ if (ai.on(AI::BehaviorTypeMask::PATH_FOLLOW)) {
+ vec2 force_to_add = this->path_follow(ai, rigidbody, transform);
+
+ if (!this->accumulate_force(ai, force, force_to_add)) {
+ return force;
+ }
+ }
+
+ return force;
+}
+
+bool AISystem::accumulate_force(const AI & ai, vec2 & running_total, vec2 & force_to_add) {
+ float magnitude = running_total.length();
+ float magnitude_remaining = ai.max_force - magnitude;
+
+ if (magnitude_remaining <= 0.0f) {
+ // If the force is already at/above the max force, return false
+ return false;
+ }
+
+ float magnitude_to_add = force_to_add.length();
+ if (magnitude_to_add < magnitude_remaining) {
+ // If the force to add is less than the remaining force, add it
+ running_total += force_to_add;
+ } else {
+ // If the force to add is greater than the remaining force, add a fraction of it
+ force_to_add.normalize();
+ running_total += force_to_add * magnitude_remaining;
+ }
+
+ return true;
+}
+
+vec2 AISystem::seek(const AI & ai, const Rigidbody & rigidbody,
+ const Transform & transform) const {
+ // Calculate the desired velocity
+ vec2 desired_velocity = ai.seek_target - transform.position;
+ desired_velocity.normalize();
+ desired_velocity *= rigidbody.data.max_linear_velocity;
+
+ return desired_velocity - rigidbody.data.linear_velocity;
+}
+
+vec2 AISystem::flee(const AI & ai, const Rigidbody & rigidbody,
+ const Transform & transform) const {
+ // Calculate the desired velocity if the entity is within the panic distance
+ vec2 desired_velocity = transform.position - ai.flee_target;
+ if (desired_velocity.length_squared() > ai.square_flee_panic_distance) {
+ return vec2{0, 0};
+ }
+ desired_velocity.normalize();
+ desired_velocity *= rigidbody.data.max_linear_velocity;
+
+ return desired_velocity - rigidbody.data.linear_velocity;
+}
+
+vec2 AISystem::arrive(const AI & ai, const Rigidbody & rigidbody,
+ const Transform & transform) const {
+ // Calculate the desired velocity (taking into account the deceleration rate)
+ vec2 to_target = ai.arrive_target - transform.position;
+ float distance = to_target.length();
+ if (distance > 0.0f) {
+ if (ai.arrive_deceleration <= 0.0f) {
+ throw std::runtime_error("Deceleration rate must be greater than 0");
+ }
+
+ float speed = distance / ai.arrive_deceleration;
+ speed = std::min(speed, rigidbody.data.max_linear_velocity);
+ vec2 desired_velocity = to_target * (speed / distance);
+
+ return desired_velocity - rigidbody.data.linear_velocity;
+ }
+
+ return vec2{0, 0};
+}
+
+vec2 AISystem::path_follow(AI & ai, const Rigidbody & rigidbody, const Transform & transform) {
+ if (ai.path.empty()) {
+ return vec2{0, 0};
+ }
+
+ // Get the target node
+ vec2 target = ai.path.at(ai.path_index);
+ // Calculate the force to apply to the entity
+ vec2 to_target = target - transform.position;
+ if (to_target.length_squared() > ai.path_node_distance * ai.path_node_distance) {
+ // If the entity is not close enough to the target node, seek it
+ ai.seek_target = target;
+ ai.arrive_target = target;
+ } else {
+ // If the entity is close enough to the target node, move to the next node
+ ai.path_index++;
+ if (ai.path_index >= ai.path.size()) {
+ if (ai.path_loop) {
+ // If the path is looping, reset the path index
+ ai.path_index = 0;
+ } else {
+ // If the path is not looping, arrive at the last node
+ ai.path_index = ai.path.size() - 1;
+ return this->arrive(ai, rigidbody, transform);
+ }
+ }
+ }
+
+ // Seek the target node
+ return this->seek(ai, rigidbody, transform);
+}
diff --git a/src/crepe/system/AISystem.h b/src/crepe/system/AISystem.h
new file mode 100644
index 0000000..04807cf
--- /dev/null
+++ b/src/crepe/system/AISystem.h
@@ -0,0 +1,81 @@
+#pragma once
+
+#include "api/AI.h"
+#include "api/Rigidbody.h"
+
+#include "System.h"
+#include "api/Transform.h"
+#include "types.h"
+
+namespace crepe {
+
+/**
+ * \brief The AISystem is used to control the movement of entities using AI.
+ *
+ * The AISystem is used to control the movement of entities using AI. The AISystem can be used to
+ * implement different behaviors such as seeking, fleeing, arriving, and path following.
+ */
+class AISystem : public System {
+public:
+ using System::System;
+
+ //! Update the AI system
+ void fixed_update() override;
+
+private:
+ /**
+ * \brief Calculate the total force to apply to the entity
+ *
+ * \param ai The AI component
+ * \param rigidbody The Rigidbody component
+ */
+ vec2 calculate(AI & ai, const Rigidbody & rigidbody);
+ /**
+ * \brief Accumulate the force to apply to the entity
+ *
+ * \param ai The AI component
+ * \param running_total The running total of the force
+ * \param force_to_add The force to add
+ * \return true if the force was added, false otherwise
+ */
+ bool accumulate_force(const AI & ai, vec2 & running_total, vec2 & force_to_add);
+
+ /**
+ * \brief Calculate the seek force
+ *
+ * \param ai The AI component
+ * \param rigidbody The Rigidbody component
+ * \param transform The Transform component
+ * \return The seek force
+ */
+ vec2 seek(const AI & ai, const Rigidbody & rigidbody, const Transform & transform) const;
+ /**
+ * \brief Calculate the flee force
+ *
+ * \param ai The AI component
+ * \param rigidbody The Rigidbody component
+ * \param transform The Transform component
+ * \return The flee force
+ */
+ vec2 flee(const AI & ai, const Rigidbody & rigidbody, const Transform & transform) const;
+ /**
+ * \brief Calculate the arrive force
+ *
+ * \param ai The AI component
+ * \param rigidbody The Rigidbody component
+ * \param transform The Transform component
+ * \return The arrive force
+ */
+ vec2 arrive(const AI & ai, const Rigidbody & rigidbody, const Transform & transform) const;
+ /**
+ * \brief Calculate the path follow force
+ *
+ * \param ai The AI component
+ * \param rigidbody The Rigidbody component
+ * \param transform The Transform component
+ * \return The path follow force
+ */
+ vec2 path_follow(AI & ai, const Rigidbody & rigidbody, const Transform & transform);
+};
+
+} // namespace crepe
diff --git a/src/crepe/system/AnimatorSystem.cpp b/src/crepe/system/AnimatorSystem.cpp
new file mode 100644
index 0000000..e5ab2fa
--- /dev/null
+++ b/src/crepe/system/AnimatorSystem.cpp
@@ -0,0 +1,40 @@
+#include "../api/Animator.h"
+#include "../manager/ComponentManager.h"
+#include "../manager/LoopTimerManager.h"
+#include <chrono>
+
+#include "AnimatorSystem.h"
+
+using namespace crepe;
+using namespace std::chrono;
+
+void AnimatorSystem::frame_update() {
+ ComponentManager & mgr = this->mediator.component_manager;
+ LoopTimerManager & timer = this->mediator.loop_timer;
+ RefVector<Animator> animations = mgr.get_components_by_type<Animator>();
+
+ float elapsed_time = duration_cast<duration<float>>(timer.get_elapsed_time()).count();
+
+ for (Animator & a : animations) {
+ if (!a.active) continue;
+ if (a.data.fps == 0) continue;
+
+ Animator::Data & ctx = a.data;
+ float frame_duration = 1.0f / ctx.fps;
+
+ int last_frame = ctx.row;
+
+ int cycle_end = (ctx.cycle_end == -1) ? a.grid_size.x : ctx.cycle_end;
+ int total_frames = cycle_end - ctx.cycle_start;
+
+ int curr_frame = static_cast<int>(elapsed_time / frame_duration) % total_frames;
+
+ ctx.row = ctx.cycle_start + curr_frame;
+ a.spritesheet.mask.x = ctx.row * a.spritesheet.mask.w;
+ a.spritesheet.mask.y = (ctx.col * a.spritesheet.mask.h);
+
+ if (!ctx.looping && curr_frame == ctx.cycle_start && last_frame == total_frames - 1) {
+ a.active = false;
+ }
+ }
+}
diff --git a/src/crepe/system/AnimatorSystem.h b/src/crepe/system/AnimatorSystem.h
new file mode 100644
index 0000000..092e131
--- /dev/null
+++ b/src/crepe/system/AnimatorSystem.h
@@ -0,0 +1,28 @@
+#pragma once
+
+#include "System.h"
+
+namespace crepe {
+
+/**
+ * \brief The AnimatorSystem is responsible for managing and updating all Animator components.
+ *
+ * This system is responsible for controlling the behavior of the animations for all entities
+ * that have the Animator component attached. It updates the animations by controlling their
+ * frame changes, looping behavior, and overall animation state.
+ */
+class AnimatorSystem : public System {
+
+public:
+ using System::System;
+ /**
+ * \brief Updates the Animator components.
+ *
+ * This method is called to update the state of all
+ * Animator components, moving the animations forward and managing their behavior (e.g.,
+ * looping).
+ */
+ void frame_update() override;
+};
+
+} // namespace crepe
diff --git a/src/crepe/system/AudioSystem.cpp b/src/crepe/system/AudioSystem.cpp
new file mode 100644
index 0000000..d4e8b9f
--- /dev/null
+++ b/src/crepe/system/AudioSystem.cpp
@@ -0,0 +1,62 @@
+#include "AudioSystem.h"
+
+#include "../manager/ComponentManager.h"
+#include "../manager/ResourceManager.h"
+#include "../types.h"
+
+using namespace crepe;
+using namespace std;
+
+void AudioSystem::fixed_update() {
+ ComponentManager & component_manager = this->mediator.component_manager;
+ ResourceManager & resource_manager = this->mediator.resource_manager;
+ RefVector<AudioSource> components
+ = component_manager.get_components_by_type<AudioSource>();
+
+ for (AudioSource & component : components) {
+ Sound & resource = resource_manager.get<Sound>(component.source);
+
+ this->diff_update(component, resource);
+
+ this->update_last(component);
+ }
+}
+
+void AudioSystem::diff_update(AudioSource & component, Sound & resource) {
+ SoundContext & context = this->get_context();
+
+ if (component.active != component.last_active) {
+ if (!component.active) {
+ context.stop(component.voice);
+ return;
+ }
+ if (component.play_on_awake) component.oneshot_play = true;
+ }
+ if (!component.active) return;
+
+ if (component.oneshot_play) {
+ component.voice = context.play(resource);
+ component.oneshot_play = false;
+ }
+ if (component.oneshot_stop) {
+ context.stop(component.voice);
+ component.oneshot_stop = false;
+ }
+ if (component.volume != component.last_volume) {
+ context.set_volume(component.voice, component.volume);
+ }
+ if (component.loop != component.last_loop) {
+ context.set_loop(component.voice, component.loop);
+ }
+}
+
+void AudioSystem::update_last(AudioSource & component) {
+ component.last_active = component.active;
+ component.last_loop = component.loop;
+ component.last_volume = component.volume;
+}
+
+SoundContext & AudioSystem::get_context() {
+ if (this->context == nullptr) this->context = make_unique<SoundContext>();
+ return *this->context.get();
+}
diff --git a/src/crepe/system/AudioSystem.h b/src/crepe/system/AudioSystem.h
new file mode 100644
index 0000000..56fc98c
--- /dev/null
+++ b/src/crepe/system/AudioSystem.h
@@ -0,0 +1,51 @@
+#pragma once
+
+#include "../api/AudioSource.h"
+#include "../facade/Sound.h"
+#include "../facade/SoundContext.h"
+
+#include "System.h"
+
+namespace crepe {
+
+class AudioSystem : public System {
+public:
+ using System::System;
+ void fixed_update() override;
+
+private:
+ /**
+ * \brief Update `last_*` members of \c component
+ *
+ * Copies all component properties stored for comparison between AudioSystem::update() calls
+ *
+ * \param component AudioSource component to update
+ */
+ void update_last(AudioSource & component);
+
+ /**
+ * \brief Compare update component
+ *
+ * Compares properties of \c component and \c data, and calls SoundContext functions where
+ * applicable.
+ *
+ * \param component AudioSource component to update
+ * \param resource Sound instance for AudioSource's Asset
+ */
+ void diff_update(AudioSource & component, Sound & resource);
+
+protected:
+ /**
+ * \brief Get SoundContext
+ *
+ * SoundContext is retrieved through this function instead of being a direct member of
+ * AudioSystem to aid with testability.
+ */
+ virtual SoundContext & get_context();
+
+private:
+ //! SoundContext
+ std::unique_ptr<SoundContext> context = nullptr;
+};
+
+} // namespace crepe
diff --git a/src/crepe/system/CMakeLists.txt b/src/crepe/system/CMakeLists.txt
new file mode 100644
index 0000000..52369d0
--- /dev/null
+++ b/src/crepe/system/CMakeLists.txt
@@ -0,0 +1,28 @@
+target_sources(crepe PUBLIC
+ System.cpp
+ ParticleSystem.cpp
+ ScriptSystem.cpp
+ PhysicsSystem.cpp
+ CollisionSystem.cpp
+ RenderSystem.cpp
+ AudioSystem.cpp
+ AnimatorSystem.cpp
+ InputSystem.cpp
+ EventSystem.cpp
+ ReplaySystem.cpp
+ AISystem.cpp
+)
+
+target_sources(crepe PUBLIC FILE_SET HEADERS FILES
+ System.h
+ ScriptSystem.h
+ PhysicsSystem.h
+ CollisionSystem.h
+ RenderSystem.h
+ AudioSystem.h
+ AnimatorSystem.h
+ InputSystem.h
+ EventSystem.h
+ ReplaySystem.h
+ AISystem.h
+)
diff --git a/src/crepe/system/CollisionSystem.cpp b/src/crepe/system/CollisionSystem.cpp
new file mode 100644
index 0000000..9d88d9f
--- /dev/null
+++ b/src/crepe/system/CollisionSystem.cpp
@@ -0,0 +1,575 @@
+#include <algorithm>
+#include <cmath>
+#include <cstddef>
+#include <functional>
+#include <optional>
+#include <utility>
+#include <variant>
+
+#include "../manager/ComponentManager.h"
+#include "../manager/EventManager.h"
+#include "api/BoxCollider.h"
+#include "api/CircleCollider.h"
+#include "api/Event.h"
+#include "api/Metadata.h"
+#include "api/Rigidbody.h"
+#include "api/Transform.h"
+#include "api/Vector2.h"
+
+#include "Collider.h"
+#include "CollisionSystem.h"
+#include "types.h"
+#include "util/OptionalRef.h"
+
+using namespace crepe;
+
+void CollisionSystem::fixed_update() {
+ std::vector<CollisionInternal> all_colliders;
+ game_object_id_t id = 0;
+ ComponentManager & mgr = this->mediator.component_manager;
+ RefVector<Rigidbody> rigidbodies = mgr.get_components_by_type<Rigidbody>();
+ // Collisions can only happen on object with a rigidbody
+ for (Rigidbody & rigidbody : rigidbodies) {
+ if (!rigidbody.active) continue;
+ id = rigidbody.game_object_id;
+ Transform & transform = mgr.get_components_by_id<Transform>(id).front().get();
+ // Check if the boxcollider is active and has the same id as the rigidbody.
+ RefVector<BoxCollider> boxcolliders = mgr.get_components_by_type<BoxCollider>();
+ for (BoxCollider & boxcollider : boxcolliders) {
+ if (boxcollider.game_object_id != id) continue;
+ if (!boxcollider.active) continue;
+ all_colliders.push_back({.id = id,
+ .collider = collider_variant{boxcollider},
+ .transform = transform,
+ .rigidbody = rigidbody});
+ }
+ // Check if the circlecollider is active and has the same id as the rigidbody.
+ RefVector<CircleCollider> circlecolliders
+ = mgr.get_components_by_type<CircleCollider>();
+ for (CircleCollider & circlecollider : circlecolliders) {
+ if (circlecollider.game_object_id != id) continue;
+ if (!circlecollider.active) continue;
+ all_colliders.push_back({.id = id,
+ .collider = collider_variant{circlecollider},
+ .transform = transform,
+ .rigidbody = rigidbody});
+ }
+ }
+
+ // Check between all colliders if there is a collision
+ std::vector<std::pair<CollisionInternal, CollisionInternal>> collided
+ = this->gather_collisions(all_colliders);
+
+ // For both objects call the collision handler
+ for (auto & collision_pair : collided) {
+ this->collision_handler_request(collision_pair.first, collision_pair.second);
+ this->collision_handler_request(collision_pair.second, collision_pair.first);
+ }
+}
+
+void CollisionSystem::collision_handler_request(CollisionInternal & this_data,
+ CollisionInternal & other_data) {
+
+ CollisionInternalType type
+ = this->get_collider_type(this_data.collider, other_data.collider);
+ std::pair<vec2, CollisionSystem::Direction> resolution_data
+ = this->collision_handler(this_data, other_data, type);
+ ComponentManager & mgr = this->mediator.component_manager;
+ OptionalRef<Metadata> this_metadata
+ = mgr.get_components_by_id<Metadata>(this_data.id).front().get();
+ OptionalRef<Metadata> other_metadata
+ = mgr.get_components_by_id<Metadata>(other_data.id).front().get();
+ OptionalRef<Collider> this_collider;
+ OptionalRef<Collider> other_collider;
+ switch (type) {
+ case CollisionInternalType::BOX_BOX: {
+ this_collider = std::get<std::reference_wrapper<BoxCollider>>(this_data.collider);
+ other_collider
+ = std::get<std::reference_wrapper<BoxCollider>>(other_data.collider);
+ break;
+ }
+ case CollisionInternalType::BOX_CIRCLE: {
+ this_collider = std::get<std::reference_wrapper<BoxCollider>>(this_data.collider);
+ other_collider
+ = std::get<std::reference_wrapper<CircleCollider>>(other_data.collider);
+ break;
+ }
+ case CollisionInternalType::CIRCLE_BOX: {
+ this_collider
+ = std::get<std::reference_wrapper<CircleCollider>>(this_data.collider);
+ other_collider
+ = std::get<std::reference_wrapper<BoxCollider>>(other_data.collider);
+ break;
+ }
+ case CollisionInternalType::CIRCLE_CIRCLE: {
+ this_collider
+ = std::get<std::reference_wrapper<CircleCollider>>(this_data.collider);
+ other_collider
+ = std::get<std::reference_wrapper<CircleCollider>>(other_data.collider);
+ break;
+ }
+ }
+
+ // collision info
+ crepe::CollisionSystem::CollisionInfo collision_info{
+ .this_collider = this_collider,
+ .this_transform = this_data.transform,
+ .this_rigidbody = this_data.rigidbody,
+ .this_metadata = this_metadata,
+ .other_collider = other_collider,
+ .other_transform = other_data.transform,
+ .other_rigidbody = other_data.rigidbody,
+ .other_metadata = other_metadata,
+ .resolution = resolution_data.first,
+ .resolution_direction = resolution_data.second,
+ };
+
+ // Determine if static needs to be called
+ this->determine_collision_handler(collision_info);
+}
+
+std::pair<vec2, CollisionSystem::Direction>
+CollisionSystem::collision_handler(CollisionInternal & data1, CollisionInternal & data2,
+ CollisionInternalType type) {
+ vec2 resolution;
+ switch (type) {
+ case CollisionInternalType::BOX_BOX: {
+ const BoxCollider & collider1
+ = std::get<std::reference_wrapper<BoxCollider>>(data1.collider);
+ const BoxCollider & collider2
+ = std::get<std::reference_wrapper<BoxCollider>>(data2.collider);
+ vec2 collider_pos1 = this->get_current_position(collider1.offset, data1.transform,
+ data1.rigidbody);
+ vec2 collider_pos2 = this->get_current_position(collider2.offset, data2.transform,
+ data2.rigidbody);
+ resolution = this->get_box_box_resolution(collider1, collider2, collider_pos1,
+ collider_pos2);
+ break;
+ }
+ case CollisionInternalType::BOX_CIRCLE: {
+ const BoxCollider & collider1
+ = std::get<std::reference_wrapper<BoxCollider>>(data1.collider);
+ const CircleCollider & collider2
+ = std::get<std::reference_wrapper<CircleCollider>>(data2.collider);
+ vec2 collider_pos1 = this->get_current_position(collider1.offset, data1.transform,
+ data1.rigidbody);
+ vec2 collider_pos2 = this->get_current_position(collider2.offset, data2.transform,
+ data2.rigidbody);
+ resolution = -this->get_circle_box_resolution(collider2, collider1, collider_pos2,
+ collider_pos1);
+ break;
+ }
+ case CollisionInternalType::CIRCLE_CIRCLE: {
+ const CircleCollider & collider1
+ = std::get<std::reference_wrapper<CircleCollider>>(data1.collider);
+ const CircleCollider & collider2
+ = std::get<std::reference_wrapper<CircleCollider>>(data2.collider);
+ vec2 collider_pos1 = this->get_current_position(collider1.offset, data1.transform,
+ data1.rigidbody);
+ vec2 collider_pos2 = this->get_current_position(collider2.offset, data2.transform,
+ data2.rigidbody);
+ resolution = this->get_circle_circle_resolution(collider1, collider2,
+ collider_pos1, collider_pos2);
+ break;
+ }
+ case CollisionInternalType::CIRCLE_BOX: {
+ const CircleCollider & collider1
+ = std::get<std::reference_wrapper<CircleCollider>>(data1.collider);
+ const BoxCollider & collider2
+ = std::get<std::reference_wrapper<BoxCollider>>(data2.collider);
+ vec2 collider_pos1 = this->get_current_position(collider1.offset, data1.transform,
+ data1.rigidbody);
+ vec2 collider_pos2 = this->get_current_position(collider2.offset, data2.transform,
+ data2.rigidbody);
+ resolution = this->get_circle_box_resolution(collider1, collider2, collider_pos1,
+ collider_pos2);
+ break;
+ }
+ }
+
+ Direction resolution_direction = Direction::NONE;
+ if (resolution.x != 0 && resolution.y != 0) {
+ resolution_direction = Direction::BOTH;
+ } else if (resolution.x != 0) {
+ resolution_direction = Direction::X_DIRECTION;
+ //checks if the other velocity has a value and if this object moved
+ if (data1.rigidbody.data.linear_velocity.x != 0
+ && data1.rigidbody.data.linear_velocity.y != 0)
+ resolution.y = -data1.rigidbody.data.linear_velocity.y
+ * (resolution.x / data1.rigidbody.data.linear_velocity.x);
+ } else if (resolution.y != 0) {
+ resolution_direction = Direction::Y_DIRECTION;
+ //checks if the other velocity has a value and if this object moved
+ if (data1.rigidbody.data.linear_velocity.x != 0
+ && data1.rigidbody.data.linear_velocity.y != 0)
+ resolution.x = -data1.rigidbody.data.linear_velocity.x
+ * (resolution.y / data1.rigidbody.data.linear_velocity.y);
+ }
+
+ return std::make_pair(resolution, resolution_direction);
+}
+
+vec2 CollisionSystem::get_box_box_resolution(const BoxCollider & box_collider1,
+ const BoxCollider & box_collider2,
+ const vec2 & final_position1,
+ const vec2 & final_position2) const {
+ vec2 resolution; // Default resolution vector
+ vec2 delta = final_position2 - final_position1;
+
+ // Compute half-dimensions of the boxes
+ float half_width1 = box_collider1.dimensions.x / 2.0;
+ float half_height1 = box_collider1.dimensions.y / 2.0;
+ float half_width2 = box_collider2.dimensions.x / 2.0;
+ float half_height2 = box_collider2.dimensions.y / 2.0;
+
+ // Calculate overlaps along X and Y axes
+ float overlap_x = (half_width1 + half_width2) - std::abs(delta.x);
+ float overlap_y = (half_height1 + half_height2) - std::abs(delta.y);
+
+ // Check if there is a collision should always be true
+ if (overlap_x > 0 && overlap_y > 0) {
+ // Determine the direction of resolution
+ if (overlap_x < overlap_y) {
+ // Resolve along the X-axis (smallest overlap)
+ resolution.x = (delta.x > 0) ? -overlap_x : overlap_x;
+ } else if (overlap_y < overlap_x) {
+ // Resolve along the Y-axis (smallest overlap)
+ resolution.y = (delta.y > 0) ? -overlap_y : overlap_y;
+ } else {
+ // Equal overlap, resolve both directions with preference
+ resolution.x = (delta.x > 0) ? -overlap_x : overlap_x;
+ resolution.y = (delta.y > 0) ? -overlap_y : overlap_y;
+ }
+ }
+
+ return resolution;
+}
+
+vec2 CollisionSystem::get_circle_circle_resolution(const CircleCollider & circle_collider1,
+ const CircleCollider & circle_collider2,
+ const vec2 & final_position1,
+ const vec2 & final_position2) const {
+ vec2 delta = final_position2 - final_position1;
+
+ // Compute the distance between the two circle centers
+ float distance = std::sqrt(delta.x * delta.x + delta.y * delta.y);
+
+ // Compute the combined radii of the two circles
+ float combined_radius = circle_collider1.radius + circle_collider2.radius;
+
+ // Compute the penetration depth
+ float penetration_depth = combined_radius - distance;
+
+ // Normalize the delta vector to get the collision direction
+ vec2 collision_normal = delta / distance;
+
+ // Compute the resolution vector
+ vec2 resolution = -collision_normal * penetration_depth;
+
+ return resolution;
+}
+
+vec2 CollisionSystem::get_circle_box_resolution(const CircleCollider & circle_collider,
+ const BoxCollider & box_collider,
+ const vec2 & circle_position,
+ const vec2 & box_position) const {
+ vec2 delta = circle_position - box_position;
+
+ // Compute half-dimensions of the box
+ float half_width = box_collider.dimensions.x / 2.0f;
+ float half_height = box_collider.dimensions.y / 2.0f;
+
+ // Clamp circle center to the nearest point on the box
+ vec2 closest_point;
+ closest_point.x = std::clamp(delta.x, -half_width, half_width);
+ closest_point.y = std::clamp(delta.y, -half_height, half_height);
+
+ // Find the vector from the circle center to the closest point
+ vec2 closest_delta = delta - closest_point;
+
+ // Normalize the delta to get the collision direction
+ float distance
+ = std::sqrt(closest_delta.x * closest_delta.x + closest_delta.y * closest_delta.y);
+ vec2 collision_normal = closest_delta / distance;
+
+ // Compute penetration depth
+ float penetration_depth = circle_collider.radius - distance;
+
+ // Compute the resolution vector
+ vec2 resolution = collision_normal * penetration_depth;
+
+ return resolution;
+}
+
+void CollisionSystem::determine_collision_handler(CollisionInfo & info) {
+ // Check rigidbody type for static
+ if (info.this_rigidbody.data.body_type == Rigidbody::BodyType::STATIC) return;
+ // If second body is static perform the static collision handler in this system
+ if (info.other_rigidbody.data.body_type == Rigidbody::BodyType::STATIC) {
+ this->static_collision_handler(info);
+ };
+ // Call collision event for user
+ CollisionEvent data(info);
+ EventManager & emgr = this->mediator.event_manager;
+ emgr.trigger_event<CollisionEvent>(data, info.this_collider.game_object_id);
+}
+
+void CollisionSystem::static_collision_handler(CollisionInfo & info) {
+ // Move object back using calculate move back value
+ info.this_transform.position += info.resolution;
+
+ switch (info.resolution_direction) {
+ case Direction::BOTH:
+ //bounce
+ if (info.this_rigidbody.data.elastisity_coefficient > 0) {
+ info.this_rigidbody.data.linear_velocity
+ = -info.this_rigidbody.data.linear_velocity
+ * info.this_rigidbody.data.elastisity_coefficient;
+ }
+ //stop movement
+ else {
+ info.this_rigidbody.data.linear_velocity = {0, 0};
+ }
+ break;
+ case Direction::Y_DIRECTION:
+ // Bounce
+ if (info.this_rigidbody.data.elastisity_coefficient > 0) {
+ info.this_rigidbody.data.linear_velocity.y
+ = -info.this_rigidbody.data.linear_velocity.y
+ * info.this_rigidbody.data.elastisity_coefficient;
+ }
+ // Stop movement
+ else {
+ info.this_rigidbody.data.linear_velocity.y = 0;
+ info.this_transform.position.x -= info.resolution.x;
+ }
+ break;
+ case Direction::X_DIRECTION:
+ // Bounce
+ if (info.this_rigidbody.data.elastisity_coefficient > 0) {
+ info.this_rigidbody.data.linear_velocity.x
+ = -info.this_rigidbody.data.linear_velocity.x
+ * info.this_rigidbody.data.elastisity_coefficient;
+ }
+ // Stop movement
+ else {
+ info.this_rigidbody.data.linear_velocity.x = 0;
+ info.this_transform.position.y -= info.resolution.y;
+ }
+ break;
+ case Direction::NONE:
+ // Not possible
+ break;
+ }
+}
+
+std::vector<std::pair<CollisionSystem::CollisionInternal, CollisionSystem::CollisionInternal>>
+CollisionSystem::gather_collisions(std::vector<CollisionInternal> & colliders) {
+
+ // TODO:
+ // If no colliders skip
+ // Check if colliders has rigidbody if not skip
+
+ // TODO:
+ // If amount is higer than lets say 16 for now use quadtree otwerwise skip
+ // Quadtree code
+ // Quadtree is placed over the input vector
+
+ // Return data of collided colliders which are variants
+ std::vector<std::pair<CollisionInternal, CollisionInternal>> collisions_ret;
+ //using visit to visit the variant to access the active and id.
+ for (size_t i = 0; i < colliders.size(); ++i) {
+ for (size_t j = i + 1; j < colliders.size(); ++j) {
+ if (colliders[i].id == colliders[j].id) continue;
+ if (!have_common_layer(colliders[i].rigidbody.data.collision_layers,
+ colliders[j].rigidbody.data.collision_layers))
+ continue;
+ CollisionInternalType type
+ = get_collider_type(colliders[i].collider, colliders[j].collider);
+ if (!get_collision(
+ {
+ .collider = colliders[i].collider,
+ .transform = colliders[i].transform,
+ .rigidbody = colliders[i].rigidbody,
+ },
+ {
+ .collider = colliders[j].collider,
+ .transform = colliders[j].transform,
+ .rigidbody = colliders[j].rigidbody,
+ },
+ type))
+ continue;
+ collisions_ret.emplace_back(colliders[i], colliders[j]);
+ }
+ }
+
+ return collisions_ret;
+}
+
+bool CollisionSystem::have_common_layer(const std::set<int> & layers1,
+ const std::set<int> & layers2) {
+
+ // Check if any number is equal in the layers
+ for (int num : layers1) {
+ if (layers2.contains(num)) {
+ // Common layer found
+ return true;
+ break;
+ }
+ }
+ // No common layer found
+ return false;
+}
+
+CollisionSystem::CollisionInternalType
+CollisionSystem::get_collider_type(const collider_variant & collider1,
+ const collider_variant & collider2) const {
+ if (std::holds_alternative<std::reference_wrapper<CircleCollider>>(collider1)) {
+ if (std::holds_alternative<std::reference_wrapper<CircleCollider>>(collider2)) {
+ return CollisionInternalType::CIRCLE_CIRCLE;
+ } else {
+ return CollisionInternalType::CIRCLE_BOX;
+ }
+ } else {
+ if (std::holds_alternative<std::reference_wrapper<CircleCollider>>(collider2)) {
+ return CollisionInternalType::BOX_CIRCLE;
+ } else {
+ return CollisionInternalType::BOX_BOX;
+ }
+ }
+}
+
+bool CollisionSystem::get_collision(const CollisionInternal & first_info,
+ const CollisionInternal & second_info,
+ CollisionInternalType type) const {
+ switch (type) {
+ case CollisionInternalType::BOX_BOX: {
+ const BoxCollider & box_collider1
+ = std::get<std::reference_wrapper<BoxCollider>>(first_info.collider);
+ const BoxCollider & box_collider2
+ = std::get<std::reference_wrapper<BoxCollider>>(second_info.collider);
+ return this->get_box_box_collision(box_collider1, box_collider2,
+ first_info.transform, second_info.transform,
+ second_info.rigidbody, second_info.rigidbody);
+ }
+ case CollisionInternalType::BOX_CIRCLE: {
+ const BoxCollider & box_collider
+ = std::get<std::reference_wrapper<BoxCollider>>(first_info.collider);
+ const CircleCollider & circle_collider
+ = std::get<std::reference_wrapper<CircleCollider>>(second_info.collider);
+ return this->get_box_circle_collision(
+ box_collider, circle_collider, first_info.transform, second_info.transform,
+ second_info.rigidbody, second_info.rigidbody);
+ }
+ case CollisionInternalType::CIRCLE_CIRCLE: {
+ const CircleCollider & circle_collider1
+ = std::get<std::reference_wrapper<CircleCollider>>(first_info.collider);
+ const CircleCollider & circle_collider2
+ = std::get<std::reference_wrapper<CircleCollider>>(second_info.collider);
+ return this->get_circle_circle_collision(
+ circle_collider1, circle_collider2, first_info.transform,
+ second_info.transform, second_info.rigidbody, second_info.rigidbody);
+ }
+ case CollisionInternalType::CIRCLE_BOX: {
+ const CircleCollider & circle_collider
+ = std::get<std::reference_wrapper<CircleCollider>>(first_info.collider);
+ const BoxCollider & box_collider
+ = std::get<std::reference_wrapper<BoxCollider>>(second_info.collider);
+ return this->get_box_circle_collision(
+ box_collider, circle_collider, first_info.transform, second_info.transform,
+ second_info.rigidbody, second_info.rigidbody);
+ }
+ }
+ return false;
+}
+
+bool CollisionSystem::get_box_box_collision(const BoxCollider & box1, const BoxCollider & box2,
+ const Transform & transform1,
+ const Transform & transform2,
+ const Rigidbody & rigidbody1,
+ const Rigidbody & rigidbody2) const {
+ // Get current positions of colliders
+ vec2 final_position1 = this->get_current_position(box1.offset, transform1, rigidbody1);
+ vec2 final_position2 = this->get_current_position(box2.offset, transform2, rigidbody2);
+
+ // Calculate half-extents (half width and half height)
+ float half_width1 = box1.dimensions.x / 2.0;
+ float half_height1 = box1.dimensions.y / 2.0;
+ float half_width2 = box2.dimensions.x / 2.0;
+ float half_height2 = box2.dimensions.y / 2.0;
+
+ // Check if the boxes overlap along the X and Y axes
+ return (final_position1.x + half_width1 > final_position2.x - half_width2
+ && final_position1.x - half_width1 < final_position2.x + half_width2
+ && final_position1.y + half_height1 > final_position2.y - half_height2
+ && final_position1.y - half_height1 < final_position2.y + half_height2);
+}
+
+bool CollisionSystem::get_box_circle_collision(const BoxCollider & box1,
+ const CircleCollider & circle2,
+ const Transform & transform1,
+ const Transform & transform2,
+ const Rigidbody & rigidbody1,
+ const Rigidbody & rigidbody2) const {
+ // Get current positions of colliders
+ vec2 final_position1 = this->get_current_position(box1.offset, transform1, rigidbody1);
+ vec2 final_position2 = this->get_current_position(circle2.offset, transform2, rigidbody2);
+
+ // Calculate box half-extents
+ float half_width = box1.dimensions.x / 2.0;
+ float half_height = box1.dimensions.y / 2.0;
+
+ // Find the closest point on the box to the circle's center
+ float closest_x = std::max(final_position1.x - half_width,
+ std::min(final_position2.x, final_position1.x + half_width));
+ float closest_y = std::max(final_position1.y - half_height,
+ std::min(final_position2.y, final_position1.y + half_height));
+
+ // Calculate the distance squared between the circle's center and the closest point on the box
+ float distance_x = final_position2.x - closest_x;
+ float distance_y = final_position2.y - closest_y;
+ float distance_squared = distance_x * distance_x + distance_y * distance_y;
+
+ // Compare distance squared with the square of the circle's radius
+ return distance_squared < circle2.radius * circle2.radius;
+}
+
+bool CollisionSystem::get_circle_circle_collision(const CircleCollider & circle1,
+ const CircleCollider & circle2,
+ const Transform & transform1,
+ const Transform & transform2,
+ const Rigidbody & rigidbody1,
+ const Rigidbody & rigidbody2) const {
+ // Get current positions of colliders
+ vec2 final_position1 = this->get_current_position(circle1.offset, transform1, rigidbody1);
+ vec2 final_position2 = this->get_current_position(circle2.offset, transform2, rigidbody2);
+
+ float distance_x = final_position1.x - final_position2.x;
+ float distance_y = final_position1.y - final_position2.y;
+ float distance_squared = distance_x * distance_x + distance_y * distance_y;
+
+ // Calculate the sum of the radii
+ float radius_sum = circle1.radius + circle2.radius;
+
+ // Check if the distance between the centers is less than or equal to the sum of the radii
+ return distance_squared < radius_sum * radius_sum;
+}
+
+vec2 CollisionSystem::get_current_position(const vec2 & collider_offset,
+ const Transform & transform,
+ const Rigidbody & rigidbody) const {
+ // Get the rotation in radians
+ float radians1 = transform.rotation * (M_PI / 180.0);
+
+ // Calculate total offset with scale
+ vec2 total_offset = (rigidbody.data.offset + collider_offset) * transform.scale;
+
+ // Rotate
+ float rotated_total_offset_x1
+ = total_offset.x * cos(radians1) - total_offset.y * sin(radians1);
+ float rotated_total_offset_y1
+ = total_offset.x * sin(radians1) + total_offset.y * cos(radians1);
+
+ // Final positions considering scaling and rotation
+ return (transform.position + vec2(rotated_total_offset_x1, rotated_total_offset_y1));
+}
diff --git a/src/crepe/system/CollisionSystem.h b/src/crepe/system/CollisionSystem.h
new file mode 100644
index 0000000..48a8f86
--- /dev/null
+++ b/src/crepe/system/CollisionSystem.h
@@ -0,0 +1,311 @@
+#pragma once
+
+#include <optional>
+#include <variant>
+#include <vector>
+
+#include "api/BoxCollider.h"
+#include "api/CircleCollider.h"
+#include "api/Event.h"
+#include "api/Metadata.h"
+#include "api/Rigidbody.h"
+#include "api/Transform.h"
+#include "api/Vector2.h"
+
+#include "Collider.h"
+#include "System.h"
+
+namespace crepe {
+
+//! A system responsible for detecting and handling collisions between colliders.
+class CollisionSystem : public System {
+public:
+ using System::System;
+
+private:
+ //! A variant type that can hold either a BoxCollider or a CircleCollider.
+ using collider_variant = std::variant<std::reference_wrapper<BoxCollider>,
+ std::reference_wrapper<CircleCollider>>;
+
+ //! Enum representing the types of collider pairs for collision detection.
+ enum class CollisionInternalType {
+ BOX_BOX,
+ CIRCLE_CIRCLE,
+ BOX_CIRCLE,
+ CIRCLE_BOX,
+ };
+
+ /**
+ * \brief A structure to store the collision data of a single collider.
+ *
+ * This structure all components and id that are for needed within this system when calculating or handeling collisions.
+ * The transform and rigidbody are mostly needed for location and rotation.
+ * In rigidbody additional info is written about what the body of the object is,
+ * and how it should respond on a collision.
+ */
+ struct CollisionInternal {
+ game_object_id_t id = 0;
+ collider_variant collider;
+ Transform & transform;
+ Rigidbody & rigidbody;
+ };
+
+ //! Enum representing movement directions during collision resolution.
+ enum class Direction {
+ //! No movement required.
+ NONE,
+ //! Movement in the X direction.
+ X_DIRECTION,
+ //! Movement in the Y direction.
+ Y_DIRECTION,
+ //! Movement in both X and Y directions.
+ BOTH
+ };
+
+public:
+ /**
+ * \brief Structure representing detailed collision information between two colliders.
+ *
+ * Includes information about the colliding objects and the resolution data for handling the collision.
+ */
+ struct CollisionInfo {
+ Collider & this_collider;
+ Transform & this_transform;
+ Rigidbody & this_rigidbody;
+ Metadata & this_metadata;
+ Collider & other_collider;
+ Transform & other_transform;
+ Rigidbody & other_rigidbody;
+ Metadata & other_metadata;
+ //! The resolution vector for the collision.
+ vec2 resolution;
+ //! The direction of movement for resolving the collision.
+ Direction resolution_direction = Direction::NONE;
+ };
+
+public:
+ //! Updates the collision system by checking for collisions between colliders and handling them.
+ void fixed_update() override;
+
+private:
+ /**
+ * \brief Determines the type of collider pair from two colliders.
+ *
+ * Uses std::holds_alternative to identify the types of the provided colliders.
+ *
+ * \param collider1 First collider variant (BoxCollider or CircleCollider).
+ * \param collider2 Second collider variant (BoxCollider or CircleCollider).
+ * \return The combined type of the two colliders.
+ */
+ CollisionInternalType get_collider_type(const collider_variant & collider1,
+ const collider_variant & collider2) const;
+
+ /**
+ * \brief Calculates the current position of a collider.
+ *
+ * Combines the Collider offset, Transform position, and Rigidbody offset to compute the position of the collider.
+ *
+ * \param collider_offset The offset of the collider.
+ * \param transform The Transform of the associated game object.
+ * \param rigidbody The Rigidbody of the associated game object.
+ * \return The calculated position of the collider.
+ */
+ vec2 get_current_position(const vec2 & collider_offset, const Transform & transform,
+ const Rigidbody & rigidbody) const;
+
+private:
+ /**
+ * \brief Handles collision resolution between two colliders.
+ *
+ * Processes collision data and adjusts objects to resolve collisions and/or calls the user oncollision script function.
+ *
+ * \param data1 Collision data for the first collider.
+ * \param data2 Collision data for the second collider.
+ */
+ void collision_handler_request(CollisionInternal & data1, CollisionInternal & data2);
+
+ /**
+ * \brief Resolves collision between two colliders and calculates the movement required.
+ *
+ * Determines the displacement and direction needed to separate colliders based on their types.
+ *
+ * \param data1 Collision data for the first collider.
+ * \param data2 Collision data for the second collider.
+ * \param type The type of collider pair.
+ * \return A pair containing the resolution vector and direction for the first collider.
+ */
+ std::pair<vec2, Direction> collision_handler(CollisionInternal & data1,
+ CollisionInternal & data2,
+ CollisionInternalType type);
+
+ /**
+ * \brief Calculates the resolution vector for two BoxColliders.
+ *
+ * Computes the displacement required to separate two overlapping BoxColliders.
+ *
+ * \param box_collider1 The first BoxCollider.
+ * \param box_collider2 The second BoxCollider.
+ * \param position1 The position of the first BoxCollider.
+ * \param position2 The position of the second BoxCollider.
+ * \return The resolution vector for the collision.
+ */
+ vec2 get_box_box_resolution(const BoxCollider & box_collider1,
+ const BoxCollider & box_collider2, const vec2 & position1,
+ const vec2 & position2) const;
+
+ /**
+ * \brief Calculates the resolution vector for two CircleCollider.
+ *
+ * Computes the displacement required to separate two overlapping CircleCollider.
+ *
+ * \param circle_collider1 The first CircleCollider.
+ * \param circle_collider2 The second CircleCollider.
+ * \param final_position1 The position of the first CircleCollider.
+ * \param final_position2 The position of the second CircleCollider.
+ * \return The resolution vector for the collision.
+ */
+ vec2 get_circle_circle_resolution(const CircleCollider & circle_collider1,
+ const CircleCollider & circle_collider2,
+ const vec2 & final_position1,
+ const vec2 & final_position2) const;
+
+ /**
+ * \brief Calculates the resolution vector for two CircleCollider.
+ *
+ * Computes the displacement required to separate two overlapping CircleCollider.
+ *
+ * \param circle_collider The first CircleCollider.
+ * \param box_collider The second CircleCollider.
+ * \param circle_position The position of the CircleCollider.
+ * \param box_position The position of the BoxCollider.
+ * \return The resolution vector for the collision.
+ */
+ vec2 get_circle_box_resolution(const CircleCollider & circle_collider,
+ const BoxCollider & box_collider,
+ const vec2 & circle_position,
+ const vec2 & box_position) const;
+
+ /**
+ * \brief Determines the appropriate collision handler for a collision.
+ *
+ * Decides the correct resolution process based on the dynamic or static nature of the colliders involved.
+ *
+ * \param info Collision information containing data about both colliders.
+ */
+ void determine_collision_handler(CollisionInfo & info);
+
+ /**
+ * \brief Handles collisions involving static objects.
+ *
+ * Resolves collisions by adjusting positions and modifying velocities if bounce is enabled.
+ *
+ * \param info Collision information containing data about both colliders.
+ */
+ void static_collision_handler(CollisionInfo & info);
+
+private:
+ /**
+ * \brief Checks for collisions between colliders.
+ *
+ * Identifies collisions and generates pairs of colliding objects for further processing.
+ *
+ * \param colliders A collection of all active colliders.
+ * \return A list of collision pairs with their associated data.
+ */
+ std::vector<std::pair<CollisionInternal, CollisionInternal>>
+ gather_collisions(std::vector<CollisionInternal> & colliders);
+
+ /**
+ * \brief Checks if two collision layers have at least one common layer.
+ *
+ * This function checks if there is any overlapping layer between the two inputs.
+ * It compares each layer from the first input to see
+ * if it exists in the second input. If at least one common layer is found,
+ * the function returns true, indicating that the two colliders share a common
+ * collision layer.
+ *
+ * \param layers1 all collision layers for the first collider.
+ * \param layers2 all collision layers for the second collider.
+ * \return Returns true if there is at least one common layer, false otherwise.
+ */
+
+ bool have_common_layer(const std::set<int> & layers1, const std::set<int> & layers2);
+
+ /**
+ * \brief Checks for collision between two colliders.
+ *
+ * Calls the appropriate collision detection function based on the collider types.
+ *
+ * \param first_info Collision data for the first collider.
+ * \param second_info Collision data for the second collider.
+ * \param type The type of collider pair.
+ * \return True if a collision is detected, otherwise false.
+ */
+ bool get_collision(const CollisionInternal & first_info,
+ const CollisionInternal & second_info,
+ CollisionInternalType type) const;
+
+ /**
+ * \brief Detects collisions between two BoxColliders.
+ *
+ * \param box1 The first BoxCollider.
+ * \param box2 The second BoxCollider.
+ * \param transform1 Transform of the first object.
+ * \param transform2 Transform of the second object.
+ * \param rigidbody1 Rigidbody of the first object.
+ * \param rigidbody2 Rigidbody of the second object.
+ * \return True if a collision is detected, otherwise false.
+ */
+ bool get_box_box_collision(const BoxCollider & box1, const BoxCollider & box2,
+ const Transform & transform1, const Transform & transform2,
+ const Rigidbody & rigidbody1,
+ const Rigidbody & rigidbody2) const;
+
+ /**
+ * \brief Check collision for box on circle collider
+ *
+ * \param box1 The BoxCollider
+ * \param circle2 The CircleCollider
+ * \param transform1 Transform of the first object.
+ * \param transform2 Transform of the second object.
+ * \param rigidbody1 Rigidbody of the first object.
+ * \param rigidbody2 Rigidbody of the second object.
+ * \return True if a collision is detected, otherwise false.
+ */
+ bool get_box_circle_collision(const BoxCollider & box1, const CircleCollider & circle2,
+ const Transform & transform1, const Transform & transform2,
+ const Rigidbody & rigidbody1,
+ const Rigidbody & rigidbody2) const;
+
+ /**
+ * \brief Check collision for circle on circle collider
+ *
+ * \param circle1 First CircleCollider
+ * \param circle2 Second CircleCollider
+ * \param transform1 Transform of the first object.
+ * \param transform2 Transform of the second object.
+ * \param rigidbody1 Rigidbody of the first object.
+ * \param rigidbody2 Rigidbody of the second object.
+ * \return True if a collision is detected, otherwise false.
+ *
+ * \return status of collision
+ */
+ bool get_circle_circle_collision(const CircleCollider & circle1,
+ const CircleCollider & circle2,
+ const Transform & transform1,
+ const Transform & transform2,
+ const Rigidbody & rigidbody1,
+ const Rigidbody & rigidbody2) const;
+};
+
+/**
+ * \brief Event triggered during a collision between objects.
+ */
+class CollisionEvent : public Event {
+public:
+ crepe::CollisionSystem::CollisionInfo info;
+ CollisionEvent(const crepe::CollisionSystem::CollisionInfo & collisionInfo)
+ : info(collisionInfo) {}
+};
+
+} // namespace crepe
diff --git a/src/crepe/system/EventSystem.cpp b/src/crepe/system/EventSystem.cpp
new file mode 100644
index 0000000..7e168ab
--- /dev/null
+++ b/src/crepe/system/EventSystem.cpp
@@ -0,0 +1,9 @@
+#include "EventSystem.h"
+#include "../manager/EventManager.h"
+
+using namespace crepe;
+
+void EventSystem::fixed_update() {
+ EventManager & ev = this->mediator.event_manager;
+ ev.dispatch_events();
+}
diff --git a/src/crepe/system/EventSystem.h b/src/crepe/system/EventSystem.h
new file mode 100644
index 0000000..0ae48d2
--- /dev/null
+++ b/src/crepe/system/EventSystem.h
@@ -0,0 +1,21 @@
+#pragma once
+
+#include "System.h"
+
+namespace crepe {
+
+/**
+ * \brief EventManager dispatch helper system
+ */
+class EventSystem : public System {
+public:
+ using System::System;
+
+ /**
+ * \brief Dispatch queued events
+ * \see EventManager::dispatch_events
+ */
+ void fixed_update() override;
+};
+
+} // namespace crepe
diff --git a/src/crepe/system/InputSystem.cpp b/src/crepe/system/InputSystem.cpp
new file mode 100644
index 0000000..d209282
--- /dev/null
+++ b/src/crepe/system/InputSystem.cpp
@@ -0,0 +1,209 @@
+#include "../api/Button.h"
+#include "../facade/SDLContext.h"
+#include "../manager/ComponentManager.h"
+#include "../manager/EventManager.h"
+#include "util/Log.h"
+
+#include "InputSystem.h"
+
+using namespace crepe;
+
+void InputSystem::fixed_update() {
+ ComponentManager & mgr = this->mediator.component_manager;
+ SDLContext & context = this->mediator.sdl_context;
+ std::vector<EventData> event_list = context.get_events();
+ RefVector<Camera> cameras = mgr.get_components_by_type<Camera>();
+ OptionalRef<Camera> curr_cam_ref;
+
+ // Find the active camera
+ for (Camera & cam : cameras) {
+ if (!cam.active) continue;
+ curr_cam_ref = cam;
+ break;
+ }
+ if (!curr_cam_ref) return;
+
+ Camera & current_cam = curr_cam_ref;
+ RefVector<Transform> transform_vec
+ = mgr.get_components_by_id<Transform>(current_cam.game_object_id);
+ Transform & cam_transform = transform_vec.front().get();
+
+ vec2 camera_origin = cam_transform.position + current_cam.data.postion_offset
+ - (current_cam.viewport_size / 2);
+
+ for (const EventData & event : event_list) {
+ // Only calculate mouse coordinates for relevant events
+ if (event.event_type == EventType::MOUSE_DOWN
+ || event.event_type == EventType::MOUSE_UP
+ || event.event_type == EventType::MOUSE_MOVE
+ || event.event_type == EventType::MOUSE_WHEEL) {
+ this->handle_mouse_event(event, camera_origin, current_cam);
+
+ } else {
+ this->handle_non_mouse_event(event);
+ }
+ }
+}
+
+void InputSystem::handle_mouse_event(const EventData & event, const vec2 & camera_origin,
+ const Camera & current_cam) {
+ EventManager & event_mgr = this->mediator.event_manager;
+ vec2 adjusted_mouse;
+ adjusted_mouse.x = event.data.mouse_data.mouse_position.x + camera_origin.x;
+ adjusted_mouse.x = event.data.mouse_data.mouse_position.y + camera_origin.y;
+ // Check if the mouse is within the viewport
+ if ((adjusted_mouse.x < camera_origin.x
+ || adjusted_mouse.x > camera_origin.x + current_cam.viewport_size.x
+ || adjusted_mouse.y < camera_origin.y
+ || adjusted_mouse.y > camera_origin.y + current_cam.viewport_size.y))
+ return;
+
+ // Handle mouse-specific events
+ switch (event.event_type) {
+ case EventType::MOUSE_DOWN:
+ event_mgr.queue_event<MousePressEvent>({
+ .mouse_pos = adjusted_mouse,
+ .button = event.data.mouse_data.mouse_button,
+ });
+ this->last_mouse_down_position = adjusted_mouse;
+ this->last_mouse_button = event.data.mouse_data.mouse_button;
+ break;
+
+ case EventType::MOUSE_UP: {
+ event_mgr.queue_event<MouseReleaseEvent>({
+ .mouse_pos = adjusted_mouse,
+ .button = event.data.mouse_data.mouse_button,
+ });
+ vec2 delta_move = adjusted_mouse - this->last_mouse_down_position;
+ int click_tolerance = Config::get_instance().input.click_tolerance;
+ if (this->last_mouse_button == event.data.mouse_data.mouse_button
+ && std::abs(delta_move.x) <= click_tolerance
+ && std::abs(delta_move.y) <= click_tolerance) {
+ event_mgr.queue_event<MouseClickEvent>({
+ .mouse_pos = adjusted_mouse,
+ .button = event.data.mouse_data.mouse_button,
+ });
+ this->handle_click(event.data.mouse_data.mouse_button, adjusted_mouse);
+ }
+ break;
+ }
+
+ case EventType::MOUSE_MOVE:
+ event_mgr.queue_event<MouseMoveEvent>({
+ .mouse_pos = adjusted_mouse,
+ .mouse_delta = event.data.mouse_data.rel_mouse_move,
+ });
+ this->handle_move(event, adjusted_mouse);
+ break;
+
+ case EventType::MOUSE_WHEEL:
+ event_mgr.queue_event<MouseScrollEvent>({
+ .mouse_pos = adjusted_mouse,
+ .scroll_direction = event.data.mouse_data.scroll_direction,
+ .scroll_delta = event.data.mouse_data.scroll_delta,
+ });
+ break;
+
+ default:
+ break;
+ }
+}
+
+void InputSystem::handle_non_mouse_event(const EventData & event) {
+ EventManager & event_mgr = this->mediator.event_manager;
+ switch (event.event_type) {
+ case EventType::KEY_DOWN:
+
+ event_mgr.queue_event<KeyPressEvent>(
+ {.repeat = event.data.key_data.key_repeat, .key = event.data.key_data.key});
+ break;
+ case EventType::KEY_UP:
+ event_mgr.queue_event<KeyReleaseEvent>({.key = event.data.key_data.key});
+ break;
+ case EventType::SHUTDOWN:
+ event_mgr.queue_event<ShutDownEvent>({});
+ break;
+ case EventType::WINDOW_EXPOSE:
+ event_mgr.queue_event<WindowExposeEvent>({});
+ break;
+ case EventType::WINDOW_RESIZE:
+ event_mgr.queue_event<WindowResizeEvent>(
+ WindowResizeEvent{.dimensions = event.data.window_data.resize_dimension});
+ break;
+ case EventType::WINDOW_MOVE:
+ event_mgr.queue_event<WindowMoveEvent>(
+ {.delta_move = event.data.window_data.move_delta});
+ break;
+ case EventType::WINDOW_MINIMIZE:
+ event_mgr.queue_event<WindowMinimizeEvent>({});
+ break;
+ case EventType::WINDOW_MAXIMIZE:
+ event_mgr.queue_event<WindowMaximizeEvent>({});
+ break;
+ case EventType::WINDOW_FOCUS_GAIN:
+ event_mgr.queue_event<WindowFocusGainEvent>({});
+ break;
+ case EventType::WINDOW_FOCUS_LOST:
+ event_mgr.queue_event<WindowFocusLostEvent>({});
+ break;
+ default:
+ break;
+ }
+}
+
+void InputSystem::handle_move(const EventData & event_data, const vec2 & mouse_pos) {
+ ComponentManager & mgr = this->mediator.component_manager;
+ EventManager & event_mgr = this->mediator.event_manager;
+ RefVector<Button> buttons = mgr.get_components_by_type<Button>();
+
+ for (Button & button : buttons) {
+ if (!button.active) continue;
+ Metadata & metadata
+ = mgr.get_components_by_id<Metadata>(button.game_object_id).front();
+ Transform & transform
+ = mgr.get_components_by_id<Transform>(button.game_object_id).front();
+ bool was_hovering = button.hover;
+ if (this->is_mouse_inside_button(mouse_pos, button, transform)) {
+ button.hover = true;
+ if (!was_hovering) {
+ event_mgr.trigger_event<ButtonEnterEvent>(metadata);
+ }
+ } else {
+ button.hover = false;
+ if (was_hovering) {
+ event_mgr.trigger_event<ButtonExitEvent>(metadata);
+ }
+ }
+ }
+}
+
+void InputSystem::handle_click(const MouseButton & mouse_button, const vec2 & mouse_pos) {
+ ComponentManager & mgr = this->mediator.component_manager;
+ EventManager & event_mgr = this->mediator.event_manager;
+ RefVector<Button> buttons = mgr.get_components_by_type<Button>();
+
+ for (Button & button : buttons) {
+ if (!button.active) continue;
+ Metadata & metadata
+ = mgr.get_components_by_id<Metadata>(button.game_object_id).front();
+ Transform & transform
+ = mgr.get_components_by_id<Transform>(button.game_object_id).front();
+
+ if (this->is_mouse_inside_button(mouse_pos, button, transform)) {
+ event_mgr.trigger_event<ButtonPressEvent>(metadata);
+ }
+ }
+}
+
+bool InputSystem::is_mouse_inside_button(const vec2 & mouse_pos, const Button & button,
+ const Transform & transform) {
+ int actual_x = transform.position.x + button.offset.x;
+ int actual_y = transform.position.y + button.offset.y;
+
+ int half_width = button.dimensions.x / 2;
+ int half_height = button.dimensions.y / 2;
+
+ // Check if the mouse is within the button's boundaries
+ return mouse_pos.x >= actual_x - half_width && mouse_pos.x <= actual_x + half_width
+ && mouse_pos.y >= actual_y - half_height && mouse_pos.y <= actual_y + half_height;
+}
diff --git a/src/crepe/system/InputSystem.h b/src/crepe/system/InputSystem.h
new file mode 100644
index 0000000..0f1bfa1
--- /dev/null
+++ b/src/crepe/system/InputSystem.h
@@ -0,0 +1,132 @@
+#pragma once
+
+#include "../api/Config.h"
+#include "../facade/EventData.h"
+
+#include "../api/Event.h"
+#include "../api/Metadata.h"
+#include "../types.h"
+#include "../util/OptionalRef.h"
+
+#include "System.h"
+
+namespace crepe {
+
+class Camera;
+class Button;
+class Transform;
+//! Event triggered when a button is clicked
+class ButtonPressEvent : public Event {
+public:
+ //! Metadata of the button.
+ const Metadata & metadata;
+ /**
+ * \param metadata Metadata of the button pressed
+ */
+ ButtonPressEvent(const Metadata & metadata) : metadata(metadata){};
+};
+//! Event triggered when the mouse enters a button
+class ButtonEnterEvent : public Event {
+public:
+ //! Metadata of the button.
+ const Metadata & metadata;
+ /**
+ * \param metadata Metadata of the button pressed
+ */
+ ButtonEnterEvent(const Metadata & metadata) : metadata(metadata){};
+};
+//! Event triggered when the mouse leaves a button
+class ButtonExitEvent : public Event {
+public:
+ //! Metadata of the button.
+ const Metadata & metadata;
+ /**
+ * \param metadata Metadata of the button pressed
+ */
+ ButtonExitEvent(const Metadata & metadata) : metadata(metadata){};
+};
+
+/**
+ * \brief Handles the processing of input events created by SDLContext
+ *
+ * This system processes events such as mouse clicks, mouse movement, and keyboard
+ * actions. It is responsible for detecting interactions with UI buttons and
+ * passing the corresponding events to the registered listeners.
+ */
+class InputSystem : public System {
+public:
+ using System::System;
+
+ /**
+ * \brief Updates the system, processing all input events.
+ * This method processes all events and triggers corresponding actions.
+ */
+ void fixed_update() override;
+
+private:
+ //! Stores the last position of the mouse when the button was pressed.
+ vec2 last_mouse_down_position;
+ // TODO: specify world/hud space and make regular `vec2`
+
+ //! Stores the last mouse button pressed.
+ MouseButton last_mouse_button = MouseButton::NONE;
+ /**
+ * \brief Handles mouse-related events.
+ * \param event The event data for the mouse event.
+ * \param camera_origin The origin position of the camera in world space.
+ * \param current_cam The currently active camera.
+ *
+ * This method processes mouse events, adjusts the mouse position to world coordinates,
+ * and triggers the appropriate mouse-specific event handling logic.
+ */
+ void handle_mouse_event(const EventData & event, const vec2 & camera_origin,
+ const Camera & current_cam);
+ /**
+ * \brief Handles non-mouse-related events.
+ * \param event The event data for the non-mouse event.
+ *
+ * This method processes events that do not involve the mouse, such as keyboard events,
+ * window events, and shutdown events, and triggers the corresponding event actions.
+ */
+ void handle_non_mouse_event(const EventData & event);
+ /**
+ * \brief Handles the mouse click event.
+ * \param mouse_button The mouse button involved in the click.
+ * \param world_mouse_x The X coordinate of the mouse in world space.
+ * \param world_mouse_y The Y coordinate of the mouse in world space.
+ *
+ * This method processes the mouse click event and triggers the corresponding button action.
+ */
+ void handle_click(const MouseButton & mouse_button, const vec2 & mouse_pos);
+
+ /**
+ * \brief Handles the mouse movement event.
+ * \param event_data The event data containing information about the mouse movement.
+ * \param world_mouse_x The X coordinate of the mouse in world space.
+ * \param world_mouse_y The Y coordinate of the mouse in world space.
+ *
+ * This method processes the mouse movement event and updates the button hover state.
+ */
+ void handle_move(const EventData & event_data, const vec2 & mouse_pos);
+
+ /**
+ * \brief Checks if the mouse position is inside the bounds of the button.
+ * \param world_mouse_x The X coordinate of the mouse in world space.
+ * \param world_mouse_y The Y coordinate of the mouse in world space.
+ * \param button The button to check.
+ * \param transform The transform component of the button.
+ * \return True if the mouse is inside the button, false otherwise.
+ */
+ bool is_mouse_inside_button(const vec2 & mouse_pos, const Button & button,
+ const Transform & transform);
+
+ /**
+ * \brief Handles the button press event, calling the on_click callback if necessary.
+ * \param button The button being pressed.
+ *
+ * This method triggers the on_click action for the button when it is pressed.
+ */
+ void handle_button_press(Button & button);
+};
+
+} // namespace crepe
diff --git a/src/crepe/system/ParticleSystem.cpp b/src/crepe/system/ParticleSystem.cpp
new file mode 100644
index 0000000..bbc7366
--- /dev/null
+++ b/src/crepe/system/ParticleSystem.cpp
@@ -0,0 +1,121 @@
+#include <chrono>
+#include <cmath>
+#include <cstdlib>
+#include <ctime>
+
+#include "../api/ParticleEmitter.h"
+#include "../api/Transform.h"
+#include "../manager/ComponentManager.h"
+#include "../manager/LoopTimerManager.h"
+
+#include "ParticleSystem.h"
+
+using namespace crepe;
+
+void ParticleSystem::fixed_update() {
+ // Get all emitters
+ const Mediator & mediator = this->mediator;
+ LoopTimerManager & loop_timer = mediator.loop_timer;
+ ComponentManager & mgr = mediator.component_manager;
+ float dt = loop_timer.get_scaled_fixed_delta_time().count();
+
+ RefVector<ParticleEmitter> emitters = mgr.get_components_by_type<ParticleEmitter>();
+
+ for (ParticleEmitter & emitter : emitters) {
+ // Get transform linked to emitter
+ const Transform & transform
+ = mgr.get_components_by_id<Transform>(emitter.game_object_id).front().get();
+
+ // Emit particles based on emission_rate
+ emitter.spawn_accumulator += emitter.data.emission_rate * dt;
+ while (emitter.spawn_accumulator >= 1.0) {
+ this->emit_particle(emitter, transform);
+ emitter.spawn_accumulator -= 1.0;
+ }
+
+ // Update all particles
+ for (Particle & particle : emitter.particles) {
+ if (particle.active) {
+ particle.update(dt);
+ }
+ }
+
+ // Check if within boundary
+ this->check_bounds(emitter, transform);
+ }
+}
+
+void ParticleSystem::emit_particle(ParticleEmitter & emitter, const Transform & transform) {
+ constexpr float DEG_TO_RAD = M_PI / 180.0;
+
+ vec2 initial_position = emitter.data.offset + transform.position;
+ float random_angle
+ = this->generate_random_angle(emitter.data.min_angle, emitter.data.max_angle);
+
+ float random_speed
+ = this->generate_random_speed(emitter.data.min_speed, emitter.data.max_speed);
+ float angle_radians = random_angle * DEG_TO_RAD;
+
+ vec2 velocity
+ = {random_speed * std::cos(angle_radians), random_speed * std::sin(angle_radians)};
+
+ for (Particle & particle : emitter.particles) {
+ if (!particle.active) {
+ particle.reset(emitter.data.end_lifespan, initial_position, velocity,
+ random_angle);
+ break;
+ }
+ }
+}
+
+void ParticleSystem::check_bounds(ParticleEmitter & emitter, const Transform & transform) {
+ vec2 offset = emitter.data.boundary.offset + transform.position + emitter.data.offset;
+ float half_width = emitter.data.boundary.width / 2.0;
+ float half_height = emitter.data.boundary.height / 2.0;
+
+ float left = offset.x - half_width;
+ float right = offset.x + half_width;
+ float top = offset.y - half_height;
+ float bottom = offset.y + half_height;
+
+ for (Particle & particle : emitter.particles) {
+ const vec2 & position = particle.position;
+ bool within_bounds = (position.x >= left && position.x <= right && position.y >= top
+ && position.y <= bottom);
+ //if not within bounds do a reset or stop velocity
+ if (!within_bounds) {
+ if (emitter.data.boundary.reset_on_exit) {
+ particle.active = false;
+ } else {
+ particle.velocity = {0, 0};
+ if (position.x < left) particle.position.x = left;
+ else if (position.x > right) particle.position.x = right;
+ if (position.y < top) particle.position.y = top;
+ else if (position.y > bottom) particle.position.y = bottom;
+ }
+ }
+ }
+}
+
+float ParticleSystem::generate_random_angle(float min_angle, float max_angle) const {
+ if (min_angle == max_angle) {
+ return min_angle;
+ } else if (min_angle < max_angle) {
+ return min_angle
+ + static_cast<float>(std::rand() % static_cast<int>(max_angle - min_angle));
+ } else {
+ float angle_offset = (360 - min_angle) + max_angle;
+ float random_angle
+ = min_angle + static_cast<float>(std::rand() % static_cast<int>(angle_offset));
+ return (random_angle >= 360) ? random_angle - 360 : random_angle;
+ }
+}
+
+float ParticleSystem::generate_random_speed(float min_speed, float max_speed) const {
+ if (min_speed == max_speed) {
+ return min_speed;
+ } else {
+ return min_speed
+ + static_cast<float>(std::rand() % static_cast<int>(max_speed - min_speed));
+ }
+}
diff --git a/src/crepe/system/ParticleSystem.h b/src/crepe/system/ParticleSystem.h
new file mode 100644
index 0000000..4296ff3
--- /dev/null
+++ b/src/crepe/system/ParticleSystem.h
@@ -0,0 +1,62 @@
+#pragma once
+
+#include <cstdint>
+
+#include "System.h"
+
+namespace crepe {
+
+class ParticleEmitter;
+class Transform;
+
+/**
+ * \brief ParticleSystem class responsible for managing particle emission, updates, and bounds
+ * checking.
+ */
+class ParticleSystem : public System {
+public:
+ using System::System;
+ /**
+ * \brief Updates all particle emitters by emitting particles, updating particle states, and
+ * checking bounds.
+ */
+ void fixed_update() override;
+
+private:
+ /**
+ * \brief Emits a particle from the specified emitter based on its emission properties.
+ *
+ * \param emitter Reference to the ParticleEmitter.
+ * \param transform Const reference to the Transform component associated with the emitter.
+ */
+ void emit_particle(ParticleEmitter & emitter, const Transform & transform);
+
+ /**
+ * \brief Checks whether particles are within the emitter’s boundary, resets or stops
+ * particles if they exit.
+ *
+ * \param emitter Reference to the ParticleEmitter.
+ * \param transform Const reference to the Transform component associated with the emitter.
+ */
+ void check_bounds(ParticleEmitter & emitter, const Transform & transform);
+
+ /**
+ * \brief Generates a random angle for particle emission within the specified range.
+ *
+ * \param min_angle Minimum emission angle in degrees.
+ * \param max_angle Maximum emission angle in degrees.
+ * \return Random angle in degrees.
+ */
+ float generate_random_angle(float min_angle, float max_angle) const;
+
+ /**
+ * \brief Generates a random speed for particle emission within the specified range.
+ *
+ * \param min_speed Minimum emission speed.
+ * \param max_speed Maximum emission speed.
+ * \return Random speed.
+ */
+ float generate_random_speed(float min_speed, float max_speed) const;
+};
+
+} // namespace crepe
diff --git a/src/crepe/system/PhysicsSystem.cpp b/src/crepe/system/PhysicsSystem.cpp
new file mode 100644
index 0000000..62f8132
--- /dev/null
+++ b/src/crepe/system/PhysicsSystem.cpp
@@ -0,0 +1,106 @@
+#include <cmath>
+
+#include "../api/Config.h"
+#include "../api/Rigidbody.h"
+#include "../api/Transform.h"
+#include "../api/Vector2.h"
+#include "../manager/ComponentManager.h"
+#include "../manager/LoopTimerManager.h"
+#include "../manager/Mediator.h"
+
+#include "PhysicsSystem.h"
+
+using namespace crepe;
+
+void PhysicsSystem::fixed_update() {
+ const Mediator & mediator = this->mediator;
+ ComponentManager & mgr = mediator.component_manager;
+ LoopTimerManager & loop_timer = mediator.loop_timer;
+ RefVector<Rigidbody> rigidbodies = mgr.get_components_by_type<Rigidbody>();
+ float dt = loop_timer.get_scaled_fixed_delta_time().count();
+
+ float gravity = Config::get_instance().physics.gravity;
+ for (Rigidbody & rigidbody : rigidbodies) {
+ if (!rigidbody.active) continue;
+ Transform & transform
+ = mgr.get_components_by_id<Transform>(rigidbody.game_object_id).front().get();
+
+ switch (rigidbody.data.body_type) {
+ case Rigidbody::BodyType::DYNAMIC:
+ if (transform.game_object_id == rigidbody.game_object_id) {
+ // Add gravity
+
+ if (rigidbody.data.mass <= 0) {
+ throw std::runtime_error("Mass must be greater than 0");
+ }
+
+ if (gravity <= 0) {
+ throw std::runtime_error("Config Gravity must be greater than 0");
+ }
+
+ if (rigidbody.data.gravity_scale > 0 && !rigidbody.data.constraints.y) {
+ rigidbody.data.linear_velocity.y
+ += (rigidbody.data.mass * rigidbody.data.gravity_scale * gravity
+ * dt);
+ }
+ // Add coefficient rotation
+ if (rigidbody.data.angular_velocity_coefficient > 0) {
+ rigidbody.data.angular_velocity
+ *= std::pow(rigidbody.data.angular_velocity_coefficient, dt);
+ }
+
+ // Add coefficient movement horizontal
+ if (rigidbody.data.linear_velocity_coefficient.x > 0
+ && !rigidbody.data.constraints.x) {
+ rigidbody.data.linear_velocity.x
+ *= std::pow(rigidbody.data.linear_velocity_coefficient.x, dt);
+ }
+
+ // Add coefficient movement horizontal
+ if (rigidbody.data.linear_velocity_coefficient.y > 0
+ && !rigidbody.data.constraints.y) {
+ rigidbody.data.linear_velocity.y
+ *= std::pow(rigidbody.data.linear_velocity_coefficient.y, dt);
+ }
+
+ // Max velocity check
+ if (rigidbody.data.angular_velocity
+ > rigidbody.data.max_angular_velocity) {
+ rigidbody.data.angular_velocity = rigidbody.data.max_angular_velocity;
+ } else if (rigidbody.data.angular_velocity
+ < -rigidbody.data.max_angular_velocity) {
+ rigidbody.data.angular_velocity = -rigidbody.data.max_angular_velocity;
+ }
+
+ // Set max velocity to maximum length
+ if (rigidbody.data.linear_velocity.length()
+ > rigidbody.data.max_linear_velocity) {
+ rigidbody.data.linear_velocity.normalize();
+ rigidbody.data.linear_velocity *= rigidbody.data.max_linear_velocity;
+ }
+
+ // Move object
+ if (!rigidbody.data.constraints.rotation) {
+ transform.rotation += rigidbody.data.angular_velocity * dt;
+ transform.rotation = std::fmod(transform.rotation, 360.0);
+ if (transform.rotation < 0) {
+ transform.rotation += 360.0;
+ }
+ }
+ if (!rigidbody.data.constraints.x) {
+ transform.position.x += rigidbody.data.linear_velocity.x * dt;
+ }
+ if (!rigidbody.data.constraints.y) {
+ transform.position.y += rigidbody.data.linear_velocity.y * dt;
+ }
+ }
+ break;
+ case Rigidbody::BodyType::KINEMATIC:
+ break; //(scripts)
+ case Rigidbody::BodyType::STATIC:
+ break; //(unmoveable objects)
+ default:
+ break;
+ }
+ }
+}
diff --git a/src/crepe/system/PhysicsSystem.h b/src/crepe/system/PhysicsSystem.h
new file mode 100644
index 0000000..5ed624f
--- /dev/null
+++ b/src/crepe/system/PhysicsSystem.h
@@ -0,0 +1,24 @@
+#pragma once
+
+#include "System.h"
+
+namespace crepe {
+
+/**
+ * \brief System that controls all physics
+ *
+ * This class is a physics system that uses a rigidbody and transform to add physics to a game
+ * object.
+ */
+class PhysicsSystem : public System {
+public:
+ using System::System;
+ /**
+ * \brief updates the physics system.
+ *
+ * It calculates new velocties and changes the postion in the transform.
+ */
+ void fixed_update() override;
+};
+
+} // namespace crepe
diff --git a/src/crepe/system/RenderSystem.cpp b/src/crepe/system/RenderSystem.cpp
new file mode 100644
index 0000000..33218f6
--- /dev/null
+++ b/src/crepe/system/RenderSystem.cpp
@@ -0,0 +1,160 @@
+#include <algorithm>
+#include <cassert>
+#include <cmath>
+#include <functional>
+#include <optional>
+#include <stdexcept>
+#include <vector>
+
+#include "../api/Camera.h"
+#include "../api/ParticleEmitter.h"
+#include "../api/Sprite.h"
+#include "../api/Text.h"
+#include "../api/Transform.h"
+#include "../facade/Font.h"
+#include "../facade/SDLContext.h"
+#include "../facade/Texture.h"
+#include "../manager/ComponentManager.h"
+#include "../manager/ResourceManager.h"
+
+#include "RenderSystem.h"
+#include "types.h"
+
+using namespace crepe;
+using namespace std;
+
+void RenderSystem::clear_screen() {
+ SDLContext & ctx = this->mediator.sdl_context;
+ ctx.clear_screen();
+}
+
+void RenderSystem::present_screen() {
+ SDLContext & ctx = this->mediator.sdl_context;
+ ctx.present_screen();
+}
+
+void RenderSystem::update_camera() {
+ ComponentManager & mgr = this->mediator.component_manager;
+ SDLContext & ctx = this->mediator.sdl_context;
+ RefVector<Camera> cameras = mgr.get_components_by_type<Camera>();
+
+ if (cameras.size() == 0) throw std::runtime_error("No cameras in current scene");
+
+ for (Camera & cam : cameras) {
+ if (!cam.active) continue;
+ const Transform & transform
+ = mgr.get_components_by_id<Transform>(cam.game_object_id).front().get();
+ vec2 new_camera_pos = transform.position + cam.data.postion_offset;
+ ctx.update_camera_view(cam, new_camera_pos);
+ return;
+ }
+ throw std::runtime_error("No active cameras in current scene");
+}
+
+bool sorting_comparison(const Sprite & a, const Sprite & b) {
+ if (a.data.sorting_in_layer != b.data.sorting_in_layer)
+ return a.data.sorting_in_layer < b.data.sorting_in_layer;
+ if (a.data.order_in_layer != b.data.order_in_layer)
+ return a.data.order_in_layer < b.data.order_in_layer;
+
+ return false;
+}
+
+RefVector<Sprite> RenderSystem::sort(RefVector<Sprite> & objs) const {
+ RefVector<Sprite> sorted_objs(objs);
+ std::sort(sorted_objs.begin(), sorted_objs.end(), sorting_comparison);
+
+ return sorted_objs;
+}
+
+void RenderSystem::frame_update() {
+ this->clear_screen();
+ this->render();
+ this->present_screen();
+}
+
+bool RenderSystem::render_particle(const Sprite & sprite, const double & scale) {
+
+ ComponentManager & mgr = this->mediator.component_manager;
+ SDLContext & ctx = this->mediator.sdl_context;
+ ResourceManager & resource_manager = this->mediator.resource_manager;
+ Texture & res = resource_manager.get<Texture>(sprite.source);
+
+ vector<reference_wrapper<ParticleEmitter>> emitters
+ = mgr.get_components_by_id<ParticleEmitter>(sprite.game_object_id);
+
+ bool rendering_particles = false;
+
+ for (const ParticleEmitter & em : emitters) {
+ if (&em.sprite != &sprite) continue;
+ rendering_particles = true;
+ if (!em.active) continue;
+
+ for (const Particle & p : em.particles) {
+ if (!p.active) continue;
+
+ ctx.draw(SDLContext::RenderContext{
+ .sprite = sprite,
+ .texture = res,
+ .pos = p.position,
+ .angle = p.angle,
+ .scale = scale,
+ });
+ }
+ }
+ return rendering_particles;
+}
+void RenderSystem::render_normal(const Sprite & sprite, const Transform & tm) {
+ SDLContext & ctx = this->mediator.sdl_context;
+ ResourceManager & resource_manager = this->mediator.resource_manager;
+ const Texture & res = resource_manager.get<Texture>(sprite.source);
+
+ ctx.draw(SDLContext::RenderContext{
+ .sprite = sprite,
+ .texture = res,
+ .pos = tm.position,
+ .angle = tm.rotation,
+ .scale = tm.scale,
+ });
+}
+
+void RenderSystem::render() {
+ ComponentManager & mgr = this->mediator.component_manager;
+ this->update_camera();
+
+ RefVector<Sprite> sprites = mgr.get_components_by_type<Sprite>();
+ ResourceManager & resource_manager = this->mediator.resource_manager;
+ RefVector<Sprite> sorted_sprites = this->sort(sprites);
+ RefVector<Text> text_components = mgr.get_components_by_type<Text>();
+ for (Text & text : text_components) {
+ const Transform & transform
+ = mgr.get_components_by_id<Transform>(text.game_object_id).front().get();
+ this->render_text(text, transform);
+ }
+ for (const Sprite & sprite : sorted_sprites) {
+ if (!sprite.active) continue;
+ const Transform & transform
+ = mgr.get_components_by_id<Transform>(sprite.game_object_id).front().get();
+
+ bool rendered_particles = this->render_particle(sprite, transform.scale);
+
+ if (rendered_particles) continue;
+
+ this->render_normal(sprite, transform);
+ }
+}
+void RenderSystem::render_text(Text & text, const Transform & tm) {
+ SDLContext & ctx = this->mediator.sdl_context;
+
+ if (!text.font.has_value()) {
+ text.font.emplace(ctx.get_font_from_name(text.font_family));
+ }
+
+ ResourceManager & resource_manager = this->mediator.resource_manager;
+
+ if (!text.font.has_value()) {
+ return;
+ }
+ const Asset & font_asset = text.font.value();
+ const Font & res = resource_manager.get<Font>(font_asset);
+}
diff --git a/src/crepe/system/RenderSystem.h b/src/crepe/system/RenderSystem.h
new file mode 100644
index 0000000..656ad5b
--- /dev/null
+++ b/src/crepe/system/RenderSystem.h
@@ -0,0 +1,83 @@
+#pragma once
+
+#include <cmath>
+
+#include "System.h"
+#include "types.h"
+
+namespace crepe {
+
+class Camera;
+class Sprite;
+class Transform;
+class Text;
+/**
+ * \brief Manages rendering operations for all game objects.
+ *
+ * RenderSystem is responsible for rendering, clearing and presenting the screen, and
+ * managing the active camera.
+ */
+class RenderSystem : public System {
+public:
+ using System::System;
+ /**
+ * \brief Updates the RenderSystem for the current frame.
+ * This method is called to perform all rendering operations for the current game frame.
+ */
+ void frame_update() override;
+
+private:
+ //! Clears the screen in preparation for rendering.
+ void clear_screen();
+
+ //! Presents the rendered frame to the display.
+ void present_screen();
+
+ //! Updates the active camera used for rendering.
+ void update_camera();
+
+ //! Renders the whole screen
+ void render();
+
+ /**
+ * \brief Renders all the particles on the screen from a given sprite.
+ *
+ * \param sprite renders the particles with given texture
+ * \param tm the Transform component for scale. This is not a const reference because each
+ * particle has a position and rotation that needs to overwrite the transform position and
+ * rotation without overwriting the current transform. and because the transform
+ * constructor is now protected i cannot make tmp inside
+ * \return true if particles have been rendered
+ */
+ bool render_particle(const Sprite & sprite, const double & scale);
+ /**
+ * \brief Renders all Text components
+ *
+ * \param text The text component to be rendered.
+ * \param tm the Transform component that holds the position,rotation and scale
+ */
+ void render_text(Text & text, const Transform & tm);
+ /**
+ * \brief renders a sprite with a Transform component on the screen
+ *
+ * \param sprite the sprite component that holds all the data
+ * \param tm the Transform component that holds the position,rotation and scale
+ */
+ void render_normal(const Sprite & sprite, const Transform & tm);
+
+ /**
+ * \brief sort a vector sprite objects with
+ *
+ * \param objs the vector that will do a sorting algorithm on
+ * \return returns a sorted reference vector
+ */
+ RefVector<Sprite> sort(RefVector<Sprite> & objs) const;
+
+ /**
+ * \todo Add text rendering using SDL_ttf for text components.
+ * \todo Implement a text component and a button component.
+ * \todo Consider adding text input functionality.
+ */
+};
+
+} // namespace crepe
diff --git a/src/crepe/system/ReplaySystem.cpp b/src/crepe/system/ReplaySystem.cpp
new file mode 100644
index 0000000..efc3be4
--- /dev/null
+++ b/src/crepe/system/ReplaySystem.cpp
@@ -0,0 +1,54 @@
+#include "../manager/ReplayManager.h"
+#include "../manager/SystemManager.h"
+
+#include "EventSystem.h"
+#include "RenderSystem.h"
+#include "ReplaySystem.h"
+
+using namespace crepe;
+using namespace std;
+
+void ReplaySystem::fixed_update() {
+ ReplayManager & replay = this->mediator.replay_manager;
+ ReplayManager::State state = replay.get_state();
+ ReplayManager::State last_state = this->last_state;
+ this->last_state = state;
+
+ switch (state) {
+ case ReplayManager::IDLE:
+ break;
+ case ReplayManager::RECORDING: {
+ replay.frame_record();
+ break;
+ }
+ case ReplayManager::PLAYING: {
+ if (last_state != ReplayManager::PLAYING) this->playback_begin();
+ bool last = replay.frame_step();
+ if (last) this->playback_end();
+ break;
+ }
+ }
+}
+
+void ReplaySystem::playback_begin() {
+ SystemManager & systems = this->mediator.system_manager;
+ ComponentManager & components = this->mediator.component_manager;
+
+ this->playback = {
+ .components = components.save(),
+ .systems = systems.save(),
+ };
+
+ systems.disable_all();
+ systems.get_system<RenderSystem>().active = true;
+ systems.get_system<ReplaySystem>().active = true;
+ systems.get_system<EventSystem>().active = true;
+}
+
+void ReplaySystem::playback_end() {
+ SystemManager & systems = this->mediator.system_manager;
+ ComponentManager & components = this->mediator.component_manager;
+
+ components.restore(this->playback.components);
+ systems.restore(this->playback.systems);
+}
diff --git a/src/crepe/system/ReplaySystem.h b/src/crepe/system/ReplaySystem.h
new file mode 100644
index 0000000..bbc8d76
--- /dev/null
+++ b/src/crepe/system/ReplaySystem.h
@@ -0,0 +1,44 @@
+#pragma once
+
+#include "../manager/ReplayManager.h"
+#include "../manager/SystemManager.h"
+
+#include "System.h"
+
+namespace crepe {
+
+/**
+ * \brief ReplayManager helper system
+ *
+ * This system records and replays recordings using ReplayManager.
+ */
+class ReplaySystem : public System {
+public:
+ using System::System;
+
+ void fixed_update() override;
+
+private:
+ //! Last ReplayManager state
+ ReplayManager::State last_state = ReplayManager::IDLE;
+
+ /**
+ * \brief Playback snapshot
+ *
+ * When starting playback, the component state is saved and most systems are disabled. This
+ * struct stores the engine state before ReplayManager::play is called.
+ */
+ struct Snapshot {
+ ComponentManager::Snapshot components;
+ SystemManager::Snapshot systems;
+ };
+ //! Before playback snapshot
+ Snapshot playback;
+
+ //! Snapshot state and disable systems during playback
+ void playback_begin();
+ //! Restore state from before \c playback_begin()
+ void playback_end();
+};
+
+} // namespace crepe
diff --git a/src/crepe/system/ScriptSystem.cpp b/src/crepe/system/ScriptSystem.cpp
new file mode 100644
index 0000000..93b4853
--- /dev/null
+++ b/src/crepe/system/ScriptSystem.cpp
@@ -0,0 +1,40 @@
+#include "../api/BehaviorScript.h"
+#include "../api/Script.h"
+#include "../manager/ComponentManager.h"
+
+#include "ScriptSystem.h"
+
+using namespace std;
+using namespace crepe;
+
+void ScriptSystem::fixed_update() {
+ LoopTimerManager & timer = this->mediator.loop_timer;
+ duration_t delta_time = timer.get_scaled_fixed_delta_time();
+ this->update(&Script::fixed_update, delta_time);
+}
+
+void ScriptSystem::frame_update() {
+ LoopTimerManager & timer = this->mediator.loop_timer;
+ duration_t delta_time = timer.get_delta_time();
+ this->update(&Script::frame_update, delta_time);
+}
+
+void ScriptSystem::update(void (Script::*update_function)(duration_t),
+ const duration_t & delta_time) {
+ ComponentManager & mgr = this->mediator.component_manager;
+ RefVector<BehaviorScript> behavior_scripts = mgr.get_components_by_type<BehaviorScript>();
+
+ for (BehaviorScript & behavior_script : behavior_scripts) {
+ if (!behavior_script.active) continue;
+
+ Script * script = behavior_script.script.get();
+ if (script == nullptr) continue;
+
+ if (!script->initialized) {
+ script->init();
+ script->initialized = true;
+ }
+
+ (*script.*update_function)(delta_time);
+ }
+}
diff --git a/src/crepe/system/ScriptSystem.h b/src/crepe/system/ScriptSystem.h
new file mode 100644
index 0000000..257b615
--- /dev/null
+++ b/src/crepe/system/ScriptSystem.h
@@ -0,0 +1,37 @@
+#pragma once
+
+#include "../manager/LoopTimerManager.h"
+
+#include "System.h"
+
+namespace crepe {
+
+class Script;
+
+/**
+ * \brief Script system
+ *
+ * The script system is responsible for all \c BehaviorScript components, and calls the methods
+ * on classes derived from \c Script.
+ */
+class ScriptSystem : public System {
+public:
+ using System::System;
+
+public:
+ //! Call Script::fixed_update() on all active \c BehaviorScript instances
+ void fixed_update() override;
+ //! Call Script::frame_update() on all active \c BehaviorScript instances
+ void frame_update() override;
+
+private:
+ /**
+ * \brief Call Script `*_update` member function on all active \c BehaviorScript instances
+ *
+ * \note This routine also calls Script::init() if this has not been done before on the \c
+ * BehaviorScript instance.
+ */
+ void update(void (Script::*update_function)(duration_t), const duration_t & delta_time);
+};
+
+} // namespace crepe
diff --git a/src/crepe/system/System.cpp b/src/crepe/system/System.cpp
new file mode 100644
index 0000000..ecc740d
--- /dev/null
+++ b/src/crepe/system/System.cpp
@@ -0,0 +1,5 @@
+#include "System.h"
+
+using namespace crepe;
+
+System::System(const Mediator & mediator) : mediator(mediator) {}
diff --git a/src/crepe/system/System.h b/src/crepe/system/System.h
new file mode 100644
index 0000000..e2ce7eb
--- /dev/null
+++ b/src/crepe/system/System.h
@@ -0,0 +1,32 @@
+#pragma once
+
+#include "../manager/Mediator.h"
+
+namespace crepe {
+
+class ComponentManager;
+
+/**
+ * \brief Base ECS system class
+ *
+ * This class is used as the base for all system classes. Classes derived from System must
+ * implement the System::update() method and copy Script::Script with the `using`-syntax.
+ */
+class System {
+public:
+ //! Code that runs in the fixed loop
+ virtual void fixed_update() {};
+ //! Code that runs in the frame loop
+ virtual void frame_update() {};
+ //! Indicates that the update functions of this system should be run
+ bool active = true;
+
+public:
+ System(const Mediator & m);
+ virtual ~System() = default;
+
+protected:
+ const Mediator & mediator;
+};
+
+} // namespace crepe
diff --git a/src/crepe/types.h b/src/crepe/types.h
new file mode 100644
index 0000000..69cc526
--- /dev/null
+++ b/src/crepe/types.h
@@ -0,0 +1,30 @@
+#pragma once
+
+#include "api/Vector2.h"
+
+#include <cstdint>
+#include <functional>
+#include <vector>
+
+namespace crepe {
+
+//! GameObject ID
+typedef uint32_t game_object_id_t;
+
+//! vector of reference_wrapper
+template <typename T>
+using RefVector = std::vector<std::reference_wrapper<T>>;
+
+//! Default Vector2<int> type
+typedef Vector2<int> ivec2;
+
+//! Default Vector2<unsigned int> type
+typedef Vector2<unsigned int> uvec2;
+
+//! Default Vector2<float> type
+typedef Vector2<float> vec2;
+
+//! Default Vector2<double> type
+typedef Vector2<double> dvec2;
+
+}; // namespace crepe
diff --git a/src/crepe/util/CMakeLists.txt b/src/crepe/util/CMakeLists.txt
index 100f028..94ed906 100644
--- a/src/crepe/util/CMakeLists.txt
+++ b/src/crepe/util/CMakeLists.txt
@@ -1,9 +1,15 @@
target_sources(crepe PUBLIC
- log.cpp
+ LogColor.cpp
+ Log.cpp
)
target_sources(crepe PUBLIC FILE_SET HEADERS FILES
- color.h
- log.h
+ LogColor.h
+ Log.h
+ Log.hpp
+ Proxy.h
+ Proxy.hpp
+ OptionalRef.h
+ OptionalRef.hpp
)
diff --git a/src/crepe/util/Log.cpp b/src/crepe/util/Log.cpp
new file mode 100644
index 0000000..ce25a1d
--- /dev/null
+++ b/src/crepe/util/Log.cpp
@@ -0,0 +1,38 @@
+#include <iostream>
+#include <string>
+
+#include "../api/Config.h"
+
+#include "Log.h"
+#include "LogColor.h"
+
+using namespace crepe;
+using namespace std;
+
+string Log::prefix(const Level & level) {
+ switch (level) {
+ case Level::TRACE:
+ return LogColor().fg_white().str("[TRACE]") + " ";
+ case Level::DEBUG:
+ return LogColor().fg_magenta().str("[DEBUG]") + " ";
+ case Level::INFO:
+ return LogColor().fg_blue().str("[INFO]") + " ";
+ case Level::WARNING:
+ return LogColor().fg_yellow().str("[WARN]") + " ";
+ case Level::ERROR:
+ return LogColor().fg_red().str("[ERROR]") + " ";
+ }
+ return "";
+}
+
+void Log::log(const Level & level, const string & msg) {
+ auto & cfg = Config::get_instance();
+ if (level < cfg.log.level) return;
+
+ string out = Log::prefix(level) + msg;
+ if (!out.ends_with("\n")) out += "\n";
+
+ // TODO: also log to file or smth
+ cout.write(out.data(), out.size());
+ cout.flush();
+}
diff --git a/src/crepe/util/Log.h b/src/crepe/util/Log.h
new file mode 100644
index 0000000..b43fe30
--- /dev/null
+++ b/src/crepe/util/Log.h
@@ -0,0 +1,63 @@
+#pragma once
+
+#include <format>
+
+namespace crepe {
+
+/**
+ * \brief Logging utility
+ *
+ * This class is used to output log messages to the console and/or log files.
+ */
+class Log {
+public:
+ //! Log message severity
+ enum Level {
+ TRACE, //!< Include (internal) function calls
+ DEBUG, //!< Include dbg_logf output
+ INFO, //!< General-purpose messages
+ WARNING, //!< Non-fatal errors
+ ERROR, //!< Fatal errors
+ };
+
+ /**
+ * \brief Log a formatted message
+ *
+ * \param level Message severity
+ * \param msg Formatted message
+ */
+ static void log(const Level & level, const std::string & msg);
+
+ /**
+ * \brief Format a message and log it
+ *
+ * \param level Message severity
+ * \param fmt Message format
+ * \param args Format arguments
+ */
+ template <class... Args>
+ static void logf(const Level & level, std::format_string<Args...> fmt, Args &&... args);
+
+ /**
+ * \brief Format a message and log it (with default severity \c INFO)
+ *
+ * \param fmt Message format
+ * \param args Format arguments
+ */
+ template <class... Args>
+ static void logf(std::format_string<Args...> fmt, Args &&... args);
+
+private:
+ /**
+ * \brief Output a message prefix depending on the log level
+ *
+ * \param level Message severity
+ *
+ * \return Colored message severity prefix string
+ */
+ static std::string prefix(const Level & level);
+};
+
+} // namespace crepe
+
+#include "Log.hpp"
diff --git a/src/crepe/util/Log.hpp b/src/crepe/util/Log.hpp
new file mode 100644
index 0000000..c2156cd
--- /dev/null
+++ b/src/crepe/util/Log.hpp
@@ -0,0 +1,17 @@
+#pragma once
+
+#include "Log.h"
+
+namespace crepe {
+
+template <class... Args>
+void Log::logf(std::format_string<Args...> fmt, Args &&... args) {
+ Log::logf(Level::INFO, fmt, std::forward<Args>(args)...);
+}
+
+template <class... Args>
+void Log::logf(const Level & level, std::format_string<Args...> fmt, Args &&... args) {
+ Log::log(level, std::format(fmt, std::forward<Args>(args)...));
+}
+
+} // namespace crepe
diff --git a/src/crepe/util/LogColor.cpp b/src/crepe/util/LogColor.cpp
new file mode 100644
index 0000000..5411898
--- /dev/null
+++ b/src/crepe/util/LogColor.cpp
@@ -0,0 +1,46 @@
+#include <cstdarg>
+
+#include "../api/Config.h"
+
+#include "LogColor.h"
+
+using namespace crepe;
+using namespace std;
+
+static constexpr const char * RESET_CODE = "\e[0m";
+
+const string LogColor::str(const string & content) const {
+ auto & cfg = Config::get_instance();
+ string out = content;
+ if (cfg.log.color) out = this->code + out;
+ if (content.size() == 0) return out;
+ if (cfg.log.color) out = out + RESET_CODE;
+ return out;
+}
+
+LogColor & LogColor::add_code(unsigned int code) {
+ this->code += format("\e[{}m", code);
+ return *this;
+}
+
+LogColor & LogColor::reset() {
+ this->code = RESET_CODE;
+ return *this;
+}
+
+LogColor & LogColor::fg_black(bool bright) { return this->add_code(bright ? 90 : 30); }
+LogColor & LogColor::fg_red(bool bright) { return this->add_code(bright ? 91 : 31); }
+LogColor & LogColor::fg_green(bool bright) { return this->add_code(bright ? 92 : 32); }
+LogColor & LogColor::fg_yellow(bool bright) { return this->add_code(bright ? 93 : 33); }
+LogColor & LogColor::fg_blue(bool bright) { return this->add_code(bright ? 94 : 34); }
+LogColor & LogColor::fg_magenta(bool bright) { return this->add_code(bright ? 95 : 35); }
+LogColor & LogColor::fg_cyan(bool bright) { return this->add_code(bright ? 96 : 36); }
+LogColor & LogColor::fg_white(bool bright) { return this->add_code(bright ? 97 : 37); }
+LogColor & LogColor::bg_black(bool bright) { return this->add_code(bright ? 100 : 40); }
+LogColor & LogColor::bg_red(bool bright) { return this->add_code(bright ? 101 : 41); }
+LogColor & LogColor::bg_green(bool bright) { return this->add_code(bright ? 102 : 42); }
+LogColor & LogColor::bg_yellow(bool bright) { return this->add_code(bright ? 103 : 43); }
+LogColor & LogColor::bg_blue(bool bright) { return this->add_code(bright ? 104 : 44); }
+LogColor & LogColor::bg_magenta(bool bright) { return this->add_code(bright ? 105 : 45); }
+LogColor & LogColor::bg_cyan(bool bright) { return this->add_code(bright ? 106 : 46); }
+LogColor & LogColor::bg_white(bool bright) { return this->add_code(bright ? 107 : 47); }
diff --git a/src/crepe/util/LogColor.h b/src/crepe/util/LogColor.h
new file mode 100644
index 0000000..132fb94
--- /dev/null
+++ b/src/crepe/util/LogColor.h
@@ -0,0 +1,80 @@
+#pragma once
+
+#include <string>
+
+namespace crepe {
+
+/**
+ * \brief Utility class for coloring text using ANSI escape codes
+ *
+ * \note Most methods in this class return a reference to \c this, which may be
+ * used to chain multiple display attributes.
+ */
+class LogColor {
+public:
+ /**
+ * \brief Get color code as STL string
+ *
+ * \param content If given, color this string and append a color reset escape sequence.
+ *
+ * \returns Color escape sequence
+ */
+ const std::string str(const std::string & content = "") const;
+
+public:
+ //! Reset color to default foreground and background color
+ LogColor & reset();
+
+public:
+ /**
+ * \name Foreground colors
+ *
+ * These functions set the foreground (text) color. The \c bright parameter
+ * makes the color brighter, or bold on some terminals.
+ * \{
+ */
+ LogColor & fg_black(bool bright = false);
+ LogColor & fg_red(bool bright = false);
+ LogColor & fg_green(bool bright = false);
+ LogColor & fg_yellow(bool bright = false);
+ LogColor & fg_blue(bool bright = false);
+ LogColor & fg_magenta(bool bright = false);
+ LogColor & fg_cyan(bool bright = false);
+ LogColor & fg_white(bool bright = false);
+ /// \}
+
+public:
+ /**
+ * \name Background colors
+ *
+ * These functions set the background color. The \c bright parameter makes
+ * the color brighter.
+ * \{
+ */
+ LogColor & bg_black(bool bright = false);
+ LogColor & bg_red(bool bright = false);
+ LogColor & bg_green(bool bright = false);
+ LogColor & bg_yellow(bool bright = false);
+ LogColor & bg_blue(bool bright = false);
+ LogColor & bg_magenta(bool bright = false);
+ LogColor & bg_cyan(bool bright = false);
+ LogColor & bg_white(bool bright = false);
+ /// \}
+
+private:
+ /**
+ * \brief Append SGR escape sequence to \c this->code
+ *
+ * \param code SGR attribute number
+ *
+ * See <https://en.wikipedia.org/wiki/ANSI_escape_code> for magic number
+ * reference.
+ */
+ LogColor & add_code(unsigned int code);
+
+private:
+ //! Color escape sequence
+ std::string code = "";
+};
+
+} // namespace crepe
diff --git a/src/crepe/util/OptionalRef.h b/src/crepe/util/OptionalRef.h
new file mode 100644
index 0000000..1b2cb3f
--- /dev/null
+++ b/src/crepe/util/OptionalRef.h
@@ -0,0 +1,66 @@
+#pragma once
+
+namespace crepe {
+
+/**
+ * \brief Optional reference utility
+ *
+ * This class doesn't need to know the full definition of \c T to be used.
+ *
+ * \tparam T Value type
+ */
+template <typename T>
+class OptionalRef {
+public:
+ //! Initialize empty (nonexistant) reference
+ OptionalRef() = default;
+ //! Initialize reference with value
+ OptionalRef(T & ref);
+ /**
+ * \brief Assign new reference
+ *
+ * \param ref Reference to assign
+ *
+ * \return Reference to this (required for operator)
+ */
+ OptionalRef<T> & operator=(T & ref);
+ /**
+ * \brief Retrieve this reference (cast)
+ *
+ * \returns Internal reference if it is set
+ *
+ * \throws std::runtime_error if this function is called while the reference it not set
+ */
+ operator T &() const;
+ /**
+ * \brief Retrieve this reference (member access)
+ *
+ * \returns Internal reference if it is set
+ *
+ * \throws std::runtime_error if this function is called while the reference it not set
+ */
+ T * operator->() const;
+ /**
+ * \brief Check if this reference is not empty
+ *
+ * \returns `true` if reference is set, or `false` if it is not
+ */
+ explicit operator bool() const noexcept;
+
+ /**
+ * \brief Make this reference empty
+ */
+ void clear() noexcept;
+
+private:
+ /**
+ * \brief Reference to the value of type \c T
+ *
+ * \note This raw pointer is *not* managed, and only used as a reference!
+ */
+ T * ref = nullptr;
+};
+
+} // namespace crepe
+
+#include "OptionalRef.hpp"
diff --git a/src/crepe/util/OptionalRef.hpp b/src/crepe/util/OptionalRef.hpp
new file mode 100644
index 0000000..5e36b3a
--- /dev/null
+++ b/src/crepe/util/OptionalRef.hpp
@@ -0,0 +1,44 @@
+#pragma once
+
+#include <stdexcept>
+
+#include "OptionalRef.h"
+
+namespace crepe {
+
+template <typename T>
+OptionalRef<T>::OptionalRef(T & ref) {
+ this->ref = &ref;
+}
+
+template <typename T>
+OptionalRef<T>::operator T &() const {
+ if (this->ref == nullptr)
+ throw std::runtime_error("OptionalRef: attempt to dereference nullptr");
+ return *this->ref;
+}
+
+template <typename T>
+T * OptionalRef<T>::operator->() const {
+ if (this->ref == nullptr)
+ throw std::runtime_error("OptionalRef: attempt to dereference nullptr");
+ return this->ref;
+}
+
+template <typename T>
+OptionalRef<T> & OptionalRef<T>::operator=(T & ref) {
+ this->ref = &ref;
+ return *this;
+}
+
+template <typename T>
+OptionalRef<T>::operator bool() const noexcept {
+ return this->ref != nullptr;
+}
+
+template <typename T>
+void OptionalRef<T>::clear() noexcept {
+ this->ref = nullptr;
+}
+
+} // namespace crepe
diff --git a/src/crepe/util/Proxy.h b/src/crepe/util/Proxy.h
new file mode 100644
index 0000000..789144a
--- /dev/null
+++ b/src/crepe/util/Proxy.h
@@ -0,0 +1,34 @@
+#pragma once
+
+#include "ValueBroker.h"
+
+namespace crepe {
+
+/**
+ * \brief Utility wrapper for \c ValueBroker
+ *
+ * This class can be used to to wrap a ValueBroker instance so it behaves like a regular
+ * variable.
+ *
+ * \tparam T Type of the underlying variable
+ */
+template <typename T>
+class Proxy {
+public:
+ //! Set operator
+ Proxy & operator=(Proxy &);
+ //! Set operator
+ Proxy & operator=(const T &);
+ //! Get operator
+ operator const T &();
+
+public:
+ Proxy(ValueBroker<T>);
+
+private:
+ ValueBroker<T> broker;
+};
+
+} // namespace crepe
+
+#include "Proxy.hpp"
diff --git a/src/crepe/util/Proxy.hpp b/src/crepe/util/Proxy.hpp
new file mode 100644
index 0000000..ef2b69f
--- /dev/null
+++ b/src/crepe/util/Proxy.hpp
@@ -0,0 +1,27 @@
+#pragma once
+
+#include "Proxy.h"
+
+namespace crepe {
+
+template <typename T>
+Proxy<T>::Proxy(ValueBroker<T> broker) : broker(broker) {}
+
+template <typename T>
+Proxy<T> & Proxy<T>::operator=(const T & val) {
+ this->broker.set(val);
+ return *this;
+}
+
+template <typename T>
+Proxy<T> & Proxy<T>::operator=(Proxy & proxy) {
+ this->broker.set(T(proxy));
+ return *this;
+}
+
+template <typename T>
+Proxy<T>::operator const T &() {
+ return this->broker.get();
+}
+
+} // namespace crepe
diff --git a/src/crepe/util/color.h b/src/crepe/util/color.h
deleted file mode 100644
index 066c9d3..0000000
--- a/src/crepe/util/color.h
+++ /dev/null
@@ -1,41 +0,0 @@
-#pragma once
-
-namespace crepe::util::color {
-
-constexpr const char * RESET = "\e[0m";
-
-constexpr const char * FG_BLACK = "\e[30m";
-constexpr const char * FG_RED = "\e[31m";
-constexpr const char * FG_GREEN = "\e[32m";
-constexpr const char * FG_YELLOW = "\e[33m";
-constexpr const char * FG_BLUE = "\e[34m";
-constexpr const char * FG_MAGENTA = "\e[35m";
-constexpr const char * FG_CYAN = "\e[36m";
-constexpr const char * FG_WHITE = "\e[37m";
-constexpr const char * BG_BLACK = "\e[40m";
-constexpr const char * BG_RED = "\e[41m";
-constexpr const char * BG_GREEN = "\e[42m";
-constexpr const char * BG_YELLOW = "\e[43m";
-constexpr const char * BG_BLUE = "\e[44m";
-constexpr const char * BG_MAGENTA = "\e[45m";
-constexpr const char * BG_CYAN = "\e[46m";
-constexpr const char * BG_WHITE = "\e[47m";
-
-constexpr const char * FG_BLACK_BRIGHT = "\e[90m";
-constexpr const char * FG_RED_BRIGHT = "\e[91m";
-constexpr const char * FG_GREEN_BRIGHT = "\e[92m";
-constexpr const char * FG_YELLOW_BRIGHT = "\e[93m";
-constexpr const char * FG_BLUE_BRIGHT = "\e[94m";
-constexpr const char * FG_MAGENTA_BRIGHT = "\e[95m";
-constexpr const char * FG_CYAN_BRIGHT = "\e[96m";
-constexpr const char * FG_WHITE_BRIGHT = "\e[97m";
-constexpr const char * BG_BLACK_BRIGHT = "\e[100m";
-constexpr const char * BG_RED_BRIGHT = "\e[101m";
-constexpr const char * BG_GREEN_BRIGHT = "\e[102m";
-constexpr const char * BG_YELLOW_BRIGHT = "\e[103m";
-constexpr const char * BG_BLUE_BRIGHT = "\e[104m";
-constexpr const char * BG_MAGENTA_BRIGHT = "\e[105m";
-constexpr const char * BG_CYAN_BRIGHT = "\e[106m";
-constexpr const char * BG_WHITE_BRIGHT = "\e[107m";
-
-} // namespace crepe::util::color
diff --git a/src/crepe/util/dbg.h b/src/crepe/util/dbg.h
new file mode 100644
index 0000000..c7283ee
--- /dev/null
+++ b/src/crepe/util/dbg.h
@@ -0,0 +1,18 @@
+#pragma once
+
+#include "Log.h"
+#include "LogColor.h"
+
+// utility macros
+#define _crepe_logf_here(level, fmt, ...) \
+ crepe::Log::logf(level, "{}" fmt, \
+ crepe::LogColor().fg_white(false).str(std::format( \
+ "{} ({}:{})", __PRETTY_FUNCTION__, __FILE_NAME__, __LINE__)), \
+ __VA_ARGS__)
+
+// very illegal global function-style macros
+// NOLINTBEGIN
+#define dbg_logf(fmt, ...) _crepe_logf_here(crepe::Log::Level::DEBUG, ": " fmt, __VA_ARGS__)
+#define dbg_log(str) _crepe_logf_here(crepe::Log::Level::DEBUG, ": {}", str)
+#define dbg_trace() _crepe_logf_here(crepe::Log::Level::TRACE, "", "")
+// NOLINTEND
diff --git a/src/crepe/util/log.cpp b/src/crepe/util/log.cpp
deleted file mode 100644
index f91d52c..0000000
--- a/src/crepe/util/log.cpp
+++ /dev/null
@@ -1,50 +0,0 @@
-#include <cstdarg>
-#include <cstdio>
-#include <cstdlib>
-#include <string>
-
-#include "log.h"
-
-using namespace crepe::util;
-
-static const char * const LOG_PREFIX[] = {
- [log_level::DEBUG] = "[DBG] ",
- [log_level::INFO] = "[INFO] ",
- [log_level::WARNING] = "[WARN] ",
- [log_level::ERROR] = "[ERR] ",
-};
-
-static void va_logf(enum log_level level, va_list args, const std::string fmt) {
- va_list args_copy;
- va_copy(args_copy, args);
-
- // prepend log level and ensure newline
- std::string format_fixed = LOG_PREFIX[level] + fmt;
- if (!format_fixed.ends_with("\n")) format_fixed += "\n";
-
- size_t sz = vsnprintf(NULL, 0, format_fixed.c_str(), args_copy) + 1;
- char * msg = (char *) malloc(sz);
- va_end(args_copy);
-
- vsnprintf(msg, sz, format_fixed.c_str(), args);
-
- // TODO: also log to file or smth
- printf("%s", msg);
- fflush(stdout);
-
- free(msg);
-}
-
-void crepe::util::logf(const char * fmt, ...) {
- va_list args;
- va_start(args, fmt);
- va_logf(crepe::util::log_level::DEBUG, args, fmt);
- va_end(args);
-}
-
-void crepe::util::logf(log_level level, const char * fmt, ...) {
- va_list args;
- va_start(args, fmt);
- va_logf(level, args, fmt);
- va_end(args);
-}
diff --git a/src/crepe/util/log.h b/src/crepe/util/log.h
deleted file mode 100644
index fa5f633..0000000
--- a/src/crepe/util/log.h
+++ /dev/null
@@ -1,36 +0,0 @@
-#pragma once
-
-// allow user to disable debug macros
-#ifndef CREPE_DISABLE_MACROS
-
-#include "color.h"
-
-// utility macros
-#define _crepe_logf_here(fmt, ...) \
- crepe::util::logf(util::log_level::DEBUG, "%s%s (%s:%d)" fmt "\n", \
- crepe::util::color::FG_WHITE, __PRETTY_FUNCTION__, \
- __FILE_NAME__, __LINE__, crepe::util::color::RESET, \
- __VA_ARGS__)
-
-// very illegal global function-style macros
-// NOLINTBEGIN
-#define dbg_logf(fmt, ...) _crepe_logf_here(": " fmt, __VA_ARGS__)
-#define dbg_log(str) _crepe_logf_here("%s: " str, "")
-#define dbg_trace() _crepe_logf_here("%s", "")
-// NOLINTEND
-
-#endif
-
-namespace crepe::util {
-
-enum log_level {
- DEBUG,
- INFO,
- WARNING,
- ERROR,
-};
-
-void logf(const char * fmt, ...);
-void logf(enum log_level level, const char * fmt, ...);
-
-} // namespace crepe::util