engine/include/ecs.h

71 lines
1.5 KiB
C
Raw Permalink Normal View History

2024-03-31 10:11:22 +00:00
#pragma once
2023-01-02 17:24:20 +00:00
#include <bitset>
2023-04-29 14:22:25 +00:00
#include <cassert>
#include <cstddef>
2023-01-02 17:24:20 +00:00
#include <cstdint>
2023-04-29 14:22:25 +00:00
#include <map>
#include <vector>
2023-04-29 14:22:25 +00:00
#include <set>
2023-04-24 10:53:43 +00:00
2023-01-02 17:24:20 +00:00
namespace engine {
2023-04-29 14:22:25 +00:00
class Scene;
2023-09-19 07:40:45 +00:00
using Entity = uint32_t; // ECS entity
constexpr size_t kMaxComponents = 10;
2023-04-29 14:22:25 +00:00
class IComponentArray {
2024-03-31 10:11:22 +00:00
public:
virtual ~IComponentArray() = default;
2023-04-29 14:22:25 +00:00
};
2023-01-02 17:24:20 +00:00
2023-04-29 14:56:49 +00:00
template <typename T>
2023-04-29 14:22:25 +00:00
class ComponentArray : public IComponentArray {
2024-03-31 10:11:22 +00:00
public:
void InsertData(Entity entity, const T& component)
{
if (component_array_.size() < entity + 1) {
component_array_.resize(entity + 1);
}
// bounds checking here as not performance critical
component_array_.at(entity) = component;
}
2023-01-02 17:24:20 +00:00
2024-03-31 10:11:22 +00:00
void DeleteData(Entity entity)
{
(void)entity; // TODO
}
2023-04-29 14:56:49 +00:00
2024-03-31 10:11:22 +00:00
T* GetData(Entity entity)
{
assert(entity < component_array_.size());
return &component_array_[entity];
}
2023-01-02 17:24:20 +00:00
2024-03-31 10:11:22 +00:00
private:
std::vector<T> component_array_{};
2023-04-29 14:22:25 +00:00
};
2023-01-02 17:24:20 +00:00
2023-04-29 14:22:25 +00:00
class System {
2024-03-31 10:11:22 +00:00
public:
System(Scene* scene, std::set<size_t> required_component_hashes);
virtual ~System() {}
System(const System&) = delete;
System& operator=(const System&) = delete;
2023-01-02 17:24:20 +00:00
2024-03-31 10:11:22 +00:00
virtual void OnUpdate(float ts) = 0;
2023-01-02 17:24:20 +00:00
2024-03-31 10:11:22 +00:00
virtual void OnComponentInsert(Entity) {}
virtual void OnComponentRemove(Entity) {}
2023-01-02 17:24:20 +00:00
2024-03-31 10:11:22 +00:00
Scene* const scene_;
2023-02-02 17:32:19 +00:00
2024-03-31 10:11:22 +00:00
std::bitset<kMaxComponents> signature_;
2023-04-29 14:56:49 +00:00
2024-03-31 10:11:22 +00:00
// entities that contain the needed components
std::set<Entity> entities_{};
2023-04-29 14:22:25 +00:00
};
2023-01-02 17:24:20 +00:00
2024-03-31 10:11:22 +00:00
} // namespace engine