Advertisement
BeneFager

Untitled

Jan 11th, 2022
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.52 KB | None | 0 0
  1. /// <summary>
  2. /// Component base class
  3. /// </summary>
  4. class Component
  5. {
  6. public:
  7.     Entity *entity; //ref to owner
  8.  
  9.  
  10.     virtual void init() {}
  11.     virtual void update() {}
  12.     virtual void draw() {}
  13.  
  14.     virtual ~Component() {}
  15. };
  16.  
  17.  
  18.  
  19. class Entity
  20. {
  21. private:
  22.     Manager &manager; //manager ref
  23.     bool active = true;
  24.     std::vector<std::unique_ptr<Component>> components;
  25.  
  26.     ComponentArray componentArray;
  27.     ComponentBitSet componentBitSet;
  28.     GroupBitset groupBitset;
  29.  
  30. public:
  31.     Entity(Manager &mManager) : manager(mManager) {}
  32.     void update()
  33.     {
  34.         for(auto &c : components) c->update();
  35.     }
  36.  
  37.     void draw()
  38.     {
  39.         for(auto &c : components) c->draw();
  40.     }
  41.     bool isActive() { return active; }
  42.     void destroy() { active = false; }
  43.  
  44.     bool hasGroup(Group mGroup)
  45.     {
  46.         return groupBitset[mGroup];
  47.     }
  48.  
  49.     void addGroup(Group mGroup);
  50.     void delGroup(Group mGroup)
  51.     {
  52.         groupBitset[mGroup] = false;
  53.     }
  54.  
  55.     template <typename T> bool hasComponent()const
  56.     {
  57.         return componentBitSet[getComponentTypeID<T>()];
  58.     }
  59.  
  60.  
  61.     template <typename T, typename... TArgs>
  62.     T &addComponent(TArgs&&... mArgs)
  63.     {
  64.         T *c(new T(std::forward<TArgs>(mArgs)...));
  65.         c->entity = this;
  66.         std::unique_ptr<Component> uPtr{ c };
  67.         components.emplace_back(std::move(uPtr));
  68.  
  69.         componentArray[getComponentTypeID<T>()] = c;
  70.         componentBitSet[getComponentTypeID<T>()] = true;
  71.  
  72.  
  73.         c->init();
  74.  
  75.         return *c;
  76.     }
  77.  
  78.     template<typename T> T &getComponent() const
  79.     {
  80.         auto ptr(componentArray[getComponentTypeID<T>()]);
  81.         return *static_cast<T *>(ptr);
  82.     }
  83.  
  84. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement