]> git.itanic.dy.fi Git - sdl-planets/blob - quadtree.h
quadtree: Collect tree statistics
[sdl-planets] / quadtree.h
1 #ifndef _QUADTREE_H_
2 #define _QUADTREE_H_
3
4 #include <string.h>
5
6 #include "utils.h"
7
8 struct quadtree {
9         struct quadtree *child[4];
10         struct quadtree *parent;
11
12         /* statistics */
13         long int children;      /* The total number of children */
14         long int depth;         /* The deepest subtree branch */
15 };
16
17 static inline void init_quadtree(struct quadtree *t)
18 {
19         memset(t, 0, sizeof(*t));
20 }
21
22 #define QUADTREE_UPLEFT         0x1
23 #define QUADTREE_UPRIGHT        0x2
24 #define QUADTREE_DOWNLEFT       0x4
25 #define QUADTREE_DOWNRIGHT      0x8
26 #define QUADTREE_SELF           0x10
27
28 struct quadtree_iterator {
29         struct quadtree *head;
30         void *ptr;
31
32         int (*direction)(struct quadtree *head, struct quadtree_iterator *it);
33         void (*callback)(struct quadtree *head, struct quadtree_iterator *it);
34 };
35
36 struct quadtree *quadtree_add(struct quadtree *parent,
37                               struct quadtree *new,
38                               int (*compare)(struct quadtree *a,
39                                              struct quadtree *b));
40
41 struct quadtree *quadtree_del(struct quadtree *node,
42                               int (*compare)(struct quadtree *a,
43                                              struct quadtree *b));
44
45 int walk_quadtree(const struct quadtree_iterator *iterator);
46
47
48 /* quadtree_find_parent - return the highest parent of the node */
49 static inline struct quadtree *quadtree_find_parent(const struct quadtree *node)
50 {
51         struct quadtree *t = (struct quadtree *)node;
52         while (t->parent)
53                 t = t->parent;
54
55         return t;
56 }
57
58 /*
59  * Recursively walk through the tree and propagate changes made to the
60  * given node up until the highest parent.
61  */
62 static inline void quadtree_recalculate_parent_stats(struct quadtree *node)
63 {
64         int i;
65
66         while (node) {
67                 node->depth = 0;
68                 node->children = 0;
69
70                 for (i = 0; i < 4; i++) {
71                         if (!node->child[i])
72                                 continue;
73
74                         node->depth = MAX(node->depth,
75                                           node->child[i]->depth + 1);
76                         node->children += node->child[i]->children + 1;
77                 }
78
79                 node = node->parent;
80         }
81 }
82
83 #endif