Entity Component System and multiple components sharing common base type

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-12 15:34:50

问题


I'm trying to implement a simple ECS for my game engine. I know that my implementation is not strictly ECS, but I'm refactoring my code to be more component-based. So far I have the following classes:

Entity: it is a container of components, and since I want my entity to have multiple components of the same type, it stores them in a std::map<ComponentID,std::vector<std::unique_ptr<Component>>>. Each component has a unique ID (an unsigned int), that I get from a simple template trick I learned on the web:

A function called GetUniqueComponentID:

using ComponentID = unsigned int;

inline ComponentID GetUniqueComponentID()
{
    static ComponentID id = 0;

    return id++;
}

contains a counter that simply generates incrementing numbers. I call this function from a function template called GetComponentID:

template <typename T>
ComponentID GetComponentID()
{
    static ComponentID id = GetUniqueComponentID();

    return id;
}

this template instantiates a different function for each component that I add to my entity, so code that needs to retrieve a component can index the map using GetComponentId<Component_type>, with the concrete component type as the template argument for the function.

The entity class has methods like AddComponent and GetComponent that respectively create a component and add it to the entity, and retrieve a component (if present):

class Entity
{
public:
    Entity();
    ~Entity();
    template <typename T, typename... TArgs>
    T &AddComponent(TArgs&&... args);
    template <typename T>
    bool HasComponent();
    //template <typename T>
    //T &GetComponent();
    template <typename T> 
    std::vector<T*> GetComponents();
    bool IsAlive() { return mIsAlive; }
    void Destroy() { mIsAlive = false; }
private:
    //std::map<ComponentID, std::unique_ptr<Component>> mComponents;              // single component per type
    std::map<ComponentID, std::vector<std::unique_ptr<Component>>> mComponents;   // multiple components per type
    bool mIsAlive = true;
};


template <typename T, typename... TArgs>
T &Entity::AddComponent(TArgs&&... args)
{
    T *c = new T(std::forward<TArgs>(args)...);
    std::unique_ptr<Component> component(c);
    component->SetEntity(this);
    mComponents[GetComponentID<T>()].push_back(std::move(component));
    return *c;
}

template <typename T>
bool Entity::HasComponent()  // use bitset (faster)
{
    std::map<ComponentID, std::vector<std::unique_ptr<Component>>>::iterator it = mComponents.find(GetComponentID<T>());
    if (it != mComponents.end())
        return true;
    return false;
}

template <typename T>
std::vector<T*> Entity::GetComponents()
{
    std::vector<T*> components;
    for (std::unique_ptr<Component> &component : mComponents[GetComponentID<T>()])
        components.push_back(static_cast<T*>(component.get()));

    return components;
}

Since I want to store multiple components of the same type, I store them in a std::map<ComponentID,std::vector<std::unique_ptr<Component>>>.

Now my question is:

I need to create a component hierarchy for a type of component: I have a ForceGenerator component that is the (abstract) base class for all kinds of concrete ForceGenerators (Springs, Gravity and so on). So I need to create the concrete components, but I need to use them polymorphically through a pointer to the base class: my physics subsystem needs only be concerned with pointers to the base ForceGenerator, calling its Update() method that takes care of updating forces.

I can't use the current approach, since I call AddComponent with a different type each time I create a specific ForceGenerator component, while I need to store them in the same array (mapped to the component ID of the base ForceGenerator).

How could I solve this problem?


回答1:


You could use default template arguments like this:

class Entity
{
template <typename T,typename StoreAs=T, typename... TArgs>
    T &Entity::AddComponent(TArgs&&... args);
};
template <typename T,typename StoreAs, typename... TArgs>
T &Entity::AddComponent(TArgs&&... args)
{
     T *c = new T(std::forward<TArgs>(args)...);
     std::unique_ptr<Component> component(c);
     component->SetEntity(this);
     mComponents[GetComponentID<StoreAs()].push_back(std::move(component));
     return *c;
}

is called like

 entity.AddComponent<T>(...)//Will instatiate AddComponent<T,T,...>
 entity.AddComponent<T,U>(...)//Will instatiate AddComponent<T,U,...>

You might even go step further and use some SFINAE to only enable this function when the component can be stored as that type: (Might or might not actually improve the error message)

template <typename T,typename StoreAs, typename... TArgs>
std::enable_if_t<std::is_base_of_v<StoreAs,T>,T&> //Return type is `T&`
Entity::AddComponent(TArgs&&... args)
{
     T *c = new T(std::forward<TArgs>(args)...);
     std::unique_ptr<Component> component(c);
     component->SetEntity(this);
     mComponents[GetComponentID<StoreAs>()].push_back(std::move(component));
     return *c;
}

I assume that Component is a base class for all components. If you have a finite,known set of components, you can store them in std::variant<List types here> instead of unique pointers.

EDIT: Apparently clang complains: "template parameter redefines default argument". Gcc didn't mind, but just to be correct, put the StoreAs initialization StoreAs=T only in Entity class, not to the implementation. I edited the source code.




回答2:


NEW PROPOSAL

Looking at the other answer I got an idea, you can inherit from another CRTP base class for define where to store (only when using mapped store).

Example:

//Just for check class
struct StoreAs {};


//Give the store type
template<typename T>
struct StoreAsT : public StoreAs {
    using store_as_type = T;
};

//Some components
struct ComponentA {    };

struct ComponentC {    };

struct ComponentB : public StoreAsT<ComponentC> {    };


//Dummy add
template<typename T>
void Add(T&& cmp) {
    if constexpr(std::is_base_of_v<StoreAs, T>) {
        std::cout << "Store as (remap)" << GetComponentID<typename T::store_as_type>() << std::endl;
    } else {
        std::cout << "Store as " << GetComponentID<T>() << std::endl;
    }
}

//Example add
int main() {

    Add(ComponentA {});
    Add(ComponentB {});
    Add(ComponentC {});

    return 0;
}

Output:

Store as 0
Store as (remap)1
Store as 1

OLD PROPOSAL:

As a easy approach but quite verbose and not a generic solution you can expand you ID generation trick:

template <typename T>
ComponentID GetComponentID()
{
    static ComponentID id = GetUniqueComponentID();

    return id;
}

to

template <typename T>
struct ComponentIDGenerator {
    static ComponentID GetComponentID() {
        static ComponentID id = GetUniqueComponentID();

        return id;
    }
};

Now instead of use GetComponentID you need to use ComponenteIDGenerator::GetComponentID() but now you can create specific specializations.

So, you can specialize to remap some ids:

template<>
struct ComponentIDGenerator<SomeForce1> {
    static ComponentID GetComponentID() {
        return ComponentIDGenerator<NotRemappedForceType>::GetComponentID();
    }
};
template<>
struct ComponentIDGenerator<SomeForce2> {
    static ComponentID GetComponentID() {
        return ComponentIDGenerator<NotRemappedForceType>::GetComponentID();
    }
};

Now both (SomeFroce1 and SomeForce2) returns the id of "NotRemappedForceType"

and at the end recover the original function:

template<typename T>
ComponentID GetComponentID() {
    return ComponentIDGenerator<T>::GetComponentID();
}


来源:https://stackoverflow.com/questions/55187404/entity-component-system-and-multiple-components-sharing-common-base-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!