munificent/game-programming-patterns

Data Locality: Double Linked Entities

Opened this issue · 0 comments

At the section about entity components and memory handling there's basically two options proposed for accessing neighboring components.

1: full entities wherever you need them with pointers to each component. Problem: accessing an entity when you only have a component.
2. Each component has an entity id. Easy to get to the entity but expensive to access the individual components.

What's the key catch with having double linked entities? Namely each component having a pointer to the entity and each entity having a pointer to each other component. Sure, it's two pointer indirections, but it still seems better than either of those listed above. Memory cost per component should be marginal, components can be freely relocated (move data, chase pointer to entity, update the pointer pointing back), entities can as well be relocated (just iterate and do the same thing for every component, more costly, sure, but better than manually looking them all up). Furthermore, the entity itself could act like a service locator and you could theoretically disable an entities' component by replacing the pointer to it with a null version of the same thing.