diff options
author | Yann Herklotz <ymherklotz@gmail.com> | 2018-06-23 15:51:37 +0100 |
---|---|---|
committer | Yann Herklotz <ymherklotz@gmail.com> | 2018-06-23 15:51:37 +0100 |
commit | 801299f3175fccb940550cba48903decd7882822 (patch) | |
tree | a065643549f7fa2103b065be16a862c5a34ef2e7 | |
parent | 083fcf24c50753b6f5fa04c5358be783be64407d (diff) | |
download | YAGE-801299f3175fccb940550cba48903decd7882822.tar.gz YAGE-801299f3175fccb940550cba48903decd7882822.zip |
Entity implementation with added 'each' function
-rw-r--r-- | yage/entity/entity.cpp | 11 | ||||
-rw-r--r-- | yage/entity/entity.h | 29 |
2 files changed, 34 insertions, 6 deletions
diff --git a/yage/entity/entity.cpp b/yage/entity/entity.cpp index 25e8e2d0..c20d15d6 100644 --- a/yage/entity/entity.cpp +++ b/yage/entity/entity.cpp @@ -3,6 +3,8 @@ #include "component.h" #include <algorithm> +#include <iostream> +#include <memory> namespace yage { @@ -29,12 +31,17 @@ bool EntityManager::is_valid(Entity entity) const return false; } -EntityManager &EntityManager::add_component(Entity entity, - BaseComponent *component) +EntityManager & +EntityManager::add_component(Entity entity, + std::unique_ptr<BaseComponent> &&component) { auto id = component->getGroup(); component_masks_[entity] = component_masks_[entity] | ComponentMask(1 << id); + if (id+1 > component_group_.size()) { + component_group_.resize(id+1); + } + component_group_[id].add(std::move(component)); return *this; } diff --git a/yage/entity/entity.h b/yage/entity/entity.h index 2aa31a66..93bea8fb 100644 --- a/yage/entity/entity.h +++ b/yage/entity/entity.h @@ -1,9 +1,12 @@ #pragma once -#include <vector> - #include "component.h" +#include <functional> +#include <iostream> +#include <memory> +#include <vector> + namespace yage { @@ -24,17 +27,35 @@ public: Entity create_entity(); EntityManager &delete_entity(Entity entity); bool is_valid(Entity entity) const; - EntityManager &add_component(Entity entity, BaseComponent *component); + EntityManager &add_component(Entity entity, + std::unique_ptr<BaseComponent> &&component); + template <typename T> + EntityManager &each(std::function<void(T &)> update); private: Entity update_next_entity(); Entity next_entity_ = 0; -public: std::vector<ComponentGroup> component_group_; std::vector<ComponentMask> component_masks_; std::vector<Entity> deleted_; }; +template <typename T> +EntityManager &EntityManager::each(std::function<void(T &)> update) +{ + T c; + auto id = static_cast<BaseComponent *>(&c)->getGroup(); + for (auto it = component_group_[id].begin(); + it != component_group_[id].end(); ++it) { + auto iteration = it - component_group_[id].begin(); + if (is_valid(iteration) && component_masks_[iteration][id]) { + update(*static_cast<T *>((*it).get())); + } + } + + return *this; +} + } // namespace yage |