Techneck/code/source-c/entity_pool.c

72 lines
2.3 KiB
C
Raw Normal View History

2023-10-14 13:04:52 +00:00
#include "entity.h"
#include "state.h"
#include <stdlib.h>
2023-10-14 19:17:30 +00:00
// TODO: Write a *real* pool allocator
void tc_reset_entity(tc_entity_s *entity)
{
if(entity->attributes != NULL) free(entity->attributes);
entity->attributes_capacity = 8;
entity->attributes =
calloc(sizeof(tc_entity_attribute_s), entity->attributes_capacity);
}
2023-10-14 13:04:52 +00:00
tc_entity_s * tc_allocate_entity()
{
tc_entity_registry_s registry = tc_game_state_g.entity_registry;
uint32_t entity_index = 0;
while(entity_index < registry.entities_capacity)
{
if(registry.entities[entity_index] == NULL)
{
2023-10-14 14:38:38 +00:00
registry.entities[entity_index] = calloc(sizeof(tc_entity_s), 1);
2023-10-14 13:04:52 +00:00
++registry.num_entities;
2023-10-14 19:17:30 +00:00
registry.entities[entity_index]->attributes_capacity = 8;
registry.entities[entity_index]->attributes =
calloc(sizeof(tc_entity_attribute_s), registry.entities[entity_index]->attributes_capacity);
tc_reset_entity(registry.entities[entity_index]);
2023-10-14 13:04:52 +00:00
return registry.entities[entity_index];
}
++entity_index;
}
registry.entities =
2023-10-14 19:17:30 +00:00
realloc(registry.entities, sizeof(tc_entity_s *) * registry.entities_capacity * 2);
memset(&registry.entities[registry.entities_capacity], 0x00, sizeof(tc_entity_s *) * registry.entities_capacity);
registry.entities_capacity *= 2;
2023-10-14 13:04:52 +00:00
registry.entities[registry.num_entities] = malloc(sizeof(tc_entity_s));
2023-10-14 19:17:30 +00:00
tc_reset_entity(registry.entities[registry.num_entities]);
2023-10-14 13:04:52 +00:00
++registry.num_entities;
return registry.entities[registry.num_entities-1];
}
void tc_deallocate_entity(tc_entity_s *entity)
{
if(entity->specific != NULL) free(entity->specific);
if(entity->attributes != NULL) free(entity->attributes);
tc_entity_registry_s registry = tc_game_state_g.entity_registry;
uint32_t entity_index = 0;
while(entity_index < registry.entities_capacity)
{
if(registry.entities[entity_index] == entity)
{
registry.entities[entity_index] = NULL;
break;
}
++entity_index;
}
free(entity);
}