Skip to content

Commit

Permalink
Make components array in Entity a pointer
Browse files Browse the repository at this point in the history
  • Loading branch information
feresr committed May 31, 2020
1 parent 8eb2f83 commit e11da22
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 10 deletions.
33 changes: 25 additions & 8 deletions include/ecs/ecs.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,41 +20,58 @@ struct Component {
class Entity {
public:

Entity() : components{new std::unordered_map<std::type_index, Component*>()} {};

Entity(const Entity& other) = delete;

Entity(Entity&& other) noexcept {
this->components = other.components;
other.components = nullptr;
}

Entity& operator=(Entity&& other) noexcept {
if (this == &other) return *this;
this->components = other.components;
other.components = nullptr;
return *this;
}

template<typename ComponentType, typename... Args>
void assign(Args&& ... arguments) {
// std::forward will detect whether arguments is an lvalue or rvalue and perform a copy or move, respectively.
auto* component = new ComponentType(std::forward<Args&&>(arguments)...);
auto typeIndex = std::type_index(typeid(ComponentType));
components.insert_or_assign(typeIndex, component);
components->insert_or_assign(typeIndex, component);
}

template<typename ComponentType>
bool remove() {
auto index = std::type_index(typeid(ComponentType));
auto found = components.find(index);
if (found != components.end()) {
auto found = components->find(index);
if (found != components->end()) {
delete found->second;
components.erase(found);
components->erase(found);
return true;
}

return false;
}

bool clearComponents() {
components.clear();
components->clear();
return true;
}

template<typename C>
C* get() {
return static_cast<C*>(components[std::type_index(typeid(C))]);
return static_cast<C*>((*components)[std::type_index(typeid(C))]);
}

template<typename C>
[[nodiscard]] bool has() const {
if (components->empty()) return false;
auto index = std::type_index(typeid(C));
return components.find(index) != components.end();
return components->find(index) != components->end();
}

template<typename A, typename B, typename... OTHERS>
Expand All @@ -70,7 +87,7 @@ class Entity {
~Entity();

private:
std::unordered_map<std::type_index, Component*> components;
std::unordered_map<std::type_index, Component*>* components;
};

class System {
Expand Down
4 changes: 2 additions & 2 deletions src/ecs/ecs.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,6 @@ void World::handleEvent(SDL_Event& event) {
}

Entity::~Entity() {
for (auto component : components) delete component.second;
components.clear();
for (auto& component : *components) delete component.second;
components->clear();
}

0 comments on commit e11da22

Please sign in to comment.