/// <summary> /// Merge all children into this node - the opposite of Split. /// Note: We only have to check one level down since a merge will never happen if the children already have children, /// since THAT won't happen unless there are already too many objects to merge. /// </summary> void Merge() { // Note: We know children != null or we wouldn't be merging for (int i = 0; i < 8; i++) { PointOctreeNode <T> curChild = children[i]; int numObjects = curChild.objects.Count; for (int j = numObjects - 1; j >= 0; j--) { OctreeObject curObj = curChild.objects[j]; objects.Add(curObj); } } // Remove the child nodes (and the objects in them - they've been added elsewhere now) children = null; }
// #### PRIVATE METHODS #### /// <summary> /// Grow the octree to fit in all objects. /// </summary> /// <param name="direction">Direction to grow.</param> void Grow(Vector3 direction) { int xDirection = direction.x >= 0 ? 1 : -1; int yDirection = direction.y >= 0 ? 1 : -1; int zDirection = direction.z >= 0 ? 1 : -1; PointOctreeNode <T> oldRoot = rootNode; float half = rootNode.SideLength / 2; float newLength = rootNode.SideLength * 2; Vector3 newCenter = rootNode.Center + new Vector3(xDirection * half, yDirection * half, zDirection * half); // Create a new, bigger octree root node rootNode = new PointOctreeNode <T>(newLength, minSize, newCenter); if (oldRoot.HasAnyObjects()) { // Create 7 new octree children to go with the old root as children of the new root int rootPos = rootNode.BestFitChild(oldRoot.Center); PointOctreeNode <T>[] children = new PointOctreeNode <T> [8]; for (int i = 0; i < 8; i++) { if (i == rootPos) { children[i] = oldRoot; } else { xDirection = i % 2 == 0 ? -1 : 1; yDirection = i > 3 ? -1 : 1; zDirection = (i < 2 || (i > 3 && i < 6)) ? -1 : 1; children[i] = new PointOctreeNode <T>(oldRoot.SideLength, minSize, newCenter + new Vector3(xDirection * half, yDirection * half, zDirection * half)); } } // Attach the new children to the new root node rootNode.SetChildren(children); } }
/// <summary> /// Shrink the octree if possible, else leave it the same. /// </summary> void Shrink() { rootNode = rootNode.ShrinkIfPossible(initialSize); }