//----------------------------------------------------------------------------------------------------------- #region Private Functions /// <summary> /// Recursively Insert the new Node until we hit a leaf node. Then branch and insert both nodes. /// </summary> /// <param name="currentNode"></param> /// <param name="newNode"></param> private void RecursiveInsert(AABBNode currentNode, AABBNode newNode) { AABBNode branch = currentNode; if (currentNode.IsLeaf) { branch = AABBNode.CreateNode(currentNode.Bounds, newNode.Bounds); branch.Parent = currentNode.Parent; if (currentNode == m_RootNode) { m_RootNode = branch; } else { branch.Parent.Children[branch.Parent.Children[0] == currentNode ? 0 : 1] = branch; } branch.SetChildren(currentNode, newNode); } else { Bounds withChild1 = branch.Children[0].Bounds.ExpandToContian(newNode.Bounds); Bounds withChild2 = branch.Children[1].Bounds.ExpandToContian(newNode.Bounds); float volume1 = withChild1.Volume(); float volume2 = withChild2.Volume(); RecursiveInsert((volume1 <= volume2) ? branch.Children[0] : branch.Children[1], newNode); } branch.RebuildBounds(); }
//----------------------------------------------------------------------------------------------------------- #region Public Functions /// <summary> /// Creates a new node with the provided bounds. /// </summary> /// <param name="bounds"></param> /// <param name="data"></param> public void Insert(Bounds bounds, T data) { AABBNode newNode = AABBNode.CreateNode(bounds, data); if (m_RootNode == null) { m_RootNode = newNode; } else { RecursiveInsert(m_RootNode, newNode); } }