#include "world.h" #include #include World* world_create(void) { World* w = (World*)calloc(1, sizeof(World)); w->next_entity = 1; return w; } void world_destroy(World* world) { if (!world) return; for (uint32_t i = 0; i < world->entity_count; i++) { Entity e = world->entities[i]; for (uint32_t c = 0; c < world->component_count; c++) { if (world->components[c][e] && world->component_tables[c].destroy) { world->component_tables[c].destroy(world->components[c][e]); } free(world->components[c][e]); } } free(world); } Entity world_create_entity(World* world) { if (world->entity_count >= MAX_ENTITIES) return 0; Entity e = world->next_entity++; world->entities[world->entity_count++] = e; world->entity_masks[e] = 0; return e; } void world_destroy_entity(World* world, Entity entity) { for (uint32_t c = 0; c < world->component_count; c++) { if (world->components[c][entity] && world->component_tables[c].destroy) { world->component_tables[c].destroy(world->components[c][entity]); } free(world->components[c][entity]); world->components[c][entity] = NULL; } world->entity_masks[entity] = 0; for (uint32_t i = 0; i < world->entity_count; i++) { if (world->entities[i] == entity) { world->entities[i] = world->entities[--world->entity_count]; break; } } } int world_entity_alive(World* world, Entity entity) { for (uint32_t i = 0; i < world->entity_count; i++) { if (world->entities[i] == entity) return 1; } return 0; } ComponentType world_register_component(World* world, uint32_t size, ComponentVTable vtable) { ComponentType type = world->component_count++; world->component_sizes[type] = size; world->component_tables[type] = vtable; return type; } void* world_add_component(World* world, Entity entity, ComponentType type) { if (world->components[type][entity]) return world->components[type][entity]; void* comp = calloc(1, world->component_sizes[type]); world->components[type][entity] = comp; world->entity_masks[entity] |= (1ULL << type); return comp; } void* world_get_component(World* world, Entity entity, ComponentType type) { return world->components[type][entity]; } void world_remove_component(World* world, Entity entity, ComponentType type) { if (world->components[type][entity]) { if (world->component_tables[type].destroy) { world->component_tables[type].destroy(world->components[type][entity]); } free(world->components[type][entity]); world->components[type][entity] = NULL; world->entity_masks[entity] &= ~(1ULL << type); } } int world_has_component(World* world, Entity entity, ComponentType type) { return (world->entity_masks[entity] & (1ULL << type)) != 0; } void world_each(World* world, uint64_t mask, SystemFunc func, void* data) { for (uint32_t i = 0; i < world->entity_count; i++) { Entity e = world->entities[i]; if ((world->entity_masks[e] & mask) == mask) { func(world, e, data); } } }