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