48 lines
1.0 KiB
C++
48 lines
1.0 KiB
C++
#pragma once
|
|
|
|
#include <memory>
|
|
#include <optional>
|
|
#include <vector>
|
|
|
|
struct Entity;
|
|
class Component;
|
|
|
|
class Component {
|
|
public:
|
|
Entity *entity = nullptr;
|
|
|
|
virtual void Setup() = 0;
|
|
virtual void Update(float dt) = 0;
|
|
virtual void Cleanup() = 0;
|
|
|
|
virtual ~Component() = default;
|
|
};
|
|
|
|
struct Entity {
|
|
std::vector<std::shared_ptr<Component>> components;
|
|
|
|
template <std::derived_from<Component> T> T &AddComponent() {
|
|
auto &ptr = components.emplace_back(std::make_shared<T>());
|
|
ptr->entity = this;
|
|
ptr->Setup();
|
|
return static_cast<T &>(*ptr);
|
|
}
|
|
|
|
template <std::derived_from<Component> T>
|
|
std::optional<std::reference_wrapper<T>> GetComponent() const {
|
|
for (auto &c : components) {
|
|
T *cast = dynamic_cast<T *>(c.get());
|
|
if (cast) {
|
|
return *cast;
|
|
}
|
|
}
|
|
return {};
|
|
}
|
|
|
|
void Update(float dt) {
|
|
for (auto &c : components) {
|
|
c->Update(dt);
|
|
}
|
|
}
|
|
};
|