I have a 2D map which wraps at the edges. So if you move off the right edge you will reappear at the left side of the map. Likewise with the three other edges.
This is inheritable a problem for the KDTree which I use to find elements in range of points. Normally you would check whether the hyper sphere collides with the hyper plane to see if you should continue searching the other side of the tree, but this check does not work with wrapping edges.
Is there any way to modify the KD Tree to work with donut 2D spaces?
Jitamaro suggested but didn't explain a method based on a "2x size" quadtree. It's a reasonable suggestion, except the quadtree uses four times as many nodes rather than two, as I'll explain below before tentatively suggesting an alternative method.
Suppose each (x,y) coordinate has
-.5 < x <= .5
and-.5 < y <= .5
and wheneverj, k
are integers, point (x+j,y+k) is identical with point (x,y). Let quadtree T cover points with coordinates in the range-1 < x,y <= 1
. Each time you add an item at (x,y) to T, where-.5 < x,y <= .5
, letx' = {x-1
ifx>0
elsex+1}
, andy' = {y-1
ify>0
elsey+1}
. Also add the item at (x,y'), (x',y'), and (x',y). [When you delete points later, again calculate (x', y') et al and delete them too.] It's easy to see that nearest-point lookups will work properly, so long as any lookup coordinate outside interval(-.5,.5]
is adjusted properly.If the four-fold number of nodes is a deal-breaker, note that if coordinates as described above are used in subtrees above say level
k=3
, and relative coordinates are stored below levelk
, it should be possible to maintain single copies of subtrees below levelk
. That is, each subtree at levelk
would have four parents. (I haven't thought about this enough to know if this totally works; will edit answer if I find it doesn't.)