First time posting here but I've been reading the site for a few years now. I'm trying to implement a simple generic type Octree in C# (using some XNA includes). I've thoroughly researched and I understand the concept, I just can't seem to make it work. Searching around yields some implementations in other languages, but they all seem custom tailored to a specific application; and I haven't really been able to make much sense out of those.
Below is my Octree class so far, the Vector3, BoundingBox, and ContainmentType are from XNA. I feed in max and min points, and a list of points that are within the boundaries. However none of the points actually get added to the tree. Any help would be much appreciated!
public class Octree<T> : ISerializable
{
Vector3 max;
Vector3 min;
OctreeNode head;
public Octree(Vector3 min, Vector3 max, List<Vector3> values)
{
this.max = max;
this.min = min;
head = new OctreeNode( min, max, values);
}
public Octree() { }
public Octree(SerializationInfo info, StreamingContext context)
{
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
}
internal class OctreeNode
{
Vector3 max;
Vector3 min;
Vector3 center;
public Vector3 position;
public T data;
public BoundingBox nodeBox;
public List<OctreeNode> subNodes;
public OctreeNode( Vector3 min, Vector3 max,List<Vector3> coords)
{
nodeBox = new BoundingBox(min, max);
subNodes = new List<OctreeNode>();
this.min = min;
this.max = max;
center = (min + ((max - min) / 2));
nodeBox = new BoundingBox(min, max);
if (coords.Count == 0)
{ return; }
subNodes.Add(new OctreeNode(center, max));
subNodes.Add(new OctreeNode(new Vector3(min.X, center.Y, center.Z), new Vector3(center.X, max.Y, min.Z)));
subNodes.Add(new OctreeNode(new Vector3(min.X, center.Y, max.Z), new Vector3(center.X, max.Y, center.Z)));
subNodes.Add(new OctreeNode(new Vector3(center.X, center.Y, max.Z), new Vector3(max.X, max.Y, center.Z)));
subNodes.Add(new OctreeNode(new Vector3(center.X, min.Y, center.Z), new Vector3(max.X, center.Y, min.Z)));
subNodes.Add(new OctreeNode(new Vector3(min.X, min.Y, center.Z), new Vector3(center.X, center.Y, min.Z)));
subNodes.Add(new OctreeNode(new Vector3(min.X, min.Y, max.Z), center));
subNodes.Add(new OctreeNode(new Vector3(center.X,min.Y,max.Z), new Vector3(max.X,center.Y,center.Z)));
List<List<Vector3>> octants = new List<List<Vector3>>();
for (int i = 0; i < 8; i++)
{
octants.Add(new List<Vector3>());
}
foreach (Vector3 v in coords)
{
int i = 0;
foreach(OctreeNode n in subNodes)
{
ContainmentType t = n.nodeBox.Contains(v);
if (t.Equals(ContainmentType.Contains))
{
octants[i].Add(v);
}
i++;
}
}
for (int i=0;i<subNodes.Count;i++)
{
if (octants[i].Count > 0)
{
Vector3 v = octants[i][0];
octants[i].Remove(v);
subNodes[i] = new OctreeNode(subNodes[i].min, subNodes[i].max, octants[i]);
}
}
}
public OctreeNode(Vector3 min, Vector3 max)
{
nodeBox = new BoundingBox(min, max);
}
}
}