[ecs] Add a function to safely get a component

It returns null if the entity is invalid or doesn't have the component.
Useful when the component is optional.
This commit is contained in:
Bill Currie 2023-07-04 16:48:15 +09:00
parent 7e338b7e29
commit 6701f921a4

View file

@ -48,11 +48,13 @@ ENTINLINE uint32_t Ent_Generation (uint32_t id);
ENTINLINE uint32_t Ent_NextGen (uint32_t id); ENTINLINE uint32_t Ent_NextGen (uint32_t id);
ENTINLINE int Ent_HasComponent (uint32_t ent, uint32_t comp, ENTINLINE int Ent_HasComponent (uint32_t ent, uint32_t comp,
ecs_registry_t *reg); ecs_registry_t *reg);
ENTINLINE void *Ent_GetComponent (uint32_t ent, uint32_t comp, ENTINLINE void *Ent_GetComponent (uint32_t ent, uint32_t comp,
ecs_registry_t *reg); ecs_registry_t *reg);
ENTINLINE void *Ent_SafeGetComponent (uint32_t ent, uint32_t comp,
ecs_registry_t *reg);
ENTINLINE void *Ent_SetComponent (uint32_t ent, uint32_t comp, ENTINLINE void *Ent_SetComponent (uint32_t ent, uint32_t comp,
ecs_registry_t *registry, const void *data); ecs_registry_t *registry, const void *data);
#undef ENTINLINE #undef ENTINLINE
#ifndef IMPLEMENT_ECS_ENTITY_Funcs #ifndef IMPLEMENT_ECS_ENTITY_Funcs
@ -103,6 +105,18 @@ Ent_GetComponent (uint32_t ent, uint32_t comp, ecs_registry_t *reg)
return data + ind * component->size; return data + ind * component->size;
} }
ENTINLINE void *
Ent_SafeGetComponent (uint32_t ent, uint32_t comp, ecs_registry_t *reg)
{
if (!ECS_EntValid (ent, reg) || !Ent_HasComponent (ent, comp, reg)) {
return 0;
}
const component_t *component = &reg->components.a[comp];
uint32_t ind = reg->comp_pools[comp].sparse[Ent_Index (ent)];
byte *data = reg->comp_pools[comp].data;
return data + ind * component->size;
}
void *Ent_AddComponent (uint32_t ent, uint32_t comp, ecs_registry_t *registry); void *Ent_AddComponent (uint32_t ent, uint32_t comp, ecs_registry_t *registry);
void Ent_RemoveComponent (uint32_t ent, uint32_t comp, void Ent_RemoveComponent (uint32_t ent, uint32_t comp,
ecs_registry_t *registry); ecs_registry_t *registry);