| | | 1 | | //======================================================================= |
| | | 2 | | // GridWorld.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 FixedMathSharp; |
| | | 9 | | using GridForge.Configuration; |
| | | 10 | | using GridForge.Grids.Storage; |
| | | 11 | | using GridForge.Grids.Topology; |
| | | 12 | | using GridForge.Spatial; |
| | | 13 | | using SwiftCollections; |
| | | 14 | | using SwiftCollections.Utility; |
| | | 15 | | using System; |
| | | 16 | | using System.Collections.Generic; |
| | | 17 | | using System.Runtime.CompilerServices; |
| | | 18 | | using System.Threading; |
| | | 19 | | |
| | | 20 | | namespace GridForge.Grids; |
| | | 21 | | |
| | | 22 | | /// <summary> |
| | | 23 | | /// Owns the mutable runtime state for one GridForge world. |
| | | 24 | | /// </summary> |
| | | 25 | | public sealed class GridWorld : IDisposable |
| | | 26 | | { |
| | | 27 | | #region Constants |
| | | 28 | | |
| | | 29 | | /// <summary> |
| | | 30 | | /// Maximum number of grids that can be managed within a world. |
| | | 31 | | /// </summary> |
| | | 32 | | public const ushort MaxGrids = ushort.MaxValue - 1; |
| | | 33 | | |
| | | 34 | | /// <summary> |
| | | 35 | | /// The default rectangular cell edge in world units. |
| | | 36 | | /// </summary> |
| | 1 | 37 | | public static readonly Fixed64 DefaultRectangularCellSize = Fixed64.One; |
| | | 38 | | |
| | | 39 | | /// <summary> |
| | | 40 | | /// The default size of a spatial hash cell used for grid lookup. |
| | | 41 | | /// </summary> |
| | | 42 | | public const int DefaultSpatialGridCellSize = 50; |
| | | 43 | | |
| | | 44 | | #endregion |
| | | 45 | | |
| | | 46 | | #region Properties |
| | | 47 | | |
| | 1 | 48 | | private static readonly Comparison<VoxelIndex> CompareVoxelIndices = |
| | 1 | 49 | | static (left, right) => left.CompareTo(right); |
| | | 50 | | |
| | | 51 | | /// <summary> |
| | | 52 | | /// The size of a spatial hash cell used for grid lookup in this world. |
| | | 53 | | /// </summary> |
| | | 54 | | public int SpatialGridCellSize { get; } |
| | | 55 | | |
| | | 56 | | /// <summary> |
| | | 57 | | /// Collection of all active grids owned by this world. |
| | | 58 | | /// </summary> |
| | | 59 | | public SwiftBucket<VoxelGrid> ActiveGrids { get; } |
| | | 60 | | |
| | | 61 | | /// <summary> |
| | | 62 | | /// Dictionary mapping exact grid configuration keys to grid indices to prevent duplicate grids. |
| | | 63 | | /// </summary> |
| | | 64 | | public SwiftDictionary<GridConfigurationKey, ushort> BoundsTracker { get; } |
| | | 65 | | |
| | | 66 | | /// <summary> |
| | | 67 | | /// Dictionary mapping spatial hash keys to grid indices for fast lookups. |
| | | 68 | | /// </summary> |
| | | 69 | | public SwiftDictionary<int, SwiftHashSet<ushort>> SpatialGridHash { get; } |
| | | 70 | | |
| | | 71 | | /// <summary> |
| | | 72 | | /// Runtime token identifying this specific world instance. |
| | | 73 | | /// </summary> |
| | | 74 | | public int SpawnToken { get; private set; } |
| | | 75 | | |
| | | 76 | | /// <summary> |
| | | 77 | | /// The current version of the world, incremented on major changes. |
| | | 78 | | /// </summary> |
| | | 79 | | public uint Version { get; private set; } |
| | | 80 | | |
| | | 81 | | /// <summary> |
| | | 82 | | /// Indicates whether this world is currently active. |
| | | 83 | | /// </summary> |
| | | 84 | | public bool IsActive { get; private set; } |
| | | 85 | | |
| | | 86 | | internal Fixed64 MaxTopologyCellEdge { get; private set; } |
| | | 87 | | |
| | 427 | 88 | | private readonly ReaderWriterLockSlim _gridLock = new(); |
| | | 89 | | |
| | | 90 | | #endregion |
| | | 91 | | |
| | | 92 | | #region Events |
| | | 93 | | |
| | | 94 | | private Action<GridEventInfo>? _onActiveGridAdded; |
| | | 95 | | private Action<GridEventInfo>? _onActiveGridRemoved; |
| | | 96 | | private Action<GridEventInfo>? _onActiveGridChange; |
| | | 97 | | private Action? _onReset; |
| | | 98 | | |
| | | 99 | | /// <summary> |
| | | 100 | | /// Event triggered when a new grid is added to this world. |
| | | 101 | | /// </summary> |
| | | 102 | | public event Action<GridEventInfo> OnActiveGridAdded |
| | | 103 | | { |
| | 156 | 104 | | add => _onActiveGridAdded += value; |
| | 154 | 105 | | remove => _onActiveGridAdded -= value; |
| | | 106 | | } |
| | | 107 | | |
| | | 108 | | /// <summary> |
| | | 109 | | /// Event triggered when a grid is removed from this world. |
| | | 110 | | /// </summary> |
| | | 111 | | public event Action<GridEventInfo> OnActiveGridRemoved |
| | | 112 | | { |
| | 156 | 113 | | add => _onActiveGridRemoved += value; |
| | 154 | 114 | | remove => _onActiveGridRemoved -= value; |
| | | 115 | | } |
| | | 116 | | |
| | | 117 | | /// <summary> |
| | | 118 | | /// Event triggered when a grid in this world undergoes a significant change. |
| | | 119 | | /// </summary> |
| | | 120 | | public event Action<GridEventInfo> OnActiveGridChange |
| | | 121 | | { |
| | 161 | 122 | | add => _onActiveGridChange += value; |
| | 155 | 123 | | remove => _onActiveGridChange -= value; |
| | | 124 | | } |
| | | 125 | | |
| | | 126 | | /// <summary> |
| | | 127 | | /// Event triggered when this world is reset. |
| | | 128 | | /// </summary> |
| | | 129 | | public event Action OnReset |
| | | 130 | | { |
| | 156 | 131 | | add => _onReset += value; |
| | 154 | 132 | | remove => _onReset -= value; |
| | | 133 | | } |
| | | 134 | | |
| | | 135 | | #endregion |
| | | 136 | | |
| | | 137 | | /// <summary> |
| | | 138 | | /// Initializes a new world with the supplied spatial-hash settings. |
| | | 139 | | /// </summary> |
| | | 140 | | /// <param name="spatialGridCellSize">Optional spatial hash cell size for this world.</param> |
| | 427 | 141 | | public GridWorld(int spatialGridCellSize = DefaultSpatialGridCellSize) |
| | | 142 | | { |
| | 427 | 143 | | ActiveGrids = new SwiftBucket<VoxelGrid>(); |
| | 427 | 144 | | BoundsTracker = new SwiftDictionary<GridConfigurationKey, ushort>(); |
| | 427 | 145 | | SpatialGridHash = new SwiftDictionary<int, SwiftHashSet<ushort>>(); |
| | | 146 | | |
| | 427 | 147 | | SpatialGridCellSize = ResolveSpatialGridCellSize(spatialGridCellSize); |
| | 427 | 148 | | SpawnToken = GetHashCode(); |
| | 427 | 149 | | Version = 1; |
| | 427 | 150 | | IsActive = true; |
| | 427 | 151 | | } |
| | | 152 | | |
| | | 153 | | #region Lifecycle |
| | | 154 | | |
| | | 155 | | /// <summary> |
| | | 156 | | /// Clears all grids and spatial data owned by this world. |
| | | 157 | | /// </summary> |
| | | 158 | | /// <param name="deactivate">If true, marks the world inactive and releases its event handlers.</param> |
| | | 159 | | public void Reset(bool deactivate = false) |
| | | 160 | | { |
| | 431 | 161 | | if (!IsActive) |
| | | 162 | | { |
| | 4 | 163 | | GridForgeLogger.Channel.Warn($"Grid world not active. Cannot reset an inactive world."); |
| | 4 | 164 | | return; |
| | | 165 | | } |
| | | 166 | | |
| | 427 | 167 | | NotifyResetHandlers(); |
| | 427 | 168 | | ReleaseActiveGrids(); |
| | 427 | 169 | | GridOccupantManager.ClearTrackedOccupancies(this); |
| | | 170 | | |
| | 427 | 171 | | if (!deactivate) |
| | 4 | 172 | | return; |
| | | 173 | | |
| | 423 | 174 | | GridOccupantManager.ReleaseTrackedOccupancies(this); |
| | 423 | 175 | | IsActive = false; |
| | 423 | 176 | | SpawnToken = 0; |
| | 423 | 177 | | _onActiveGridAdded = null; |
| | 423 | 178 | | _onActiveGridRemoved = null; |
| | 423 | 179 | | _onActiveGridChange = null; |
| | 423 | 180 | | _onReset = null; |
| | 423 | 181 | | } |
| | | 182 | | |
| | | 183 | | private void NotifyResetHandlers() |
| | | 184 | | { |
| | 427 | 185 | | Action? resetHandlers = _onReset; |
| | 427 | 186 | | if (resetHandlers == null) |
| | 406 | 187 | | return; |
| | | 188 | | |
| | 21 | 189 | | var handlerDelegates = resetHandlers.GetInvocationList(); |
| | 306 | 190 | | for (int i = 0; i < handlerDelegates.Length; i++) |
| | | 191 | | { |
| | | 192 | | try |
| | | 193 | | { |
| | 132 | 194 | | ((Action)handlerDelegates[i])(); |
| | 130 | 195 | | } |
| | 2 | 196 | | catch (Exception ex) |
| | | 197 | | { |
| | 2 | 198 | | GridForgeLogger.Channel.Error($"World reset notification error: {ex.Message}"); |
| | 2 | 199 | | } |
| | | 200 | | } |
| | 21 | 201 | | } |
| | | 202 | | |
| | | 203 | | private void ReleaseActiveGrids() |
| | | 204 | | { |
| | 1610 | 205 | | foreach (VoxelGrid grid in ActiveGrids) |
| | 378 | 206 | | Pools.GridPool.Release(grid); |
| | | 207 | | |
| | 427 | 208 | | ActiveGrids.Clear(); |
| | 427 | 209 | | BoundsTracker.Clear(); |
| | 427 | 210 | | SpatialGridHash.Clear(); |
| | 427 | 211 | | MaxTopologyCellEdge = Fixed64.Zero; |
| | 427 | 212 | | } |
| | | 213 | | |
| | | 214 | | /// <inheritdoc /> |
| | | 215 | | public void Dispose() |
| | | 216 | | { |
| | 425 | 217 | | Reset(deactivate: true); |
| | 425 | 218 | | _gridLock.Dispose(); |
| | 425 | 219 | | GC.SuppressFinalize(this); |
| | 425 | 220 | | } |
| | | 221 | | |
| | | 222 | | #endregion |
| | | 223 | | |
| | | 224 | | #region Grid Management |
| | | 225 | | |
| | | 226 | | /// <summary> |
| | | 227 | | /// Adds a new grid to this world and registers it in the spatial hash. |
| | | 228 | | /// </summary> |
| | | 229 | | /// <param name="configuration">The grid configuration to normalize and register.</param> |
| | | 230 | | /// <param name="allocatedIndex">The allocated world-local grid slot on success.</param> |
| | | 231 | | /// <returns>True if the grid was added; otherwise false.</returns> |
| | | 232 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 233 | | public bool TryAddGrid(GridConfiguration configuration, out ushort allocatedIndex) => |
| | 363 | 234 | | TryAddGridCore(configuration, null, null, out allocatedIndex); |
| | | 235 | | |
| | | 236 | | /// <summary> |
| | | 237 | | /// Adds a new grid to this world and materializes the supplied sparse voxel indices when sparse storage is configur |
| | | 238 | | /// Dense grids ignore the configured voxel input and materialize every in-bounds voxel. |
| | | 239 | | /// </summary> |
| | | 240 | | /// <param name="configuration">The grid configuration to normalize and register.</param> |
| | | 241 | | /// <param name="configuredVoxels">Grid-local voxel indices to materialize for sparse storage.</param> |
| | | 242 | | /// <param name="allocatedIndex">The allocated world-local grid slot on success.</param> |
| | | 243 | | /// <returns>True if the grid was added; otherwise false.</returns> |
| | | 244 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 245 | | public bool TryAddGrid( |
| | | 246 | | GridConfiguration configuration, |
| | | 247 | | IEnumerable<VoxelIndex>? configuredVoxels, |
| | | 248 | | out ushort allocatedIndex) => |
| | 59 | 249 | | TryAddGridCore(configuration, configuredVoxels, null, out allocatedIndex); |
| | | 250 | | |
| | | 251 | | /// <summary> |
| | | 252 | | /// Adds a new grid to this world and materializes true cells from the supplied sparse voxel mask when sparse storag |
| | | 253 | | /// Dense grids ignore the configured voxel input and materialize every in-bounds voxel. |
| | | 254 | | /// </summary> |
| | | 255 | | /// <param name="configuration">The grid configuration to normalize and register.</param> |
| | | 256 | | /// <param name="configuredVoxels">A [x, y, z] mask whose true values identify sparse voxels to materialize. Sparse |
| | | 257 | | /// <param name="allocatedIndex">The allocated world-local grid slot on success.</param> |
| | | 258 | | /// <returns>True if the grid was added; otherwise false.</returns> |
| | | 259 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 260 | | public bool TryAddGrid( |
| | | 261 | | GridConfiguration configuration, |
| | | 262 | | bool[,,]? configuredVoxels, |
| | | 263 | | out ushort allocatedIndex) => |
| | 7 | 264 | | TryAddGridCore(configuration, null, configuredVoxels, out allocatedIndex); |
| | | 265 | | |
| | | 266 | | private bool TryAddGridCore( |
| | | 267 | | GridConfiguration configuration, |
| | | 268 | | IEnumerable<VoxelIndex>? configuredVoxels, |
| | | 269 | | bool[,,]? configuredVoxelMask, |
| | | 270 | | out ushort allocatedIndex) |
| | | 271 | | { |
| | 429 | 272 | | allocatedIndex = ushort.MaxValue; |
| | | 273 | | |
| | 429 | 274 | | if (!CanAddGrid()) |
| | 5 | 275 | | return false; |
| | | 276 | | |
| | 424 | 277 | | if (!TryNormalizeConfiguration( |
| | 424 | 278 | | configuration, |
| | 424 | 279 | | out GridConfiguration normalizedConfiguration, |
| | 424 | 280 | | out IGridTopology topology, |
| | 424 | 281 | | out GridDimensions dimensions) |
| | 424 | 282 | | || !TryValidateGridDimensions(dimensions)) |
| | | 283 | | { |
| | 6 | 284 | | return false; |
| | | 285 | | } |
| | | 286 | | |
| | 418 | 287 | | if (!TryPrepareConfiguredVoxels( |
| | 418 | 288 | | normalizedConfiguration, |
| | 418 | 289 | | dimensions, |
| | 418 | 290 | | configuredVoxels, |
| | 418 | 291 | | configuredVoxelMask, |
| | 418 | 292 | | out VoxelIndex[] preparedVoxels)) |
| | | 293 | | { |
| | 12 | 294 | | return false; |
| | | 295 | | } |
| | | 296 | | |
| | 406 | 297 | | GridConfigurationKey boundsKey = normalizedConfiguration.ToGridKey(); |
| | | 298 | | |
| | 406 | 299 | | if (TryFindExistingGrid(boundsKey, out allocatedIndex)) |
| | 3 | 300 | | return false; |
| | | 301 | | |
| | 403 | 302 | | VoxelGrid newGrid = Pools.GridPool.Rent(); |
| | 403 | 303 | | GridEventInfo addedGridInfo = default; |
| | | 304 | | |
| | 403 | 305 | | _gridLock.EnterWriteLock(); |
| | | 306 | | try |
| | | 307 | | { |
| | 403 | 308 | | allocatedIndex = (ushort)ActiveGrids.Add(newGrid); |
| | 403 | 309 | | BoundsTracker.Add(boundsKey, allocatedIndex); |
| | | 310 | | |
| | 403 | 311 | | newGrid.Initialize(this, allocatedIndex, normalizedConfiguration, topology, preparedVoxels); |
| | 403 | 312 | | UpdateMaxTopologyCellEdge(newGrid.Topology.MaxCellEdge); |
| | 403 | 313 | | RegisterGridSpatialCells(newGrid, allocatedIndex); |
| | | 314 | | |
| | 403 | 315 | | Version++; |
| | 403 | 316 | | addedGridInfo = CreateGridEventInfo(newGrid, GridEventKind.GridAdded); |
| | 403 | 317 | | } |
| | | 318 | | finally |
| | | 319 | | { |
| | 403 | 320 | | _gridLock.ExitWriteLock(); |
| | 403 | 321 | | } |
| | | 322 | | |
| | 403 | 323 | | NotifyActiveGridAdded(addedGridInfo); |
| | 403 | 324 | | return true; |
| | | 325 | | } |
| | | 326 | | |
| | | 327 | | /// <summary> |
| | | 328 | | /// Removes a grid from this world and updates all references to ensure integrity. |
| | | 329 | | /// </summary> |
| | | 330 | | /// <param name="removeIndex">The world-local grid slot to remove.</param> |
| | | 331 | | /// <returns>True if the grid was removed; otherwise false.</returns> |
| | | 332 | | public bool TryRemoveGrid(ushort removeIndex) |
| | | 333 | | { |
| | 27 | 334 | | if (!IsActive || !ActiveGrids.IsAllocated(removeIndex)) |
| | 2 | 335 | | return false; |
| | | 336 | | |
| | | 337 | | VoxelGrid gridToRemove; |
| | 25 | 338 | | GridEventInfo removedGridInfo = default; |
| | | 339 | | |
| | 25 | 340 | | _gridLock.EnterWriteLock(); |
| | | 341 | | try |
| | | 342 | | { |
| | 25 | 343 | | gridToRemove = ActiveGrids[removeIndex]; |
| | 25 | 344 | | Fixed64 removedMaxCellEdge = gridToRemove.Topology.MaxCellEdge; |
| | 25 | 345 | | UnregisterGridSpatialCells(gridToRemove, removeIndex); |
| | 25 | 346 | | BoundsTracker.Remove(gridToRemove.Configuration.ToGridKey()); |
| | 25 | 347 | | ActiveGrids.RemoveAt(removeIndex); |
| | 25 | 348 | | RecalculateMaxTopologyCellEdgeIfNeeded(removedMaxCellEdge); |
| | | 349 | | |
| | 25 | 350 | | Version++; |
| | 25 | 351 | | removedGridInfo = CreateGridEventInfo(gridToRemove, GridEventKind.GridRemoved); |
| | 25 | 352 | | } |
| | | 353 | | finally |
| | | 354 | | { |
| | 25 | 355 | | _gridLock.ExitWriteLock(); |
| | 25 | 356 | | } |
| | | 357 | | |
| | 25 | 358 | | Pools.GridPool.Release(gridToRemove); |
| | 25 | 359 | | NotifyActiveGridRemoved(removedGridInfo); |
| | | 360 | | |
| | 25 | 361 | | if (ActiveGrids.Count == 0) |
| | 15 | 362 | | ActiveGrids.TrimExcessCapacity(); |
| | | 363 | | |
| | 25 | 364 | | return true; |
| | | 365 | | } |
| | | 366 | | |
| | | 367 | | #endregion |
| | | 368 | | |
| | | 369 | | private bool CanAddGrid() |
| | | 370 | | { |
| | 429 | 371 | | if (!IsActive) |
| | | 372 | | { |
| | 3 | 373 | | GridForgeLogger.Channel.Error($"Grid world not active. Cannot add grids to an inactive world."); |
| | 3 | 374 | | return false; |
| | | 375 | | } |
| | | 376 | | |
| | 426 | 377 | | if ((uint)ActiveGrids.Count >= MaxGrids) |
| | | 378 | | { |
| | 2 | 379 | | GridForgeLogger.Channel.Warn($"No more grids can be added at this time."); |
| | 2 | 380 | | return false; |
| | | 381 | | } |
| | | 382 | | |
| | 424 | 383 | | return true; |
| | | 384 | | } |
| | | 385 | | |
| | | 386 | | private static bool TryPrepareConfiguredVoxels( |
| | | 387 | | GridConfiguration configuration, |
| | | 388 | | GridDimensions dimensions, |
| | | 389 | | IEnumerable<VoxelIndex>? configuredVoxels, |
| | | 390 | | bool[,,]? configuredVoxelMask, |
| | | 391 | | out VoxelIndex[] preparedVoxels) |
| | | 392 | | { |
| | 418 | 393 | | preparedVoxels = Array.Empty<VoxelIndex>(); |
| | 418 | 394 | | if (configuration.StorageKind != GridStorageKind.Sparse) |
| | 343 | 395 | | return true; |
| | | 396 | | |
| | 75 | 397 | | if (configuredVoxelMask != null) |
| | 7 | 398 | | return TryPrepareConfiguredVoxelMask(configuredVoxelMask, dimensions, out preparedVoxels); |
| | | 399 | | |
| | 68 | 400 | | return TryPrepareConfiguredVoxelIndices(configuredVoxels, dimensions, out preparedVoxels); |
| | | 401 | | } |
| | | 402 | | |
| | | 403 | | private static bool TryValidateGridDimensions(GridDimensions dimensions) |
| | | 404 | | { |
| | 423 | 405 | | long layerSize = (long)dimensions.Width * dimensions.Height; |
| | 423 | 406 | | if (layerSize > int.MaxValue || layerSize * dimensions.Length > int.MaxValue) |
| | | 407 | | { |
| | 4 | 408 | | GridForgeLogger.Channel.Warn($"Grid dimensions exceed the supported int voxel address space."); |
| | 4 | 409 | | return false; |
| | | 410 | | } |
| | | 411 | | |
| | 419 | 412 | | return true; |
| | | 413 | | } |
| | | 414 | | |
| | | 415 | | private static bool TryPrepareConfiguredVoxelMask( |
| | | 416 | | bool[,,] configuredVoxelMask, |
| | | 417 | | GridDimensions dimensions, |
| | | 418 | | out VoxelIndex[] preparedVoxels) |
| | | 419 | | { |
| | 7 | 420 | | preparedVoxels = Array.Empty<VoxelIndex>(); |
| | | 421 | | |
| | 7 | 422 | | if (configuredVoxelMask.GetLength(0) != dimensions.Width |
| | 7 | 423 | | || configuredVoxelMask.GetLength(1) != dimensions.Height |
| | 7 | 424 | | || configuredVoxelMask.GetLength(2) != dimensions.Length) |
| | | 425 | | { |
| | 5 | 426 | | GridForgeLogger.Channel.Warn($"Sparse voxel mask dimensions must match normalized grid dimensions."); |
| | 5 | 427 | | return false; |
| | | 428 | | } |
| | | 429 | | |
| | 2 | 430 | | int configuredCount = 0; |
| | 12 | 431 | | for (int x = 0; x < dimensions.Width; x++) |
| | | 432 | | { |
| | 16 | 433 | | for (int y = 0; y < dimensions.Height; y++) |
| | | 434 | | { |
| | 24 | 435 | | for (int z = 0; z < dimensions.Length; z++) |
| | | 436 | | { |
| | 8 | 437 | | if (configuredVoxelMask[x, y, z]) |
| | 2 | 438 | | configuredCount++; |
| | | 439 | | } |
| | | 440 | | } |
| | | 441 | | } |
| | | 442 | | |
| | 2 | 443 | | if (configuredCount == 0) |
| | 1 | 444 | | return true; |
| | | 445 | | |
| | 1 | 446 | | preparedVoxels = new VoxelIndex[configuredCount]; |
| | 1 | 447 | | int index = 0; |
| | 6 | 448 | | for (int x = 0; x < dimensions.Width; x++) |
| | | 449 | | { |
| | 8 | 450 | | for (int y = 0; y < dimensions.Height; y++) |
| | | 451 | | { |
| | 12 | 452 | | for (int z = 0; z < dimensions.Length; z++) |
| | | 453 | | { |
| | 4 | 454 | | if (configuredVoxelMask[x, y, z]) |
| | 2 | 455 | | preparedVoxels[index++] = new VoxelIndex(x, y, z); |
| | | 456 | | } |
| | | 457 | | } |
| | | 458 | | } |
| | | 459 | | |
| | 1 | 460 | | return true; |
| | | 461 | | } |
| | | 462 | | |
| | | 463 | | private static bool TryPrepareConfiguredVoxelIndices( |
| | | 464 | | IEnumerable<VoxelIndex>? configuredVoxels, |
| | | 465 | | GridDimensions dimensions, |
| | | 466 | | out VoxelIndex[] preparedVoxels) |
| | | 467 | | { |
| | 68 | 468 | | preparedVoxels = Array.Empty<VoxelIndex>(); |
| | 68 | 469 | | if (configuredVoxels == null) |
| | 9 | 470 | | return true; |
| | | 471 | | |
| | 59 | 472 | | SwiftList<VoxelIndex> indices = configuredVoxels is ICollection<VoxelIndex> collection |
| | 59 | 473 | | ? new SwiftList<VoxelIndex>(collection.Count) |
| | 59 | 474 | | : new SwiftList<VoxelIndex>(); |
| | | 475 | | |
| | 291 | 476 | | foreach (VoxelIndex configuredVoxel in configuredVoxels) |
| | | 477 | | { |
| | 90 | 478 | | if (!IsConfiguredVoxelInBounds(configuredVoxel, dimensions)) |
| | | 479 | | { |
| | 7 | 480 | | GridForgeLogger.Channel.Warn($"Sparse voxel index {configuredVoxel} is outside normalized grid dimension |
| | 7 | 481 | | return false; |
| | | 482 | | } |
| | | 483 | | |
| | 83 | 484 | | indices.Add(configuredVoxel); |
| | | 485 | | } |
| | | 486 | | |
| | 52 | 487 | | if (indices.Count == 0) |
| | 1 | 488 | | return true; |
| | | 489 | | |
| | 51 | 490 | | preparedVoxels = indices.ToArray(); |
| | 51 | 491 | | Array.Sort(preparedVoxels, CompareVoxelIndices); |
| | 51 | 492 | | CompactPreparedVoxels(ref preparedVoxels); |
| | 51 | 493 | | return true; |
| | 7 | 494 | | } |
| | | 495 | | |
| | | 496 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 497 | | private static bool IsConfiguredVoxelInBounds(VoxelIndex voxelIndex, GridDimensions dimensions) => |
| | 90 | 498 | | (uint)voxelIndex.x < (uint)dimensions.Width |
| | 90 | 499 | | && (uint)voxelIndex.y < (uint)dimensions.Height |
| | 90 | 500 | | && (uint)voxelIndex.z < (uint)dimensions.Length; |
| | | 501 | | |
| | | 502 | | private static void CompactPreparedVoxels(ref VoxelIndex[] preparedVoxels) |
| | | 503 | | { |
| | 51 | 504 | | if (preparedVoxels.Length < 2) |
| | 30 | 505 | | return; |
| | | 506 | | |
| | 21 | 507 | | int writeIndex = 1; |
| | 21 | 508 | | VoxelIndex previous = preparedVoxels[0]; |
| | 106 | 509 | | for (int readIndex = 1; readIndex < preparedVoxels.Length; readIndex++) |
| | | 510 | | { |
| | 32 | 511 | | VoxelIndex current = preparedVoxels[readIndex]; |
| | 32 | 512 | | if (current == previous) |
| | | 513 | | continue; |
| | | 514 | | |
| | 30 | 515 | | preparedVoxels[writeIndex++] = current; |
| | 30 | 516 | | previous = current; |
| | | 517 | | } |
| | | 518 | | |
| | 21 | 519 | | if (writeIndex != preparedVoxels.Length) |
| | 2 | 520 | | Array.Resize(ref preparedVoxels, writeIndex); |
| | 21 | 521 | | } |
| | | 522 | | |
| | | 523 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 524 | | private void UpdateMaxTopologyCellEdge(Fixed64 candidate) |
| | | 525 | | { |
| | 403 | 526 | | if (candidate > MaxTopologyCellEdge) |
| | 353 | 527 | | MaxTopologyCellEdge = candidate; |
| | 403 | 528 | | } |
| | | 529 | | |
| | | 530 | | private void RecalculateMaxTopologyCellEdgeIfNeeded(Fixed64 removedMaxCellEdge) |
| | | 531 | | { |
| | 25 | 532 | | if (removedMaxCellEdge < MaxTopologyCellEdge) |
| | 1 | 533 | | return; |
| | | 534 | | |
| | 24 | 535 | | Fixed64 maxCellEdge = Fixed64.Zero; |
| | 70 | 536 | | foreach (VoxelGrid grid in ActiveGrids) |
| | | 537 | | { |
| | 11 | 538 | | if (grid.Topology.MaxCellEdge > maxCellEdge) |
| | 9 | 539 | | maxCellEdge = grid.Topology.MaxCellEdge; |
| | | 540 | | } |
| | | 541 | | |
| | 24 | 542 | | MaxTopologyCellEdge = maxCellEdge; |
| | 24 | 543 | | } |
| | | 544 | | |
| | | 545 | | private bool TryFindExistingGrid(GridConfigurationKey boundsKey, out ushort allocatedIndex) |
| | | 546 | | { |
| | 406 | 547 | | _gridLock.EnterReadLock(); |
| | | 548 | | try |
| | | 549 | | { |
| | 406 | 550 | | if (BoundsTracker.TryGetValue(boundsKey, out allocatedIndex)) |
| | | 551 | | { |
| | 3 | 552 | | GridForgeLogger.Channel.Warn($"A grid with these bounds has already been allocated."); |
| | 3 | 553 | | return true; |
| | | 554 | | } |
| | 403 | 555 | | } |
| | | 556 | | finally |
| | | 557 | | { |
| | 406 | 558 | | _gridLock.ExitReadLock(); |
| | 406 | 559 | | } |
| | | 560 | | |
| | 403 | 561 | | allocatedIndex = ushort.MaxValue; |
| | 403 | 562 | | return false; |
| | 3 | 563 | | } |
| | | 564 | | |
| | | 565 | | private void RegisterGridSpatialCells(VoxelGrid newGrid, ushort allocatedIndex) |
| | | 566 | | { |
| | 1782 | 567 | | foreach (int cellIndex in GetSpatialGridCells(newGrid.BoundsMin, newGrid.BoundsMax)) |
| | | 568 | | { |
| | 488 | 569 | | if (!SpatialGridHash.TryGetValue(cellIndex, out SwiftHashSet<ushort> gridList)) |
| | | 570 | | { |
| | 423 | 571 | | gridList = new SwiftHashSet<ushort>(); |
| | 423 | 572 | | SpatialGridHash.Add(cellIndex, gridList); |
| | | 573 | | } |
| | | 574 | | |
| | 488 | 575 | | LinkGridWithCellNeighbors(newGrid, allocatedIndex, gridList); |
| | 488 | 576 | | gridList.Add(allocatedIndex); |
| | | 577 | | } |
| | 403 | 578 | | } |
| | | 579 | | |
| | | 580 | | private void LinkGridWithCellNeighbors( |
| | | 581 | | VoxelGrid newGrid, |
| | | 582 | | ushort allocatedIndex, |
| | | 583 | | SwiftHashSet<ushort> gridList) |
| | | 584 | | { |
| | 1128 | 585 | | foreach (ushort neighborIndex in gridList) |
| | | 586 | | { |
| | 76 | 587 | | if (!ActiveGrids.IsAllocated(neighborIndex) || neighborIndex == allocatedIndex) |
| | | 588 | | continue; |
| | | 589 | | |
| | 75 | 590 | | VoxelGrid neighborGrid = ActiveGrids[neighborIndex]; |
| | 75 | 591 | | if (!VoxelGrid.IsGridOverlapValid(newGrid, neighborGrid)) |
| | | 592 | | continue; |
| | | 593 | | |
| | 41 | 594 | | newGrid.TryAddGridNeighbor(neighborGrid); |
| | 41 | 595 | | neighborGrid.TryAddGridNeighbor(newGrid); |
| | | 596 | | } |
| | 488 | 597 | | } |
| | | 598 | | |
| | | 599 | | private void UnregisterGridSpatialCells(VoxelGrid gridToRemove, ushort removeIndex) |
| | | 600 | | { |
| | 116 | 601 | | foreach (int cellIndex in GetSpatialGridCells(gridToRemove.BoundsMin, gridToRemove.BoundsMax)) |
| | | 602 | | { |
| | 33 | 603 | | if (!SpatialGridHash.TryGetValue(cellIndex, out SwiftHashSet<ushort> gridList)) |
| | | 604 | | continue; |
| | | 605 | | |
| | 32 | 606 | | gridList.Remove(gridToRemove.GridIndex); |
| | | 607 | | |
| | 32 | 608 | | if (gridToRemove.IsConjoined) |
| | 6 | 609 | | UnlinkGridCellNeighbors(gridToRemove, removeIndex, gridList); |
| | | 610 | | |
| | 32 | 611 | | if (gridList.Count == 0) |
| | 22 | 612 | | SpatialGridHash.Remove(cellIndex); |
| | | 613 | | } |
| | 25 | 614 | | } |
| | | 615 | | |
| | | 616 | | private void UnlinkGridCellNeighbors( |
| | | 617 | | VoxelGrid gridToRemove, |
| | | 618 | | ushort removeIndex, |
| | | 619 | | SwiftHashSet<ushort> gridList) |
| | | 620 | | { |
| | 30 | 621 | | foreach (ushort neighborIndex in gridList) |
| | | 622 | | { |
| | 9 | 623 | | if (!ActiveGrids.IsAllocated(neighborIndex) || neighborIndex == removeIndex) |
| | | 624 | | continue; |
| | | 625 | | |
| | 8 | 626 | | VoxelGrid neighborGrid = ActiveGrids[neighborIndex]; |
| | 8 | 627 | | if (VoxelGrid.IsGridOverlapValid(gridToRemove, neighborGrid)) |
| | 8 | 628 | | neighborGrid.TryRemoveGridNeighbor(gridToRemove); |
| | | 629 | | } |
| | 6 | 630 | | } |
| | | 631 | | |
| | | 632 | | #region Lookup |
| | | 633 | | |
| | | 634 | | /// <summary> |
| | | 635 | | /// Retrieves a grid by its world-local index. |
| | | 636 | | /// </summary> |
| | | 637 | | /// <param name="index">The world-local grid slot to resolve.</param> |
| | | 638 | | /// <param name="outGrid">The resolved grid, if found.</param> |
| | | 639 | | /// <returns>True if the grid was resolved; otherwise false.</returns> |
| | | 640 | | public bool TryGetGrid(int index, out VoxelGrid? outGrid) |
| | | 641 | | { |
| | 348 | 642 | | outGrid = null; |
| | 348 | 643 | | if (!CanResolveGrid(index)) |
| | 13 | 644 | | return false; |
| | | 645 | | |
| | 335 | 646 | | outGrid = ActiveGrids[index]; |
| | 335 | 647 | | return true; |
| | | 648 | | } |
| | | 649 | | |
| | | 650 | | /// <summary> |
| | | 651 | | /// Retrieves the grid containing a given world position. |
| | | 652 | | /// </summary> |
| | | 653 | | /// <param name="position">The world position to resolve.</param> |
| | | 654 | | /// <param name="outGrid">The resolved grid, if found.</param> |
| | | 655 | | /// <returns>True if a containing grid was found; otherwise false.</returns> |
| | | 656 | | public bool TryGetGrid(Vector3d position, out VoxelGrid? outGrid) |
| | | 657 | | { |
| | 155 | 658 | | outGrid = null; |
| | 155 | 659 | | if (!TryGetSpatialGridCandidates(position, out SwiftHashSet<ushort>? gridList)) |
| | 3 | 660 | | return false; |
| | | 661 | | |
| | 152 | 662 | | if (TryGetContainingGrid(position, gridList!, out outGrid)) |
| | 67 | 663 | | return true; |
| | | 664 | | |
| | 85 | 665 | | GridForgeLogger.Channel.Info($"No grid contains position {position}."); |
| | 85 | 666 | | return false; |
| | | 667 | | } |
| | | 668 | | |
| | | 669 | | /// <summary> |
| | | 670 | | /// Retrieves the grid containing a 2D XZ-plane world position on the default world Y layer. |
| | | 671 | | /// </summary> |
| | | 672 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 673 | | /// <param name="outGrid">The resolved grid, if found.</param> |
| | | 674 | | /// <returns>True if a containing grid was found; otherwise false.</returns> |
| | | 675 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 676 | | public bool TryGetGrid(Vector2d position, out VoxelGrid? outGrid) => |
| | 1 | 677 | | TryGetGrid(position, default, out outGrid); |
| | | 678 | | |
| | | 679 | | /// <summary> |
| | | 680 | | /// Retrieves the grid containing a 2D XZ-plane world position on the supplied world Y layer. |
| | | 681 | | /// </summary> |
| | | 682 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 683 | | /// <param name="layerY">The world Y layer to resolve. Defaults to zero when omitted by paired overloads.</param> |
| | | 684 | | /// <param name="outGrid">The resolved grid, if found.</param> |
| | | 685 | | /// <returns>True if a containing grid was found; otherwise false.</returns> |
| | | 686 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 687 | | public bool TryGetGrid(Vector2d position, Fixed64 layerY, out VoxelGrid? outGrid) => |
| | 3 | 688 | | TryGetGrid(GridPlane2d.ToWorld(position, layerY), out outGrid); |
| | | 689 | | |
| | | 690 | | /// <summary> |
| | | 691 | | /// Retrieves the active grid whose bounds are nearest to the supplied world position. |
| | | 692 | | /// </summary> |
| | | 693 | | /// <param name="position">The world position to resolve.</param> |
| | | 694 | | /// <param name="outGrid">The closest grid, if found.</param> |
| | | 695 | | /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are |
| | | 696 | | /// <returns>True if a closest active grid was resolved; otherwise false.</returns> |
| | | 697 | | public bool TryGetClosestGrid( |
| | | 698 | | Vector3d position, |
| | | 699 | | out VoxelGrid? outGrid, |
| | | 700 | | GridTopologyKind? topologyKind = null) |
| | | 701 | | { |
| | 26 | 702 | | outGrid = null; |
| | 26 | 703 | | if (!CanResolveActiveGrid()) |
| | 1 | 704 | | return false; |
| | | 705 | | |
| | 25 | 706 | | Fixed64 closestDistanceSquared = Fixed64.MaxValue; |
| | 118 | 707 | | foreach (VoxelGrid candidateGrid in ActiveGrids) |
| | | 708 | | { |
| | 34 | 709 | | if (!candidateGrid.IsActive |
| | 34 | 710 | | || !MatchesTopologyKind(candidateGrid, topologyKind)) |
| | | 711 | | { |
| | | 712 | | continue; |
| | | 713 | | } |
| | | 714 | | |
| | 30 | 715 | | Fixed64 distanceSquared = GetDistanceSquaredToBounds(position, candidateGrid.BoundsMin, candidateGrid.Bounds |
| | 30 | 716 | | if (outGrid == null || distanceSquared < closestDistanceSquared) |
| | | 717 | | { |
| | 23 | 718 | | outGrid = candidateGrid; |
| | 23 | 719 | | closestDistanceSquared = distanceSquared; |
| | | 720 | | } |
| | | 721 | | } |
| | | 722 | | |
| | 25 | 723 | | return outGrid != null; |
| | | 724 | | } |
| | | 725 | | |
| | | 726 | | /// <summary> |
| | | 727 | | /// Retrieves the active grid whose bounds are nearest to a 2D XZ-plane world position on the default world Y layer. |
| | | 728 | | /// </summary> |
| | | 729 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 730 | | /// <param name="outGrid">The closest grid, if found.</param> |
| | | 731 | | /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are |
| | | 732 | | /// <returns>True if a closest active grid was resolved; otherwise false.</returns> |
| | | 733 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 734 | | public bool TryGetClosestGrid( |
| | | 735 | | Vector2d position, |
| | | 736 | | out VoxelGrid? outGrid, |
| | | 737 | | GridTopologyKind? topologyKind = null) => |
| | 1 | 738 | | TryGetClosestGrid(position, default, out outGrid, topologyKind); |
| | | 739 | | |
| | | 740 | | /// <summary> |
| | | 741 | | /// Retrieves the active grid whose bounds are nearest to a 2D XZ-plane world position on the supplied world Y layer |
| | | 742 | | /// </summary> |
| | | 743 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 744 | | /// <param name="layerY">The world Y layer to resolve. Defaults to zero when omitted by paired overloads.</param> |
| | | 745 | | /// <param name="outGrid">The closest grid, if found.</param> |
| | | 746 | | /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are |
| | | 747 | | /// <returns>True if a closest active grid was resolved; otherwise false.</returns> |
| | | 748 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 749 | | public bool TryGetClosestGrid( |
| | | 750 | | Vector2d position, |
| | | 751 | | Fixed64 layerY, |
| | | 752 | | out VoxelGrid? outGrid, |
| | | 753 | | GridTopologyKind? topologyKind = null) => |
| | 3 | 754 | | TryGetClosestGrid(GridPlane2d.ToWorld(position, layerY), out outGrid, topologyKind); |
| | | 755 | | |
| | | 756 | | /// <summary> |
| | | 757 | | /// Retrieves a grid by a world-scoped voxel identity. |
| | | 758 | | /// </summary> |
| | | 759 | | /// <param name="worldVoxelIndex">The voxel identity whose grid should be resolved.</param> |
| | | 760 | | /// <param name="result">The resolved grid, if found.</param> |
| | | 761 | | /// <returns>True if the grid was resolved; otherwise false.</returns> |
| | | 762 | | public bool TryGetGrid(WorldVoxelIndex worldVoxelIndex, out VoxelGrid? result) |
| | | 763 | | { |
| | 72 | 764 | | result = null; |
| | 72 | 765 | | if (worldVoxelIndex.WorldSpawnToken != SpawnToken |
| | 72 | 766 | | || !TryGetGrid(worldVoxelIndex.GridIndex, out VoxelGrid? resolvedGrid) |
| | 72 | 767 | | || worldVoxelIndex.GridSpawnToken != resolvedGrid!.SpawnToken) |
| | | 768 | | { |
| | 13 | 769 | | return false; |
| | | 770 | | } |
| | | 771 | | |
| | 59 | 772 | | result = resolvedGrid; |
| | 59 | 773 | | return true; |
| | | 774 | | } |
| | | 775 | | |
| | | 776 | | /// <summary> |
| | | 777 | | /// Retrieves the grid and voxel containing a given world position. |
| | | 778 | | /// </summary> |
| | | 779 | | /// <param name="position">The world position to resolve.</param> |
| | | 780 | | /// <param name="outGrid">The resolved grid, if found.</param> |
| | | 781 | | /// <param name="outVoxel">The resolved voxel, if found.</param> |
| | | 782 | | /// <returns>True if both the grid and voxel were resolved; otherwise false.</returns> |
| | | 783 | | public bool TryGetGridAndVoxel( |
| | | 784 | | Vector3d position, |
| | | 785 | | out VoxelGrid? outGrid, |
| | | 786 | | out Voxel? outVoxel) |
| | | 787 | | { |
| | 45 | 788 | | outVoxel = null; |
| | 45 | 789 | | return TryGetGrid(position, out outGrid) |
| | 45 | 790 | | && outGrid!.TryGetVoxel(position, out outVoxel); |
| | | 791 | | } |
| | | 792 | | |
| | | 793 | | /// <summary> |
| | | 794 | | /// Retrieves the grid and voxel containing a 2D XZ-plane world position on the default world Y layer. |
| | | 795 | | /// </summary> |
| | | 796 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 797 | | /// <param name="outGrid">The resolved grid, if found.</param> |
| | | 798 | | /// <param name="outVoxel">The resolved voxel, if found.</param> |
| | | 799 | | /// <returns>True if both the grid and voxel were resolved; otherwise false.</returns> |
| | | 800 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 801 | | public bool TryGetGridAndVoxel( |
| | | 802 | | Vector2d position, |
| | | 803 | | out VoxelGrid? outGrid, |
| | | 804 | | out Voxel? outVoxel) => |
| | 1 | 805 | | TryGetGridAndVoxel(position, default, out outGrid, out outVoxel); |
| | | 806 | | |
| | | 807 | | /// <summary> |
| | | 808 | | /// Retrieves the grid and voxel containing a 2D XZ-plane world position on the supplied world Y layer. |
| | | 809 | | /// </summary> |
| | | 810 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 811 | | /// <param name="layerY">The world Y layer to resolve. Defaults to zero when omitted by paired overloads.</param> |
| | | 812 | | /// <param name="outGrid">The resolved grid, if found.</param> |
| | | 813 | | /// <param name="outVoxel">The resolved voxel, if found.</param> |
| | | 814 | | /// <returns>True if both the grid and voxel were resolved; otherwise false.</returns> |
| | | 815 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 816 | | public bool TryGetGridAndVoxel( |
| | | 817 | | Vector2d position, |
| | | 818 | | Fixed64 layerY, |
| | | 819 | | out VoxelGrid? outGrid, |
| | | 820 | | out Voxel? outVoxel) => |
| | 3 | 821 | | TryGetGridAndVoxel(GridPlane2d.ToWorld(position, layerY), out outGrid, out outVoxel); |
| | | 822 | | |
| | | 823 | | /// <summary> |
| | | 824 | | /// Retrieves the physical voxel whose center is nearest to the supplied world position and the grid that owns it. |
| | | 825 | | /// Sparse grids only consider configured physical voxels. |
| | | 826 | | /// </summary> |
| | | 827 | | /// <param name="position">The world position to resolve.</param> |
| | | 828 | | /// <param name="outGrid">The grid that owns the closest physical voxel, if found.</param> |
| | | 829 | | /// <param name="outVoxel">The closest physical voxel, if found.</param> |
| | | 830 | | /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are |
| | | 831 | | /// <returns>True if a physical voxel was resolved; otherwise false.</returns> |
| | | 832 | | public bool TryGetClosestGridAndVoxel( |
| | | 833 | | Vector3d position, |
| | | 834 | | out VoxelGrid? outGrid, |
| | | 835 | | out Voxel? outVoxel, |
| | | 836 | | GridTopologyKind? topologyKind = null) |
| | | 837 | | { |
| | 15 | 838 | | outGrid = null; |
| | 15 | 839 | | outVoxel = null; |
| | 15 | 840 | | if (!CanResolveActiveGrid()) |
| | 2 | 841 | | return false; |
| | | 842 | | |
| | 13 | 843 | | Fixed64 closestDistanceSquared = Fixed64.MaxValue; |
| | 13 | 844 | | if (TryGetClosestGrid(position, out VoxelGrid? closestBoundsGrid, topologyKind) |
| | 13 | 845 | | && closestBoundsGrid!.ConfiguredVoxelCount != 0 |
| | 13 | 846 | | && closestBoundsGrid.TryGetClosestVoxel(position, out outVoxel, out closestDistanceSquared)) |
| | | 847 | | { |
| | 10 | 848 | | outGrid = closestBoundsGrid; |
| | | 849 | | } |
| | | 850 | | |
| | 60 | 851 | | foreach (VoxelGrid candidateGrid in ActiveGrids) |
| | | 852 | | { |
| | 17 | 853 | | if (candidateGrid == null |
| | 17 | 854 | | || !candidateGrid.IsActive |
| | 17 | 855 | | || candidateGrid.ConfiguredVoxelCount == 0 |
| | 17 | 856 | | || !MatchesTopologyKind(candidateGrid, topologyKind)) |
| | | 857 | | { |
| | | 858 | | continue; |
| | | 859 | | } |
| | 14 | 860 | | if (ReferenceEquals(candidateGrid, outGrid)) |
| | | 861 | | continue; |
| | | 862 | | |
| | 5 | 863 | | Fixed64 boundsDistanceSquared = GetDistanceSquaredToBounds(position, candidateGrid.BoundsMin, candidateGrid. |
| | 5 | 864 | | if (outVoxel != null && boundsDistanceSquared > closestDistanceSquared) |
| | | 865 | | continue; |
| | | 866 | | |
| | 4 | 867 | | candidateGrid.TryGetClosestVoxel( |
| | 4 | 868 | | position, |
| | 4 | 869 | | out Voxel? candidateVoxel, |
| | 4 | 870 | | out Fixed64 candidateDistanceSquared); |
| | | 871 | | |
| | 4 | 872 | | if (IsBetterClosestVoxel( |
| | 4 | 873 | | candidateDistanceSquared, |
| | 4 | 874 | | candidateGrid, |
| | 4 | 875 | | candidateVoxel!, |
| | 4 | 876 | | closestDistanceSquared, |
| | 4 | 877 | | outGrid, |
| | 4 | 878 | | outVoxel)) |
| | | 879 | | { |
| | 3 | 880 | | outGrid = candidateGrid; |
| | 3 | 881 | | outVoxel = candidateVoxel; |
| | 3 | 882 | | closestDistanceSquared = candidateDistanceSquared; |
| | | 883 | | } |
| | | 884 | | } |
| | | 885 | | |
| | 13 | 886 | | return outVoxel != null; |
| | | 887 | | } |
| | | 888 | | |
| | | 889 | | /// <summary> |
| | | 890 | | /// Retrieves the physical voxel whose center is nearest to a 2D XZ-plane world position on the default world Y laye |
| | | 891 | | /// Sparse grids only consider configured physical voxels. |
| | | 892 | | /// </summary> |
| | | 893 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 894 | | /// <param name="outGrid">The grid that owns the closest physical voxel, if found.</param> |
| | | 895 | | /// <param name="outVoxel">The closest physical voxel, if found.</param> |
| | | 896 | | /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are |
| | | 897 | | /// <returns>True if a physical voxel was resolved; otherwise false.</returns> |
| | | 898 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 899 | | public bool TryGetClosestGridAndVoxel( |
| | | 900 | | Vector2d position, |
| | | 901 | | out VoxelGrid? outGrid, |
| | | 902 | | out Voxel? outVoxel, |
| | | 903 | | GridTopologyKind? topologyKind = null) => |
| | 1 | 904 | | TryGetClosestGridAndVoxel(position, default, out outGrid, out outVoxel, topologyKind); |
| | | 905 | | |
| | | 906 | | /// <summary> |
| | | 907 | | /// Retrieves the physical voxel whose center is nearest to a 2D XZ-plane world position on the supplied world Y lay |
| | | 908 | | /// Sparse grids only consider configured physical voxels. |
| | | 909 | | /// </summary> |
| | | 910 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 911 | | /// <param name="layerY">The world Y layer to resolve. Defaults to zero when omitted by paired overloads.</param> |
| | | 912 | | /// <param name="outGrid">The grid that owns the closest physical voxel, if found.</param> |
| | | 913 | | /// <param name="outVoxel">The closest physical voxel, if found.</param> |
| | | 914 | | /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are |
| | | 915 | | /// <returns>True if a physical voxel was resolved; otherwise false.</returns> |
| | | 916 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 917 | | public bool TryGetClosestGridAndVoxel( |
| | | 918 | | Vector2d position, |
| | | 919 | | Fixed64 layerY, |
| | | 920 | | out VoxelGrid? outGrid, |
| | | 921 | | out Voxel? outVoxel, |
| | | 922 | | GridTopologyKind? topologyKind = null) => |
| | 3 | 923 | | TryGetClosestGridAndVoxel(GridPlane2d.ToWorld(position, layerY), out outGrid, out outVoxel, topologyKind); |
| | | 924 | | |
| | | 925 | | /// <summary> |
| | | 926 | | /// Retrieves the grid and voxel for a given voxel identity. |
| | | 927 | | /// </summary> |
| | | 928 | | /// <param name="worldVoxelIndex">The voxel identity to resolve.</param> |
| | | 929 | | /// <param name="outGrid">The resolved grid, if found.</param> |
| | | 930 | | /// <param name="result">The resolved voxel, if found.</param> |
| | | 931 | | /// <returns>True if both the grid and voxel were resolved; otherwise false.</returns> |
| | | 932 | | public bool TryGetGridAndVoxel( |
| | | 933 | | WorldVoxelIndex worldVoxelIndex, |
| | | 934 | | out VoxelGrid? outGrid, |
| | | 935 | | out Voxel? result) |
| | | 936 | | { |
| | 63 | 937 | | result = null; |
| | 63 | 938 | | return TryGetGrid(worldVoxelIndex, out outGrid) |
| | 63 | 939 | | && outGrid!.TryGetVoxel(worldVoxelIndex.VoxelIndex, out result); |
| | | 940 | | } |
| | | 941 | | |
| | | 942 | | /// <summary> |
| | | 943 | | /// Retrieves a voxel from a world position. |
| | | 944 | | /// </summary> |
| | | 945 | | /// <param name="position">The world position to resolve.</param> |
| | | 946 | | /// <param name="result">The resolved voxel, if found.</param> |
| | | 947 | | /// <returns>True if the voxel was resolved; otherwise false.</returns> |
| | | 948 | | public bool TryGetVoxel( |
| | | 949 | | Vector3d position, |
| | | 950 | | out Voxel? result) |
| | | 951 | | { |
| | 97 | 952 | | result = null; |
| | 97 | 953 | | return TryGetGrid(position, out VoxelGrid? grid) |
| | 97 | 954 | | && grid!.TryGetVoxel(position, out result); |
| | | 955 | | } |
| | | 956 | | |
| | | 957 | | /// <summary> |
| | | 958 | | /// Retrieves a voxel from a 2D XZ-plane world position on the default world Y layer. |
| | | 959 | | /// </summary> |
| | | 960 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 961 | | /// <param name="result">The resolved voxel, if found.</param> |
| | | 962 | | /// <returns>True if the voxel was resolved; otherwise false.</returns> |
| | | 963 | | public bool TryGetVoxel( |
| | | 964 | | Vector2d position, |
| | | 965 | | out Voxel? result) |
| | | 966 | | { |
| | 1 | 967 | | return TryGetVoxel(position, default, out result); |
| | | 968 | | } |
| | | 969 | | |
| | | 970 | | /// <summary> |
| | | 971 | | /// Retrieves a voxel from a 2D XZ-plane world position on the supplied world Y layer. |
| | | 972 | | /// </summary> |
| | | 973 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 974 | | /// <param name="layerY">The world Y layer to resolve. Defaults to zero when omitted by paired overloads.</param> |
| | | 975 | | /// <param name="result">The resolved voxel, if found.</param> |
| | | 976 | | /// <returns>True if the voxel was resolved; otherwise false.</returns> |
| | | 977 | | public bool TryGetVoxel( |
| | | 978 | | Vector2d position, |
| | | 979 | | Fixed64 layerY, |
| | | 980 | | out Voxel? result) |
| | | 981 | | { |
| | 3 | 982 | | return TryGetVoxel(GridPlane2d.ToWorld(position, layerY), out result); |
| | | 983 | | } |
| | | 984 | | |
| | | 985 | | /// <summary> |
| | | 986 | | /// Retrieves the physical voxel whose center is nearest to the supplied world position. |
| | | 987 | | /// Sparse grids only consider configured physical voxels. |
| | | 988 | | /// </summary> |
| | | 989 | | /// <param name="position">The world position to resolve.</param> |
| | | 990 | | /// <param name="result">The closest physical voxel, if found.</param> |
| | | 991 | | /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are |
| | | 992 | | /// <returns>True if a physical voxel was resolved; otherwise false.</returns> |
| | | 993 | | public bool TryGetClosestVoxel( |
| | | 994 | | Vector3d position, |
| | | 995 | | out Voxel? result, |
| | | 996 | | GridTopologyKind? topologyKind = null) |
| | | 997 | | { |
| | 6 | 998 | | result = null; |
| | 6 | 999 | | if (!TryGetClosestGridAndVoxel(position, out _, out Voxel? closestVoxel, topologyKind)) |
| | 2 | 1000 | | return false; |
| | | 1001 | | |
| | 4 | 1002 | | result = closestVoxel; |
| | 4 | 1003 | | return true; |
| | | 1004 | | } |
| | | 1005 | | |
| | | 1006 | | /// <summary> |
| | | 1007 | | /// Retrieves the physical voxel whose center is nearest to a 2D XZ-plane world position on the default world Y laye |
| | | 1008 | | /// Sparse grids only consider configured physical voxels. |
| | | 1009 | | /// </summary> |
| | | 1010 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 1011 | | /// <param name="result">The closest physical voxel, if found.</param> |
| | | 1012 | | /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are |
| | | 1013 | | /// <returns>True if a physical voxel was resolved; otherwise false.</returns> |
| | | 1014 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1015 | | public bool TryGetClosestVoxel( |
| | | 1016 | | Vector2d position, |
| | | 1017 | | out Voxel? result, |
| | | 1018 | | GridTopologyKind? topologyKind = null) => |
| | 1 | 1019 | | TryGetClosestVoxel(position, default, out result, topologyKind); |
| | | 1020 | | |
| | | 1021 | | /// <summary> |
| | | 1022 | | /// Retrieves the physical voxel whose center is nearest to a 2D XZ-plane world position on the supplied world Y lay |
| | | 1023 | | /// Sparse grids only consider configured physical voxels. |
| | | 1024 | | /// </summary> |
| | | 1025 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 1026 | | /// <param name="layerY">The world Y layer to resolve. Defaults to zero when omitted by paired overloads.</param> |
| | | 1027 | | /// <param name="result">The closest physical voxel, if found.</param> |
| | | 1028 | | /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are |
| | | 1029 | | /// <returns>True if a physical voxel was resolved; otherwise false.</returns> |
| | | 1030 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1031 | | public bool TryGetClosestVoxel( |
| | | 1032 | | Vector2d position, |
| | | 1033 | | Fixed64 layerY, |
| | | 1034 | | out Voxel? result, |
| | | 1035 | | GridTopologyKind? topologyKind = null) => |
| | 3 | 1036 | | TryGetClosestVoxel(GridPlane2d.ToWorld(position, layerY), out result, topologyKind); |
| | | 1037 | | |
| | | 1038 | | /// <summary> |
| | | 1039 | | /// Retrieves a voxel from a world-scoped voxel identity. |
| | | 1040 | | /// </summary> |
| | | 1041 | | /// <param name="worldVoxelIndex">The voxel identity to resolve.</param> |
| | | 1042 | | /// <param name="result">The resolved voxel, if found.</param> |
| | | 1043 | | /// <returns>True if the voxel was resolved; otherwise false.</returns> |
| | | 1044 | | public bool TryGetVoxel( |
| | | 1045 | | WorldVoxelIndex worldVoxelIndex, |
| | | 1046 | | out Voxel? result) |
| | | 1047 | | { |
| | 2 | 1048 | | result = null; |
| | 2 | 1049 | | return TryGetGrid(worldVoxelIndex, out VoxelGrid? grid) |
| | 2 | 1050 | | && grid!.TryGetVoxel(worldVoxelIndex.VoxelIndex, out result); |
| | | 1051 | | } |
| | | 1052 | | |
| | | 1053 | | #endregion |
| | | 1054 | | |
| | | 1055 | | #region Internal Helpers |
| | | 1056 | | |
| | | 1057 | | internal static bool TryNormalizeConfiguration( |
| | | 1058 | | GridConfiguration configuration, |
| | | 1059 | | out GridConfiguration normalizedConfiguration, |
| | | 1060 | | out IGridTopology topology, |
| | | 1061 | | out GridDimensions dimensions) |
| | | 1062 | | { |
| | 434 | 1063 | | normalizedConfiguration = default; |
| | 434 | 1064 | | topology = null!; |
| | 434 | 1065 | | dimensions = default; |
| | 434 | 1066 | | if (!GridTopologyFactory.TryCreate(configuration, out IGridTopology? createdTopology)) |
| | 11 | 1067 | | return false; |
| | | 1068 | | |
| | 423 | 1069 | | (Vector3d boundsMin, Vector3d boundsMax) = |
| | 423 | 1070 | | createdTopology!.NormalizeBounds(configuration.BoundsMin, configuration.BoundsMax); |
| | | 1071 | | |
| | 423 | 1072 | | normalizedConfiguration = new GridConfiguration( |
| | 423 | 1073 | | boundsMin, |
| | 423 | 1074 | | boundsMax, |
| | 423 | 1075 | | configuration.ScanCellSize, |
| | 423 | 1076 | | configuration.TopologyKind, |
| | 423 | 1077 | | configuration.TopologyMetrics, |
| | 423 | 1078 | | configuration.StorageKind); |
| | 423 | 1079 | | topology = createdTopology; |
| | 423 | 1080 | | dimensions = topology.CalculateDimensions(boundsMin, boundsMax); |
| | 423 | 1081 | | return true; |
| | | 1082 | | } |
| | | 1083 | | |
| | | 1084 | | /// <summary> |
| | | 1085 | | /// Increments the version of the specified grid and optionally the world version. |
| | | 1086 | | /// </summary> |
| | | 1087 | | public void IncrementGridVersion(int index, bool significant = false) |
| | | 1088 | | { |
| | 5 | 1089 | | if (!IsActive) |
| | | 1090 | | { |
| | 3 | 1091 | | GridForgeLogger.Channel.Warn($"Grid world not active. Cannot increment grid versions."); |
| | 3 | 1092 | | return; |
| | | 1093 | | } |
| | | 1094 | | |
| | 2 | 1095 | | _gridLock.EnterWriteLock(); |
| | | 1096 | | try |
| | | 1097 | | { |
| | 2 | 1098 | | if (significant) |
| | 1 | 1099 | | Version++; |
| | | 1100 | | |
| | 2 | 1101 | | if (ActiveGrids.IsAllocated(index)) |
| | 1 | 1102 | | ActiveGrids[index].IncrementVersion(); |
| | 2 | 1103 | | } |
| | | 1104 | | finally |
| | | 1105 | | { |
| | 2 | 1106 | | _gridLock.ExitWriteLock(); |
| | 2 | 1107 | | } |
| | 2 | 1108 | | } |
| | | 1109 | | |
| | | 1110 | | /// <summary> |
| | | 1111 | | /// Enumerates the spatial-hash cells that intersect the supplied bounds. |
| | | 1112 | | /// </summary> |
| | | 1113 | | public IEnumerable<int> GetSpatialGridCells(Vector3d min, Vector3d max) |
| | | 1114 | | { |
| | 432 | 1115 | | (int xMin, int yMin, int zMin, int xMax, int yMax, int zMax) = GetSpatialGridCellBounds(min, max); |
| | | 1116 | | |
| | 1792 | 1117 | | for (int z = zMin; z <= zMax; z++) |
| | | 1118 | | { |
| | 1856 | 1119 | | for (int y = yMin; y <= yMax; y++) |
| | | 1120 | | { |
| | 2086 | 1121 | | for (int x = xMin; x <= xMax; x++) |
| | 579 | 1122 | | yield return SwiftHashTools.CombineHashCodes(x, y, z); |
| | | 1123 | | } |
| | | 1124 | | } |
| | 432 | 1125 | | } |
| | | 1126 | | |
| | | 1127 | | /// <summary> |
| | | 1128 | | /// Computes normalized spatial-hash cell bounds for the supplied world-space bounds. |
| | | 1129 | | /// </summary> |
| | | 1130 | | internal (int xMin, int yMin, int zMin, int xMax, int yMax, int zMax) GetSpatialGridCellBounds( |
| | | 1131 | | Vector3d min, |
| | | 1132 | | Vector3d max) |
| | | 1133 | | { |
| | 1224 | 1134 | | (int xMin, int yMin, int zMin) = SnapToSpatialGrid(min); |
| | 1224 | 1135 | | (int xMax, int yMax, int zMax) = SnapToSpatialGrid(max); |
| | | 1136 | | |
| | 1224 | 1137 | | (xMin, xMax) = xMin > xMax ? (xMax, xMin) : (xMin, xMax); |
| | 1224 | 1138 | | (yMin, yMax) = yMin > yMax ? (yMax, yMin) : (yMin, yMax); |
| | 1224 | 1139 | | (zMin, zMax) = zMin > zMax ? (zMax, zMin) : (zMin, zMax); |
| | | 1140 | | |
| | 1224 | 1141 | | return (xMin, yMin, zMin, xMax, yMax, zMax); |
| | | 1142 | | } |
| | | 1143 | | |
| | | 1144 | | /// <summary> |
| | | 1145 | | /// Finds active grids in this world that overlap the supplied target grid. |
| | | 1146 | | /// </summary> |
| | | 1147 | | public IEnumerable<VoxelGrid> FindOverlappingGrids(VoxelGrid targetGrid) |
| | | 1148 | | { |
| | 5 | 1149 | | SwiftHashSet<VoxelGrid> overlappingGrids = new(); |
| | | 1150 | | |
| | 5 | 1151 | | if (!IsActive) |
| | | 1152 | | { |
| | 3 | 1153 | | GridForgeLogger.Channel.Warn($"Grid world not active. Cannot resolve overlaps."); |
| | 3 | 1154 | | return overlappingGrids; |
| | | 1155 | | } |
| | | 1156 | | |
| | 24 | 1157 | | foreach (int cellIndex in GetSpatialGridCells(targetGrid.BoundsMin, targetGrid.BoundsMax)) |
| | 10 | 1158 | | AddOverlappingGridsFromCell(targetGrid, cellIndex, overlappingGrids); |
| | | 1159 | | |
| | 2 | 1160 | | return overlappingGrids; |
| | | 1161 | | } |
| | | 1162 | | |
| | | 1163 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1164 | | private static bool MatchesTopologyKind(VoxelGrid grid, GridTopologyKind? topologyKind) => |
| | 49 | 1165 | | !topologyKind.HasValue || grid.TopologyKind == topologyKind.Value; |
| | | 1166 | | |
| | | 1167 | | private static bool IsBetterClosestVoxel( |
| | | 1168 | | Fixed64 candidateDistanceSquared, |
| | | 1169 | | VoxelGrid candidateGrid, |
| | | 1170 | | Voxel candidateVoxel, |
| | | 1171 | | Fixed64 closestDistanceSquared, |
| | | 1172 | | VoxelGrid? closestGrid, |
| | | 1173 | | Voxel? closestVoxel) |
| | | 1174 | | { |
| | 4 | 1175 | | if (closestVoxel == null || closestGrid == null) |
| | 1 | 1176 | | return true; |
| | | 1177 | | |
| | 3 | 1178 | | if (candidateDistanceSquared != closestDistanceSquared) |
| | 1 | 1179 | | return candidateDistanceSquared < closestDistanceSquared; |
| | | 1180 | | |
| | 2 | 1181 | | return candidateGrid.GridIndex < closestGrid.GridIndex; |
| | | 1182 | | } |
| | | 1183 | | |
| | | 1184 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1185 | | private static Fixed64 GetDistanceSquaredToBounds(Vector3d position, Vector3d boundsMin, Vector3d boundsMax) |
| | | 1186 | | { |
| | 35 | 1187 | | Fixed64 x = GetAxisDistanceToBounds(position.X, boundsMin.X, boundsMax.X); |
| | 35 | 1188 | | Fixed64 y = GetAxisDistanceToBounds(position.Y, boundsMin.Y, boundsMax.Y); |
| | 35 | 1189 | | Fixed64 z = GetAxisDistanceToBounds(position.Z, boundsMin.Z, boundsMax.Z); |
| | 35 | 1190 | | return x * x + y * y + z * z; |
| | | 1191 | | } |
| | | 1192 | | |
| | | 1193 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1194 | | private static Fixed64 GetAxisDistanceToBounds(Fixed64 coordinate, Fixed64 min, Fixed64 max) |
| | | 1195 | | { |
| | 105 | 1196 | | if (coordinate < min) |
| | 17 | 1197 | | return min - coordinate; |
| | | 1198 | | |
| | 88 | 1199 | | return coordinate > max ? coordinate - max : Fixed64.Zero; |
| | | 1200 | | } |
| | | 1201 | | |
| | | 1202 | | private bool CanResolveGrid(int index) |
| | | 1203 | | { |
| | 348 | 1204 | | if (!CanResolveActiveGrid()) |
| | 2 | 1205 | | return false; |
| | | 1206 | | |
| | 346 | 1207 | | if (!IsGridIndexInActiveRange(index)) |
| | | 1208 | | { |
| | 7 | 1209 | | GridForgeLogger.Channel.Error($"GridIndex '{index}' is out-of-bounds for ActiveGrids."); |
| | 7 | 1210 | | return false; |
| | | 1211 | | } |
| | | 1212 | | |
| | 339 | 1213 | | return IsGridIndexAllocated(index); |
| | | 1214 | | } |
| | | 1215 | | |
| | | 1216 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1217 | | private bool CanResolveActiveGrid() |
| | | 1218 | | { |
| | 389 | 1219 | | if (IsActive) |
| | 384 | 1220 | | return true; |
| | | 1221 | | |
| | 5 | 1222 | | GridForgeLogger.Channel.Warn($"Grid world not active. Cannot resolve grids."); |
| | 5 | 1223 | | return false; |
| | | 1224 | | } |
| | | 1225 | | |
| | | 1226 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1227 | | private bool IsGridIndexInActiveRange(int index) => |
| | 346 | 1228 | | (uint)index < MaxGrids && (uint)index <= ActiveGrids.Count; |
| | | 1229 | | |
| | | 1230 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1231 | | private bool IsGridIndexAllocated(int index) |
| | | 1232 | | { |
| | 339 | 1233 | | if (ActiveGrids.IsAllocated(index)) |
| | 335 | 1234 | | return true; |
| | | 1235 | | |
| | 4 | 1236 | | GridForgeLogger.Channel.Error($"GridIndex '{index}' has not been allocated to ActiveGrids."); |
| | 4 | 1237 | | return false; |
| | | 1238 | | } |
| | | 1239 | | |
| | | 1240 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1241 | | private bool TryGetSpatialGridCandidates( |
| | | 1242 | | Vector3d position, |
| | | 1243 | | out SwiftHashSet<ushort>? gridList) |
| | | 1244 | | { |
| | 155 | 1245 | | gridList = null; |
| | 155 | 1246 | | if (!IsActive) |
| | | 1247 | | { |
| | 2 | 1248 | | GridForgeLogger.Channel.Warn($"Grid world not active. Cannot resolve positions."); |
| | 2 | 1249 | | return false; |
| | | 1250 | | } |
| | | 1251 | | |
| | 153 | 1252 | | return SpatialGridHash.TryGetValue(GetSpatialGridKey(position), out gridList); |
| | | 1253 | | } |
| | | 1254 | | |
| | | 1255 | | private bool TryGetContainingGrid( |
| | | 1256 | | Vector3d position, |
| | | 1257 | | SwiftHashSet<ushort> gridList, |
| | | 1258 | | out VoxelGrid? outGrid) |
| | | 1259 | | { |
| | 152 | 1260 | | outGrid = null; |
| | | 1261 | | |
| | 573 | 1262 | | foreach (ushort candidateIndex in gridList) |
| | | 1263 | | { |
| | 168 | 1264 | | if (TryGetActiveGridCandidate(candidateIndex, out VoxelGrid? candidateGrid) |
| | 168 | 1265 | | && candidateGrid!.IsInBounds(position)) |
| | | 1266 | | { |
| | 67 | 1267 | | outGrid = candidateGrid; |
| | 67 | 1268 | | return true; |
| | | 1269 | | } |
| | | 1270 | | } |
| | | 1271 | | |
| | 85 | 1272 | | return false; |
| | 67 | 1273 | | } |
| | | 1274 | | |
| | | 1275 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1276 | | private bool TryGetActiveGridCandidate(ushort gridIndex, out VoxelGrid? grid) |
| | | 1277 | | { |
| | 175 | 1278 | | grid = null; |
| | 175 | 1279 | | if (!ActiveGrids.IsAllocated(gridIndex)) |
| | 2 | 1280 | | return false; |
| | | 1281 | | |
| | 173 | 1282 | | grid = ActiveGrids[gridIndex]; |
| | 173 | 1283 | | return grid.IsActive; |
| | | 1284 | | } |
| | | 1285 | | |
| | | 1286 | | private void AddOverlappingGridsFromCell( |
| | | 1287 | | VoxelGrid targetGrid, |
| | | 1288 | | int cellIndex, |
| | | 1289 | | SwiftHashSet<VoxelGrid> overlappingGrids) |
| | | 1290 | | { |
| | 10 | 1291 | | if (!SpatialGridHash.TryGetValue(cellIndex, out SwiftHashSet<ushort> gridList)) |
| | 1 | 1292 | | return; |
| | | 1293 | | |
| | 50 | 1294 | | foreach (ushort neighborIndex in gridList) |
| | 16 | 1295 | | TryAddOverlappingGrid(targetGrid, neighborIndex, overlappingGrids); |
| | 9 | 1296 | | } |
| | | 1297 | | |
| | | 1298 | | private void TryAddOverlappingGrid( |
| | | 1299 | | VoxelGrid targetGrid, |
| | | 1300 | | ushort neighborIndex, |
| | | 1301 | | SwiftHashSet<VoxelGrid> overlappingGrids) |
| | | 1302 | | { |
| | 16 | 1303 | | if (neighborIndex == targetGrid.GridIndex |
| | 16 | 1304 | | || !TryGetActiveGridCandidate(neighborIndex, out VoxelGrid? neighborGrid)) |
| | | 1305 | | { |
| | 10 | 1306 | | return; |
| | | 1307 | | } |
| | | 1308 | | |
| | 6 | 1309 | | if (VoxelGrid.IsGridOverlapValid(targetGrid, neighborGrid!)) |
| | 4 | 1310 | | overlappingGrids.Add(neighborGrid!); |
| | 6 | 1311 | | } |
| | | 1312 | | |
| | | 1313 | | /// <summary> |
| | | 1314 | | /// Computes the spatial-hash key for the supplied world-space position. |
| | | 1315 | | /// </summary> |
| | | 1316 | | public int GetSpatialGridKey(Vector3d position) |
| | | 1317 | | { |
| | 163 | 1318 | | (int x, int y, int z) = ( |
| | 163 | 1319 | | position.X.FloorToInt() / SpatialGridCellSize, |
| | 163 | 1320 | | position.Y.FloorToInt() / SpatialGridCellSize, |
| | 163 | 1321 | | position.Z.FloorToInt() / SpatialGridCellSize |
| | 163 | 1322 | | ); |
| | | 1323 | | |
| | 163 | 1324 | | return SwiftHashTools.CombineHashCodes(x, y, z); |
| | | 1325 | | } |
| | | 1326 | | |
| | | 1327 | | internal void NotifyActiveGridChange(VoxelGrid? grid) |
| | | 1328 | | { |
| | 1381 | 1329 | | if (grid == null || !grid.IsActive) |
| | 4 | 1330 | | return; |
| | | 1331 | | |
| | 1377 | 1332 | | NotifyActiveGridChange(CreateGridEventInfo(grid, GridEventKind.GridChanged)); |
| | 1377 | 1333 | | } |
| | | 1334 | | |
| | | 1335 | | internal void NotifyActiveGridChange( |
| | | 1336 | | VoxelGrid? grid, |
| | | 1337 | | GridEventKind changeKind, |
| | | 1338 | | VoxelIndex voxelIndex, |
| | | 1339 | | Vector3d affectedPosition) |
| | | 1340 | | { |
| | 46 | 1341 | | if (grid == null || !grid.IsActive) |
| | 2 | 1342 | | return; |
| | | 1343 | | |
| | 44 | 1344 | | NotifyActiveGridChange(CreateGridEventInfo(grid, changeKind, voxelIndex, affectedPosition, affectedPosition)); |
| | 44 | 1345 | | } |
| | | 1346 | | |
| | | 1347 | | #endregion |
| | | 1348 | | |
| | | 1349 | | #region Private Helpers |
| | | 1350 | | |
| | | 1351 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1352 | | private static int ResolveSpatialGridCellSize(int spatialGridCellSize) |
| | | 1353 | | { |
| | 427 | 1354 | | if (spatialGridCellSize <= 0) |
| | | 1355 | | { |
| | 3 | 1356 | | GridForgeLogger.Channel.Warn($"Spatial grid cell size must be greater than zero. Falling back to default siz |
| | 3 | 1357 | | return DefaultSpatialGridCellSize; |
| | | 1358 | | } |
| | | 1359 | | |
| | 424 | 1360 | | return spatialGridCellSize; |
| | | 1361 | | } |
| | | 1362 | | |
| | | 1363 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1364 | | private GridEventInfo CreateGridEventInfo(VoxelGrid grid, GridEventKind changeKind) => |
| | 1805 | 1365 | | new( |
| | 1805 | 1366 | | SpawnToken, |
| | 1805 | 1367 | | grid.GridIndex, |
| | 1805 | 1368 | | grid.SpawnToken, |
| | 1805 | 1369 | | grid.Configuration, |
| | 1805 | 1370 | | grid.Version, |
| | 1805 | 1371 | | changeKind, |
| | 1805 | 1372 | | default, |
| | 1805 | 1373 | | grid.BoundsMin, |
| | 1805 | 1374 | | grid.BoundsMax); |
| | | 1375 | | |
| | | 1376 | | private GridEventInfo CreateGridEventInfo( |
| | | 1377 | | VoxelGrid grid, |
| | | 1378 | | GridEventKind changeKind, |
| | | 1379 | | VoxelIndex voxelIndex, |
| | | 1380 | | Vector3d affectedBoundsMin, |
| | | 1381 | | Vector3d affectedBoundsMax) => |
| | 44 | 1382 | | new( |
| | 44 | 1383 | | SpawnToken, |
| | 44 | 1384 | | grid.GridIndex, |
| | 44 | 1385 | | grid.SpawnToken, |
| | 44 | 1386 | | grid.Configuration, |
| | 44 | 1387 | | grid.Version, |
| | 44 | 1388 | | changeKind, |
| | 44 | 1389 | | voxelIndex, |
| | 44 | 1390 | | affectedBoundsMin, |
| | 44 | 1391 | | affectedBoundsMax); |
| | | 1392 | | |
| | | 1393 | | private void NotifyActiveGridAdded(GridEventInfo eventInfo) |
| | | 1394 | | { |
| | 403 | 1395 | | Action<GridEventInfo>? handlers = _onActiveGridAdded; |
| | 403 | 1396 | | if (handlers == null) |
| | 394 | 1397 | | return; |
| | | 1398 | | |
| | 9 | 1399 | | var handlerDelegates = handlers.GetInvocationList(); |
| | 38 | 1400 | | for (int i = 0; i < handlerDelegates.Length; i++) |
| | | 1401 | | { |
| | | 1402 | | try |
| | | 1403 | | { |
| | 10 | 1404 | | ((Action<GridEventInfo>)handlerDelegates[i])(eventInfo); |
| | 9 | 1405 | | } |
| | 1 | 1406 | | catch (Exception ex) |
| | | 1407 | | { |
| | 1 | 1408 | | GridForgeLogger.Channel.Error($"[Grid {eventInfo.GridIndex}] added notification error: {ex.Message}"); |
| | 1 | 1409 | | } |
| | | 1410 | | } |
| | 9 | 1411 | | } |
| | | 1412 | | |
| | | 1413 | | private void NotifyActiveGridRemoved(GridEventInfo eventInfo) |
| | | 1414 | | { |
| | 25 | 1415 | | Action<GridEventInfo>? handlers = _onActiveGridRemoved; |
| | 25 | 1416 | | if (handlers == null) |
| | 20 | 1417 | | return; |
| | | 1418 | | |
| | 5 | 1419 | | var handlerDelegates = handlers.GetInvocationList(); |
| | 22 | 1420 | | for (int i = 0; i < handlerDelegates.Length; i++) |
| | | 1421 | | { |
| | | 1422 | | try |
| | | 1423 | | { |
| | 6 | 1424 | | ((Action<GridEventInfo>)handlerDelegates[i])(eventInfo); |
| | 5 | 1425 | | } |
| | 1 | 1426 | | catch (Exception ex) |
| | | 1427 | | { |
| | 1 | 1428 | | GridForgeLogger.Channel.Error($"[Grid {eventInfo.GridIndex}] removed notification error: {ex.Message}"); |
| | 1 | 1429 | | } |
| | | 1430 | | } |
| | 5 | 1431 | | } |
| | | 1432 | | |
| | | 1433 | | private void NotifyActiveGridChange(GridEventInfo eventInfo) |
| | | 1434 | | { |
| | 1421 | 1435 | | Action<GridEventInfo>? handlers = _onActiveGridChange; |
| | 1421 | 1436 | | if (handlers == null) |
| | 626 | 1437 | | return; |
| | | 1438 | | |
| | 795 | 1439 | | var handlerDelegates = handlers.GetInvocationList(); |
| | 44188 | 1440 | | for (int i = 0; i < handlerDelegates.Length; i++) |
| | | 1441 | | { |
| | | 1442 | | try |
| | | 1443 | | { |
| | 21299 | 1444 | | ((Action<GridEventInfo>)handlerDelegates[i])(eventInfo); |
| | 21297 | 1445 | | } |
| | 2 | 1446 | | catch (Exception ex) |
| | | 1447 | | { |
| | 2 | 1448 | | GridForgeLogger.Channel.Error($"[Grid {eventInfo.GridIndex}] change notification error: {ex.Message}"); |
| | 2 | 1449 | | } |
| | | 1450 | | } |
| | 795 | 1451 | | } |
| | | 1452 | | |
| | | 1453 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1454 | | private (int xMin, int yMin, int zMin) SnapToSpatialGrid(Vector3d position) |
| | | 1455 | | { |
| | 2448 | 1456 | | return ( |
| | 2448 | 1457 | | (position.X.Abs() / SpatialGridCellSize).FloorToInt() * position.X.Sign(), |
| | 2448 | 1458 | | (position.Y.Abs() / SpatialGridCellSize).FloorToInt() * position.Y.Sign(), |
| | 2448 | 1459 | | (position.Z.Abs() / SpatialGridCellSize).FloorToInt() * position.Z.Sign() |
| | 2448 | 1460 | | ); |
| | | 1461 | | } |
| | | 1462 | | |
| | | 1463 | | #endregion |
| | | 1464 | | } |