Phil CK

Entity Identifier

Last updated on

ECS is all the rage atm, but its not that new. One of my hobby engines defined entities as uint32_t with the first byte reserved, and the rest defining the instance.

I used the first byte to define if the uint32_t in question was a reference or not. This allowed me to know if the entity was ‘owned’ somewhere else, however you could sneak any type information in here.

/* entity.c */
#include <stdint.h>
#include <stdio.h>


uint32_t
create(const uint32_t type, const uint32_t instance) {
  return (type << 24) | instance;
}


uint32_t
type(const uint32_t entity) {
  return entity >> 24;
}


uint32_t
instance(const uint32_t entity) {
  return entity & 0xFFFFFF;
}

uint32_t instance_counter = 0;

int
main() {

  instance_counter++;

  uint32_t entity = create(1, instance_counter);
  uint32_t entity_ref = create(0, instance_counter);

  printf("Entity %d, Entity Ref %d\n", instance(entity), instance(entity_ref));

  return 0;
}

Outputs …

Entity 1, Entity Ref 1

Compile and run with GCC

gcc entity.c && ./a.out

or Clang

clang entity.c && ./a.out