123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- /*
- * 2D Game Engine
- * ECS.h:
- * Based on pikuma.com 2D game engine in C++ and Lua course
- * Copyright (c) 2021 986-Studio. All rights reserved.
- *
- * Created by Manoël Trapier on 11/02/2021.
- */
- #ifndef GAMEENGINE_ECS_H
- #define GAMEENGINE_ECS_H
- #include <stdint.h>
- #include <bitset>
- #include <vector>
- #include <unordered_map>
- #include <typeindex>
- #include <Pool.h>
- const uint32_t MAX_COMPONENTS = 32;
- typedef std::bitset<MAX_COMPONENTS> Signature;
- struct IComponent
- {
- protected:
- static uint32_t nextId;
- };
- template <typename T> class Component: public IComponent
- {
- public:
- static uint32_t getId()
- {
- static auto id = IComponent::nextId++;
- return id;
- }
- };
- class Entity
- {
- private:
- uint32_t id;
- public:
- explicit Entity(uint32_t id): id(id) {};
- Entity(const Entity & entity) = default;
- uint32_t getId() const;
- Entity& operator=(const Entity & other) = default;
- bool operator==(const Entity &other) const { return this->id == other.id; };
- bool operator!=(const Entity &other) const { return this->id != other.id; };
- bool operator>(const Entity &other) const { return this->id > other.id; };
- bool operator<(const Entity &other) const { return this->id < other.id; };
- };
- class System
- {
- private:
- Signature componentSignature;
- std::vector<Entity> entities;
- public:
- System() = default;
- ~System() = default;
- void addEntity(Entity entity);
- void removeEntity(Entity entity);
- std::vector<Entity> getEntities() const;
- const Signature& getComponentSignature() const;
- template<typename T> void requireComponent();
- };
- template<typename T> void System::requireComponent()
- {
- const auto componentId = Component<T>::getId();
- this->componentSignature.set(componentId);
- }
- class Registry
- {
- private:
- uint32_t numEntities = 0;
- std::vector<IPool*> componentPools;
- std::vector<Signature> entityComponentSignatures;
- std::unordered_map<std::type_index, System*> systems;
- public:
- Registry() = default;
- ~Registry() = default;
- };
- #endif /* GAMEENGINE_ECS_H */
|