Spatial Partitioning Data Structures with examples and comparisons
Quadtree is a data structure to efficiently store data of points on a two-dimensional space(plane). It works like as a binary tree, but instead of two partitions (left, right), a quadtree organize the data with four partitions (top-left, top-right, bottom-left, bottom-right).
- Divide the plane into four boxes(partitions)
- Check if the point is inside the partition, then insert
- If a partition doesn't contain points, insert the point
- If a partition contains more points than the capacity, create four child partitions inside it
- Recurse all steps for each of the children, until the point is inserted
- Check if the point is inside the partition
- If all children doesn't contain the point, return the points in the actual partition
- Recurse all steps for each of the children, choosing the child checking if the point is in the left or right and top or bottom
Think there's n particles in a partition on the plane, how to check if each particle is colliding with each other?
- Iterate each point
- Check if it's colliding each other point by iteration.
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(particles[i].intersect(particles[j]))
// is colliding
}
}
This approach has O(n2) time complexity
- Add each point in a Quad Tree
- Iterate each point
- Search for possible collisions points in the Quad Tree
- Check if it's colling with the found points
Plus: Quad Trees organizes data by partitions, every partition could be processed separately by a thread, meaning that this method accepts multithreading
QuadTree tree = QuadTree();
for(int i = 0; i < N; i++) {
tree.insert(particles[i]);
}
for(int i = 0; i < N; i++) {
Particles[] found = tree.search(particles[i]);
for(Particle other : found) {
if(particles[i].intersect(other))
// is colliding
}
}
This approach has O(n log(n)) time complexity
For a small quantity of particles, the quadtree optimization don't worth the effort But when things scales, the quadtree optimization is 9-10x faster than the iteration method.