| | | 1 | | //======================================================================= |
| | | 2 | | // SwiftBVH.cs |
| | | 3 | | //======================================================================= |
| | | 4 | | // MIT License, Copyright (c) 2024–present David Oravsky (mrdav30) |
| | | 5 | | // See LICENSE file in the project root for full license information. |
| | | 6 | | //======================================================================= |
| | | 7 | | |
| | | 8 | | using SwiftCollections.Diagnostics; |
| | | 9 | | using SwiftCollections.Utility; |
| | | 10 | | using System; |
| | | 11 | | using System.Collections.Generic; |
| | | 12 | | using System.Runtime.CompilerServices; |
| | | 13 | | |
| | | 14 | | namespace SwiftCollections.Query; |
| | | 15 | | |
| | | 16 | | /// <summary> |
| | | 17 | | /// Represents a Bounding Volume Hierarchy (BVH) optimized for spatial queries. |
| | | 18 | | /// </summary> |
| | | 19 | | /// <remarks> |
| | | 20 | | /// <para> |
| | | 21 | | /// This class is not thread-safe. Concurrent access from multiple threads must be |
| | | 22 | | /// serialized externally (e.g., with a lock or by limiting access to a single thread). |
| | | 23 | | /// </para> |
| | | 24 | | /// </remarks> |
| | | 25 | | public class SwiftBVH<TKey, TVolume> |
| | | 26 | | where TKey : notnull |
| | | 27 | | where TVolume : struct, IBoundVolume<TVolume> |
| | | 28 | | { |
| | | 29 | | #region Static & Constants |
| | | 30 | | |
| | | 31 | | private const string _diagnosticSource = nameof(SwiftBVH<TKey, TVolume>); |
| | | 32 | | |
| | | 33 | | #endregion |
| | | 34 | | |
| | | 35 | | #region Fields |
| | | 36 | | |
| | | 37 | | private SwiftBVHNode<TKey, TVolume>[] _nodePool; |
| | | 38 | | private int _peakIndex; |
| | | 39 | | private int _leafCount; |
| | | 40 | | |
| | | 41 | | private readonly QueryKeyIndexMap<TKey> _keyToNodeIndex; |
| | 44 | 42 | | private readonly QueryTraversalScratch _queryScratch = new(); |
| | | 43 | | |
| | 44 | 44 | | private readonly SwiftIntStack _freeIndices = new(); |
| | | 45 | | |
| | | 46 | | private int _rootNodeIndex; |
| | | 47 | | |
| | | 48 | | #endregion |
| | | 49 | | |
| | | 50 | | #region Constructor |
| | | 51 | | |
| | | 52 | | /// <summary> |
| | | 53 | | /// Initializes a new instance of the <see cref="SwiftBVH{TKey, TVolume}"/> class with the specified capacity. |
| | | 54 | | /// </summary> |
| | 44 | 55 | | public SwiftBVH(int capacity) |
| | | 56 | | { |
| | 44 | 57 | | capacity = SwiftHashTools.NextPowerOfTwo(capacity); |
| | 44 | 58 | | _nodePool = new SwiftBVHNode<TKey, TVolume>[capacity].Populate(() => |
| | 44 | 59 | | new SwiftBVHNode<TKey, TVolume>() { ParentIndex = -1, LeftChildIndex = -1, RightChildIndex = -1 }); |
| | 44 | 60 | | _keyToNodeIndex = new QueryKeyIndexMap<TKey>(capacity); |
| | | 61 | | |
| | 44 | 62 | | _rootNodeIndex = -1; |
| | | 63 | | |
| | 44 | 64 | | _freeIndices = new SwiftIntStack(SwiftIntStack.DefaultCapacity); |
| | 44 | 65 | | } |
| | | 66 | | |
| | | 67 | | #endregion |
| | | 68 | | |
| | | 69 | | #region Properties |
| | | 70 | | |
| | | 71 | | /// <summary> |
| | | 72 | | /// Gets the underlying pool of nodes used in the BVH. |
| | | 73 | | /// </summary> |
| | 8053 | 74 | | public SwiftBVHNode<TKey, TVolume>[] NodePool => _nodePool; |
| | | 75 | | |
| | | 76 | | /// <summary> |
| | | 77 | | /// Gets the root node of the BVH. |
| | | 78 | | /// </summary> |
| | 6 | 79 | | public SwiftBVHNode<TKey, TVolume> RootNode => _rootNodeIndex >= 0 && _nodePool[_rootNodeIndex].IsAllocated |
| | 6 | 80 | | ? _nodePool[_rootNodeIndex] |
| | 6 | 81 | | : SwiftBVHNode<TKey, TVolume>.Default; |
| | | 82 | | |
| | | 83 | | /// <summary> |
| | | 84 | | /// Gets the index of the root node in the BVH. |
| | | 85 | | /// </summary> |
| | 204 | 86 | | public int RootNodeIndex => _rootNodeIndex; |
| | | 87 | | |
| | | 88 | | /// <summary> |
| | | 89 | | /// Gets the total number of leaf nodes in the BVH. |
| | | 90 | | /// </summary> |
| | 6 | 91 | | public int Count => _leafCount; |
| | | 92 | | |
| | | 93 | | #endregion |
| | | 94 | | |
| | | 95 | | #region Collection Manipulation |
| | | 96 | | |
| | | 97 | | /// <summary> |
| | | 98 | | /// Allocates a new node with the specified value, bounds, and leaf status. |
| | | 99 | | /// Reuses indices from the freelist when available. |
| | | 100 | | /// </summary> |
| | | 101 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 102 | | private int AllocateNode(TKey value, TVolume bounds, bool isLeaf) |
| | | 103 | | { |
| | | 104 | | int index; |
| | | 105 | | |
| | | 106 | | // Check if there are any reusable indices in the freelist |
| | 26440 | 107 | | if (_freeIndices.Count > 0) |
| | 4 | 108 | | index = _freeIndices.Pop(); // Reuse an available index |
| | | 109 | | else |
| | | 110 | | { |
| | 26436 | 111 | | if (_peakIndex + 1 >= _nodePool.Length) |
| | 26 | 112 | | Resize(_nodePool.Length * 2); |
| | | 113 | | |
| | | 114 | | // Allocate a new index if freelist is empty |
| | 26436 | 115 | | index = _peakIndex++; |
| | | 116 | | } |
| | | 117 | | |
| | 26440 | 118 | | ref SwiftBVHNode<TKey, TVolume> node = ref _nodePool[index]; |
| | 26440 | 119 | | node.Reset(); // Explicit reset |
| | 26440 | 120 | | node.MyIndex = index; |
| | 26440 | 121 | | node.Value = value; |
| | 26440 | 122 | | node.Bounds = bounds; |
| | | 123 | | |
| | 26440 | 124 | | if (isLeaf) |
| | | 125 | | { |
| | 13240 | 126 | | node.IsLeaf = isLeaf; |
| | 13240 | 127 | | node.SubtreeSize = 1; |
| | 13240 | 128 | | _leafCount++; |
| | | 129 | | } |
| | | 130 | | |
| | 26440 | 131 | | node.IsAllocated = true; |
| | | 132 | | |
| | 26440 | 133 | | return index; |
| | | 134 | | } |
| | | 135 | | |
| | | 136 | | /// <summary> |
| | | 137 | | /// Inserts a bounding volume with an associated value into the BVH. |
| | | 138 | | /// Ensures tree balance and updates hash buckets. |
| | | 139 | | /// </summary> |
| | | 140 | | public bool Insert(TKey value, TVolume bounds) |
| | | 141 | | { |
| | 13240 | 142 | | int newNodeIndex = AllocateNode(value, bounds, true); // Allocate new node as a leaf |
| | 13240 | 143 | | _rootNodeIndex = InsertIntoTree(_rootNodeIndex, newNodeIndex); |
| | 13240 | 144 | | InsertIntoBuckets(value, newNodeIndex); |
| | 13240 | 145 | | return true; |
| | | 146 | | } |
| | | 147 | | |
| | | 148 | | /// <summary> |
| | | 149 | | /// Inserts a node into the tree while maintaining tree balance. |
| | | 150 | | /// Adjusts parent-child relationships as necessary. |
| | | 151 | | /// </summary> |
| | | 152 | | [MethodImpl(MethodImplOptions.NoInlining)] |
| | | 153 | | private int InsertIntoTree(int parentNodeIndex, int newNodeIndex) |
| | | 154 | | { |
| | 151862 | 155 | | if (parentNodeIndex < 0 || !_nodePool[parentNodeIndex].IsAllocated) |
| | 40 | 156 | | return newNodeIndex; |
| | | 157 | | |
| | 151822 | 158 | | if (_nodePool[parentNodeIndex].IsLeaf) |
| | 13200 | 159 | | return CreateParentForLeaves(parentNodeIndex, newNodeIndex); |
| | | 160 | | |
| | 138622 | 161 | | InsertIntoBestChild(parentNodeIndex, newNodeIndex); |
| | 138622 | 162 | | RefreshParentNode(parentNodeIndex); |
| | 138622 | 163 | | return parentNodeIndex; |
| | | 164 | | } |
| | | 165 | | |
| | | 166 | | private int CreateParentForLeaves(int existingLeafIndex, int newLeafIndex) |
| | | 167 | | { |
| | 13200 | 168 | | TVolume combinedBounds = _nodePool[existingLeafIndex].Bounds.Union(_nodePool[newLeafIndex].Bounds); |
| | 13200 | 169 | | int oldParentIndex = _nodePool[existingLeafIndex].ParentIndex; |
| | 13200 | 170 | | int newParentIndex = AllocateNode(default!, combinedBounds, false); |
| | | 171 | | |
| | 13200 | 172 | | ref SwiftBVHNode<TKey, TVolume> newParentNode = ref _nodePool[newParentIndex]; |
| | 13200 | 173 | | newParentNode.ParentIndex = oldParentIndex; |
| | 13200 | 174 | | newParentNode.LeftChildIndex = existingLeafIndex; |
| | 13200 | 175 | | newParentNode.RightChildIndex = newLeafIndex; |
| | 13200 | 176 | | newParentNode.SubtreeSize = 1 + _nodePool[existingLeafIndex].SubtreeSize + _nodePool[newLeafIndex].SubtreeSize; |
| | | 177 | | |
| | 13200 | 178 | | _nodePool[existingLeafIndex].ParentIndex = newParentIndex; |
| | 13200 | 179 | | _nodePool[newLeafIndex].ParentIndex = newParentIndex; |
| | | 180 | | |
| | 13200 | 181 | | return newParentIndex; |
| | | 182 | | } |
| | | 183 | | |
| | | 184 | | private void InsertIntoBestChild(int parentNodeIndex, int newNodeIndex) |
| | | 185 | | { |
| | 138622 | 186 | | ref SwiftBVHNode<TKey, TVolume> parentNode = ref _nodePool[parentNodeIndex]; |
| | 138622 | 187 | | if (ShouldInsertIntoLeftChild(parentNodeIndex, newNodeIndex)) |
| | 70128 | 188 | | parentNode.LeftChildIndex = InsertIntoTree(parentNode.LeftChildIndex, newNodeIndex); |
| | | 189 | | else |
| | 68494 | 190 | | parentNode.RightChildIndex = InsertIntoTree(parentNode.RightChildIndex, newNodeIndex); |
| | 68494 | 191 | | } |
| | | 192 | | |
| | | 193 | | private bool ShouldInsertIntoLeftChild(int parentNodeIndex, int newNodeIndex) |
| | | 194 | | { |
| | 138622 | 195 | | SwiftBVHNode<TKey, TVolume> parentNode = _nodePool[parentNodeIndex]; |
| | 138622 | 196 | | SwiftBVHNode<TKey, TVolume> leftChild = _nodePool[parentNode.LeftChildIndex]; |
| | 138622 | 197 | | SwiftBVHNode<TKey, TVolume> rightChild = _nodePool[parentNode.RightChildIndex]; |
| | 138622 | 198 | | int leftSize = GetSubtreeSize(leftChild); |
| | 138622 | 199 | | int rightSize = GetSubtreeSize(rightChild); |
| | | 200 | | |
| | 138622 | 201 | | if (IsSeverelyUnbalanced(leftSize, rightSize)) |
| | 12649 | 202 | | return leftSize <= rightSize; |
| | | 203 | | |
| | 125973 | 204 | | return ShouldInsertIntoLowerCostChild( |
| | 125973 | 205 | | leftChild, |
| | 125973 | 206 | | rightChild, |
| | 125973 | 207 | | leftSize, |
| | 125973 | 208 | | rightSize, |
| | 125973 | 209 | | _nodePool[newNodeIndex].Bounds); |
| | | 210 | | } |
| | | 211 | | |
| | | 212 | | private static bool IsSeverelyUnbalanced(int leftSize, int rightSize) |
| | | 213 | | { |
| | 138622 | 214 | | int maxSize = Math.Max(leftSize, rightSize); |
| | 138622 | 215 | | int minSize = Math.Min(leftSize, rightSize); |
| | 138622 | 216 | | return maxSize > minSize * 2; |
| | | 217 | | } |
| | | 218 | | |
| | | 219 | | private static bool ShouldInsertIntoLowerCostChild( |
| | | 220 | | SwiftBVHNode<TKey, TVolume> leftChild, |
| | | 221 | | SwiftBVHNode<TKey, TVolume> rightChild, |
| | | 222 | | int leftSize, |
| | | 223 | | int rightSize, |
| | | 224 | | TVolume newBounds) |
| | | 225 | | { |
| | 125973 | 226 | | long leftCost = leftChild.Bounds.GetCost(newBounds); |
| | 125973 | 227 | | long rightCost = rightChild.Bounds.GetCost(newBounds); |
| | | 228 | | |
| | 125973 | 229 | | if (leftCost == rightCost) |
| | 5737 | 230 | | return leftSize <= rightSize; |
| | | 231 | | |
| | 120236 | 232 | | return leftCost < rightCost; |
| | | 233 | | } |
| | | 234 | | |
| | | 235 | | private void RefreshParentNode(int parentNodeIndex) |
| | | 236 | | { |
| | 139111 | 237 | | ref SwiftBVHNode<TKey, TVolume> parentNode = ref _nodePool[parentNodeIndex]; |
| | 139111 | 238 | | SwiftBVHNode<TKey, TVolume> leftChild = _nodePool[parentNode.LeftChildIndex]; |
| | 139111 | 239 | | SwiftBVHNode<TKey, TVolume> rightChild = _nodePool[parentNode.RightChildIndex]; |
| | | 240 | | |
| | 139111 | 241 | | parentNode.Bounds = GetCombinedBounds(leftChild, rightChild); |
| | 139111 | 242 | | parentNode.SubtreeSize = 1 + GetSubtreeSize(leftChild) + GetSubtreeSize(rightChild); |
| | 139111 | 243 | | } |
| | | 244 | | |
| | | 245 | | private static int GetSubtreeSize(SwiftBVHNode<TKey, TVolume> node) |
| | | 246 | | { |
| | 555466 | 247 | | return node.SubtreeSize; |
| | | 248 | | } |
| | | 249 | | |
| | | 250 | | /// <summary> |
| | | 251 | | /// Inserts a value into the hash bucket for fast lookup. |
| | | 252 | | /// Handles collisions with linear probing. |
| | | 253 | | /// </summary> |
| | | 254 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 255 | | private void InsertIntoBuckets(TKey value, int nodeIndex) |
| | | 256 | | { |
| | 13240 | 257 | | _keyToNodeIndex.Insert(value, nodeIndex); |
| | 13240 | 258 | | } |
| | | 259 | | |
| | | 260 | | /// <summary> |
| | | 261 | | /// Updates the bounding volume of a node and propagates changes up the tree. |
| | | 262 | | /// Ensures consistency in parent bounds and subtree sizes. |
| | | 263 | | /// </summary> |
| | | 264 | | public void UpdateEntryBounds(TKey value, TVolume newBounds) |
| | | 265 | | { |
| | 8 | 266 | | SwiftThrowHelper.ThrowIfNullGeneric(value, nameof(value)); |
| | | 267 | | |
| | 8 | 268 | | int index = _keyToNodeIndex.Find(value, MatchesEntryKey); |
| | 9 | 269 | | if (index == -1) return; |
| | | 270 | | |
| | 7 | 271 | | ref SwiftBVHNode<TKey, TVolume> node = ref _nodePool[index]; |
| | 8 | 272 | | if (!node.IsAllocated) return; // Skip update if node has been removed |
| | | 273 | | |
| | 6 | 274 | | TVolume oldBounds = node.Bounds; |
| | 6 | 275 | | if (oldBounds.BoundsEquals(newBounds)) |
| | 1 | 276 | | return; // Skip unnecessary updates |
| | | 277 | | |
| | 5 | 278 | | node.Bounds = newBounds; |
| | | 279 | | |
| | | 280 | | // Propagate changes up the tree |
| | 5 | 281 | | int parentIndex = node.ParentIndex; |
| | 9 | 282 | | while (parentIndex != -1) |
| | | 283 | | { |
| | 5 | 284 | | ref SwiftBVHNode<TKey, TVolume> parent = ref _nodePool[parentIndex]; |
| | 5 | 285 | | SwiftBVHNode<TKey, TVolume> leftChild = _nodePool[parent.LeftChildIndex]; |
| | 5 | 286 | | SwiftBVHNode<TKey, TVolume> rightChild = _nodePool[parent.RightChildIndex]; |
| | | 287 | | |
| | 5 | 288 | | TVolume newParentBounds = GetCombinedBounds(leftChild, rightChild); |
| | 5 | 289 | | if (parent.Bounds.BoundsEquals(newParentBounds)) |
| | | 290 | | break; // No further updates needed |
| | | 291 | | |
| | 4 | 292 | | parent.Bounds = newParentBounds; |
| | 4 | 293 | | parentIndex = parent.ParentIndex; |
| | | 294 | | } |
| | 5 | 295 | | } |
| | | 296 | | |
| | | 297 | | /// <summary> |
| | | 298 | | /// Removes a value and its associated bounding volume from the BVH. |
| | | 299 | | /// Updates tree structure and clears hash bucket entries. |
| | | 300 | | /// </summary> |
| | | 301 | | public bool Remove(TKey value) |
| | | 302 | | { |
| | 135 | 303 | | SwiftThrowHelper.ThrowIfNullGeneric(value, nameof(value)); |
| | | 304 | | |
| | 135 | 305 | | int nodeIndex = _keyToNodeIndex.Find(value, MatchesEntryKey); |
| | 137 | 306 | | if (nodeIndex == -1) return false; |
| | | 307 | | |
| | | 308 | | // If the node is the root and the only node, reset the BVH |
| | 133 | 309 | | if (nodeIndex == RootNodeIndex && _leafCount == 1) |
| | | 310 | | { |
| | 2 | 311 | | Clear(); |
| | 2 | 312 | | return true; |
| | | 313 | | } |
| | | 314 | | |
| | 131 | 315 | | RemoveFromBuckets(value); // Ensure the bucket is cleared before further operations |
| | | 316 | | |
| | | 317 | | // Remove node and update tree structure |
| | 131 | 318 | | RemoveFromTree(nodeIndex); |
| | | 319 | | |
| | 131 | 320 | | return true; |
| | | 321 | | } |
| | | 322 | | |
| | | 323 | | /// <summary> |
| | | 324 | | /// Removes an entry from the hash buckets, resolving collisions as necessary. |
| | | 325 | | /// </summary> |
| | | 326 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 327 | | private void RemoveFromBuckets(TKey value) |
| | | 328 | | { |
| | 131 | 329 | | _keyToNodeIndex.Remove(value, MatchesEntryKey, IsLeafNode, GetNodeValue); |
| | 131 | 330 | | } |
| | | 331 | | |
| | | 332 | | /// <summary> |
| | | 333 | | /// Removes a leaf node from the tree, collapses its parent, and propagates |
| | | 334 | | /// bound and subtree-size updates upward. Every internal node is guaranteed |
| | | 335 | | /// to have exactly two children after this operation completes. |
| | | 336 | | /// </summary> |
| | | 337 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 338 | | private void RemoveFromTree(int nodeIndex) |
| | | 339 | | { |
| | 131 | 340 | | int parentIndex = _nodePool[nodeIndex].ParentIndex; |
| | | 341 | | |
| | 131 | 342 | | int siblingIndex = ReleaseLeafAndParent(nodeIndex, parentIndex, out int grandParentIndex); |
| | 131 | 343 | | PromoteSiblingToGrandParent(siblingIndex, parentIndex, grandParentIndex); |
| | 131 | 344 | | if (grandParentIndex != -1) |
| | 125 | 345 | | RefreshAncestors(grandParentIndex); |
| | 131 | 346 | | } |
| | | 347 | | |
| | | 348 | | private int ReleaseLeafAndParent(int nodeIndex, int parentIndex, out int grandParentIndex) |
| | | 349 | | { |
| | 131 | 350 | | ref SwiftBVHNode<TKey, TVolume> parent = ref _nodePool[parentIndex]; |
| | 131 | 351 | | int siblingIndex = parent.LeftChildIndex == nodeIndex |
| | 131 | 352 | | ? parent.RightChildIndex |
| | 131 | 353 | | : parent.LeftChildIndex; |
| | 131 | 354 | | grandParentIndex = parent.ParentIndex; |
| | | 355 | | |
| | | 356 | | // Push parent before the leaf so that the leaf index sits on top of the |
| | | 357 | | // freelist stack and is reused first by the next allocation. |
| | 131 | 358 | | parent.Reset(); |
| | 131 | 359 | | _freeIndices.Push(parentIndex); |
| | | 360 | | |
| | 131 | 361 | | _leafCount--; |
| | 131 | 362 | | _nodePool[nodeIndex].Reset(); |
| | 131 | 363 | | _freeIndices.Push(nodeIndex); |
| | | 364 | | |
| | 131 | 365 | | return siblingIndex; |
| | | 366 | | } |
| | | 367 | | |
| | | 368 | | private void PromoteSiblingToGrandParent(int siblingIndex, int parentIndex, int grandParentIndex) |
| | | 369 | | { |
| | 131 | 370 | | if (siblingIndex != -1) |
| | 131 | 371 | | _nodePool[siblingIndex].ParentIndex = grandParentIndex; |
| | | 372 | | |
| | 131 | 373 | | if (grandParentIndex == -1) |
| | | 374 | | { |
| | 6 | 375 | | _rootNodeIndex = siblingIndex; |
| | 6 | 376 | | return; |
| | | 377 | | } |
| | | 378 | | |
| | 125 | 379 | | ref SwiftBVHNode<TKey, TVolume> grandParent = ref _nodePool[grandParentIndex]; |
| | 125 | 380 | | if (grandParent.LeftChildIndex == parentIndex) |
| | 65 | 381 | | grandParent.LeftChildIndex = siblingIndex; |
| | | 382 | | else |
| | 60 | 383 | | grandParent.RightChildIndex = siblingIndex; |
| | 60 | 384 | | } |
| | | 385 | | |
| | | 386 | | private void RefreshAncestors(int current) |
| | | 387 | | { |
| | 614 | 388 | | while (current != -1) |
| | | 389 | | { |
| | 489 | 390 | | RefreshParentNode(current); |
| | 489 | 391 | | current = _nodePool[current].ParentIndex; |
| | | 392 | | } |
| | 125 | 393 | | } |
| | | 394 | | |
| | | 395 | | #endregion |
| | | 396 | | |
| | | 397 | | #region Capacity Management |
| | | 398 | | |
| | | 399 | | /// <summary> |
| | | 400 | | /// Ensures the BVH has sufficient capacity, resizing the node pool and buckets if needed. |
| | | 401 | | /// </summary> |
| | | 402 | | public void EnsureCapacity(int capacity) |
| | | 403 | | { |
| | 2 | 404 | | capacity = SwiftHashTools.NextPowerOfTwo(capacity); |
| | 2 | 405 | | if (capacity > _nodePool.Length) |
| | 1 | 406 | | Resize(capacity); |
| | 2 | 407 | | } |
| | | 408 | | |
| | | 409 | | /// <summary> |
| | | 410 | | /// Resizes the internal node pool to accommodate additional nodes. |
| | | 411 | | /// Preserves existing nodes and reinitializes the expanded capacity. |
| | | 412 | | /// </summary> |
| | | 413 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 414 | | private void Resize(int newSize) |
| | | 415 | | { |
| | 27 | 416 | | SwiftBVHNode<TKey, TVolume>[] newArray = new SwiftBVHNode<TKey, TVolume>[newSize]; |
| | 27 | 417 | | Array.Copy(_nodePool, 0, newArray, 0, _peakIndex); |
| | | 418 | | |
| | 70438 | 419 | | for (int i = _peakIndex; i < newSize; i++) |
| | 35192 | 420 | | newArray[i].Reset(); // set default index lookup values |
| | | 421 | | |
| | 27 | 422 | | _nodePool = newArray; |
| | | 423 | | |
| | 27 | 424 | | ResizeBuckets(newSize); |
| | 27 | 425 | | SwiftCollectionDiagnostics.Shared.Info($"Resized BVH storage to {newSize} nodes.", _diagnosticSource); |
| | 27 | 426 | | } |
| | | 427 | | |
| | | 428 | | /// <summary> |
| | | 429 | | /// Resizes and rehashes the hash buckets to maintain lookup efficiency. |
| | | 430 | | /// Rehashes existing nodes after resizing. |
| | | 431 | | /// </summary> |
| | | 432 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 433 | | private void ResizeBuckets(int newSize) |
| | | 434 | | { |
| | 27 | 435 | | _keyToNodeIndex.ResizeAndRehash(newSize, _peakIndex, IsLeafNode, GetNodeValue); |
| | 27 | 436 | | } |
| | | 437 | | |
| | | 438 | | #endregion |
| | | 439 | | |
| | | 440 | | #region Utility Methods |
| | | 441 | | |
| | | 442 | | /// <summary> |
| | | 443 | | /// Gets the combined bounding volume of two child nodes. |
| | | 444 | | /// Handles cases where one or both children are missing. |
| | | 445 | | /// </summary> |
| | | 446 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 447 | | private static TVolume GetCombinedBounds(SwiftBVHNode<TKey, TVolume> leftChild, SwiftBVHNode<TKey, TVolume> rightChi |
| | | 448 | | { |
| | 139116 | 449 | | return leftChild.Bounds.Union(rightChild.Bounds); |
| | | 450 | | } |
| | | 451 | | |
| | | 452 | | /// <summary> |
| | | 453 | | /// Queries the BVH for values whose bounding volumes intersect with the specified volume. |
| | | 454 | | /// Uses a stack-based approach for efficient traversal. |
| | | 455 | | /// </summary> |
| | | 456 | | public void Query(TVolume queryBounds, ICollection<TKey> results) |
| | | 457 | | { |
| | 30 | 458 | | SwiftThrowHelper.ThrowIfNull(results, nameof(results)); |
| | | 459 | | |
| | 33 | 460 | | if (RootNodeIndex == -1) return; |
| | | 461 | | |
| | 27 | 462 | | SwiftIntStack nodeStack = _queryScratch.RentIntStack(_peakIndex + 1); |
| | 27 | 463 | | nodeStack.Push(RootNodeIndex); |
| | | 464 | | |
| | 21078 | 465 | | while (nodeStack.Count > 0) |
| | | 466 | | { |
| | 21053 | 467 | | int index = nodeStack.Pop(); |
| | 21053 | 468 | | QueryNode(index, queryBounds, results, nodeStack); |
| | | 469 | | } |
| | 25 | 470 | | } |
| | | 471 | | |
| | | 472 | | private void QueryNode(int index, TVolume queryBounds, ICollection<TKey> results, SwiftIntStack nodeStack) |
| | | 473 | | { |
| | 21053 | 474 | | ref SwiftBVHNode<TKey, TVolume> node = ref _nodePool[index]; |
| | 21053 | 475 | | ThrowIfQueryNodeIsUnallocated(index, node); |
| | | 476 | | |
| | 21051 | 477 | | if (!queryBounds.Intersects(node.Bounds)) |
| | 307 | 478 | | return; |
| | | 479 | | |
| | 20744 | 480 | | if (node.IsLeaf) |
| | | 481 | | { |
| | 10231 | 482 | | results.Add(node.Value); |
| | 10231 | 483 | | return; |
| | | 484 | | } |
| | | 485 | | |
| | 10513 | 486 | | PushChildNodes(node, nodeStack); |
| | 10513 | 487 | | } |
| | | 488 | | |
| | | 489 | | private static void PushChildNodes(SwiftBVHNode<TKey, TVolume> node, SwiftIntStack nodeStack) |
| | | 490 | | { |
| | 10513 | 491 | | if (node.HasLeftChild) |
| | 10513 | 492 | | nodeStack.Push(node.LeftChildIndex); |
| | 10513 | 493 | | if (node.HasRightChild) |
| | 10513 | 494 | | nodeStack.Push(node.RightChildIndex); |
| | 10513 | 495 | | } |
| | | 496 | | |
| | | 497 | | private static void ThrowIfQueryNodeIsUnallocated(int index, SwiftBVHNode<TKey, TVolume> node) |
| | | 498 | | { |
| | 21053 | 499 | | if (node.IsAllocated) |
| | 21051 | 500 | | return; |
| | | 501 | | |
| | 2 | 502 | | SwiftCollectionDiagnostics.Shared.Error($"Encountered an unallocated node at index {index} during query traversa |
| | 2 | 503 | | throw new InvalidOperationException($"Encountered an unallocated node at index {index} during query traversal.") |
| | | 504 | | } |
| | | 505 | | |
| | | 506 | | /// <summary> |
| | | 507 | | /// Finds the index of a node by its value in the BVH using hash buckets. |
| | | 508 | | /// Returns -1 if the value is not found. |
| | | 509 | | /// </summary> |
| | | 510 | | public int FindEntry(TKey value) |
| | | 511 | | { |
| | 12 | 512 | | SwiftThrowHelper.ThrowIfNullGeneric(value, nameof(value)); |
| | 12 | 513 | | return _keyToNodeIndex.Find(value, MatchesEntryKey); |
| | | 514 | | } |
| | | 515 | | |
| | | 516 | | /// <summary> |
| | | 517 | | /// Clears the BVH, resetting all nodes, buckets, and metadata. |
| | | 518 | | /// </summary> |
| | | 519 | | public void Clear() |
| | | 520 | | { |
| | 5 | 521 | | if (RootNodeIndex == -1) return; |
| | | 522 | | |
| | 208 | 523 | | for (int i = 0; i < _peakIndex; i++) |
| | 101 | 524 | | _nodePool[i].Reset(); |
| | | 525 | | |
| | 3 | 526 | | _keyToNodeIndex.Clear(); |
| | | 527 | | |
| | 3 | 528 | | _freeIndices.Reset(); |
| | | 529 | | |
| | 3 | 530 | | _leafCount = 0; |
| | 3 | 531 | | _peakIndex = 0; |
| | 3 | 532 | | _rootNodeIndex = -1; |
| | 3 | 533 | | } |
| | | 534 | | |
| | | 535 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 18528 | 536 | | private TKey GetNodeValue(int index) => _nodePool[index].Value; |
| | | 537 | | |
| | | 538 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 36082 | 539 | | private bool IsLeafNode(int index) => _nodePool[index].IsLeaf; |
| | | 540 | | |
| | | 541 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 542 | | private bool MatchesEntryKey(int index, TKey value) |
| | | 543 | | { |
| | 286 | 544 | | return _nodePool[index].IsLeaf && EqualityComparer<TKey>.Default.Equals(_nodePool[index].Value, value); |
| | | 545 | | } |
| | | 546 | | |
| | | 547 | | #endregion |
| | | 548 | | } |