| | | 1 | | using FixedMathSharp; |
| | | 2 | | using GridForge.Configuration; |
| | | 3 | | using GridForge.Spatial; |
| | | 4 | | using SwiftCollections; |
| | | 5 | | using System; |
| | | 6 | | using System.Collections.Generic; |
| | | 7 | | using System.Threading; |
| | | 8 | | |
| | | 9 | | namespace GridForge.Grids; |
| | | 10 | | |
| | | 11 | | /// <summary> |
| | | 12 | | /// Owns the mutable runtime state for one GridForge world. |
| | | 13 | | /// </summary> |
| | | 14 | | public sealed class GridWorld : IDisposable |
| | | 15 | | { |
| | | 16 | | #region Constants |
| | | 17 | | |
| | | 18 | | /// <summary> |
| | | 19 | | /// Maximum number of grids that can be managed within a world. |
| | | 20 | | /// </summary> |
| | | 21 | | public const ushort MaxGrids = ushort.MaxValue - 1; |
| | | 22 | | |
| | | 23 | | /// <summary> |
| | | 24 | | /// The default size of each grid voxel in world units. |
| | | 25 | | /// </summary> |
| | 1 | 26 | | public static readonly Fixed64 DefaultVoxelSize = Fixed64.One; |
| | | 27 | | |
| | | 28 | | /// <summary> |
| | | 29 | | /// The default size of a spatial hash cell used for grid lookup. |
| | | 30 | | /// </summary> |
| | | 31 | | public const int DefaultSpatialGridCellSize = 50; |
| | | 32 | | |
| | | 33 | | #endregion |
| | | 34 | | |
| | | 35 | | #region Properties |
| | | 36 | | |
| | | 37 | | /// <summary> |
| | | 38 | | /// The size of each grid voxel in world units for this world. |
| | | 39 | | /// </summary> |
| | 249562 | 40 | | public Fixed64 VoxelSize { get; } |
| | | 41 | | |
| | | 42 | | /// <summary> |
| | | 43 | | /// The size of a spatial hash cell used for grid lookup in this world. |
| | | 44 | | /// </summary> |
| | 4344 | 45 | | public int SpatialGridCellSize { get; } |
| | | 46 | | |
| | | 47 | | /// <summary> |
| | | 48 | | /// Resolution for snapping or searching within the grid. |
| | | 49 | | /// </summary> |
| | 30 | 50 | | public Fixed64 VoxelResolution => VoxelSize * Fixed64.Half; |
| | | 51 | | |
| | | 52 | | /// <summary> |
| | | 53 | | /// Collection of all active grids owned by this world. |
| | | 54 | | /// </summary> |
| | 2956 | 55 | | public SwiftBucket<VoxelGrid> ActiveGrids { get; } |
| | | 56 | | |
| | | 57 | | /// <summary> |
| | | 58 | | /// Dictionary mapping exact bounds keys to grid indices to prevent duplicate grids. |
| | | 59 | | /// </summary> |
| | 555 | 60 | | public SwiftDictionary<BoundsKey, ushort> BoundsTracker { get; } |
| | | 61 | | |
| | | 62 | | /// <summary> |
| | | 63 | | /// Dictionary mapping spatial hash keys to grid indices for fast lookups. |
| | | 64 | | /// </summary> |
| | 1750 | 65 | | public SwiftDictionary<int, SwiftHashSet<ushort>> SpatialGridHash { get; } |
| | | 66 | | |
| | | 67 | | /// <summary> |
| | | 68 | | /// Runtime token identifying this specific world instance. |
| | | 69 | | /// </summary> |
| | 80442 | 70 | | public int SpawnToken { get; private set; } |
| | | 71 | | |
| | | 72 | | /// <summary> |
| | | 73 | | /// The current version of the world, incremented on major changes. |
| | | 74 | | /// </summary> |
| | 570 | 75 | | public uint Version { get; private set; } |
| | | 76 | | |
| | | 77 | | /// <summary> |
| | | 78 | | /// Indicates whether this world is currently active. |
| | | 79 | | /// </summary> |
| | 1779 | 80 | | public bool IsActive { get; private set; } |
| | | 81 | | |
| | 182 | 82 | | private readonly ReaderWriterLockSlim _gridLock = new(); |
| | | 83 | | |
| | | 84 | | #endregion |
| | | 85 | | |
| | | 86 | | #region Events |
| | | 87 | | |
| | | 88 | | private Action<GridEventInfo>? _onActiveGridAdded; |
| | | 89 | | private Action<GridEventInfo>? _onActiveGridRemoved; |
| | | 90 | | private Action<GridEventInfo>? _onActiveGridChange; |
| | | 91 | | private Action? _onReset; |
| | | 92 | | |
| | | 93 | | /// <summary> |
| | | 94 | | /// Event triggered when a new grid is added to this world. |
| | | 95 | | /// </summary> |
| | | 96 | | public event Action<GridEventInfo> OnActiveGridAdded |
| | | 97 | | { |
| | 135 | 98 | | add => _onActiveGridAdded += value; |
| | 135 | 99 | | remove => _onActiveGridAdded -= value; |
| | | 100 | | } |
| | | 101 | | |
| | | 102 | | /// <summary> |
| | | 103 | | /// Event triggered when a grid is removed from this world. |
| | | 104 | | /// </summary> |
| | | 105 | | public event Action<GridEventInfo> OnActiveGridRemoved |
| | | 106 | | { |
| | 135 | 107 | | add => _onActiveGridRemoved += value; |
| | 135 | 108 | | remove => _onActiveGridRemoved -= value; |
| | | 109 | | } |
| | | 110 | | |
| | | 111 | | /// <summary> |
| | | 112 | | /// Event triggered when a grid in this world undergoes a significant change. |
| | | 113 | | /// </summary> |
| | | 114 | | public event Action<GridEventInfo> OnActiveGridChange |
| | | 115 | | { |
| | 0 | 116 | | add => _onActiveGridChange += value; |
| | 0 | 117 | | remove => _onActiveGridChange -= value; |
| | | 118 | | } |
| | | 119 | | |
| | | 120 | | /// <summary> |
| | | 121 | | /// Event triggered when this world is reset. |
| | | 122 | | /// </summary> |
| | | 123 | | public event Action OnReset |
| | | 124 | | { |
| | 135 | 125 | | add => _onReset += value; |
| | 135 | 126 | | remove => _onReset -= value; |
| | | 127 | | } |
| | | 128 | | |
| | | 129 | | #endregion |
| | | 130 | | |
| | | 131 | | /// <summary> |
| | | 132 | | /// Initializes a new world with the supplied voxel and spatial-hash settings. |
| | | 133 | | /// </summary> |
| | | 134 | | /// <param name="voxelSize">Optional voxel size for this world.</param> |
| | | 135 | | /// <param name="spatialGridCellSize">Optional spatial hash cell size for this world.</param> |
| | 182 | 136 | | public GridWorld( |
| | 182 | 137 | | Fixed64? voxelSize = null, |
| | 182 | 138 | | int spatialGridCellSize = DefaultSpatialGridCellSize) |
| | | 139 | | { |
| | 182 | 140 | | ActiveGrids = new SwiftBucket<VoxelGrid>(); |
| | 182 | 141 | | BoundsTracker = new SwiftDictionary<BoundsKey, ushort>(); |
| | 182 | 142 | | SpatialGridHash = new SwiftDictionary<int, SwiftHashSet<ushort>>(); |
| | | 143 | | |
| | 182 | 144 | | VoxelSize = ResolveVoxelSize(voxelSize); |
| | 182 | 145 | | SpatialGridCellSize = ResolveSpatialGridCellSize(spatialGridCellSize); |
| | 182 | 146 | | SpawnToken = GetHashCode(); |
| | 182 | 147 | | Version = 1; |
| | 182 | 148 | | IsActive = true; |
| | 182 | 149 | | } |
| | | 150 | | |
| | | 151 | | #region Lifecycle |
| | | 152 | | |
| | | 153 | | /// <summary> |
| | | 154 | | /// Clears all grids and spatial data owned by this world. |
| | | 155 | | /// </summary> |
| | | 156 | | /// <param name="deactivate">If true, marks the world inactive and releases its event handlers.</param> |
| | | 157 | | public void Reset(bool deactivate = false) |
| | | 158 | | { |
| | 179 | 159 | | if (!IsActive) |
| | | 160 | | { |
| | 0 | 161 | | GridForgeLogger.Channel.Warn($"Grid world not active. Cannot reset an inactive world."); |
| | 0 | 162 | | return; |
| | | 163 | | } |
| | | 164 | | |
| | 179 | 165 | | Action? resetHandlers = _onReset; |
| | 179 | 166 | | if (resetHandlers != null) |
| | | 167 | | { |
| | 16 | 168 | | var handlerDelegates = resetHandlers.GetInvocationList(); |
| | 282 | 169 | | for (int i = 0; i < handlerDelegates.Length; i++) |
| | | 170 | | { |
| | | 171 | | try |
| | | 172 | | { |
| | 125 | 173 | | ((Action)handlerDelegates[i])(); |
| | 125 | 174 | | } |
| | 0 | 175 | | catch (Exception ex) |
| | | 176 | | { |
| | 0 | 177 | | GridForgeLogger.Channel.Error($"World reset notification error: {ex.Message}"); |
| | 0 | 178 | | } |
| | | 179 | | } |
| | | 180 | | } |
| | | 181 | | |
| | 698 | 182 | | foreach (VoxelGrid grid in ActiveGrids) |
| | 170 | 183 | | Pools.GridPool.Release(grid); |
| | | 184 | | |
| | 179 | 185 | | ActiveGrids.Clear(); |
| | 179 | 186 | | BoundsTracker.Clear(); |
| | 179 | 187 | | SpatialGridHash.Clear(); |
| | 179 | 188 | | GridOccupantManager.ClearTrackedOccupancies(this); |
| | | 189 | | |
| | 179 | 190 | | if (!deactivate) |
| | 1 | 191 | | return; |
| | | 192 | | |
| | 178 | 193 | | GridOccupantManager.ReleaseTrackedOccupancies(this); |
| | 178 | 194 | | IsActive = false; |
| | 178 | 195 | | SpawnToken = 0; |
| | 178 | 196 | | _onActiveGridAdded = null; |
| | 178 | 197 | | _onActiveGridRemoved = null; |
| | 178 | 198 | | _onActiveGridChange = null; |
| | 178 | 199 | | _onReset = null; |
| | 178 | 200 | | } |
| | | 201 | | |
| | | 202 | | /// <inheritdoc /> |
| | | 203 | | public void Dispose() |
| | | 204 | | { |
| | 178 | 205 | | Reset(deactivate: true); |
| | 178 | 206 | | _gridLock.Dispose(); |
| | 178 | 207 | | GC.SuppressFinalize(this); |
| | 178 | 208 | | } |
| | | 209 | | |
| | | 210 | | #endregion |
| | | 211 | | |
| | | 212 | | #region Grid Management |
| | | 213 | | |
| | | 214 | | /// <summary> |
| | | 215 | | /// Adds a new grid to this world and registers it in the spatial hash. |
| | | 216 | | /// </summary> |
| | | 217 | | /// <param name="configuration">The grid configuration to normalize and register.</param> |
| | | 218 | | /// <param name="allocatedIndex">The allocated world-local grid slot on success.</param> |
| | | 219 | | /// <returns>True if the grid was added; otherwise false.</returns> |
| | | 220 | | public bool TryAddGrid(GridConfiguration configuration, out ushort allocatedIndex) |
| | | 221 | | { |
| | 182 | 222 | | allocatedIndex = ushort.MaxValue; |
| | | 223 | | |
| | 182 | 224 | | if (!IsActive) |
| | | 225 | | { |
| | 0 | 226 | | GridForgeLogger.Channel.Error($"Grid world not active. Cannot add grids to an inactive world."); |
| | 0 | 227 | | return false; |
| | | 228 | | } |
| | | 229 | | |
| | 182 | 230 | | if ((uint)ActiveGrids.Count > MaxGrids) |
| | | 231 | | { |
| | 0 | 232 | | GridForgeLogger.Channel.Warn($"No more grids can be added at this time."); |
| | 0 | 233 | | return false; |
| | | 234 | | } |
| | | 235 | | |
| | 182 | 236 | | GridConfiguration normalizedConfiguration = NormalizeConfiguration(configuration); |
| | 182 | 237 | | BoundsKey boundsKey = normalizedConfiguration.ToBoundsKey(); |
| | | 238 | | |
| | 182 | 239 | | _gridLock.EnterReadLock(); |
| | | 240 | | try |
| | | 241 | | { |
| | 182 | 242 | | if (BoundsTracker.TryGetValue(boundsKey, out allocatedIndex)) |
| | | 243 | | { |
| | 0 | 244 | | GridForgeLogger.Channel.Warn($"A grid with these bounds has already been allocated."); |
| | 0 | 245 | | return false; |
| | | 246 | | } |
| | 182 | 247 | | } |
| | | 248 | | finally |
| | | 249 | | { |
| | 182 | 250 | | _gridLock.ExitReadLock(); |
| | 182 | 251 | | } |
| | | 252 | | |
| | 182 | 253 | | VoxelGrid newGrid = Pools.GridPool.Rent(); |
| | 182 | 254 | | GridEventInfo addedGridInfo = default; |
| | | 255 | | |
| | 182 | 256 | | _gridLock.EnterWriteLock(); |
| | | 257 | | try |
| | | 258 | | { |
| | 182 | 259 | | allocatedIndex = (ushort)ActiveGrids.Add(newGrid); |
| | 182 | 260 | | BoundsTracker.Add(boundsKey, allocatedIndex); |
| | | 261 | | |
| | 182 | 262 | | newGrid.Initialize(this, allocatedIndex, normalizedConfiguration); |
| | 812 | 263 | | foreach (int cellIndex in GetSpatialGridCells(normalizedConfiguration.BoundsMin, normalizedConfiguration.Bou |
| | | 264 | | { |
| | 224 | 265 | | if (!SpatialGridHash.ContainsKey(cellIndex)) |
| | 206 | 266 | | SpatialGridHash.Add(cellIndex, new SwiftHashSet<ushort>()); |
| | | 267 | | |
| | 494 | 268 | | foreach (ushort neighborIndex in SpatialGridHash[cellIndex]) |
| | | 269 | | { |
| | 23 | 270 | | if (!ActiveGrids.IsAllocated(neighborIndex) || neighborIndex == allocatedIndex) |
| | | 271 | | continue; |
| | | 272 | | |
| | 23 | 273 | | VoxelGrid neighborGrid = ActiveGrids[neighborIndex]; |
| | 23 | 274 | | if (!VoxelGrid.IsGridOverlapValid(newGrid, neighborGrid)) |
| | | 275 | | continue; |
| | | 276 | | |
| | 14 | 277 | | newGrid.TryAddGridNeighbor(neighborGrid); |
| | 14 | 278 | | neighborGrid.TryAddGridNeighbor(newGrid); |
| | | 279 | | } |
| | | 280 | | |
| | 224 | 281 | | SpatialGridHash[cellIndex].Add(allocatedIndex); |
| | | 282 | | } |
| | | 283 | | |
| | 182 | 284 | | Version++; |
| | 182 | 285 | | addedGridInfo = CreateGridEventInfo(newGrid); |
| | 182 | 286 | | } |
| | | 287 | | finally |
| | | 288 | | { |
| | 182 | 289 | | _gridLock.ExitWriteLock(); |
| | 182 | 290 | | } |
| | | 291 | | |
| | 182 | 292 | | NotifyActiveGridAdded(addedGridInfo); |
| | 182 | 293 | | return true; |
| | 0 | 294 | | } |
| | | 295 | | |
| | | 296 | | /// <summary> |
| | | 297 | | /// Removes a grid from this world and updates all references to ensure integrity. |
| | | 298 | | /// </summary> |
| | | 299 | | /// <param name="removeIndex">The world-local grid slot to remove.</param> |
| | | 300 | | /// <returns>True if the grid was removed; otherwise false.</returns> |
| | | 301 | | public bool TryRemoveGrid(ushort removeIndex) |
| | | 302 | | { |
| | 12 | 303 | | if (!IsActive || !ActiveGrids.IsAllocated(removeIndex)) |
| | 0 | 304 | | return false; |
| | | 305 | | |
| | | 306 | | VoxelGrid gridToRemove; |
| | 12 | 307 | | GridEventInfo removedGridInfo = default; |
| | | 308 | | |
| | 12 | 309 | | _gridLock.EnterWriteLock(); |
| | | 310 | | try |
| | | 311 | | { |
| | 12 | 312 | | gridToRemove = ActiveGrids[removeIndex]; |
| | 48 | 313 | | foreach (int cellIndex in GetSpatialGridCells(gridToRemove.BoundsMin, gridToRemove.BoundsMax)) |
| | | 314 | | { |
| | 12 | 315 | | if (!SpatialGridHash.ContainsKey(cellIndex)) |
| | | 316 | | continue; |
| | | 317 | | |
| | 12 | 318 | | SpatialGridHash[cellIndex].Remove(gridToRemove.GridIndex); |
| | | 319 | | |
| | 12 | 320 | | if (gridToRemove.IsConjoined) |
| | | 321 | | { |
| | 20 | 322 | | foreach (ushort neighborIndex in SpatialGridHash[cellIndex]) |
| | | 323 | | { |
| | 6 | 324 | | if (!ActiveGrids.IsAllocated(neighborIndex) || neighborIndex == removeIndex) |
| | | 325 | | continue; |
| | | 326 | | |
| | 6 | 327 | | VoxelGrid neighborGrid = ActiveGrids[neighborIndex]; |
| | 6 | 328 | | if (!VoxelGrid.IsGridOverlapValid(gridToRemove, neighborGrid)) |
| | | 329 | | continue; |
| | | 330 | | |
| | 6 | 331 | | neighborGrid.TryRemoveGridNeighbor(gridToRemove); |
| | | 332 | | } |
| | | 333 | | } |
| | | 334 | | |
| | 12 | 335 | | if (SpatialGridHash[cellIndex].Count == 0) |
| | 6 | 336 | | SpatialGridHash.Remove(cellIndex); |
| | | 337 | | } |
| | | 338 | | |
| | 12 | 339 | | BoundsTracker.Remove(gridToRemove.Configuration.ToBoundsKey()); |
| | 12 | 340 | | ActiveGrids.RemoveAt(removeIndex); |
| | | 341 | | |
| | 12 | 342 | | Version++; |
| | 12 | 343 | | removedGridInfo = CreateGridEventInfo(gridToRemove); |
| | 12 | 344 | | } |
| | | 345 | | finally |
| | | 346 | | { |
| | 12 | 347 | | _gridLock.ExitWriteLock(); |
| | 12 | 348 | | } |
| | | 349 | | |
| | 12 | 350 | | Pools.GridPool.Release(gridToRemove); |
| | 12 | 351 | | NotifyActiveGridRemoved(removedGridInfo); |
| | | 352 | | |
| | 12 | 353 | | if (ActiveGrids.Count == 0) |
| | 6 | 354 | | ActiveGrids.TrimExcessCapacity(); |
| | | 355 | | |
| | 12 | 356 | | return true; |
| | | 357 | | } |
| | | 358 | | |
| | | 359 | | #endregion |
| | | 360 | | |
| | | 361 | | #region Lookup |
| | | 362 | | |
| | | 363 | | /// <summary> |
| | | 364 | | /// Retrieves a grid by its world-local index. |
| | | 365 | | /// </summary> |
| | | 366 | | /// <param name="index">The world-local grid slot to resolve.</param> |
| | | 367 | | /// <param name="outGrid">The resolved grid, if found.</param> |
| | | 368 | | /// <returns>True if the grid was resolved; otherwise false.</returns> |
| | | 369 | | public bool TryGetGrid(int index, out VoxelGrid? outGrid) |
| | | 370 | | { |
| | 275 | 371 | | outGrid = null; |
| | 275 | 372 | | if (!IsActive) |
| | | 373 | | { |
| | 0 | 374 | | GridForgeLogger.Channel.Warn($"Grid world not active. Cannot resolve grids."); |
| | 0 | 375 | | return false; |
| | | 376 | | } |
| | | 377 | | |
| | 275 | 378 | | if ((uint)index > ActiveGrids.Count) |
| | | 379 | | { |
| | 0 | 380 | | GridForgeLogger.Channel.Error($"GridIndex '{index}' is out-of-bounds for ActiveGrids."); |
| | 0 | 381 | | return false; |
| | | 382 | | } |
| | | 383 | | |
| | 275 | 384 | | if (!ActiveGrids.IsAllocated(index)) |
| | | 385 | | { |
| | 1 | 386 | | GridForgeLogger.Channel.Error($"GridIndex '{index}' has not been allocated to ActiveGrids."); |
| | 1 | 387 | | return false; |
| | | 388 | | } |
| | | 389 | | |
| | 274 | 390 | | outGrid = ActiveGrids[index]; |
| | 274 | 391 | | return true; |
| | | 392 | | } |
| | | 393 | | |
| | | 394 | | /// <summary> |
| | | 395 | | /// Retrieves the grid containing a given world position. |
| | | 396 | | /// </summary> |
| | | 397 | | /// <param name="position">The world position to resolve.</param> |
| | | 398 | | /// <param name="outGrid">The resolved grid, if found.</param> |
| | | 399 | | /// <returns>True if a containing grid was found; otherwise false.</returns> |
| | | 400 | | public bool TryGetGrid(Vector3d position, out VoxelGrid? outGrid) |
| | | 401 | | { |
| | 197 | 402 | | outGrid = null; |
| | 197 | 403 | | if (!IsActive) |
| | | 404 | | { |
| | 0 | 405 | | GridForgeLogger.Channel.Warn($"Grid world not active. Cannot resolve positions."); |
| | 0 | 406 | | return false; |
| | | 407 | | } |
| | | 408 | | |
| | 197 | 409 | | int cellIndex = GetSpatialGridKey(position); |
| | 197 | 410 | | if (!SpatialGridHash.TryGetValue(cellIndex, out SwiftHashSet<ushort> gridList)) |
| | 1 | 411 | | return false; |
| | | 412 | | |
| | 866 | 413 | | foreach (ushort candidateIndex in gridList) |
| | | 414 | | { |
| | 246 | 415 | | if (!TryGetGrid(candidateIndex, out VoxelGrid? candidateGrid) || !ActiveGrids[candidateIndex].IsActive) |
| | | 416 | | continue; |
| | | 417 | | |
| | 246 | 418 | | if (candidateGrid?.IsInBounds(position) == true) |
| | | 419 | | { |
| | 18 | 420 | | outGrid = candidateGrid; |
| | 18 | 421 | | return true; |
| | | 422 | | } |
| | | 423 | | } |
| | | 424 | | |
| | 178 | 425 | | GridForgeLogger.Channel.Info($"No grid contains position {position}."); |
| | 178 | 426 | | return false; |
| | 18 | 427 | | } |
| | | 428 | | |
| | | 429 | | /// <summary> |
| | | 430 | | /// Retrieves a grid by a world-scoped voxel identity. |
| | | 431 | | /// </summary> |
| | | 432 | | /// <param name="worldVoxelIndex">The voxel identity whose grid should be resolved.</param> |
| | | 433 | | /// <param name="result">The resolved grid, if found.</param> |
| | | 434 | | /// <returns>True if the grid was resolved; otherwise false.</returns> |
| | | 435 | | public bool TryGetGrid(WorldVoxelIndex worldVoxelIndex, out VoxelGrid? result) |
| | | 436 | | { |
| | 35 | 437 | | result = null; |
| | 35 | 438 | | if (worldVoxelIndex.WorldSpawnToken != SpawnToken |
| | 35 | 439 | | || !TryGetGrid(worldVoxelIndex.GridIndex, out VoxelGrid? resolvedGrid) |
| | 35 | 440 | | || worldVoxelIndex.GridSpawnToken != resolvedGrid?.SpawnToken) |
| | | 441 | | { |
| | 12 | 442 | | return false; |
| | | 443 | | } |
| | | 444 | | |
| | 23 | 445 | | result = resolvedGrid; |
| | 23 | 446 | | return true; |
| | | 447 | | } |
| | | 448 | | |
| | | 449 | | /// <summary> |
| | | 450 | | /// Retrieves the grid and voxel containing a given world position. |
| | | 451 | | /// </summary> |
| | | 452 | | /// <param name="position">The world position to resolve.</param> |
| | | 453 | | /// <param name="outGrid">The resolved grid, if found.</param> |
| | | 454 | | /// <param name="outVoxel">The resolved voxel, if found.</param> |
| | | 455 | | /// <returns>True if both the grid and voxel were resolved; otherwise false.</returns> |
| | | 456 | | public bool TryGetGridAndVoxel( |
| | | 457 | | Vector3d position, |
| | | 458 | | out VoxelGrid? outGrid, |
| | | 459 | | out Voxel? outVoxel) |
| | | 460 | | { |
| | 14 | 461 | | outVoxel = null; |
| | 14 | 462 | | return TryGetGrid(position, out outGrid) |
| | 14 | 463 | | && outGrid?.TryGetVoxel(position, out outVoxel) == true; |
| | | 464 | | } |
| | | 465 | | |
| | | 466 | | /// <summary> |
| | | 467 | | /// Retrieves the grid and voxel for a given voxel identity. |
| | | 468 | | /// </summary> |
| | | 469 | | /// <param name="worldVoxelIndex">The voxel identity to resolve.</param> |
| | | 470 | | /// <param name="outGrid">The resolved grid, if found.</param> |
| | | 471 | | /// <param name="result">The resolved voxel, if found.</param> |
| | | 472 | | /// <returns>True if both the grid and voxel were resolved; otherwise false.</returns> |
| | | 473 | | public bool TryGetGridAndVoxel( |
| | | 474 | | WorldVoxelIndex worldVoxelIndex, |
| | | 475 | | out VoxelGrid? outGrid, |
| | | 476 | | out Voxel? result) |
| | | 477 | | { |
| | 33 | 478 | | result = null; |
| | 33 | 479 | | return TryGetGrid(worldVoxelIndex, out outGrid) |
| | 33 | 480 | | && outGrid?.TryGetVoxel(worldVoxelIndex.VoxelIndex, out result) == true; |
| | | 481 | | } |
| | | 482 | | |
| | | 483 | | /// <summary> |
| | | 484 | | /// Retrieves a voxel from a world position. |
| | | 485 | | /// </summary> |
| | | 486 | | /// <param name="position">The world position to resolve.</param> |
| | | 487 | | /// <param name="result">The resolved voxel, if found.</param> |
| | | 488 | | /// <returns>True if the voxel was resolved; otherwise false.</returns> |
| | | 489 | | public bool TryGetVoxel( |
| | | 490 | | Vector3d position, |
| | | 491 | | out Voxel? result) |
| | | 492 | | { |
| | 183 | 493 | | result = null; |
| | 183 | 494 | | return TryGetGrid(position, out VoxelGrid? grid) |
| | 183 | 495 | | && grid?.TryGetVoxel(position, out result) == true; |
| | | 496 | | } |
| | | 497 | | |
| | | 498 | | /// <summary> |
| | | 499 | | /// Retrieves a voxel from a world-scoped voxel identity. |
| | | 500 | | /// </summary> |
| | | 501 | | /// <param name="worldVoxelIndex">The voxel identity to resolve.</param> |
| | | 502 | | /// <param name="result">The resolved voxel, if found.</param> |
| | | 503 | | /// <returns>True if the voxel was resolved; otherwise false.</returns> |
| | | 504 | | public bool TryGetVoxel( |
| | | 505 | | WorldVoxelIndex worldVoxelIndex, |
| | | 506 | | out Voxel? result) |
| | | 507 | | { |
| | 1 | 508 | | result = null; |
| | 1 | 509 | | return TryGetGrid(worldVoxelIndex, out VoxelGrid? grid) |
| | 1 | 510 | | && grid?.TryGetVoxel(worldVoxelIndex.VoxelIndex, out result) == true; |
| | | 511 | | } |
| | | 512 | | |
| | | 513 | | #endregion |
| | | 514 | | |
| | | 515 | | #region Internal Helpers |
| | | 516 | | |
| | | 517 | | internal GridConfiguration NormalizeConfiguration(GridConfiguration configuration) |
| | | 518 | | { |
| | 182 | 519 | | (Vector3d boundsMin, Vector3d boundsMax) = |
| | 182 | 520 | | SnapBoundsToVoxelSize(configuration.BoundsMin, configuration.BoundsMax); |
| | | 521 | | |
| | 182 | 522 | | return new GridConfiguration(boundsMin, boundsMax, configuration.ScanCellSize); |
| | | 523 | | } |
| | | 524 | | |
| | | 525 | | /// <summary> |
| | | 526 | | /// Increments the version of the specified grid and optionally the world version. |
| | | 527 | | /// </summary> |
| | | 528 | | public void IncrementGridVersion(int index, bool significant = false) |
| | | 529 | | { |
| | 0 | 530 | | if (!IsActive) |
| | | 531 | | { |
| | 0 | 532 | | GridForgeLogger.Channel.Warn($"Grid world not active. Cannot increment grid versions."); |
| | 0 | 533 | | return; |
| | | 534 | | } |
| | | 535 | | |
| | 0 | 536 | | _gridLock.EnterWriteLock(); |
| | | 537 | | try |
| | | 538 | | { |
| | 0 | 539 | | if (significant) |
| | 0 | 540 | | Version++; |
| | | 541 | | |
| | 0 | 542 | | if (ActiveGrids.IsAllocated(index)) |
| | 0 | 543 | | ActiveGrids[index].IncrementVersion(); |
| | 0 | 544 | | } |
| | | 545 | | finally |
| | | 546 | | { |
| | 0 | 547 | | _gridLock.ExitWriteLock(); |
| | 0 | 548 | | } |
| | 0 | 549 | | } |
| | | 550 | | |
| | | 551 | | /// <summary> |
| | | 552 | | /// Enumerates the spatial-hash cells that intersect the supplied bounds. |
| | | 553 | | /// </summary> |
| | | 554 | | public IEnumerable<int> GetSpatialGridCells(Vector3d min, Vector3d max) |
| | | 555 | | { |
| | 359 | 556 | | (int xMin, int yMin, int zMin, int xMax, int yMax, int zMax) = GetSpatialGridCellBounds(min, max); |
| | | 557 | | |
| | 1460 | 558 | | for (int z = zMin; z <= zMax; z++) |
| | | 559 | | { |
| | 1484 | 560 | | for (int y = yMin; y <= yMax; y++) |
| | | 561 | | { |
| | 1572 | 562 | | for (int x = xMin; x <= xMax; x++) |
| | 415 | 563 | | yield return SwiftHashTools.CombineHashCodes(x, y, z); |
| | | 564 | | } |
| | | 565 | | } |
| | 359 | 566 | | } |
| | | 567 | | |
| | | 568 | | /// <summary> |
| | | 569 | | /// Computes normalized spatial-hash cell bounds for the supplied world-space bounds. |
| | | 570 | | /// </summary> |
| | | 571 | | internal (int xMin, int yMin, int zMin, int xMax, int yMax, int zMax) GetSpatialGridCellBounds( |
| | | 572 | | Vector3d min, |
| | | 573 | | Vector3d max) |
| | | 574 | | { |
| | 624 | 575 | | (int xMin, int yMin, int zMin) = SnapToSpatialGrid(min); |
| | 624 | 576 | | (int xMax, int yMax, int zMax) = SnapToSpatialGrid(max); |
| | | 577 | | |
| | 624 | 578 | | (xMin, xMax) = xMin > xMax ? (xMax, xMin) : (xMin, xMax); |
| | 624 | 579 | | (yMin, yMax) = yMin > yMax ? (yMax, yMin) : (yMin, yMax); |
| | 624 | 580 | | (zMin, zMax) = zMin > zMax ? (zMax, zMin) : (zMin, zMax); |
| | | 581 | | |
| | 624 | 582 | | return (xMin, yMin, zMin, xMax, yMax, zMax); |
| | | 583 | | } |
| | | 584 | | |
| | | 585 | | /// <summary> |
| | | 586 | | /// Finds active grids in this world that overlap the supplied target grid. |
| | | 587 | | /// </summary> |
| | | 588 | | public IEnumerable<VoxelGrid> FindOverlappingGrids(VoxelGrid targetGrid) |
| | | 589 | | { |
| | 0 | 590 | | SwiftHashSet<VoxelGrid> overlappingGrids = new(); |
| | | 591 | | |
| | 0 | 592 | | if (!IsActive) |
| | | 593 | | { |
| | 0 | 594 | | GridForgeLogger.Channel.Warn($"Grid world not active. Cannot resolve overlaps."); |
| | 0 | 595 | | return overlappingGrids; |
| | | 596 | | } |
| | | 597 | | |
| | 0 | 598 | | foreach (int cellIndex in GetSpatialGridCells(targetGrid.BoundsMin, targetGrid.BoundsMax)) |
| | | 599 | | { |
| | 0 | 600 | | if (!SpatialGridHash.TryGetValue(cellIndex, out SwiftHashSet<ushort> gridList)) |
| | | 601 | | continue; |
| | | 602 | | |
| | 0 | 603 | | foreach (ushort neighborIndex in gridList) |
| | | 604 | | { |
| | 0 | 605 | | if (!ActiveGrids.IsAllocated(neighborIndex) || neighborIndex == targetGrid.GridIndex) |
| | | 606 | | continue; |
| | | 607 | | |
| | 0 | 608 | | VoxelGrid neighborGrid = ActiveGrids[neighborIndex]; |
| | 0 | 609 | | if (VoxelGrid.IsGridOverlapValid(targetGrid, neighborGrid)) |
| | 0 | 610 | | overlappingGrids.Add(neighborGrid); |
| | | 611 | | } |
| | | 612 | | } |
| | | 613 | | |
| | 0 | 614 | | return overlappingGrids; |
| | | 615 | | } |
| | | 616 | | |
| | | 617 | | /// <summary> |
| | | 618 | | /// Computes the spatial-hash key for the supplied world-space position. |
| | | 619 | | /// </summary> |
| | | 620 | | public int GetSpatialGridKey(Vector3d position) |
| | | 621 | | { |
| | 200 | 622 | | (int x, int y, int z) = ( |
| | 200 | 623 | | position.x.FloorToInt() / SpatialGridCellSize, |
| | 200 | 624 | | position.y.FloorToInt() / SpatialGridCellSize, |
| | 200 | 625 | | position.z.FloorToInt() / SpatialGridCellSize |
| | 200 | 626 | | ); |
| | | 627 | | |
| | 200 | 628 | | return SwiftHashTools.CombineHashCodes(x, y, z); |
| | | 629 | | } |
| | | 630 | | |
| | | 631 | | /// <summary> |
| | | 632 | | /// Ceil-snaps a world-space position to this world's voxel size. |
| | | 633 | | /// </summary> |
| | | 634 | | public Vector3d CeilToVoxelSize(Vector3d position) |
| | | 635 | | { |
| | 613 | 636 | | return new Vector3d( |
| | 613 | 637 | | (position.x.Abs() / VoxelSize).CeilToInt() * VoxelSize * position.x.Sign(), |
| | 613 | 638 | | (position.y.Abs() / VoxelSize).CeilToInt() * VoxelSize * position.y.Sign(), |
| | 613 | 639 | | (position.z.Abs() / VoxelSize).CeilToInt() * VoxelSize * position.z.Sign() |
| | 613 | 640 | | ); |
| | | 641 | | } |
| | | 642 | | |
| | | 643 | | /// <summary> |
| | | 644 | | /// Floor-snaps a world-space position to this world's voxel size. |
| | | 645 | | /// </summary> |
| | | 646 | | public Vector3d FloorToVoxelSize(Vector3d position) |
| | | 647 | | { |
| | 763 | 648 | | return new Vector3d( |
| | 763 | 649 | | (position.x.Abs() / VoxelSize).FloorToInt() * VoxelSize * position.x.Sign(), |
| | 763 | 650 | | (position.y.Abs() / VoxelSize).FloorToInt() * VoxelSize * position.y.Sign(), |
| | 763 | 651 | | (position.z.Abs() / VoxelSize).FloorToInt() * VoxelSize * position.z.Sign() |
| | 763 | 652 | | ); |
| | | 653 | | } |
| | | 654 | | |
| | | 655 | | /// <summary> |
| | | 656 | | /// Snaps the supplied bounds to this world's voxel size. |
| | | 657 | | /// </summary> |
| | | 658 | | public (Vector3d min, Vector3d max) SnapBoundsToVoxelSize( |
| | | 659 | | Vector3d min, |
| | | 660 | | Vector3d max, |
| | | 661 | | Fixed64? padding = null) |
| | | 662 | | { |
| | 612 | 663 | | Fixed64 fixedPadding = padding.HasValue && padding.Value > Fixed64.Zero |
| | 612 | 664 | | ? padding.Value |
| | 612 | 665 | | : Fixed64.Zero; |
| | | 666 | | |
| | 612 | 667 | | min -= fixedPadding; |
| | 612 | 668 | | max += fixedPadding; |
| | | 669 | | |
| | 612 | 670 | | Vector3d snapMin = FloorToVoxelSize(min); |
| | 612 | 671 | | Vector3d snapMax = CeilToVoxelSize(max); |
| | | 672 | | |
| | 612 | 673 | | (snapMin.x, snapMax.x) = snapMin.x > snapMax.x ? (snapMax.x, snapMin.x) : (snapMin.x, snapMax.x); |
| | 612 | 674 | | (snapMin.y, snapMax.y) = snapMin.y > snapMax.y ? (snapMax.y, snapMin.y) : (snapMin.y, snapMax.y); |
| | 612 | 675 | | (snapMin.z, snapMax.z) = snapMin.z > snapMax.z ? (snapMax.z, snapMin.z) : (snapMin.z, snapMax.z); |
| | | 676 | | |
| | 612 | 677 | | return (snapMin, snapMax); |
| | | 678 | | } |
| | | 679 | | |
| | | 680 | | internal void NotifyActiveGridChange(VoxelGrid grid) |
| | | 681 | | { |
| | 1237 | 682 | | if (grid == null || !grid.IsActive) |
| | 0 | 683 | | return; |
| | | 684 | | |
| | 1237 | 685 | | NotifyActiveGridChange(CreateGridEventInfo(grid)); |
| | 1237 | 686 | | } |
| | | 687 | | |
| | | 688 | | #endregion |
| | | 689 | | |
| | | 690 | | #region Private Helpers |
| | | 691 | | |
| | | 692 | | private static Fixed64 ResolveVoxelSize(Fixed64? voxelSize) |
| | | 693 | | { |
| | 182 | 694 | | Fixed64 resolved = voxelSize ?? DefaultVoxelSize; |
| | 182 | 695 | | if (resolved <= Fixed64.Zero) |
| | | 696 | | { |
| | 0 | 697 | | GridForgeLogger.Channel.Warn($"Voxel size must be greater than zero. Falling back to default size {DefaultVo |
| | 0 | 698 | | return DefaultVoxelSize; |
| | | 699 | | } |
| | | 700 | | |
| | 182 | 701 | | return resolved; |
| | | 702 | | } |
| | | 703 | | |
| | | 704 | | private static int ResolveSpatialGridCellSize(int spatialGridCellSize) |
| | | 705 | | { |
| | 182 | 706 | | if (spatialGridCellSize <= 0) |
| | | 707 | | { |
| | 0 | 708 | | GridForgeLogger.Channel.Warn($"Spatial grid cell size must be greater than zero. Falling back to default siz |
| | 0 | 709 | | return DefaultSpatialGridCellSize; |
| | | 710 | | } |
| | | 711 | | |
| | 182 | 712 | | return spatialGridCellSize; |
| | | 713 | | } |
| | | 714 | | |
| | | 715 | | private GridEventInfo CreateGridEventInfo(VoxelGrid grid) |
| | | 716 | | { |
| | 1431 | 717 | | return new GridEventInfo(SpawnToken, grid.GridIndex, grid.SpawnToken, grid.Configuration, grid.Version); |
| | | 718 | | } |
| | | 719 | | |
| | | 720 | | private void NotifyActiveGridAdded(GridEventInfo eventInfo) |
| | | 721 | | { |
| | 182 | 722 | | Action<GridEventInfo>? handlers = _onActiveGridAdded; |
| | 182 | 723 | | if (handlers == null) |
| | 178 | 724 | | return; |
| | | 725 | | |
| | 4 | 726 | | var handlerDelegates = handlers.GetInvocationList(); |
| | 16 | 727 | | for (int i = 0; i < handlerDelegates.Length; i++) |
| | | 728 | | { |
| | | 729 | | try |
| | | 730 | | { |
| | 4 | 731 | | ((Action<GridEventInfo>)handlerDelegates[i])(eventInfo); |
| | 4 | 732 | | } |
| | 0 | 733 | | catch (Exception ex) |
| | | 734 | | { |
| | 0 | 735 | | GridForgeLogger.Channel.Error($"[Grid {eventInfo.GridIndex}] added notification error: {ex.Message}"); |
| | 0 | 736 | | } |
| | | 737 | | } |
| | 4 | 738 | | } |
| | | 739 | | |
| | | 740 | | private void NotifyActiveGridRemoved(GridEventInfo eventInfo) |
| | | 741 | | { |
| | 12 | 742 | | Action<GridEventInfo>? handlers = _onActiveGridRemoved; |
| | 12 | 743 | | if (handlers == null) |
| | 10 | 744 | | return; |
| | | 745 | | |
| | 2 | 746 | | var handlerDelegates = handlers.GetInvocationList(); |
| | 8 | 747 | | for (int i = 0; i < handlerDelegates.Length; i++) |
| | | 748 | | { |
| | | 749 | | try |
| | | 750 | | { |
| | 2 | 751 | | ((Action<GridEventInfo>)handlerDelegates[i])(eventInfo); |
| | 2 | 752 | | } |
| | 0 | 753 | | catch (Exception ex) |
| | | 754 | | { |
| | 0 | 755 | | GridForgeLogger.Channel.Error($"[Grid {eventInfo.GridIndex}] removed notification error: {ex.Message}"); |
| | 0 | 756 | | } |
| | | 757 | | } |
| | 2 | 758 | | } |
| | | 759 | | |
| | | 760 | | private void NotifyActiveGridChange(GridEventInfo eventInfo) |
| | | 761 | | { |
| | 1237 | 762 | | Action<GridEventInfo>? handlers = _onActiveGridChange; |
| | 1237 | 763 | | if (handlers == null) |
| | 1237 | 764 | | return; |
| | | 765 | | |
| | 0 | 766 | | var handlerDelegates = handlers.GetInvocationList(); |
| | 0 | 767 | | for (int i = 0; i < handlerDelegates.Length; i++) |
| | | 768 | | { |
| | | 769 | | try |
| | | 770 | | { |
| | 0 | 771 | | ((Action<GridEventInfo>)handlerDelegates[i])(eventInfo); |
| | 0 | 772 | | } |
| | 0 | 773 | | catch (Exception ex) |
| | | 774 | | { |
| | 0 | 775 | | GridForgeLogger.Channel.Error($"[Grid {eventInfo.GridIndex}] change notification error: {ex.Message}"); |
| | 0 | 776 | | } |
| | | 777 | | } |
| | 0 | 778 | | } |
| | | 779 | | |
| | | 780 | | private (int xMin, int yMin, int zMin) SnapToSpatialGrid(Vector3d position) |
| | | 781 | | { |
| | 1248 | 782 | | return ( |
| | 1248 | 783 | | (position.x.Abs() / SpatialGridCellSize).FloorToInt() * position.x.Sign(), |
| | 1248 | 784 | | (position.y.Abs() / SpatialGridCellSize).FloorToInt() * position.y.Sign(), |
| | 1248 | 785 | | (position.z.Abs() / SpatialGridCellSize).FloorToInt() * position.z.Sign() |
| | 1248 | 786 | | ); |
| | | 787 | | } |
| | | 788 | | |
| | | 789 | | #endregion |
| | | 790 | | } |