95 lines
3.2 KiB
C++
95 lines
3.2 KiB
C++
#ifndef HYDRACOMPONENTARRAY
|
|
#define HYDRACOMPONENTARRAY
|
|
|
|
#include "../engine/HydraObject.h"
|
|
|
|
#include <array>
|
|
#include <unordered_map>
|
|
#include <mutex>
|
|
|
|
class IHydraComponentArray
|
|
{
|
|
public:
|
|
virtual ~IHydraComponentArray() = default;
|
|
virtual void EntityDeleted(HydraID entity_id) = 0;
|
|
};
|
|
|
|
template<typename T>
|
|
class HydraComponentArray : public IHydraComponentArray
|
|
{
|
|
private:
|
|
std::array<T, MAX_ACTORS> m_components;
|
|
std::unordered_map<HydraID, HydraID> m_entity_to_component;
|
|
std::unordered_map<HydraID, HydraID> m_component_to_entity;
|
|
|
|
std::mutex m_mutex;
|
|
uint32_t m_component_count = 0;
|
|
public:
|
|
void RemoveComponent(HydraID entity_id)
|
|
{
|
|
std::lock_guard<std::mutex> lock(m_mutex);
|
|
assert(m_entity_to_component.find(entity_id) == m_entity_to_component.end() && "Trying to remove a component that doesnt exist");
|
|
|
|
HydraID component_index = m_entity_to_component[entity_id];
|
|
HydraID last_component_index = m_component_count -1;
|
|
HydraID last_entity_id = m_component_to_entity[last_component_index];
|
|
|
|
if(last_component_index != component_index)
|
|
{
|
|
m_components[component_index] = m_components[last_component_index];
|
|
m_entity_to_component[last_entity_id] = component_index;
|
|
m_components[last_component_index] = {};
|
|
}
|
|
else
|
|
{
|
|
m_components[component_index] = {};
|
|
}
|
|
|
|
m_entity_to_component.erase(entity_id);
|
|
m_component_to_entity.erase(component_index);
|
|
|
|
}
|
|
|
|
void AddComponent(HydraID entity_id, T component)
|
|
{
|
|
std::lock_guard<std::mutex> lock(m_mutex);
|
|
assert(m_entity_to_component.find(entity_id) == m_entity_to_component.end() && "Trying to add a component that already exist");
|
|
m_components[m_component_count] = component;
|
|
m_entity_to_component.insert({entity_id, m_component_count});
|
|
m_component_to_entity.insert({m_component_count, entity_id});
|
|
m_component_count++;
|
|
}
|
|
|
|
bool HasComponent(HydraID entity_id)
|
|
{
|
|
std::lock_guard<std::mutex> lock(m_mutex);
|
|
return m_entity_to_component.find(entity_id) != m_entity_to_component.end();
|
|
}
|
|
|
|
T& GetComponent(HydraID entity_id)
|
|
{
|
|
std::lock_guard<std::mutex> lock(m_mutex);
|
|
if(m_entity_to_component.find(entity_id) == m_entity_to_component.end())
|
|
{
|
|
std::cout << "HERE";
|
|
}
|
|
assert(m_entity_to_component.find(entity_id) != m_entity_to_component.end() && "Trying to get a component that doesnt exist");
|
|
HydraID component_index = m_entity_to_component[entity_id];
|
|
return m_components[component_index];
|
|
}
|
|
|
|
void EntityDeleted(HydraID entity_id)
|
|
{
|
|
std::lock_guard<std::mutex> lock(m_mutex);
|
|
if(m_entity_to_component.find(entity_id) != m_entity_to_component.end())
|
|
{
|
|
RemoveComponent(entity_id);
|
|
}
|
|
}
|
|
|
|
|
|
|
|
};
|
|
|
|
#endif /* HYDRACOMPONENTARRAY */
|