naev 0.12.6
quadtree.h
1/*
2 * This code was initially authored by the Stackoverflow user dragon-energy and
3 * posted under following page:
4 * https://stackoverflow.com/questions/41946007/efficient-and-well-explained-implementation-of-a-quadtree-for-2d-collision-det
5 *
6 * As for the license, the author has kindly noted:
7 *
8 * "Oh and feel free to use this code I post however you want, even for
9 * commercial projects. I would really love it if people let me know if they
10 * find it useful, but do as you wish."
11 *
12 * And generally all Stackoverflow-posted code is by default licensed with CC
13 * BY-SA 4.0: https://creativecommons.org/licenses/by-sa/4.0/
14 */
15#pragma once
16
17#include "intlist.h"
18
19typedef struct Quadtree Quadtree;
20
21struct Quadtree {
22 // Stores all the nodes in the quadtree. The first node in this
23 // sequence is always the root.
24 IntList nodes;
25
26 // Stores all the elements in the quadtree.
27 IntList elts;
28
29 // Stores all the element nodes in the quadtree.
30 IntList enodes;
31
32 // Stores the quadtree extents.
33 int root_mx, root_my, root_sx, root_sy;
34
35 // Maximum allowed elements in a leaf before the leaf is subdivided/split
36 // unless the leaf is at the maximum allowed tree depth.
37 int max_elements;
38
39 // Stores the maximum depth allowed for the quadtree.
40 int max_depth;
41
42 // Temporary buffer used for queries.
43
44 char *temp;
45
46 // Stores the size of the temporary buffer.
47 int temp_size;
48};
49
50// Function signature used for traversing a tree node.
51typedef void QtNodeFunc( Quadtree *qt, void *user_data, int node, int depth,
52 int mx, int my, int sx, int sy );
53
54// Creates a quadtree with the requested extents, maximum elements per leaf, and
55// maximum tree depth.
56void qt_create( Quadtree *qt, int x1, int y1, int x2, int y2, int max_elements,
57 int max_depth );
58
59// Destroys the quadtree.
60void qt_destroy( Quadtree *qt );
61
62// Clears the quadtree making it empty.
63void qt_clear( Quadtree *qt );
64
65// Inserts a new element to the tree.
66// Returns an index to the new element.
67int qt_insert( Quadtree *qt, int id, int x1, int y1, int x2, int y2 );
68
69// Removes the specified element from the tree.
70void qt_remove( Quadtree *qt, int element );
71
72// Cleans up the tree, removing empty leaves.
73void qt_cleanup( Quadtree *qt );
74
75// Outputs a list of elements found in the specified rectangle.
76void qt_query( Quadtree *qt, IntList *out, int x1, int y1, int x2, int y2 );
77
78// Traverses all the nodes in the tree, calling 'branch' for branch nodes and
79// 'leaf' for leaf nodes.
80void qt_traverse( Quadtree *qt, void *user_data, QtNodeFunc *branch,
81 QtNodeFunc *leaf );