12 static void _trap(int line)
15 printf("Trapped from line %d, use debugger to get backtrace\n",
22 #define trap() _trap(__LINE__)
24 static int quadtree_compare_coord(const struct vector *a,
25 const struct vector *b)
41 static int quadtree_compare(const struct quadtree *a, const struct quadtree *b)
43 return quadtree_compare_coord(&a->pos, &b->pos);
46 static void validate_subtree(const struct quadtree *node)
53 printf("Attempted to validate a null pointer\n");
58 for (i = 0; i < 4; i++) {
62 if (node->child[i]->parent != node) {
63 printf("%s:%d Fatal! Tree inconsistency detected at "
64 "child %d %p in node %p, incorrent parent %p\n",
65 __func__, __LINE__, i, node->child[i], node,
66 node->child[i]->parent);
72 if (node->child[i] == node->parent) {
73 printf("%s:%d Fatal! Tree loop detected "
74 "at child %d in node %p\n",
75 __func__, __LINE__, i, node);
81 dir = quadtree_compare(node, node->child[i]);
84 printf("%s:%d Fatal! Spatial inconsistency detected "
85 "at child %d in node %p\n"
86 "parent: (%f %f), child (%f %f), "
88 __func__, __LINE__, i, node,
89 node->pos.x, node->pos.y,
90 node->child[i]->pos.x, node->child[i]->pos.y,
96 children += node->child[i]->children + 1;
98 validate_subtree(node->child[i]);
101 if (node->depth < 0) {
102 printf("%s:%d Tree statistics inconsistency detected! "
103 "Negative depth: %ld\n",
104 __func__, __LINE__, node->depth);
107 if (node->children != children) {
108 printf("%s:%d Tree statistics inconsistency detected! "
109 "child count mismatch. Expected %ld, got %ld\n",
110 __func__, __LINE__, children, node->children);
115 for (i = 0; i < 4 && node->children; i++) {
119 if (node->depth == node->child[i]->depth + 1)
122 if (node->child[i]->depth > node->depth) {
123 printf("%s:%d Tree statistics inconsistency detected! "
124 "child depth mismatch %ld > %ld\n",
125 __func__, __LINE__, node->child[i]->depth,
131 printf("%s:%d Tree statistics inconsistency detected! "
132 "child depth mismatch.",
139 static void validate_tree(const struct quadtree *node)
147 return validate_subtree(node);
149 for (i = 0; i < 4; i++)
150 if (node->parent->child[i] == node)
154 printf("%s:%d Tree inconsistency detected! "
155 "Wrong parent %p for node %p\n",
156 __func__, __LINE__, node->parent, node);
161 validate_tree(node->parent);
164 void _quadtree_validate_tree(const struct quadtree *node)
169 static struct quadtree *_quadtree_add(struct quadtree *parent,
170 struct quadtree *new)
174 ret = quadtree_compare(parent, new);
176 if (ret < 0 || ret >= 4) {
177 printf("Invalid comparison result of %d\n", ret);
181 if (parent->child[ret])
182 return _quadtree_add(parent->child[ret], new);
184 parent->child[ret] = new;
185 new->parent = parent;
186 for (i = 0; i < 4; i++)
192 static void _recalculate_node_area_stats(struct quadtree *node)
194 /* The space covered by the parent node's corner
195 * points needs be as wide as its widest child node's
198 #define CHILD_CORNER_SAFE(node, ch_idx, cor_idx, axis) \
199 ((node)->child[ch_idx] ? \
200 (node)->child[ch_idx]->corner[cor_idx].axis : \
203 node->corner[0].x = MIN(CHILD_CORNER_SAFE(node, 0, 0, x),
204 CHILD_CORNER_SAFE(node, 2, 0, x));
205 node->corner[0].y = MIN(CHILD_CORNER_SAFE(node, 0, 0, y),
206 CHILD_CORNER_SAFE(node, 1, 0, y));
207 node->corner[1].x = MAX(CHILD_CORNER_SAFE(node, 1, 1, x),
208 CHILD_CORNER_SAFE(node, 3, 1, x));
209 node->corner[1].y = MAX(CHILD_CORNER_SAFE(node, 2, 1, y),
210 CHILD_CORNER_SAFE(node, 3, 1, y));
211 #undef CHILD_CORNER_SAFE
214 static void recalculate_parent_area_stats(struct quadtree *node)
217 _recalculate_node_area_stats(node);
224 * Recursively walk through the tree and propagate changes made to the
225 * given node up until the highest parent.
227 static void quadtree_recalculate_parent_stats(struct quadtree *node,
228 struct quadtree_ops *ops)
236 for (i = 0; i < 4; i++) {
240 node->depth = MAX(node->depth,
241 node->child[i]->depth + 1);
242 node->children += node->child[i]->children + 1;
245 _recalculate_node_area_stats(node);
247 if (ops->recalculate_stats)
248 ops->recalculate_stats(node);
255 * quadtree_add - add a node to a quadtree
256 * @parent: parent node
257 * @new: the new node to be added
259 * Add a node to a quadtree. The tree is kept in order, the new node
260 * is placed in the end of appropriate branch.
262 * The case of nodes sharing identical coordinates is not taken into
266 struct quadtree *quadtree_add(struct quadtree *parent, struct quadtree *new,
267 struct quadtree_ops *ops)
272 validate_tree(parent);
274 _quadtree_add(parent, new);
277 printf("adding node %p to parent %p\n", new, parent);
281 quadtree_recalculate_parent_stats(new, ops);
288 static int is_within(struct vector *pos, struct vector *corner)
290 if ((pos->x >= corner[1].x) && (pos->x <= corner[0].x) &&
291 (pos->y >= corner[1].y) && (pos->y <= corner[0].y))
296 static int rectangle_and_circle_overlap(struct vector *corner,
297 struct vector *pos, double radius)
299 int vertically_overlapping = 0, horizontally_overlapping = 0;
301 if ((pos->x < corner[1].x && pos->x + radius > corner[0].x) ||
302 (pos->x > corner[0].x && pos->x - radius < corner[1].x))
303 horizontally_overlapping = 1;
305 if ((pos->y < corner[1].y && pos->y + radius > corner[0].y) ||
306 (pos->y > corner[0].y && pos->y - radius < corner[1].y))
307 vertically_overlapping = 1;
309 return horizontally_overlapping && vertically_overlapping;
312 static int quadrants_to_search(struct quadtree *node, struct vector *pos,
320 if (node->child[0] &&
321 rectangle_and_circle_overlap(node->child[0]->corner, pos, dist))
322 direction |= QUADTREE_UPLEFT;
324 if (node->child[1] &&
325 rectangle_and_circle_overlap(node->child[1]->corner, pos, dist))
326 direction |= QUADTREE_UPRIGHT;
328 if (node->child[2] &&
329 rectangle_and_circle_overlap(node->child[2]->corner, pos, dist))
330 direction |= QUADTREE_DOWNLEFT;
332 if (node->child[3] &&
333 rectangle_and_circle_overlap(node->child[3]->corner, pos, dist))
334 direction |= QUADTREE_DOWNRIGHT;
339 static struct quadtree *quadtree_find_nearest(struct quadtree *tree,
341 struct vector *corner,
342 struct quadtree *nearest,
346 struct quadtree *node;
347 double distance = 0, dist;
353 vector_sub(&nearest->pos, pos, &tmp);
354 distance = vector_abs(&tmp);
356 if (!is_within(&nearest->pos, corner)) {
358 printf("Discarding nearest %p "
359 "as outside of search window\n", nearest);
364 directions = quadrants_to_search(tree, pos, distance);
366 printf("%d: Directions: %x\n", depth, directions);
367 for (i = 0; i < 4; i++) {
371 if (!(directions & (1 << i)))
375 node = quadtree_find_nearest(tree->child[i], pos, corner,
381 if (node != nearest) {
382 vector_sub(&node->pos, pos, &tmp);
383 dist = vector_abs(&tmp);
384 if (dist < distance || !nearest) {
389 * Update the directions where to search for
390 * since those may not be valid any more
392 directions = quadrants_to_search(tree, pos, distance);
397 if (nearest && !is_within(&nearest->pos, corner)) {
399 printf("%d: Node %p (%f %f) is not within "
400 "search window (%f %f) (%f %f)\n", depth,
401 nearest, nearest->pos.x, nearest->pos.y,
402 corner[0].x, corner[0].y,
403 corner[1].x, corner[1].y);
407 printf("%d: Node %p (%f %f) is nearest node, dist %f\n",
409 nearest ? nearest->pos.x : -1,
410 nearest ? nearest->pos.y : -1,
411 nearest ? distance : -1);
415 static struct quadtree *quadtree_find_nearest_noparent(struct quadtree *tree,
417 struct vector *corner)
419 struct quadtree *nearest = NULL;
421 struct quadtree *node;
422 double dist = 0, dist2;
425 nearest = quadtree_find_nearest(tree, pos, corner, nearest, 0);
431 printf("Avoiding parent or NULL node %p\n", nearest);
434 * oops, we don't want to pick the parent node, let's choose
438 for (i = 0; i < 4; i++) {
443 nearest = quadtree_find_nearest(tree->child[i], pos,
449 vector_sub(pos, &nearest->pos, &sub);
450 dist = vector_abs(&sub);
453 node = quadtree_find_nearest(tree->child[i], pos, corner,
459 vector_sub(pos, &node->pos, &sub);
460 dist2 = vector_abs(&sub);
472 static void get_middle_point(struct vector *corner, struct vector *middle)
474 middle->x = (corner[0].x + corner[1].x) / (double)2;
475 middle->y = (corner[0].y + corner[1].y) / (double)2;
478 static int quadtree_split_by_node(struct quadtree *node,
479 struct vector *corner, int dir)
481 if (!is_within(&node->pos, corner)) {
483 printf("Not within search rectangle\n");
488 printf("Search rectangle was before (%f %f) (%f %f), (%f %f)\n",
489 corner[0].x, corner[0].y,
490 corner[1].x, corner[1].y,
491 node->pos.x, node->pos.y);
494 case QUADTREE_UPLEFT:
495 corner[0] = node->pos;
497 case QUADTREE_UPRIGHT:
498 corner[0].y = node->pos.y;
499 corner[1].x = node->pos.x;
501 case QUADTREE_DOWNRIGHT:
502 corner[1] = node->pos;
504 case QUADTREE_DOWNLEFT:
505 corner[0].x = node->pos.x;
506 corner[1].y = node->pos.y;
513 printf("Search rectangle is now (%f %f) (%f %f), (%f %f)\n",
514 corner[0].x, corner[0].y,
515 corner[1].x, corner[1].y,
516 node->pos.x, node->pos.y);
518 if ((corner[0].x < corner[1].x) ||
519 (corner[0].y < corner[1].y))
526 * Quickly detach a node from a tree. Move all child nodes under
529 static int _quadtree_del(struct quadtree *node, struct quadtree *parent)
534 /* Detach from the tree */
536 for (i = 0; i < 4; i++) {
537 if (node->parent->child[i] == node) {
538 node->parent->child[i] = 0;
547 for (i = 0; i < 4; i++) {
552 _quadtree_del(n, parent);
553 _quadtree_add(parent, n);
554 recalculate_parent_area_stats(n);
561 * Move everything under @tree node to @parent node, everything
562 * else except the @tree node itself
564 static int optimally_move_tree(struct quadtree *tree, struct quadtree *parent,
565 struct vector *corner_orig,
566 struct quadtree_ops *ops)
568 struct vector corner[2], mid;
569 struct quadtree *t, *tmp;
572 get_middle_point(corner_orig, &mid);
573 t = quadtree_find_nearest_noparent(tree, &mid, corner_orig);
577 printf("Cannot find nearest node\n");
583 * Now we have the t node which contains the object of the
584 * spatial middle coordinates of the tree.
588 printf("Relocating node %p (%f %f) under parent %p\n", t,
589 t->pos.x, t->pos.y, parent);
590 printf("There are %ld child nodes left\n", tree->children);
593 _quadtree_del(t, tree);
594 quadtree_add(parent, t, ops);
602 * Now split the search rectangle in quadtres and do the same
603 * with all of the quarters.
606 corner[0] = corner_orig[0];
607 corner[1] = corner_orig[1];
608 if (quadtree_split_by_node(t, corner, QUADTREE_UPLEFT))
609 moved += optimally_move_tree(tree, parent, corner, ops);
611 corner[0] = corner_orig[0];
612 corner[1] = corner_orig[1];
613 if (quadtree_split_by_node(t, corner, QUADTREE_UPRIGHT))
614 moved += optimally_move_tree(tree, parent, corner, ops);
616 corner[0] = corner_orig[0];
617 corner[1] = corner_orig[1];
618 if (quadtree_split_by_node(t, corner, QUADTREE_DOWNLEFT))
619 moved += optimally_move_tree(tree, parent, corner, ops);
621 corner[0] = corner_orig[0];
622 corner[1] = corner_orig[1];
623 if (quadtree_split_by_node(t, corner, QUADTREE_DOWNRIGHT))
624 moved += optimally_move_tree(tree, parent, corner, ops);
626 get_middle_point(corner_orig, &mid);
627 tmp = quadtree_find_nearest(tree, &mid, corner_orig, NULL, 0);
628 if (tmp && tmp != tree)
633 printf("Now moved %d nodes, %ld left\n", moved, tree->children);
639 * quadtree_del - Detach a node from the tree
641 * Return value: The new root node of the tree. If we are detaching
642 * anything but the root node of the entire tree, the returned root
643 * value will be the original root of the tree.
645 struct quadtree *quadtree_del(struct quadtree *node,
646 struct quadtree_ops *ops)
648 struct quadtree *parent = NULL;
649 struct vector corner[2];
650 int i, children = node->children, moved;
655 printf("Deleting node %p under parent %p\n",
657 printf("Relocating %ld children\n", node->children);
663 * We are deleting the root node. This means we have
664 * to select a new root node and reconstruct the
665 * entire tree under it again.
668 printf("Deleting root node\n");
671 for (i = 0; i < 4; i++) {
675 parent = node->child[i];
676 _quadtree_del(parent, node);
678 quadtree_recalculate_parent_stats(parent, ops);
683 * The node has a parent. Detach the node from it and
684 * relocate the children.
687 for (i = 0; i < 4; i++) {
688 if (node->parent->child[i] == node) {
689 node->parent->child[i] = 0;
696 parent = node->parent;
699 * The sub branch is now detached from the main
700 * tree. Fix the stats.
702 quadtree_recalculate_parent_stats(parent, ops);
705 validate_tree(parent);
710 * Now we are ready to prepare for relocating the nodes under
714 corner[0] = node->corner[1];
715 corner[1] = node->corner[0];
717 printf("\nInitial Search rectangle (%f %f) (%f %f), (%f %f)\n",
718 corner[0].x, corner[0].y,
719 corner[1].x, corner[1].y,
720 node->pos.x, node->pos.y);
723 moved = optimally_move_tree(node, parent, corner, ops);
726 if (moved != children) {
727 printf("Got %d children but %d were moved\n",
729 printf("nearest children left:\n");
730 for (i = 0 ; i < 4; i++)
732 printf(" node %d %p, (%f %f)\n",
734 node->child[i]->pos.x,
735 node->child[i]->pos.y);
739 printf("Delete done, returning parent %p\n", parent);
744 validate_tree(parent);
745 return quadtree_find_parent(parent);
748 static void check_for_crossed_subnodes(struct quadtree *node,
749 struct vector *limit, struct quadtree_ops *ops)
751 int direction = 0, i;
752 int up = 0, left = 0, right = 0, down = 0;
754 for (i = 0; i < 2; i++) {
755 if (limit[i].x < node->pos.x)
759 if (limit[i].y < node->pos.y)
766 direction |= QUADTREE_UPLEFT;
768 direction |= QUADTREE_UPRIGHT;
770 direction |= QUADTREE_DOWNLEFT;
772 direction |= QUADTREE_DOWNRIGHT;
773 if ((left && right) || (up && down))
774 direction |= QUADTREE_SELF;
776 if ((direction & QUADTREE_UPLEFT) && node->child[0])
777 check_for_crossed_subnodes(node->child[0], limit, ops);
779 if ((direction & QUADTREE_UPRIGHT) && node->child[1])
780 check_for_crossed_subnodes(node->child[0], limit, ops);
782 if ((direction & QUADTREE_DOWNLEFT) && node->child[2])
783 check_for_crossed_subnodes(node->child[0], limit, ops);
785 if ((direction & QUADTREE_DOWNRIGHT) && node->child[3])
786 check_for_crossed_subnodes(node->child[0], limit, ops);
788 if (direction & QUADTREE_SELF) {
789 struct quadtree *parent;
791 parent = quadtree_del(node, ops);
792 quadtree_add(parent, node, ops);
796 struct quadtree *quadtree_move(struct quadtree *node, struct vector new_pos,
797 struct quadtree_ops *ops)
799 struct quadtree *parent, *tree_parent;
802 /* Check if we have crossed any of the parents */
803 parent = node->parent;
805 if (node->pos.x < parent->pos.x && new_pos.x > parent->pos.x)
807 if (node->pos.x > parent->pos.x && new_pos.x < parent->pos.x)
809 if (node->pos.y < parent->pos.y && new_pos.y > parent->pos.y)
811 if (node->pos.y > parent->pos.y && new_pos.y < parent->pos.y)
815 parent = parent->parent;
820 * If the node has crossed the boundaries, remove it
821 * from the tree and add it again to it. It is then
822 * guaranteed to be in the correct position of the
825 tree_parent = quadtree_del(node, ops);
827 quadtree_add(tree_parent, node, ops);
828 quadtree_recalculate_parent_stats(node, ops);
832 /* Move the node into its new location */
837 * Now, search the subtree for any children that are
838 * located in wrong place and move them into correct
839 * place within the tree.
841 struct vector limit[2];
843 limit[0] = node->pos;
845 check_for_crossed_subnodes(node, limit, ops);
848 quadtree_recalculate_parent_stats(node, ops);
849 return quadtree_find_parent(node);
853 static int _walk_tree(struct quadtree *head, const struct quadtree_iterator *it)
855 int direction, count = 0;
857 direction = it->direction(head, (struct quadtree_iterator *)it);
859 if ((direction & QUADTREE_UPLEFT) && head->child[0])
860 count += _walk_tree(head->child[0], it);
862 if ((direction & QUADTREE_UPRIGHT) && head->child[1])
863 count += _walk_tree(head->child[1], it);
865 if ((direction & QUADTREE_DOWNLEFT) && head->child[2])
866 count += _walk_tree(head->child[2], it);
868 if ((direction & QUADTREE_DOWNRIGHT) && head->child[3])
869 count += _walk_tree(head->child[3], it);
871 if ((direction & QUADTREE_SELF) && it->callback) {
872 it->callback(head, (struct quadtree_iterator *)it);
879 int walk_quadtree(const struct quadtree_iterator *it)
881 return _walk_tree(it->head, it);