Hello there,
I'm currently working on an ECS engine in C. Specifically, I'm implementing a “component pool” that enables components to quickly be created / destroyed. Each component holds data along with an “entity ID” such that the component can be associated with an entity.
The requirement of my pool is that the components are in contiguous memory. However, there is no guarantee on order of the components with regard to entity ID.
For example, if I did the following:
insert_into_pool(new_component(), ENTITY_0);
insert_into_pool(new_component(), ENTITY_1);
insert_into_pool(new_component(), ENTITY_2);
insert_into_pool(new_component(), ENTITY_3);
// component_order
// Entity 0 Component
// Entity 1 Component
// Entity 2 Component
// Entity 3 Component
remove_from_pool(ENTITY_1);
// component_order
// Entity 0 Component
// Entity 3 Component
// Entity 2 Component
Note that whenever a component is removed, the last component is moved to fill the vacant slot such that active components remain contiguous.
However, this creates an issue that now I need some sort of method to retrieve a component using a provided entity ID. That is, I will want to get components out of the pool by only specifying the entity ID.
My current method is to use a simple map and would something like the following
int32_t entity_map[MAX_ENTITIES]; // gets updated in "insert" function
Component* get_from_pool(entity_id)
{
location = entity_map[entity_id];
return pool_data + location * component_size;
}
So this is a pretty simple method and is relatively fast since it's just a look up table. However, it seems to very memory inefficient.
Let's say the max entities I support is 16384. But then let's say the component type in question is not super common, and would likely only ever be used by 100 entities. It seems very wasteful to allocate a 16834 look-up array when there would only be 100 entities that use the component.
Are there any other methods for tracking entity IDs within component pools?