| | | 1 | | //======================================================================= |
| | | 2 | | // SwiftSpatialHash.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 mutable spatial hash that indexes keyed bounding volumes into deterministic integer grid cells. |
| | | 18 | | /// </summary> |
| | | 19 | | /// <typeparam name="TKey">The key used to identify each stored entry.</typeparam> |
| | | 20 | | /// <typeparam name="TVolume">The volume type used for broad-phase registration and queries.</typeparam> |
| | | 21 | | public class SwiftSpatialHash<TKey, TVolume> |
| | | 22 | | where TKey : notnull |
| | | 23 | | where TVolume : struct, IBoundVolume<TVolume> |
| | | 24 | | { |
| | | 25 | | private const string _diagnosticSource = nameof(SwiftSpatialHash<TKey, TVolume>); |
| | | 26 | | |
| | | 27 | | private readonly ISpatialHashCellMapper<TVolume> _cellMapper; |
| | | 28 | | private readonly QueryKeyIndexMap<TKey> _keyToEntryIndex; |
| | | 29 | | private readonly SwiftDictionary<SwiftSpatialHashCellIndex, SwiftList<int>> _cells; |
| | | 30 | | private readonly SwiftIntStack _freeEntries; |
| | | 31 | | |
| | | 32 | | private SpatialHashEntry[] _entries; |
| | | 33 | | private int _peakCount; |
| | | 34 | | private int _count; |
| | | 35 | | private int _queryStamp; |
| | | 36 | | |
| | | 37 | | /// <summary> |
| | | 38 | | /// Initializes a new instance of the <see cref="SwiftSpatialHash{TKey, TVolume}"/> class. |
| | | 39 | | /// </summary> |
| | | 40 | | /// <param name="capacity">The initial entry capacity.</param> |
| | | 41 | | /// <param name="cellMapper">The mapper that projects volumes into deterministic cell coordinates.</param> |
| | | 42 | | public SwiftSpatialHash(int capacity, ISpatialHashCellMapper<TVolume> cellMapper) |
| | 14 | 43 | | : this(capacity, cellMapper, SwiftSpatialHashOptions.Default) |
| | | 44 | | { |
| | 14 | 45 | | } |
| | | 46 | | |
| | | 47 | | /// <summary> |
| | | 48 | | /// Initializes a new instance of the <see cref="SwiftSpatialHash{TKey, TVolume}"/> class. |
| | | 49 | | /// </summary> |
| | | 50 | | /// <param name="capacity">The initial entry capacity.</param> |
| | | 51 | | /// <param name="cellMapper">The mapper that projects volumes into deterministic cell coordinates.</param> |
| | | 52 | | /// <param name="options">Spatial hash query options.</param> |
| | 19 | 53 | | public SwiftSpatialHash(int capacity, ISpatialHashCellMapper<TVolume> cellMapper, SwiftSpatialHashOptions options) |
| | | 54 | | { |
| | 19 | 55 | | SwiftThrowHelper.ThrowIfNull(cellMapper, nameof(cellMapper)); |
| | | 56 | | |
| | 19 | 57 | | capacity = SwiftHashTools.NextPowerOfTwo(capacity); |
| | | 58 | | |
| | 19 | 59 | | _cellMapper = cellMapper; |
| | 19 | 60 | | _keyToEntryIndex = new QueryKeyIndexMap<TKey>(capacity); |
| | 19 | 61 | | _cells = new SwiftDictionary<SwiftSpatialHashCellIndex, SwiftList<int>>(capacity); |
| | 19 | 62 | | _freeEntries = new SwiftIntStack(); |
| | 19 | 63 | | _entries = new SpatialHashEntry[capacity]; |
| | 19 | 64 | | Options = options; |
| | 19 | 65 | | } |
| | | 66 | | |
| | | 67 | | /// <summary> |
| | | 68 | | /// Gets the number of active entries stored in the spatial hash. |
| | | 69 | | /// </summary> |
| | 3 | 70 | | public int Count => _count; |
| | | 71 | | |
| | | 72 | | /// <summary> |
| | | 73 | | /// Gets the options used by this spatial hash. |
| | | 74 | | /// </summary> |
| | | 75 | | public SwiftSpatialHashOptions Options { get; } |
| | | 76 | | |
| | | 77 | | /// <summary> |
| | | 78 | | /// Inserts a new entry or replaces the bounds of an existing key. |
| | | 79 | | /// </summary> |
| | | 80 | | /// <param name="key">The entry key.</param> |
| | | 81 | | /// <param name="bounds">The entry bounds.</param> |
| | | 82 | | /// <returns><c>true</c> when a new key was added; <c>false</c> when an existing key was replaced.</returns> |
| | | 83 | | public bool Insert(TKey key, TVolume bounds) |
| | | 84 | | { |
| | 60 | 85 | | SwiftThrowHelper.ThrowIfNull(key, nameof(key)); |
| | | 86 | | |
| | 60 | 87 | | int existingIndex = FindEntryIndex(key); |
| | 60 | 88 | | if (existingIndex >= 0) |
| | | 89 | | { |
| | 1 | 90 | | UpdateEntryBounds(existingIndex, bounds); |
| | 1 | 91 | | return false; |
| | | 92 | | } |
| | | 93 | | |
| | 59 | 94 | | EnsureCapacity(_count + 1); |
| | | 95 | | |
| | 59 | 96 | | int entryIndex = AllocateEntry(key, bounds); |
| | 59 | 97 | | AddEntryToCells(entryIndex, bounds); |
| | 59 | 98 | | _keyToEntryIndex.Insert(key, entryIndex); |
| | 59 | 99 | | _count++; |
| | 59 | 100 | | return true; |
| | | 101 | | } |
| | | 102 | | |
| | | 103 | | /// <summary> |
| | | 104 | | /// Removes an entry from the spatial hash. |
| | | 105 | | /// </summary> |
| | | 106 | | /// <param name="key">The entry key.</param> |
| | | 107 | | /// <returns><c>true</c> when the key existed and was removed; otherwise, <c>false</c>.</returns> |
| | | 108 | | public bool Remove(TKey key) |
| | | 109 | | { |
| | 4 | 110 | | SwiftThrowHelper.ThrowIfNullGeneric(key, nameof(key)); |
| | | 111 | | |
| | 4 | 112 | | int entryIndex = FindEntryIndex(key); |
| | 4 | 113 | | if (entryIndex < 0) |
| | 1 | 114 | | return false; |
| | | 115 | | |
| | 3 | 116 | | RemoveEntryFromCells(entryIndex, _entries[entryIndex].Bounds); |
| | 3 | 117 | | _keyToEntryIndex.Remove(key, MatchesEntryKey, IsAllocatedEntry, GetEntryKey); |
| | 3 | 118 | | _entries[entryIndex].Reset(); |
| | 3 | 119 | | _freeEntries.Push(entryIndex); |
| | 3 | 120 | | _count--; |
| | 3 | 121 | | return true; |
| | | 122 | | } |
| | | 123 | | |
| | | 124 | | /// <summary> |
| | | 125 | | /// Updates the bounds for an existing entry. |
| | | 126 | | /// </summary> |
| | | 127 | | /// <param name="key">The entry key.</param> |
| | | 128 | | /// <param name="newBounds">The replacement bounds.</param> |
| | | 129 | | /// <returns><c>true</c> when the key existed; otherwise, <c>false</c>.</returns> |
| | | 130 | | public bool UpdateEntryBounds(TKey key, TVolume newBounds) |
| | | 131 | | { |
| | 3 | 132 | | SwiftThrowHelper.ThrowIfNullGeneric(key, nameof(key)); |
| | | 133 | | |
| | 3 | 134 | | int entryIndex = FindEntryIndex(key); |
| | 3 | 135 | | if (entryIndex < 0) |
| | 1 | 136 | | return false; |
| | | 137 | | |
| | 2 | 138 | | return UpdateEntryBounds(entryIndex, newBounds); |
| | | 139 | | } |
| | | 140 | | |
| | | 141 | | /// <summary> |
| | | 142 | | /// Determines whether the spatial hash contains the specified key. |
| | | 143 | | /// </summary> |
| | | 144 | | public bool Contains(TKey key) |
| | | 145 | | { |
| | 4 | 146 | | SwiftThrowHelper.ThrowIfNullGeneric(key, nameof(key)); |
| | 4 | 147 | | return FindEntryIndex(key) >= 0; |
| | | 148 | | } |
| | | 149 | | |
| | | 150 | | /// <summary> |
| | | 151 | | /// Attempts to retrieve the bounds registered for the supplied key. |
| | | 152 | | /// </summary> |
| | | 153 | | public bool TryGetBounds(TKey key, out TVolume bounds) |
| | | 154 | | { |
| | 2 | 155 | | SwiftThrowHelper.ThrowIfNullGeneric(key, nameof(key)); |
| | | 156 | | |
| | 2 | 157 | | int entryIndex = FindEntryIndex(key); |
| | 2 | 158 | | if (entryIndex < 0) |
| | | 159 | | { |
| | 1 | 160 | | bounds = default; |
| | 1 | 161 | | return false; |
| | | 162 | | } |
| | | 163 | | |
| | 1 | 164 | | bounds = _entries[entryIndex].Bounds; |
| | 1 | 165 | | return true; |
| | | 166 | | } |
| | | 167 | | |
| | | 168 | | /// <summary> |
| | | 169 | | /// Queries the spatial hash and returns only entries whose bounds intersect the supplied query volume. |
| | | 170 | | /// </summary> |
| | | 171 | | public void Query(TVolume queryBounds, ICollection<TKey> results) |
| | | 172 | | { |
| | 17 | 173 | | SwiftThrowHelper.ThrowIfNull(results, nameof(results)); |
| | 17 | 174 | | ExecuteQuery(queryBounds, 0, true, results); |
| | 17 | 175 | | } |
| | | 176 | | |
| | | 177 | | /// <summary> |
| | | 178 | | /// Queries the spatial hash using the supplied query volume plus the configured neighborhood padding. |
| | | 179 | | /// </summary> |
| | | 180 | | public void QueryNeighborhood(TVolume queryBounds, ICollection<TKey> results) |
| | | 181 | | { |
| | 2 | 182 | | SwiftThrowHelper.ThrowIfNull(results, nameof(results)); |
| | 2 | 183 | | ExecuteQuery(queryBounds, Options.NeighborhoodPadding, false, results); |
| | 2 | 184 | | } |
| | | 185 | | |
| | | 186 | | /// <summary> |
| | | 187 | | /// Ensures the spatial hash can store the specified number of entries without growing its entry storage. |
| | | 188 | | /// </summary> |
| | | 189 | | public void EnsureCapacity(int capacity) |
| | | 190 | | { |
| | 59 | 191 | | capacity = SwiftHashTools.NextPowerOfTwo(capacity); |
| | 59 | 192 | | if (capacity <= _entries.Length) |
| | 54 | 193 | | return; |
| | | 194 | | |
| | 5 | 195 | | ResizeEntryStorage(capacity); |
| | 5 | 196 | | } |
| | | 197 | | |
| | | 198 | | /// <summary> |
| | | 199 | | /// Removes all entries and cell registrations from the spatial hash. |
| | | 200 | | /// </summary> |
| | | 201 | | public void Clear() |
| | | 202 | | { |
| | 2 | 203 | | if (_count == 0) |
| | 1 | 204 | | return; |
| | | 205 | | |
| | 6 | 206 | | for (int i = 0; i < _peakCount; i++) |
| | 2 | 207 | | _entries[i].Reset(); |
| | | 208 | | |
| | 1 | 209 | | _cells.Clear(); |
| | 1 | 210 | | _keyToEntryIndex.Clear(); |
| | 1 | 211 | | _freeEntries.Reset(); |
| | 1 | 212 | | _peakCount = 0; |
| | 1 | 213 | | _count = 0; |
| | 1 | 214 | | _queryStamp = 0; |
| | 1 | 215 | | } |
| | | 216 | | |
| | | 217 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 218 | | private int AllocateEntry(TKey key, TVolume bounds) |
| | | 219 | | { |
| | | 220 | | int entryIndex; |
| | 59 | 221 | | if (_freeEntries.Count > 0) |
| | 1 | 222 | | entryIndex = _freeEntries.Pop(); |
| | | 223 | | else |
| | 58 | 224 | | entryIndex = _peakCount++; |
| | | 225 | | |
| | 59 | 226 | | _entries[entryIndex].Key = key; |
| | 59 | 227 | | _entries[entryIndex].Bounds = bounds; |
| | 59 | 228 | | _entries[entryIndex].IsAllocated = true; |
| | 59 | 229 | | _entries[entryIndex].QueryStamp = 0; |
| | 59 | 230 | | return entryIndex; |
| | | 231 | | } |
| | | 232 | | |
| | | 233 | | private bool UpdateEntryBounds(int entryIndex, TVolume newBounds) |
| | | 234 | | { |
| | 3 | 235 | | TVolume currentBounds = _entries[entryIndex].Bounds; |
| | 3 | 236 | | if (currentBounds.BoundsEquals(newBounds)) |
| | 1 | 237 | | return true; |
| | | 238 | | |
| | 2 | 239 | | RemoveEntryFromCells(entryIndex, currentBounds); |
| | 2 | 240 | | _entries[entryIndex].Bounds = newBounds; |
| | 2 | 241 | | AddEntryToCells(entryIndex, newBounds); |
| | 2 | 242 | | return true; |
| | | 243 | | } |
| | | 244 | | |
| | | 245 | | private void ExecuteQuery(TVolume queryBounds, int padding, bool requireIntersection, ICollection<TKey> results) |
| | | 246 | | { |
| | 19 | 247 | | if (_count == 0) |
| | 2 | 248 | | return; |
| | | 249 | | |
| | 17 | 250 | | int queryStamp = RentQueryStamp(); |
| | 17 | 251 | | _cellMapper.GetCellRange(queryBounds, out SwiftSpatialHashCellIndex minCell, out SwiftSpatialHashCellIndex maxCe |
| | | 252 | | |
| | 128 | 253 | | for (int x = minCell.X - padding; x <= maxCell.X + padding; x++) |
| | | 254 | | { |
| | 388 | 255 | | for (int y = minCell.Y - padding; y <= maxCell.Y + padding; y++) |
| | | 256 | | { |
| | 1312 | 257 | | for (int z = minCell.Z - padding; z <= maxCell.Z + padding; z++) |
| | | 258 | | { |
| | 509 | 259 | | var cell = new SwiftSpatialHashCellIndex(x, y, z); |
| | 509 | 260 | | ProcessQueryCell(cell, queryBounds, queryStamp, requireIntersection, results); |
| | | 261 | | } |
| | | 262 | | } |
| | | 263 | | } |
| | 17 | 264 | | } |
| | | 265 | | |
| | | 266 | | private void ProcessQueryCell( |
| | | 267 | | SwiftSpatialHashCellIndex cell, |
| | | 268 | | TVolume queryBounds, |
| | | 269 | | int queryStamp, |
| | | 270 | | bool requireIntersection, |
| | | 271 | | ICollection<TKey> results) |
| | | 272 | | { |
| | 509 | 273 | | if (!_cells.TryGetValue(cell, out SwiftList<int> entryIndices)) |
| | 412 | 274 | | return; |
| | | 275 | | |
| | 452 | 276 | | for (int i = 0; i < entryIndices.Count; i++) |
| | 129 | 277 | | TryAddQueryResult(entryIndices[i], queryBounds, queryStamp, requireIntersection, results); |
| | 97 | 278 | | } |
| | | 279 | | |
| | | 280 | | private void TryAddQueryResult( |
| | | 281 | | int entryIndex, |
| | | 282 | | TVolume queryBounds, |
| | | 283 | | int queryStamp, |
| | | 284 | | bool requireIntersection, |
| | | 285 | | ICollection<TKey> results) |
| | | 286 | | { |
| | 129 | 287 | | ref SpatialHashEntry entry = ref _entries[entryIndex]; |
| | 129 | 288 | | if (entry.QueryStamp == queryStamp) |
| | 77 | 289 | | return; |
| | | 290 | | |
| | 52 | 291 | | entry.QueryStamp = queryStamp; |
| | | 292 | | |
| | 52 | 293 | | if (requireIntersection && !entry.Bounds.Intersects(queryBounds)) |
| | 1 | 294 | | return; |
| | | 295 | | |
| | 51 | 296 | | results.Add(entry.Key); |
| | 51 | 297 | | } |
| | | 298 | | |
| | | 299 | | private void AddEntryToCells(int entryIndex, TVolume bounds) |
| | | 300 | | { |
| | 61 | 301 | | _cellMapper.GetCellRange(bounds, out SwiftSpatialHashCellIndex minCell, out SwiftSpatialHashCellIndex maxCell); |
| | | 302 | | |
| | 292 | 303 | | for (int x = minCell.X; x <= maxCell.X; x++) |
| | | 304 | | { |
| | 464 | 305 | | for (int y = minCell.Y; y <= maxCell.Y; y++) |
| | | 306 | | { |
| | 944 | 307 | | for (int z = minCell.Z; z <= maxCell.Z; z++) |
| | | 308 | | { |
| | 325 | 309 | | var cell = new SwiftSpatialHashCellIndex(x, y, z); |
| | 325 | 310 | | if (!_cells.TryGetValue(cell, out SwiftList<int> entryIndices)) |
| | | 311 | | { |
| | 292 | 312 | | entryIndices = new SwiftList<int>(1); |
| | 292 | 313 | | _cells[cell] = entryIndices; |
| | | 314 | | } |
| | | 315 | | |
| | 325 | 316 | | entryIndices.Add(entryIndex); |
| | | 317 | | } |
| | | 318 | | } |
| | | 319 | | } |
| | 61 | 320 | | } |
| | | 321 | | |
| | | 322 | | private void RemoveEntryFromCells(int entryIndex, TVolume bounds) |
| | | 323 | | { |
| | 5 | 324 | | _cellMapper.GetCellRange(bounds, out SwiftSpatialHashCellIndex minCell, out SwiftSpatialHashCellIndex maxCell); |
| | | 325 | | |
| | 30 | 326 | | for (int x = minCell.X; x <= maxCell.X; x++) |
| | | 327 | | { |
| | 64 | 328 | | for (int y = minCell.Y; y <= maxCell.Y; y++) |
| | | 329 | | { |
| | 148 | 330 | | for (int z = minCell.Z; z <= maxCell.Z; z++) |
| | | 331 | | { |
| | 52 | 332 | | var cell = new SwiftSpatialHashCellIndex(x, y, z); |
| | 52 | 333 | | RemoveEntryFromCell(cell, entryIndex); |
| | | 334 | | } |
| | | 335 | | } |
| | | 336 | | } |
| | 5 | 337 | | } |
| | | 338 | | |
| | | 339 | | private void RemoveEntryFromCell(SwiftSpatialHashCellIndex cell, int entryIndex) |
| | | 340 | | { |
| | 52 | 341 | | SwiftList<int> entryIndices = _cells[cell]; |
| | 52 | 342 | | RemoveEntryIndex(entryIndices, entryIndex); |
| | 52 | 343 | | if (entryIndices.Count == 0) |
| | 51 | 344 | | _cells.Remove(cell); |
| | 52 | 345 | | } |
| | | 346 | | |
| | | 347 | | private static void RemoveEntryIndex(SwiftList<int> entryIndices, int entryIndex) |
| | | 348 | | { |
| | 52 | 349 | | entryIndices.RemoveAt(entryIndices.IndexOf(entryIndex)); |
| | 52 | 350 | | } |
| | | 351 | | |
| | | 352 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 353 | | private int FindEntryIndex(TKey key) |
| | | 354 | | { |
| | 73 | 355 | | return _keyToEntryIndex.Find(key, MatchesEntryKey); |
| | | 356 | | } |
| | | 357 | | |
| | | 358 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 359 | | private void ResizeEntryStorage(int newCapacity) |
| | | 360 | | { |
| | 5 | 361 | | Array.Resize(ref _entries, newCapacity); |
| | 5 | 362 | | _cells.EnsureCapacity(newCapacity); |
| | 5 | 363 | | _keyToEntryIndex.ResizeAndRehash(newCapacity, _peakCount, IsAllocatedEntry, GetEntryKey); |
| | 5 | 364 | | SwiftCollectionDiagnostics.Shared.Info($"Resized spatial hash entry storage to {newCapacity} entries.", _diagnos |
| | 5 | 365 | | } |
| | | 366 | | |
| | | 367 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 368 | | private int RentQueryStamp() |
| | | 369 | | { |
| | 17 | 370 | | if (_queryStamp == int.MaxValue) |
| | | 371 | | { |
| | 10 | 372 | | for (int i = 0; i < _peakCount; i++) |
| | 3 | 373 | | _entries[i].QueryStamp = 0; |
| | | 374 | | |
| | 2 | 375 | | _queryStamp = 0; |
| | 2 | 376 | | SwiftCollectionDiagnostics.Shared.Warn($"Query stamp overflow detected. Spatial hash query stamps were reset |
| | | 377 | | } |
| | | 378 | | |
| | 17 | 379 | | return ++_queryStamp; |
| | | 380 | | } |
| | | 381 | | |
| | | 382 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 383 | | private bool MatchesEntryKey(int index, TKey key) |
| | | 384 | | { |
| | 12 | 385 | | return EqualityComparer<TKey>.Default.Equals(_entries[index].Key, key); |
| | | 386 | | } |
| | | 387 | | |
| | | 388 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 31 | 389 | | private bool IsAllocatedEntry(int index) => _entries[index].IsAllocated; |
| | | 390 | | |
| | | 391 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 31 | 392 | | private TKey GetEntryKey(int index) => _entries[index].Key; |
| | | 393 | | |
| | | 394 | | private struct SpatialHashEntry |
| | | 395 | | { |
| | | 396 | | public TKey Key; |
| | | 397 | | public TVolume Bounds; |
| | | 398 | | public int QueryStamp; |
| | | 399 | | public bool IsAllocated; |
| | | 400 | | |
| | | 401 | | public void Reset() |
| | | 402 | | { |
| | 5 | 403 | | Key = default!; |
| | 5 | 404 | | Bounds = default; |
| | 5 | 405 | | QueryStamp = 0; |
| | 5 | 406 | | IsAllocated = false; |
| | 5 | 407 | | } |
| | | 408 | | } |
| | | 409 | | } |