Okay so I created some (working) code last night.
For the sake of simplicity, I dropped the "multiple entities in a single location" requirement. We will just store a pointer to the entity and can implement multiple entities in the same position later on using a simple linked list.
My code right now looks a bit like this:
#define COMPASS_NW 1
#define COMPASS_NE 2
#define COMPASS_SE 3
#define COMPASS_SW 4
struct map {
struct grid_node * root;
}
struct grid_node {
void * entity;
int posy;
int posx;
struct grid_node * children[4];
};
So basically a pointed quad tree [1], I guess. But now there's no way to guarantee that the tree will be balanced. The degenerate case looks quite bad. So I started looking for a different scheme and came up with the following:
struct map {
struct grid_node * root;
}
struct grid_node {
void * children[4];
}
Then, we'd create a tree in which every entity is stored at the same depth (log(size of map), or the number of bits in a coordinate). To find the grid_node where we need to store the pointer, we keep popping up bits of posy and posx and use those bits to determine which of the children we need to follow (= a few shift and ANDs). The only drawback I can spot is that we'll need to dereference at least 8 pointers to get to the entities, but if we can make that fast I think it should be OK.
So, /prog/, what you think? I go with pointed quad trees or the other structure I just described?
[1]
http://en.wikipedia.org/wiki/Quad_tree#Point_quadtree