| | | 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 System; |
| | | 9 | | using System.Collections.Generic; |
| | | 10 | | using System.Diagnostics; |
| | | 11 | | using System.Runtime.CompilerServices; |
| | | 12 | | using System.Threading; |
| | | 13 | | using FixedMathSharp; |
| | | 14 | | using GridForge.Configuration; |
| | | 15 | | using GridForge.Grids.Storage; |
| | | 16 | | using GridForge.Grids.Topology; |
| | | 17 | | using GridForge.Spatial; |
| | | 18 | | using SwiftCollections; |
| | | 19 | | using SwiftCollections.Pool; |
| | | 20 | | using SwiftCollections.Query; |
| | | 21 | | |
| | | 22 | | namespace GridForge.Grids; |
| | | 23 | | |
| | | 24 | | /// <summary> |
| | | 25 | | /// Owns the mutable runtime state for one GridForge world. |
| | | 26 | | /// </summary> |
| | | 27 | | public sealed partial class GridWorld : IDisposable |
| | | 28 | | { |
| | | 29 | | #region Constants |
| | | 30 | | |
| | | 31 | | /// <summary> |
| | | 32 | | /// Maximum number of grids that can be managed within a world. |
| | | 33 | | /// </summary> |
| | | 34 | | public const ushort MaxGrids = ushort.MaxValue - 1; |
| | | 35 | | |
| | | 36 | | /// <summary> |
| | | 37 | | /// The default rectangular cell edge in world units. |
| | | 38 | | /// </summary> |
| | 1 | 39 | | public static readonly Fixed64 DefaultRectangularCellSize = Fixed64.One; |
| | | 40 | | |
| | | 41 | | /// <summary> |
| | | 42 | | /// The default cell size used to tune ordinary-grid lookup. |
| | | 43 | | /// Oversized grids are indexed automatically outside this tier. |
| | | 44 | | /// </summary> |
| | | 45 | | public const int DefaultSpatialGridCellSize = 50; |
| | | 46 | | |
| | | 47 | | private const int BoundaryContactSourceWordCount = (MaxGrids + 63) / 64; |
| | | 48 | | private const int BoundaryContactSourceSummaryWordCount = |
| | | 49 | | (BoundaryContactSourceWordCount + 63) / 64; |
| | | 50 | | |
| | | 51 | | #endregion |
| | | 52 | | |
| | | 53 | | #region Properties |
| | | 54 | | |
| | 1 | 55 | | private static readonly Comparison<VoxelIndex> CompareVoxelIndices = |
| | 1 | 56 | | static (left, right) => left.CompareTo(right); |
| | | 57 | | |
| | | 58 | | /// <summary> |
| | | 59 | | /// The cell size used to tune ordinary-grid lookup in this world. |
| | | 60 | | /// Oversized grids are indexed automatically outside this tier. |
| | | 61 | | /// </summary> |
| | | 62 | | public int SpatialGridCellSize { get; } |
| | | 63 | | |
| | | 64 | | /// <summary> |
| | | 65 | | /// Collection of all active grids owned by this world. |
| | | 66 | | /// </summary> |
| | | 67 | | public SwiftBucket<VoxelGrid> ActiveGrids { get; } |
| | | 68 | | |
| | | 69 | | /// <summary> |
| | | 70 | | /// Dictionary mapping exact grid configuration keys to grid indices to prevent duplicate grids. |
| | | 71 | | /// </summary> |
| | | 72 | | public SwiftDictionary<GridConfigurationKey, ushort> BoundsTracker { get; } |
| | | 73 | | |
| | | 74 | | /// <summary> |
| | | 75 | | /// Nonzero process-unique 64-bit runtime allocation token for this active world. |
| | | 76 | | /// Zero indicates an inactive world. |
| | | 77 | | /// </summary> |
| | | 78 | | public long SpawnToken { get; private set; } |
| | | 79 | | |
| | | 80 | | /// <summary> |
| | | 81 | | /// The current version of the world, incremented on major changes. |
| | | 82 | | /// </summary> |
| | | 83 | | public uint Version { get; private set; } |
| | | 84 | | |
| | | 85 | | /// <summary> |
| | | 86 | | /// The most recent world-local committed change sequence. |
| | | 87 | | /// </summary> |
| | | 88 | | public ulong ChangeSequence |
| | | 89 | | { |
| | | 90 | | get |
| | | 91 | | { |
| | 47 | 92 | | lock (ChangeSyncRoot) |
| | 47 | 93 | | return _changeSequence; |
| | 47 | 94 | | } |
| | | 95 | | } |
| | | 96 | | |
| | | 97 | | /// <summary> |
| | | 98 | | /// Indicates whether this world is currently active. |
| | | 99 | | /// </summary> |
| | | 100 | | public bool IsActive { get; private set; } |
| | | 101 | | |
| | | 102 | | internal Fixed64 MaxTopologyCellEdge { get; private set; } |
| | | 103 | | |
| | 1327 | 104 | | internal void EnterReadLock() => _gridLock.EnterReadLock(); |
| | | 105 | | |
| | 1327 | 106 | | internal void ExitReadLock() => _gridLock.ExitReadLock(); |
| | | 107 | | |
| | 565 | 108 | | internal bool IsWriteLockHeld => _gridLock.IsWriteLockHeld; |
| | | 109 | | |
| | | 110 | | private static long s_worldAllocationCounter; |
| | | 111 | | private static long s_obstacleRegistrationCounter; |
| | | 112 | | |
| | 785 | 113 | | private readonly ReaderWriterLockSlim _gridLock = new(); |
| | | 114 | | internal object ChangeSyncRoot { get; } = new object(); |
| | 785 | 115 | | private readonly SwiftQueue<GridCommittedChange> _committedChanges = new SwiftQueue<GridCommittedChange>(); |
| | 785 | 116 | | private readonly SwiftList<ushort> _gridCandidates = new(); |
| | 785 | 117 | | private readonly SwiftDictionary<ushort, SwiftList<ushort>> _boundaryContactTargetsBySource = new(); |
| | 785 | 118 | | private readonly SwiftDictionary<ushort, SwiftList<ushort>> _boundaryContactSourcesByTarget = new(); |
| | | 119 | | private readonly GridSpatialIndex _spatialIndex; |
| | | 120 | | private ulong[]? _boundaryContactSourceWords; |
| | | 121 | | private ulong[]? _boundaryContactSourceSummaryWords; |
| | | 122 | | private int _boundaryContactSourceSummaryLength; |
| | | 123 | | private long _gridGenerationCounter; |
| | | 124 | | private ulong _changeSequence; |
| | | 125 | | private ulong _publishedChangeSequence; |
| | | 126 | | private bool _isPublishingCommittedChanges; |
| | | 127 | | private volatile bool _isDisposed; |
| | | 128 | | private int _committedPublicationOwnerThreadId; |
| | | 129 | | private int _navigationMaintenanceOwnerThreadId; |
| | | 130 | | |
| | | 131 | | #endregion |
| | | 132 | | |
| | | 133 | | #region Events |
| | | 134 | | |
| | | 135 | | private Action<GridEventInfo>? _onActiveGridAdded; |
| | | 136 | | private Action<GridEventInfo>? _onActiveGridRemoved; |
| | | 137 | | private Action<GridEventInfo>? _onActiveGridChange; |
| | | 138 | | private Action<GridEventInfo>? _onChangeCommitted; |
| | | 139 | | private Action? _onReset; |
| | | 140 | | |
| | | 141 | | /// <summary> |
| | | 142 | | /// Event triggered when a new grid is added to this world. |
| | | 143 | | /// </summary> |
| | | 144 | | public event Action<GridEventInfo> OnActiveGridAdded |
| | | 145 | | { |
| | | 146 | | add |
| | | 147 | | { |
| | 171 | 148 | | lock (ChangeSyncRoot) |
| | 171 | 149 | | _onActiveGridAdded += value; |
| | 171 | 150 | | } |
| | | 151 | | remove |
| | | 152 | | { |
| | 168 | 153 | | lock (ChangeSyncRoot) |
| | 168 | 154 | | _onActiveGridAdded -= value; |
| | 168 | 155 | | } |
| | | 156 | | } |
| | | 157 | | |
| | | 158 | | /// <summary> |
| | | 159 | | /// Event triggered when a grid is removed from this world. |
| | | 160 | | /// </summary> |
| | | 161 | | public event Action<GridEventInfo> OnActiveGridRemoved |
| | | 162 | | { |
| | | 163 | | add |
| | | 164 | | { |
| | 171 | 165 | | lock (ChangeSyncRoot) |
| | 171 | 166 | | _onActiveGridRemoved += value; |
| | 171 | 167 | | } |
| | | 168 | | remove |
| | | 169 | | { |
| | 168 | 170 | | lock (ChangeSyncRoot) |
| | 168 | 171 | | _onActiveGridRemoved -= value; |
| | 168 | 172 | | } |
| | | 173 | | } |
| | | 174 | | |
| | | 175 | | /// <summary> |
| | | 176 | | /// Event triggered when a grid in this world undergoes a significant change. |
| | | 177 | | /// </summary> |
| | | 178 | | public event Action<GridEventInfo> OnActiveGridChange |
| | | 179 | | { |
| | | 180 | | add |
| | | 181 | | { |
| | 175 | 182 | | lock (ChangeSyncRoot) |
| | 175 | 183 | | _onActiveGridChange += value; |
| | 175 | 184 | | } |
| | | 185 | | remove |
| | | 186 | | { |
| | 169 | 187 | | lock (ChangeSyncRoot) |
| | 169 | 188 | | _onActiveGridChange -= value; |
| | 169 | 189 | | } |
| | | 190 | | } |
| | | 191 | | |
| | | 192 | | /// <summary> |
| | | 193 | | /// Receives every committed grid lifecycle, sparse-presence, and obstacle mutation in |
| | | 194 | | /// ascending <see cref="GridEventInfo.ChangeSequence"/> order. |
| | | 195 | | /// </summary> |
| | | 196 | | public event Action<GridEventInfo> OnChangeCommitted |
| | | 197 | | { |
| | | 198 | | add |
| | | 199 | | { |
| | 13 | 200 | | lock (ChangeSyncRoot) |
| | 13 | 201 | | _onChangeCommitted += value; |
| | 13 | 202 | | } |
| | | 203 | | remove |
| | | 204 | | { |
| | 7 | 205 | | lock (ChangeSyncRoot) |
| | 7 | 206 | | _onChangeCommitted -= value; |
| | 7 | 207 | | } |
| | | 208 | | } |
| | | 209 | | |
| | | 210 | | /// <summary> |
| | | 211 | | /// Event triggered when this world is reset. |
| | | 212 | | /// </summary> |
| | | 213 | | public event Action OnReset |
| | | 214 | | { |
| | | 215 | | add |
| | | 216 | | { |
| | 171 | 217 | | lock (ChangeSyncRoot) |
| | 171 | 218 | | _onReset += value; |
| | 171 | 219 | | } |
| | | 220 | | remove |
| | | 221 | | { |
| | 168 | 222 | | lock (ChangeSyncRoot) |
| | 168 | 223 | | _onReset -= value; |
| | 168 | 224 | | } |
| | | 225 | | } |
| | | 226 | | |
| | | 227 | | #endregion |
| | | 228 | | |
| | | 229 | | /// <summary> |
| | | 230 | | /// Initializes a new world with optional ordinary-grid lookup tuning. |
| | | 231 | | /// </summary> |
| | | 232 | | /// <param name="spatialGridCellSize">Optional ordinary-grid lookup cell size for this world.</param> |
| | 785 | 233 | | public GridWorld(int spatialGridCellSize = DefaultSpatialGridCellSize) |
| | | 234 | | { |
| | 785 | 235 | | ActiveGrids = new SwiftBucket<VoxelGrid>(); |
| | 785 | 236 | | BoundsTracker = new SwiftDictionary<GridConfigurationKey, ushort>(); |
| | | 237 | | |
| | 785 | 238 | | SpatialGridCellSize = ResolveSpatialGridCellSize(spatialGridCellSize); |
| | 785 | 239 | | _spatialIndex = new GridSpatialIndex(SpatialGridCellSize); |
| | 785 | 240 | | SpawnToken = RuntimeIdentityAllocator.Allocate(ref s_worldAllocationCounter); |
| | 785 | 241 | | Version = 1; |
| | 785 | 242 | | IsActive = true; |
| | 785 | 243 | | } |
| | | 244 | | |
| | | 245 | | #region Lifecycle |
| | | 246 | | |
| | | 247 | | /// <summary> |
| | | 248 | | /// Clears all grids and spatial data owned by this world. |
| | | 249 | | /// </summary> |
| | | 250 | | /// <param name="deactivate">If true, marks the world inactive and releases its event handlers.</param> |
| | | 251 | | public void Reset(bool deactivate = false) |
| | | 252 | | { |
| | 801 | 253 | | if (!IsActive) |
| | | 254 | | { |
| | 9 | 255 | | GridForgeLogger.Channel.Warn($"Grid world not active. Cannot reset an inactive world."); |
| | 9 | 256 | | return; |
| | | 257 | | } |
| | | 258 | | |
| | 792 | 259 | | NotifyResetHandlers(); |
| | | 260 | | bool drainCommittedChanges; |
| | 792 | 261 | | _gridLock.EnterWriteLock(); |
| | | 262 | | try |
| | | 263 | | { |
| | 792 | 264 | | lock (ChangeSyncRoot) |
| | | 265 | | { |
| | 792 | 266 | | bool wasPublishingCommittedChanges = _isPublishingCommittedChanges; |
| | 792 | 267 | | ReleaseActiveGrids(); |
| | 792 | 268 | | GridOccupantManager.ClearTrackedOccupancies(this); |
| | 792 | 269 | | Version++; |
| | | 270 | | |
| | 792 | 271 | | GridEventInfo resetEvent = new GridEventInfo( |
| | 792 | 272 | | SpawnToken, |
| | 792 | 273 | | ushort.MaxValue, |
| | 792 | 274 | | 0, |
| | 792 | 275 | | default, |
| | 792 | 276 | | 0, |
| | 792 | 277 | | GridEventKind.WorldReset, |
| | 792 | 278 | | changeStamp: AllocateChangeStamp()); |
| | 792 | 279 | | EnqueueCommittedChange(new GridCommittedChange(resetEvent)); |
| | 792 | 280 | | drainCommittedChanges = !wasPublishingCommittedChanges; |
| | | 281 | | |
| | 792 | 282 | | if (deactivate) |
| | | 283 | | { |
| | 781 | 284 | | GridOccupantManager.ReleaseTrackedOccupancies(this); |
| | 781 | 285 | | IsActive = false; |
| | | 286 | | } |
| | 792 | 287 | | } |
| | | 288 | | } |
| | | 289 | | finally |
| | | 290 | | { |
| | 792 | 291 | | _gridLock.ExitWriteLock(); |
| | 792 | 292 | | } |
| | | 293 | | |
| | 792 | 294 | | if (drainCommittedChanges) |
| | 791 | 295 | | DrainCommittedChanges(); |
| | | 296 | | |
| | 792 | 297 | | if (!deactivate) |
| | 11 | 298 | | return; |
| | | 299 | | |
| | 781 | 300 | | lock (ChangeSyncRoot) |
| | | 301 | | { |
| | 781 | 302 | | SpawnToken = 0; |
| | 781 | 303 | | _onActiveGridAdded = null; |
| | 781 | 304 | | _onActiveGridRemoved = null; |
| | 781 | 305 | | _onActiveGridChange = null; |
| | 781 | 306 | | _onChangeCommitted = null; |
| | 781 | 307 | | _onReset = null; |
| | 781 | 308 | | } |
| | 781 | 309 | | } |
| | | 310 | | |
| | | 311 | | private void NotifyResetHandlers() |
| | | 312 | | { |
| | 792 | 313 | | Action? resetHandlers = _onReset; |
| | 792 | 314 | | if (resetHandlers == null) |
| | 770 | 315 | | return; |
| | | 316 | | |
| | 22 | 317 | | var handlerDelegates = resetHandlers.GetInvocationList(); |
| | 312 | 318 | | for (int i = 0; i < handlerDelegates.Length; i++) |
| | | 319 | | { |
| | | 320 | | try |
| | | 321 | | { |
| | 134 | 322 | | ((Action)handlerDelegates[i])(); |
| | 132 | 323 | | } |
| | 2 | 324 | | catch (Exception ex) |
| | | 325 | | { |
| | 2 | 326 | | GridForgeLogger.Channel.Error($"World reset notification error: {ex.Message}"); |
| | 2 | 327 | | } |
| | | 328 | | } |
| | 22 | 329 | | } |
| | | 330 | | |
| | | 331 | | private void ReleaseActiveGrids() |
| | | 332 | | { |
| | 792 | 333 | | _spatialIndex.Clear(); |
| | 792 | 334 | | ReleaseBoundaryContactPairs(); |
| | | 335 | | |
| | 3302 | 336 | | foreach (VoxelGrid grid in ActiveGrids) |
| | 859 | 337 | | Pools.GridPool.Release(grid); |
| | | 338 | | |
| | 792 | 339 | | ActiveGrids.Clear(); |
| | 792 | 340 | | BoundsTracker.Clear(); |
| | 792 | 341 | | MaxTopologyCellEdge = Fixed64.Zero; |
| | 792 | 342 | | } |
| | | 343 | | |
| | | 344 | | /// <inheritdoc /> |
| | | 345 | | public void Dispose() |
| | | 346 | | { |
| | 785 | 347 | | Reset(deactivate: true); |
| | 785 | 348 | | _isDisposed = true; |
| | 785 | 349 | | _gridLock.Dispose(); |
| | 785 | 350 | | GC.SuppressFinalize(this); |
| | 785 | 351 | | } |
| | | 352 | | |
| | | 353 | | #endregion |
| | | 354 | | |
| | | 355 | | #region Grid Management |
| | | 356 | | |
| | | 357 | | /// <summary> |
| | | 358 | | /// Allocates a nonzero process-unique identity for one obstacle registration lifetime. |
| | | 359 | | /// </summary> |
| | | 360 | | /// <returns>A fresh opaque obstacle token.</returns> |
| | | 361 | | /// <exception cref="InvalidOperationException">The world is inactive or its token space is exhausted.</exception> |
| | | 362 | | public ObstacleToken AllocateObstacleToken() |
| | | 363 | | { |
| | 459 | 364 | | if (!IsActive) |
| | 1 | 365 | | throw new InvalidOperationException("Cannot allocate an obstacle token from an inactive world."); |
| | | 366 | | |
| | 458 | 367 | | return new ObstacleToken(RuntimeIdentityAllocator.Allocate(ref s_obstacleRegistrationCounter)); |
| | | 368 | | } |
| | | 369 | | |
| | | 370 | | /// <summary> |
| | | 371 | | /// Captures presence and obstacle state for a sorted requested address span without |
| | | 372 | | /// enumerating unrelated grids or unrequested physical voxels. |
| | | 373 | | /// </summary> |
| | | 374 | | /// <param name="configurationKey">The exact normalized configuration identity to resolve.</param> |
| | | 375 | | /// <param name="requestedVoxels">Strictly ascending, unique, in-bounds topology-local addresses.</param> |
| | | 376 | | /// <param name="baseline">The atomic baseline on success.</param> |
| | | 377 | | /// <returns>True when the requested active grid generation was captured; otherwise false.</returns> |
| | | 378 | | public bool TryCaptureNavigationBaseline( |
| | | 379 | | GridConfigurationKey configurationKey, |
| | | 380 | | ReadOnlySpan<VoxelIndex> requestedVoxels, |
| | | 381 | | out GridNavigationBaseline? baseline) |
| | | 382 | | { |
| | 11 | 383 | | baseline = null; |
| | 11 | 384 | | if (!IsActive) |
| | 1 | 385 | | return false; |
| | | 386 | | |
| | 10 | 387 | | if (Volatile.Read(ref _navigationMaintenanceOwnerThreadId) |
| | 10 | 388 | | == Environment.CurrentManagedThreadId) |
| | | 389 | | { |
| | 1 | 390 | | return TryCaptureNavigationBaselineCore(configurationKey, requestedVoxels, out baseline); |
| | | 391 | | } |
| | | 392 | | |
| | 9 | 393 | | _gridLock.EnterReadLock(); |
| | | 394 | | try |
| | | 395 | | { |
| | 9 | 396 | | lock (ChangeSyncRoot) |
| | 9 | 397 | | return TryCaptureNavigationBaselineCore(configurationKey, requestedVoxels, out baseline); |
| | | 398 | | } |
| | | 399 | | finally |
| | | 400 | | { |
| | 9 | 401 | | _gridLock.ExitReadLock(); |
| | 9 | 402 | | } |
| | 9 | 403 | | } |
| | | 404 | | |
| | | 405 | | /// <summary> |
| | | 406 | | /// Executes one short navigation maintenance snapshot while grid mutations are frozen. |
| | | 407 | | /// Committed-change prefix detachment and all required navigation baseline captures can |
| | | 408 | | /// therefore observe one deterministic world state. |
| | | 409 | | /// </summary> |
| | | 410 | | /// <param name="maintenance">The non-mutating maintenance callback to execute.</param> |
| | | 411 | | /// <remarks> |
| | | 412 | | /// The callback may call <see cref="TryCaptureNavigationBaseline"/> without lock recursion. |
| | | 413 | | /// It must not mutate this world, wait for code that may mutate this world, or retain live |
| | | 414 | | /// grid/voxel references beyond the callback. This method must not be called from a committed- |
| | | 415 | | /// change notification handler. Those handlers remain outside the mutation lock and may enqueue |
| | | 416 | | /// represented events after this snapshot completes. |
| | | 417 | | /// </remarks> |
| | | 418 | | public void ExecuteNavigationMaintenanceSnapshot(Action maintenance) |
| | | 419 | | { |
| | 3 | 420 | | SwiftThrowHelper.ThrowIfNull(maintenance, nameof(maintenance)); |
| | 3 | 421 | | ThrowIfNavigationMaintenanceUnavailable(); |
| | | 422 | | |
| | 1 | 423 | | while (true) |
| | | 424 | | { |
| | 3 | 425 | | if (TryEnterNavigationMaintenanceSnapshot()) |
| | | 426 | | { |
| | | 427 | | try |
| | | 428 | | { |
| | 2 | 429 | | maintenance(); |
| | 2 | 430 | | return; |
| | | 431 | | } |
| | | 432 | | finally |
| | | 433 | | { |
| | 2 | 434 | | ExitNavigationMaintenanceSnapshot(); |
| | 2 | 435 | | } |
| | | 436 | | } |
| | | 437 | | |
| | 1 | 438 | | WaitForPublishedChangePrefix(); |
| | | 439 | | } |
| | 2 | 440 | | } |
| | | 441 | | |
| | | 442 | | /// <summary> |
| | | 443 | | /// Begins or restarts a bounded exact boundary-contact query against the current committed world state. |
| | | 444 | | /// </summary> |
| | | 445 | | /// <param name="cursor">The caller-owned cursor to reset and bind.</param> |
| | | 446 | | public void BeginBoundaryContacts(GridBoundaryContactCursor cursor) |
| | | 447 | | { |
| | 26 | 448 | | SwiftThrowHelper.ThrowIfNull(cursor, nameof(cursor)); |
| | 26 | 449 | | ThrowIfNavigationMaintenanceUnavailable(); |
| | | 450 | | |
| | 1 | 451 | | while (true) |
| | | 452 | | { |
| | 27 | 453 | | if (TryEnterNavigationMaintenanceSnapshot()) |
| | | 454 | | { |
| | | 455 | | try |
| | | 456 | | { |
| | 26 | 457 | | cursor.Begin(SpawnToken, Version, _changeSequence); |
| | 26 | 458 | | return; |
| | | 459 | | } |
| | | 460 | | finally |
| | | 461 | | { |
| | 26 | 462 | | ExitNavigationMaintenanceSnapshot(); |
| | 26 | 463 | | } |
| | | 464 | | } |
| | | 465 | | |
| | 1 | 466 | | WaitForPublishedChangePrefix(); |
| | | 467 | | } |
| | 26 | 468 | | } |
| | | 469 | | |
| | | 470 | | /// <summary> |
| | | 471 | | /// Begins or restarts a bounded exact boundary-contact query restricted to one active grid. |
| | | 472 | | /// </summary> |
| | | 473 | | /// <param name="configurationKey">The exact normalized configuration identity to resolve.</param> |
| | | 474 | | /// <param name="cursor">The caller-owned cursor to reset and bind.</param> |
| | | 475 | | /// <returns>True when the requested active grid was bound; otherwise false.</returns> |
| | | 476 | | public bool TryBeginBoundaryContacts( |
| | | 477 | | GridConfigurationKey configurationKey, |
| | | 478 | | GridBoundaryContactCursor cursor) |
| | | 479 | | { |
| | 14 | 480 | | SwiftThrowHelper.ThrowIfNull(cursor, nameof(cursor)); |
| | 14 | 481 | | ThrowIfNavigationMaintenanceUnavailable(); |
| | | 482 | | |
| | 1 | 483 | | while (true) |
| | | 484 | | { |
| | 15 | 485 | | if (TryEnterNavigationMaintenanceSnapshot()) |
| | | 486 | | { |
| | | 487 | | try |
| | | 488 | | { |
| | 14 | 489 | | if (!BoundsTracker.TryGetValue(configurationKey, out ushort gridIndex)) |
| | | 490 | | { |
| | 1 | 491 | | cursor.MarkStale(); |
| | 1 | 492 | | return false; |
| | | 493 | | } |
| | | 494 | | |
| | 13 | 495 | | VoxelGrid grid = ActiveGrids[gridIndex]; |
| | 13 | 496 | | cursor.BeginFiltered( |
| | 13 | 497 | | SpawnToken, |
| | 13 | 498 | | Version, |
| | 13 | 499 | | _changeSequence, |
| | 13 | 500 | | gridIndex, |
| | 13 | 501 | | grid.SpawnToken, |
| | 13 | 502 | | grid.LastChangeSequence); |
| | 13 | 503 | | return true; |
| | | 504 | | } |
| | | 505 | | finally |
| | | 506 | | { |
| | 14 | 507 | | ExitNavigationMaintenanceSnapshot(); |
| | 14 | 508 | | } |
| | | 509 | | } |
| | | 510 | | |
| | 1 | 511 | | WaitForPublishedChangePrefix(); |
| | | 512 | | } |
| | 14 | 513 | | } |
| | | 514 | | |
| | | 515 | | /// <summary> |
| | | 516 | | /// Advances a bounded exact boundary-contact query under one short navigation-maintenance snapshot. |
| | | 517 | | /// </summary> |
| | | 518 | | /// <param name="cursor">The caller-owned cursor previously begun through this world.</param> |
| | | 519 | | /// <param name="results">Caller-owned storage for contacts emitted by this chunk.</param> |
| | | 520 | | /// <param name="candidateProbeLimit">The maximum pair, source-address, and target probes for this chunk.</param> |
| | | 521 | | /// <param name="outputLimit">The maximum contacts to write during this chunk.</param> |
| | | 522 | | /// <param name="candidateProbesConsumed">The exact number of candidate probes consumed by this chunk.</param> |
| | | 523 | | /// <param name="outputCount">The number of contacts written to <paramref name="results"/>.</param> |
| | | 524 | | /// <returns>The resulting cursor state.</returns> |
| | | 525 | | /// <remarks> |
| | | 526 | | /// A <see cref="GridBoundaryContactCursorStatus.Stale"/> result writes no contacts and resets the |
| | | 527 | | /// cursor ordinal. The caller must discard every contact returned since the preceding begin. |
| | | 528 | | /// Completed cursors remain bound and are revalidated on every later call, including zero-budget calls. |
| | | 529 | | /// </remarks> |
| | | 530 | | public GridBoundaryContactCursorStatus AdvanceBoundaryContacts( |
| | | 531 | | GridBoundaryContactCursor cursor, |
| | | 532 | | Span<VoxelContactManifold> results, |
| | | 533 | | int candidateProbeLimit, |
| | | 534 | | int outputLimit, |
| | | 535 | | out int candidateProbesConsumed, |
| | | 536 | | out int outputCount) |
| | | 537 | | { |
| | 107 | 538 | | SwiftThrowHelper.ThrowIfNull(cursor, nameof(cursor)); |
| | 107 | 539 | | SwiftThrowHelper.ThrowIfNegative(candidateProbeLimit, nameof(candidateProbeLimit)); |
| | 107 | 540 | | SwiftThrowHelper.ThrowIfNegative(outputLimit, nameof(outputLimit)); |
| | 107 | 541 | | if (outputLimit > results.Length) |
| | 1 | 542 | | throw new ArgumentOutOfRangeException(nameof(outputLimit)); |
| | | 543 | | |
| | 106 | 544 | | return AdvanceBoundaryContactsUnderGate( |
| | 106 | 545 | | cursor, |
| | 106 | 546 | | results, |
| | 106 | 547 | | default, |
| | 106 | 548 | | includeConfigurationKeys: false, |
| | 106 | 549 | | candidateProbeLimit, |
| | 106 | 550 | | outputLimit, |
| | 106 | 551 | | out candidateProbesConsumed, |
| | 106 | 552 | | out outputCount); |
| | | 553 | | } |
| | | 554 | | |
| | | 555 | | /// <summary> |
| | | 556 | | /// Advances a bounded exact boundary-contact query and emits durable grid identities with each contact. |
| | | 557 | | /// </summary> |
| | | 558 | | /// <param name="cursor">The caller-owned cursor previously begun through this world.</param> |
| | | 559 | | /// <param name="results">Caller-owned storage for contacts and their normalized grid identities.</param> |
| | | 560 | | /// <param name="candidateProbeLimit">The maximum pair, source-address, and target probes for this chunk.</param> |
| | | 561 | | /// <param name="outputLimit">The maximum contacts to write during this chunk.</param> |
| | | 562 | | /// <param name="candidateProbesConsumed">The exact number of candidate probes consumed by this chunk.</param> |
| | | 563 | | /// <param name="outputCount">The number of contacts written to <paramref name="results"/>.</param> |
| | | 564 | | /// <returns>The resulting cursor state.</returns> |
| | | 565 | | /// <remarks> |
| | | 566 | | /// Every emitted identity belongs to <see cref="GridBoundaryContactCursor.RunStamp"/>. |
| | | 567 | | /// A stale result writes no contacts and resets that stamp to its default value. |
| | | 568 | | /// </remarks> |
| | | 569 | | public GridBoundaryContactCursorStatus AdvanceBoundaryContacts( |
| | | 570 | | GridBoundaryContactCursor cursor, |
| | | 571 | | Span<GridBoundaryContact> results, |
| | | 572 | | int candidateProbeLimit, |
| | | 573 | | int outputLimit, |
| | | 574 | | out int candidateProbesConsumed, |
| | | 575 | | out int outputCount) |
| | | 576 | | { |
| | 9 | 577 | | SwiftThrowHelper.ThrowIfNull(cursor, nameof(cursor)); |
| | 9 | 578 | | SwiftThrowHelper.ThrowIfNegative(candidateProbeLimit, nameof(candidateProbeLimit)); |
| | 9 | 579 | | SwiftThrowHelper.ThrowIfNegative(outputLimit, nameof(outputLimit)); |
| | 9 | 580 | | if (outputLimit > results.Length) |
| | 1 | 581 | | throw new ArgumentOutOfRangeException(nameof(outputLimit)); |
| | | 582 | | |
| | 8 | 583 | | return AdvanceBoundaryContactsUnderGate( |
| | 8 | 584 | | cursor, |
| | 8 | 585 | | default, |
| | 8 | 586 | | results, |
| | 8 | 587 | | includeConfigurationKeys: true, |
| | 8 | 588 | | candidateProbeLimit, |
| | 8 | 589 | | outputLimit, |
| | 8 | 590 | | out candidateProbesConsumed, |
| | 8 | 591 | | out outputCount); |
| | | 592 | | } |
| | | 593 | | |
| | | 594 | | private GridBoundaryContactCursorStatus AdvanceBoundaryContactsUnderGate( |
| | | 595 | | GridBoundaryContactCursor cursor, |
| | | 596 | | Span<VoxelContactManifold> manifoldResults, |
| | | 597 | | Span<GridBoundaryContact> boundResults, |
| | | 598 | | bool includeConfigurationKeys, |
| | | 599 | | int candidateProbeLimit, |
| | | 600 | | int outputLimit, |
| | | 601 | | out int candidateProbesConsumed, |
| | | 602 | | out int outputCount) |
| | | 603 | | { |
| | 114 | 604 | | ThrowIfNavigationMaintenanceUnavailable(); |
| | 114 | 605 | | candidateProbesConsumed = 0; |
| | 114 | 606 | | outputCount = 0; |
| | 1 | 607 | | while (true) |
| | | 608 | | { |
| | 115 | 609 | | if (TryEnterNavigationMaintenanceSnapshot()) |
| | | 610 | | { |
| | | 611 | | try |
| | | 612 | | { |
| | 114 | 613 | | return AdvanceBoundaryContactsCore( |
| | 114 | 614 | | cursor, |
| | 114 | 615 | | manifoldResults, |
| | 114 | 616 | | boundResults, |
| | 114 | 617 | | includeConfigurationKeys, |
| | 114 | 618 | | candidateProbeLimit, |
| | 114 | 619 | | outputLimit, |
| | 114 | 620 | | out candidateProbesConsumed, |
| | 114 | 621 | | out outputCount); |
| | | 622 | | } |
| | | 623 | | finally |
| | | 624 | | { |
| | 114 | 625 | | ExitNavigationMaintenanceSnapshot(); |
| | 114 | 626 | | } |
| | | 627 | | } |
| | | 628 | | |
| | 1 | 629 | | WaitForPublishedChangePrefix(); |
| | | 630 | | } |
| | 114 | 631 | | } |
| | | 632 | | |
| | | 633 | | private GridBoundaryContactCursorStatus AdvanceBoundaryContactsCore( |
| | | 634 | | GridBoundaryContactCursor cursor, |
| | | 635 | | Span<VoxelContactManifold> manifoldResults, |
| | | 636 | | Span<GridBoundaryContact> boundResults, |
| | | 637 | | bool includeConfigurationKeys, |
| | | 638 | | int candidateProbeLimit, |
| | | 639 | | int outputLimit, |
| | | 640 | | out int candidateProbesConsumed, |
| | | 641 | | out int outputCount) |
| | | 642 | | { |
| | 114 | 643 | | candidateProbesConsumed = 0; |
| | 114 | 644 | | outputCount = 0; |
| | 114 | 645 | | if (!IsBoundaryContactCursorCurrent(cursor)) |
| | 10 | 646 | | return cursor.MarkStale(); |
| | | 647 | | |
| | 104 | 648 | | if (cursor.CurrentStatus == GridBoundaryContactCursorStatus.Complete) |
| | 2 | 649 | | return cursor.CurrentStatus; |
| | | 650 | | |
| | | 651 | | while (true) |
| | | 652 | | { |
| | 320 | 653 | | if (cursor.HasPendingContact) |
| | | 654 | | { |
| | 52 | 655 | | if (outputCount == outputLimit) |
| | 1 | 656 | | return GridBoundaryContactCursorStatus.More; |
| | | 657 | | |
| | 51 | 658 | | if (includeConfigurationKeys) |
| | | 659 | | { |
| | 8 | 660 | | boundResults[outputCount++] = new GridBoundaryContact( |
| | 8 | 661 | | cursor.SourceConfigurationKey, |
| | 8 | 662 | | cursor.TargetConfigurationKey, |
| | 8 | 663 | | cursor.PendingContact); |
| | | 664 | | } |
| | | 665 | | else |
| | | 666 | | { |
| | 43 | 667 | | manifoldResults[outputCount++] = cursor.PendingContact; |
| | | 668 | | } |
| | 51 | 669 | | cursor.PendingContact = default; |
| | 51 | 670 | | cursor.HasPendingContact = false; |
| | 51 | 671 | | if (outputCount == outputLimit) |
| | 40 | 672 | | return GridBoundaryContactCursorStatus.More; |
| | | 673 | | } |
| | | 674 | | |
| | 279 | 675 | | switch (cursor.Stage) |
| | | 676 | | { |
| | | 677 | | case GridBoundaryContactCursor.TraversalStage.Pair: |
| | 122 | 678 | | if (cursor.IsFiltered) |
| | | 679 | | { |
| | 23 | 680 | | if (!TryAdvanceFilteredBoundaryContactPair( |
| | 23 | 681 | | cursor, |
| | 23 | 682 | | candidateProbeLimit, |
| | 23 | 683 | | ref candidateProbesConsumed, |
| | 23 | 684 | | out ushort filteredSource, |
| | 23 | 685 | | out ushort filteredTarget)) |
| | | 686 | | { |
| | 12 | 687 | | return cursor.CurrentStatus; |
| | | 688 | | } |
| | | 689 | | |
| | 11 | 690 | | BindBoundaryContactPair(cursor, filteredSource, filteredTarget); |
| | 11 | 691 | | cursor.Stage = GridBoundaryContactCursor.TraversalStage.Source; |
| | 11 | 692 | | continue; |
| | | 693 | | } |
| | | 694 | | |
| | 99 | 695 | | if (!cursor.HasPairSource) |
| | | 696 | | { |
| | 69 | 697 | | if (cursor.PairSourceWord != 0) |
| | | 698 | | { |
| | 17 | 699 | | int sourceBit = GetTrailingZeroCount(cursor.PairSourceWord); |
| | 17 | 700 | | cursor.PairSourceWord &= cursor.PairSourceWord - 1UL; |
| | 17 | 701 | | cursor.PairSourceGridIndex = (ushort)( |
| | 17 | 702 | | (cursor.PairSourceWordIndex << 6) + sourceBit); |
| | 17 | 703 | | cursor.PairTargetOrdinal = 0; |
| | 17 | 704 | | cursor.HasPairSource = true; |
| | 17 | 705 | | continue; |
| | | 706 | | } |
| | | 707 | | |
| | 52 | 708 | | if (cursor.PairSourceSummaryWord != 0) |
| | | 709 | | { |
| | 19 | 710 | | if (candidateProbesConsumed == candidateProbeLimit) |
| | 2 | 711 | | return GridBoundaryContactCursorStatus.More; |
| | | 712 | | |
| | 17 | 713 | | int wordBit = GetTrailingZeroCount(cursor.PairSourceSummaryWord); |
| | 17 | 714 | | cursor.PairSourceSummaryWord &= cursor.PairSourceSummaryWord - 1UL; |
| | 17 | 715 | | cursor.PairSourceWordIndex = |
| | 17 | 716 | | ((cursor.PairSourceSummaryWordIndex - 1) << 6) + wordBit; |
| | 17 | 717 | | cursor.PairSourceWord = _boundaryContactSourceWords![cursor.PairSourceWordIndex]; |
| | 17 | 718 | | ConsumeBoundaryContactProbe(cursor, ref candidateProbesConsumed); |
| | 17 | 719 | | continue; |
| | | 720 | | } |
| | | 721 | | |
| | 33 | 722 | | if (_boundaryContactSourceSummaryWords == null |
| | 33 | 723 | | || cursor.PairSourceSummaryWordIndex |
| | 33 | 724 | | >= _boundaryContactSourceSummaryLength) |
| | | 725 | | { |
| | 14 | 726 | | cursor.CurrentStatus = GridBoundaryContactCursorStatus.Complete; |
| | 14 | 727 | | return cursor.CurrentStatus; |
| | | 728 | | } |
| | | 729 | | |
| | 19 | 730 | | if (candidateProbesConsumed == candidateProbeLimit) |
| | 1 | 731 | | return GridBoundaryContactCursorStatus.More; |
| | | 732 | | |
| | 18 | 733 | | cursor.PairSourceSummaryWord = _boundaryContactSourceSummaryWords[ |
| | 18 | 734 | | cursor.PairSourceSummaryWordIndex++]; |
| | 18 | 735 | | ConsumeBoundaryContactProbe(cursor, ref candidateProbesConsumed); |
| | 18 | 736 | | continue; |
| | | 737 | | } |
| | | 738 | | |
| | 30 | 739 | | bool foundPairTargets = _boundaryContactTargetsBySource.TryGetValue( |
| | 30 | 740 | | cursor.PairSourceGridIndex, |
| | 30 | 741 | | out SwiftList<ushort>? pairTargets); |
| | | 742 | | Debug.Assert(foundPairTargets && pairTargets != null); |
| | 30 | 743 | | if (cursor.PairTargetOrdinal >= pairTargets.Count) |
| | | 744 | | { |
| | 12 | 745 | | cursor.HasPairSource = false; |
| | 12 | 746 | | continue; |
| | | 747 | | } |
| | | 748 | | |
| | 18 | 749 | | if (candidateProbesConsumed == candidateProbeLimit) |
| | 1 | 750 | | return GridBoundaryContactCursorStatus.More; |
| | | 751 | | |
| | 17 | 752 | | ushort pairTarget = pairTargets[cursor.PairTargetOrdinal++]; |
| | 17 | 753 | | ConsumeBoundaryContactProbe(cursor, ref candidateProbesConsumed); |
| | 17 | 754 | | BindBoundaryContactPair(cursor, cursor.PairSourceGridIndex, pairTarget); |
| | 17 | 755 | | cursor.Stage = GridBoundaryContactCursor.TraversalStage.Source; |
| | 17 | 756 | | continue; |
| | | 757 | | |
| | | 758 | | case GridBoundaryContactCursor.TraversalStage.Source: |
| | 77 | 759 | | VoxelGrid sourceGrid = ActiveGrids[cursor.SourceGridIndex]; |
| | 77 | 760 | | VoxelGrid targetGrid = ActiveGrids[cursor.TargetGridIndex]; |
| | 77 | 761 | | if (!cursor.HasSourceRange) |
| | | 762 | | { |
| | 22 | 763 | | cursor.ClearPairProgress(); |
| | 22 | 764 | | continue; |
| | | 765 | | } |
| | | 766 | | |
| | 55 | 767 | | if (candidateProbesConsumed == candidateProbeLimit) |
| | 4 | 768 | | return GridBoundaryContactCursorStatus.More; |
| | | 769 | | |
| | 51 | 770 | | VoxelIndex sourceIndex = cursor.SourceAddress; |
| | 51 | 771 | | cursor.HasSourceRange = AdvanceBoundaryContactAddress( |
| | 51 | 772 | | ref cursor.SourceAddress, |
| | 51 | 773 | | cursor.SourceMinimum, |
| | 51 | 774 | | cursor.SourceMaximum); |
| | 51 | 775 | | ConsumeBoundaryContactProbe(cursor, ref candidateProbesConsumed); |
| | 51 | 776 | | if (!TryCreateTopologyPrism(sourceGrid, sourceIndex, out cursor.SourcePrism) |
| | 51 | 777 | | || !TopologyVoxelRangeUtility.TryGetCandidateRange( |
| | 51 | 778 | | targetGrid, |
| | 51 | 779 | | cursor.SourcePrism.GetAabb().Expand(targetGrid.Topology.MaxCellEdge), |
| | 51 | 780 | | out cursor.TargetMinimum, |
| | 51 | 781 | | out cursor.TargetMaximum)) |
| | | 782 | | { |
| | | 783 | | continue; |
| | | 784 | | } |
| | | 785 | | |
| | 51 | 786 | | cursor.TargetAddress = cursor.TargetMinimum; |
| | 51 | 787 | | cursor.Stage = GridBoundaryContactCursor.TraversalStage.Target; |
| | 51 | 788 | | continue; |
| | | 789 | | |
| | | 790 | | default: |
| | 80 | 791 | | if (candidateProbesConsumed == candidateProbeLimit) |
| | 27 | 792 | | return GridBoundaryContactCursorStatus.More; |
| | | 793 | | |
| | 53 | 794 | | ProbeBoundaryContactTarget(cursor, ref candidateProbesConsumed); |
| | 53 | 795 | | continue; |
| | | 796 | | } |
| | | 797 | | } |
| | | 798 | | } |
| | | 799 | | |
| | | 800 | | private bool IsBoundaryContactCursorCurrent(GridBoundaryContactCursor cursor) |
| | | 801 | | { |
| | 114 | 802 | | if (cursor.CurrentStatus == GridBoundaryContactCursorStatus.Stale |
| | 114 | 803 | | || cursor.WorldSpawnToken != SpawnToken |
| | 114 | 804 | | || cursor.WorldVersion != Version |
| | 114 | 805 | | || cursor.WorldChangeSequence != _changeSequence) |
| | | 806 | | { |
| | 7 | 807 | | return false; |
| | | 808 | | } |
| | | 809 | | |
| | 107 | 810 | | if (cursor.IsFiltered |
| | 107 | 811 | | && ActiveGrids[cursor.FilterGridIndex].LastChangeSequence |
| | 107 | 812 | | != cursor.FilterGridLastChangeSequence) |
| | | 813 | | { |
| | 1 | 814 | | return false; |
| | | 815 | | } |
| | | 816 | | |
| | 106 | 817 | | if (cursor.SourceGridSpawnToken == 0) |
| | 36 | 818 | | return true; |
| | | 819 | | |
| | 70 | 820 | | return ActiveGrids[cursor.SourceGridIndex].LastChangeSequence |
| | 70 | 821 | | == cursor.SourceGridLastChangeSequence |
| | 70 | 822 | | && ActiveGrids[cursor.TargetGridIndex].LastChangeSequence |
| | 70 | 823 | | == cursor.TargetGridLastChangeSequence; |
| | | 824 | | } |
| | | 825 | | |
| | | 826 | | private bool TryAdvanceFilteredBoundaryContactPair( |
| | | 827 | | GridBoundaryContactCursor cursor, |
| | | 828 | | int candidateProbeLimit, |
| | | 829 | | ref int candidateProbesConsumed, |
| | | 830 | | out ushort sourceGridIndex, |
| | | 831 | | out ushort targetGridIndex) |
| | | 832 | | { |
| | 23 | 833 | | sourceGridIndex = 0; |
| | 23 | 834 | | targetGridIndex = 0; |
| | 45 | 835 | | while (cursor.FilteredPairPhase < 2) |
| | | 836 | | { |
| | 36 | 837 | | SwiftDictionary<ushort, SwiftList<ushort>> rows = cursor.FilteredPairPhase == 0 |
| | 36 | 838 | | ? _boundaryContactSourcesByTarget |
| | 36 | 839 | | : _boundaryContactTargetsBySource; |
| | 36 | 840 | | if (!cursor.HasFilteredPairRow) |
| | | 841 | | { |
| | 21 | 842 | | if (candidateProbesConsumed == candidateProbeLimit) |
| | 1 | 843 | | return false; |
| | | 844 | | |
| | 20 | 845 | | cursor.FilteredPairRowCount = rows.TryGetValue( |
| | 20 | 846 | | cursor.FilterGridIndex, |
| | 20 | 847 | | out SwiftList<ushort>? row) |
| | 20 | 848 | | ? row.Count |
| | 20 | 849 | | : 0; |
| | 20 | 850 | | cursor.FilteredPairRowOrdinal = 0; |
| | 20 | 851 | | if (cursor.FilteredPairRowCount != 0) |
| | | 852 | | { |
| | 8 | 853 | | cursor.PendingFilteredGridIndex = row![0]; |
| | 8 | 854 | | cursor.FilteredPairRowOrdinal = 1; |
| | 8 | 855 | | cursor.HasPendingFilteredPair = true; |
| | | 856 | | } |
| | 20 | 857 | | cursor.HasFilteredPairRow = true; |
| | 20 | 858 | | ConsumeBoundaryContactProbe(cursor, ref candidateProbesConsumed); |
| | | 859 | | } |
| | | 860 | | |
| | 35 | 861 | | if (cursor.HasPendingFilteredPair) |
| | | 862 | | { |
| | 12 | 863 | | if (candidateProbesConsumed == candidateProbeLimit) |
| | 1 | 864 | | return false; |
| | | 865 | | |
| | 11 | 866 | | ushort incidentGridIndex = cursor.PendingFilteredGridIndex; |
| | 11 | 867 | | cursor.PendingFilteredGridIndex = 0; |
| | 11 | 868 | | cursor.HasPendingFilteredPair = false; |
| | 11 | 869 | | ConsumeBoundaryContactProbe(cursor, ref candidateProbesConsumed); |
| | 11 | 870 | | if (cursor.FilteredPairPhase == 0) |
| | | 871 | | { |
| | 3 | 872 | | sourceGridIndex = incidentGridIndex; |
| | 3 | 873 | | targetGridIndex = cursor.FilterGridIndex; |
| | | 874 | | } |
| | | 875 | | else |
| | | 876 | | { |
| | 8 | 877 | | sourceGridIndex = cursor.FilterGridIndex; |
| | 8 | 878 | | targetGridIndex = incidentGridIndex; |
| | | 879 | | } |
| | | 880 | | |
| | 11 | 881 | | return true; |
| | | 882 | | } |
| | | 883 | | |
| | 23 | 884 | | if (cursor.FilteredPairRowOrdinal < cursor.FilteredPairRowCount) |
| | | 885 | | { |
| | 4 | 886 | | if (candidateProbesConsumed == candidateProbeLimit) |
| | 1 | 887 | | return false; |
| | | 888 | | |
| | 3 | 889 | | bool foundRow = rows.TryGetValue( |
| | 3 | 890 | | cursor.FilterGridIndex, |
| | 3 | 891 | | out SwiftList<ushort>? row); |
| | | 892 | | Debug.Assert(foundRow && row != null); |
| | 3 | 893 | | cursor.PendingFilteredGridIndex = row[cursor.FilteredPairRowOrdinal++]; |
| | 3 | 894 | | cursor.HasPendingFilteredPair = true; |
| | 3 | 895 | | ConsumeBoundaryContactProbe(cursor, ref candidateProbesConsumed); |
| | 3 | 896 | | continue; |
| | | 897 | | } |
| | | 898 | | |
| | 19 | 899 | | cursor.FilteredPairPhase++; |
| | 19 | 900 | | cursor.FilteredPairRowCount = 0; |
| | 19 | 901 | | cursor.FilteredPairRowOrdinal = 0; |
| | 19 | 902 | | cursor.HasFilteredPairRow = false; |
| | | 903 | | } |
| | | 904 | | |
| | 9 | 905 | | cursor.CurrentStatus = GridBoundaryContactCursorStatus.Complete; |
| | 9 | 906 | | return false; |
| | | 907 | | } |
| | | 908 | | |
| | | 909 | | private void BindBoundaryContactPair( |
| | | 910 | | GridBoundaryContactCursor cursor, |
| | | 911 | | ushort sourceGridIndex, |
| | | 912 | | ushort targetGridIndex) |
| | | 913 | | { |
| | 28 | 914 | | VoxelGrid sourceGrid = ActiveGrids[sourceGridIndex]; |
| | 28 | 915 | | VoxelGrid targetGrid = ActiveGrids[targetGridIndex]; |
| | 28 | 916 | | cursor.SourceGridIndex = sourceGridIndex; |
| | 28 | 917 | | cursor.TargetGridIndex = targetGridIndex; |
| | 28 | 918 | | cursor.SourceGridSpawnToken = sourceGrid.SpawnToken; |
| | 28 | 919 | | cursor.TargetGridSpawnToken = targetGrid.SpawnToken; |
| | 28 | 920 | | cursor.SourceGridLastChangeSequence = sourceGrid.LastChangeSequence; |
| | 28 | 921 | | cursor.TargetGridLastChangeSequence = targetGrid.LastChangeSequence; |
| | 28 | 922 | | cursor.SourceConfigurationKey = sourceGrid.Configuration.ToGridKey(); |
| | 28 | 923 | | cursor.TargetConfigurationKey = targetGrid.Configuration.ToGridKey(); |
| | | 924 | | |
| | 28 | 925 | | bool createdEnvelope = TryCreateBoundaryContactEnvelope( |
| | 28 | 926 | | targetGrid, |
| | 28 | 927 | | out FixedBoundVolume targetEnvelope); |
| | 28 | 928 | | bool createdSourcePrism = TryCreateTopologyPrism( |
| | 28 | 929 | | sourceGrid, |
| | 28 | 930 | | default, |
| | 28 | 931 | | out GridCellPrism firstSourcePrism); |
| | | 932 | | Debug.Assert(createdEnvelope && createdSourcePrism); |
| | | 933 | | |
| | 28 | 934 | | TopologyVoxelAabb firstSourceBounds = firstSourcePrism.GetAabb(); |
| | 28 | 935 | | Vector3d lowerExtent = sourceGrid.BoundsMin - firstSourceBounds.Min; |
| | 28 | 936 | | Vector3d upperExtent = firstSourceBounds.Max - sourceGrid.BoundsMin; |
| | 28 | 937 | | var sourceCandidateBounds = new TopologyVoxelAabb( |
| | 28 | 938 | | targetEnvelope.Min - upperExtent, |
| | 28 | 939 | | targetEnvelope.Max + lowerExtent); |
| | 28 | 940 | | cursor.HasSourceRange = TopologyVoxelRangeUtility.TryGetCandidateRange( |
| | 28 | 941 | | sourceGrid, |
| | 28 | 942 | | sourceCandidateBounds, |
| | 28 | 943 | | out cursor.SourceMinimum, |
| | 28 | 944 | | out cursor.SourceMaximum); |
| | 28 | 945 | | cursor.SourceAddress = cursor.SourceMinimum; |
| | 28 | 946 | | } |
| | | 947 | | |
| | | 948 | | private void ProbeBoundaryContactTarget( |
| | | 949 | | GridBoundaryContactCursor cursor, |
| | | 950 | | ref int candidateProbesConsumed) |
| | | 951 | | { |
| | 53 | 952 | | VoxelGrid targetGrid = ActiveGrids[cursor.TargetGridIndex]; |
| | 53 | 953 | | VoxelIndex targetIndex = cursor.TargetAddress; |
| | 53 | 954 | | if (!AdvanceBoundaryContactAddress( |
| | 53 | 955 | | ref cursor.TargetAddress, |
| | 53 | 956 | | cursor.TargetMinimum, |
| | 53 | 957 | | cursor.TargetMaximum)) |
| | | 958 | | { |
| | 51 | 959 | | cursor.Stage = GridBoundaryContactCursor.TraversalStage.Source; |
| | | 960 | | } |
| | 53 | 961 | | ConsumeBoundaryContactProbe(cursor, ref candidateProbesConsumed); |
| | | 962 | | |
| | 53 | 963 | | bool createdTargetPrism = TryCreateTopologyPrism( |
| | 53 | 964 | | targetGrid, |
| | 53 | 965 | | targetIndex, |
| | 53 | 966 | | out GridCellPrism targetPrism); |
| | | 967 | | Debug.Assert(createdTargetPrism); |
| | | 968 | | |
| | 53 | 969 | | VoxelContactManifold contact = GridCellGeometry.GetContact(cursor.SourcePrism, targetPrism); |
| | 53 | 970 | | if (contact.Kind != VoxelContactKind.Separated) |
| | | 971 | | { |
| | 51 | 972 | | cursor.PendingContact = contact; |
| | 51 | 973 | | cursor.HasPendingContact = true; |
| | | 974 | | } |
| | 53 | 975 | | } |
| | | 976 | | |
| | | 977 | | private static bool AdvanceBoundaryContactAddress( |
| | | 978 | | ref VoxelIndex address, |
| | | 979 | | VoxelIndex minimum, |
| | | 980 | | VoxelIndex maximum) |
| | | 981 | | { |
| | 104 | 982 | | if (address.z < maximum.z) |
| | | 983 | | { |
| | 18 | 984 | | address.z++; |
| | 18 | 985 | | return true; |
| | | 986 | | } |
| | | 987 | | |
| | 86 | 988 | | address.z = minimum.z; |
| | 86 | 989 | | if (address.y < maximum.y) |
| | | 990 | | { |
| | 6 | 991 | | address.y++; |
| | 6 | 992 | | return true; |
| | | 993 | | } |
| | | 994 | | |
| | 80 | 995 | | address.y = minimum.y; |
| | 80 | 996 | | if (address.x < maximum.x) |
| | | 997 | | { |
| | 4 | 998 | | address.x++; |
| | 4 | 999 | | return true; |
| | | 1000 | | } |
| | | 1001 | | |
| | 76 | 1002 | | return false; |
| | | 1003 | | } |
| | | 1004 | | |
| | | 1005 | | private bool TryCreateTopologyPrism( |
| | | 1006 | | VoxelGrid grid, |
| | | 1007 | | VoxelIndex index, |
| | | 1008 | | out GridCellPrism prism) |
| | | 1009 | | { |
| | 132 | 1010 | | return GridCellGeometry.TryCreatePrism( |
| | 132 | 1011 | | grid.Configuration.TopologyKind, |
| | 132 | 1012 | | grid.Configuration.TopologyMetrics, |
| | 132 | 1013 | | grid.GetWorldPosition(index), |
| | 132 | 1014 | | new WorldVoxelIndex(SpawnToken, grid.GridIndex, grid.SpawnToken, index), |
| | 132 | 1015 | | out prism); |
| | | 1016 | | } |
| | | 1017 | | |
| | | 1018 | | private static int GetTrailingZeroCount(ulong value) |
| | | 1019 | | { |
| | 34 | 1020 | | int count = 0; |
| | 66 | 1021 | | while ((value & 1UL) == 0) |
| | | 1022 | | { |
| | 32 | 1023 | | value >>= 1; |
| | 32 | 1024 | | count++; |
| | | 1025 | | } |
| | | 1026 | | |
| | 34 | 1027 | | return count; |
| | | 1028 | | } |
| | | 1029 | | |
| | | 1030 | | private static void ConsumeBoundaryContactProbe( |
| | | 1031 | | GridBoundaryContactCursor cursor, |
| | | 1032 | | ref int candidateProbesConsumed) |
| | | 1033 | | { |
| | 190 | 1034 | | candidateProbesConsumed++; |
| | 190 | 1035 | | if (cursor.CandidateOrdinal != ulong.MaxValue) |
| | 189 | 1036 | | cursor.CandidateOrdinal++; |
| | 190 | 1037 | | } |
| | | 1038 | | |
| | | 1039 | | private void ThrowIfNavigationMaintenanceUnavailable() |
| | | 1040 | | { |
| | 219 | 1041 | | SwiftThrowHelper.ThrowIfTrue( |
| | 219 | 1042 | | !IsActive, |
| | 219 | 1043 | | message: "Cannot capture navigation maintenance state from an inactive world."); |
| | 217 | 1044 | | SwiftThrowHelper.ThrowIfTrue( |
| | 217 | 1045 | | Volatile.Read(ref _committedPublicationOwnerThreadId) |
| | 217 | 1046 | | == Environment.CurrentManagedThreadId, |
| | 217 | 1047 | | message: "Cannot enter navigation maintenance from a committed-change notification handler."); |
| | 216 | 1048 | | } |
| | | 1049 | | |
| | | 1050 | | private bool TryEnterNavigationMaintenanceSnapshot() |
| | | 1051 | | { |
| | 222 | 1052 | | _gridLock.EnterReadLock(); |
| | 222 | 1053 | | Monitor.Enter(ChangeSyncRoot); |
| | 222 | 1054 | | if (_publishedChangeSequence != _changeSequence) |
| | | 1055 | | { |
| | 6 | 1056 | | Monitor.Exit(ChangeSyncRoot); |
| | 6 | 1057 | | _gridLock.ExitReadLock(); |
| | 6 | 1058 | | return false; |
| | | 1059 | | } |
| | | 1060 | | |
| | 216 | 1061 | | _navigationMaintenanceOwnerThreadId = Environment.CurrentManagedThreadId; |
| | 216 | 1062 | | return true; |
| | | 1063 | | } |
| | | 1064 | | |
| | | 1065 | | private void ExitNavigationMaintenanceSnapshot() |
| | | 1066 | | { |
| | 216 | 1067 | | _navigationMaintenanceOwnerThreadId = 0; |
| | 216 | 1068 | | Monitor.Exit(ChangeSyncRoot); |
| | 216 | 1069 | | _gridLock.ExitReadLock(); |
| | 216 | 1070 | | } |
| | | 1071 | | |
| | | 1072 | | private void WaitForPublishedChangePrefix() |
| | | 1073 | | { |
| | | 1074 | | // A committed handler may legally perform a reentrant structural mutation. Never |
| | | 1075 | | // wait for that handler while holding the read lock it needs to promote past. |
| | 6 | 1076 | | lock (ChangeSyncRoot) |
| | | 1077 | | { |
| | 12 | 1078 | | while (_publishedChangeSequence != _changeSequence) |
| | 6 | 1079 | | Monitor.Wait(ChangeSyncRoot); |
| | 6 | 1080 | | } |
| | 6 | 1081 | | } |
| | | 1082 | | |
| | | 1083 | | private bool TryCaptureNavigationBaselineCore( |
| | | 1084 | | GridConfigurationKey configurationKey, |
| | | 1085 | | ReadOnlySpan<VoxelIndex> requestedVoxels, |
| | | 1086 | | out GridNavigationBaseline? baseline) |
| | | 1087 | | { |
| | | 1088 | | Debug.Assert(Monitor.IsEntered(ChangeSyncRoot)); |
| | 10 | 1089 | | baseline = null; |
| | 10 | 1090 | | if (!BoundsTracker.TryGetValue(configurationKey, out ushort gridIndex)) |
| | | 1091 | | { |
| | 1 | 1092 | | return false; |
| | | 1093 | | } |
| | | 1094 | | |
| | 9 | 1095 | | VoxelGrid grid = ActiveGrids[gridIndex]; |
| | 9 | 1096 | | if (!AreNavigationBaselineAddressesValid(grid, requestedVoxels)) |
| | | 1097 | | { |
| | 3 | 1098 | | return false; |
| | | 1099 | | } |
| | | 1100 | | |
| | 6 | 1101 | | NavigationBaselineVoxelState[] states = new NavigationBaselineVoxelState[requestedVoxels.Length]; |
| | 28 | 1102 | | for (int i = 0; i < requestedVoxels.Length; i++) |
| | | 1103 | | { |
| | 8 | 1104 | | VoxelIndex requestedVoxel = requestedVoxels[i]; |
| | 8 | 1105 | | bool isPresent = grid.TryGetVoxel(requestedVoxel, out Voxel? voxel); |
| | 8 | 1106 | | states[i] = new NavigationBaselineVoxelState( |
| | 8 | 1107 | | requestedVoxel, |
| | 8 | 1108 | | isPresent, |
| | 8 | 1109 | | isPresent ? voxel!.ObstacleCount : (byte)0); |
| | | 1110 | | } |
| | | 1111 | | |
| | 6 | 1112 | | baseline = new GridNavigationBaseline( |
| | 6 | 1113 | | _changeSequence, |
| | 6 | 1114 | | SpawnToken, |
| | 6 | 1115 | | grid.SpawnToken, |
| | 6 | 1116 | | grid.LastChangeSequence, |
| | 6 | 1117 | | grid.GridIndex, |
| | 6 | 1118 | | configurationKey, |
| | 6 | 1119 | | states); |
| | 6 | 1120 | | return true; |
| | | 1121 | | } |
| | | 1122 | | |
| | | 1123 | | private static bool AreNavigationBaselineAddressesValid( |
| | | 1124 | | VoxelGrid grid, |
| | | 1125 | | ReadOnlySpan<VoxelIndex> requestedVoxels) |
| | | 1126 | | { |
| | 38 | 1127 | | for (int i = 0; i < requestedVoxels.Length; i++) |
| | | 1128 | | { |
| | 13 | 1129 | | VoxelIndex requestedVoxel = requestedVoxels[i]; |
| | 13 | 1130 | | if (!grid.IsValidVoxelIndex(requestedVoxel.x, requestedVoxel.y, requestedVoxel.z) |
| | 13 | 1131 | | || (i > 0 && requestedVoxels[i - 1].CompareTo(requestedVoxel) >= 0)) |
| | | 1132 | | { |
| | 3 | 1133 | | return false; |
| | | 1134 | | } |
| | | 1135 | | } |
| | | 1136 | | |
| | 6 | 1137 | | return true; |
| | | 1138 | | } |
| | | 1139 | | |
| | | 1140 | | /// <summary> |
| | | 1141 | | /// Adds a new grid to this world and registers it in the spatial index. |
| | | 1142 | | /// </summary> |
| | | 1143 | | /// <param name="configuration">The grid configuration to normalize and register.</param> |
| | | 1144 | | /// <param name="allocatedIndex">The allocated world-local grid slot on success.</param> |
| | | 1145 | | /// <returns>True if the grid was added; otherwise false.</returns> |
| | | 1146 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1147 | | public bool TryAddGrid(GridConfiguration configuration, out ushort allocatedIndex) => |
| | 840 | 1148 | | TryAddGridCore(configuration, null, null, out allocatedIndex); |
| | | 1149 | | |
| | | 1150 | | /// <summary> |
| | | 1151 | | /// Adds a new grid to this world and materializes the supplied sparse voxel indices when sparse storage is configur |
| | | 1152 | | /// Dense grids ignore the configured voxel input and materialize every in-bounds voxel. |
| | | 1153 | | /// </summary> |
| | | 1154 | | /// <param name="configuration">The grid configuration to normalize and register.</param> |
| | | 1155 | | /// <param name="configuredVoxels">Grid-local voxel indices to materialize for sparse storage.</param> |
| | | 1156 | | /// <param name="allocatedIndex">The allocated world-local grid slot on success.</param> |
| | | 1157 | | /// <returns>True if the grid was added; otherwise false.</returns> |
| | | 1158 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1159 | | public bool TryAddGrid( |
| | | 1160 | | GridConfiguration configuration, |
| | | 1161 | | IEnumerable<VoxelIndex>? configuredVoxels, |
| | | 1162 | | out ushort allocatedIndex) => |
| | 97 | 1163 | | TryAddGridCore(configuration, configuredVoxels, null, out allocatedIndex); |
| | | 1164 | | |
| | | 1165 | | /// <summary> |
| | | 1166 | | /// Adds a new grid to this world and materializes true cells from the supplied sparse voxel mask when sparse storag |
| | | 1167 | | /// Dense grids ignore the configured voxel input and materialize every in-bounds voxel. |
| | | 1168 | | /// </summary> |
| | | 1169 | | /// <param name="configuration">The grid configuration to normalize and register.</param> |
| | | 1170 | | /// <param name="configuredVoxels">A [x, y, z] mask whose true values identify sparse voxels to materialize. Sparse |
| | | 1171 | | /// <param name="allocatedIndex">The allocated world-local grid slot on success.</param> |
| | | 1172 | | /// <returns>True if the grid was added; otherwise false.</returns> |
| | | 1173 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1174 | | public bool TryAddGrid( |
| | | 1175 | | GridConfiguration configuration, |
| | | 1176 | | bool[,,]? configuredVoxels, |
| | | 1177 | | out ushort allocatedIndex) => |
| | 7 | 1178 | | TryAddGridCore(configuration, null, configuredVoxels, out allocatedIndex); |
| | | 1179 | | |
| | | 1180 | | private bool TryAddGridCore( |
| | | 1181 | | GridConfiguration configuration, |
| | | 1182 | | IEnumerable<VoxelIndex>? configuredVoxels, |
| | | 1183 | | bool[,,]? configuredVoxelMask, |
| | | 1184 | | out ushort allocatedIndex) |
| | | 1185 | | { |
| | 944 | 1186 | | allocatedIndex = ushort.MaxValue; |
| | | 1187 | | |
| | 944 | 1188 | | if (!configuration.TryNormalize(out NormalizedGridConfiguration descriptor)) |
| | 6 | 1189 | | return false; |
| | | 1190 | | |
| | 938 | 1191 | | GridConfiguration normalizedConfiguration = descriptor.Configuration; |
| | 938 | 1192 | | IGridTopology topology = descriptor.Topology!; |
| | 938 | 1193 | | GridDimensions dimensions = descriptor.Dimensions; |
| | | 1194 | | |
| | 938 | 1195 | | if (!TryPrepareConfiguredVoxels( |
| | 938 | 1196 | | normalizedConfiguration, |
| | 938 | 1197 | | dimensions, |
| | 938 | 1198 | | configuredVoxels, |
| | 938 | 1199 | | configuredVoxelMask, |
| | 938 | 1200 | | out VoxelIndex[] preparedVoxels)) |
| | | 1201 | | { |
| | 12 | 1202 | | return false; |
| | | 1203 | | } |
| | | 1204 | | |
| | 926 | 1205 | | if (_isDisposed) |
| | | 1206 | | { |
| | 3 | 1207 | | GridForgeLogger.Channel.Error($"Grid world not active. Cannot add grids to an inactive world."); |
| | 3 | 1208 | | return false; |
| | | 1209 | | } |
| | | 1210 | | |
| | 923 | 1211 | | GridConfigurationKey boundsKey = descriptor.Key; |
| | 923 | 1212 | | VoxelGrid? newGrid = null; |
| | 923 | 1213 | | GridEventInfo addedGridInfo = default; |
| | | 1214 | | bool drainCommittedChanges; |
| | | 1215 | | |
| | 923 | 1216 | | _gridLock.EnterWriteLock(); |
| | | 1217 | | try |
| | | 1218 | | { |
| | 923 | 1219 | | lock (ChangeSyncRoot) |
| | | 1220 | | { |
| | 923 | 1221 | | if (!CanAddGrid() || TryFindExistingGridUnsafe(boundsKey, out allocatedIndex)) |
| | 8 | 1222 | | return false; |
| | | 1223 | | |
| | 915 | 1224 | | long gridGeneration = RuntimeIdentityAllocator.Allocate(ref _gridGenerationCounter); |
| | 915 | 1225 | | newGrid = Pools.GridPool.Rent(); |
| | | 1226 | | |
| | 915 | 1227 | | allocatedIndex = (ushort)ActiveGrids.Add(newGrid); |
| | 915 | 1228 | | BoundsTracker.Add(boundsKey, allocatedIndex); |
| | | 1229 | | |
| | 915 | 1230 | | newGrid.Initialize(this, allocatedIndex, gridGeneration, normalizedConfiguration, topology, preparedVoxe |
| | 915 | 1231 | | UpdateMaxTopologyCellEdge(newGrid.Topology.MaxCellEdge); |
| | 915 | 1232 | | RegisterGrid(newGrid, allocatedIndex); |
| | | 1233 | | |
| | 915 | 1234 | | Version++; |
| | 915 | 1235 | | addedGridInfo = CreateGridEventInfo( |
| | 915 | 1236 | | newGrid, |
| | 915 | 1237 | | GridEventKind.GridAdded, |
| | 915 | 1238 | | AllocateChangeStamp()); |
| | 915 | 1239 | | drainCommittedChanges = EnqueueCommittedChange(new GridCommittedChange(addedGridInfo)); |
| | 915 | 1240 | | } |
| | | 1241 | | } |
| | | 1242 | | finally |
| | | 1243 | | { |
| | 923 | 1244 | | _gridLock.ExitWriteLock(); |
| | 923 | 1245 | | } |
| | | 1246 | | |
| | 915 | 1247 | | if (drainCommittedChanges) |
| | 914 | 1248 | | DrainCommittedChanges(); |
| | 915 | 1249 | | return true; |
| | 8 | 1250 | | } |
| | | 1251 | | |
| | | 1252 | | /// <summary> |
| | | 1253 | | /// Removes a grid from this world and updates all references to ensure integrity. |
| | | 1254 | | /// </summary> |
| | | 1255 | | /// <param name="removeIndex">The world-local grid slot to remove.</param> |
| | | 1256 | | /// <returns>True if the grid was removed; otherwise false.</returns> |
| | | 1257 | | public bool TryRemoveGrid(ushort removeIndex) |
| | | 1258 | | { |
| | 58 | 1259 | | if (!IsActive) |
| | 1 | 1260 | | return false; |
| | | 1261 | | |
| | 57 | 1262 | | VoxelGrid? gridToRemove = null; |
| | 57 | 1263 | | GridEventInfo removedGridInfo = default; |
| | | 1264 | | bool drainCommittedChanges; |
| | | 1265 | | |
| | 57 | 1266 | | _gridLock.EnterWriteLock(); |
| | | 1267 | | try |
| | | 1268 | | { |
| | 57 | 1269 | | lock (ChangeSyncRoot) |
| | | 1270 | | { |
| | 57 | 1271 | | if (!IsActive || !ActiveGrids.IsAllocated(removeIndex)) |
| | 1 | 1272 | | return false; |
| | | 1273 | | |
| | 56 | 1274 | | gridToRemove = ActiveGrids[removeIndex]; |
| | 56 | 1275 | | Fixed64 removedMaxCellEdge = gridToRemove.Topology.MaxCellEdge; |
| | 56 | 1276 | | UnregisterGrid(gridToRemove, removeIndex); |
| | 56 | 1277 | | BoundsTracker.Remove(gridToRemove.Configuration.ToGridKey()); |
| | 56 | 1278 | | ActiveGrids.RemoveAt(removeIndex); |
| | 56 | 1279 | | RecalculateMaxTopologyCellEdgeIfNeeded(removedMaxCellEdge); |
| | | 1280 | | |
| | 56 | 1281 | | Version++; |
| | 56 | 1282 | | removedGridInfo = CreateGridEventInfo( |
| | 56 | 1283 | | gridToRemove, |
| | 56 | 1284 | | GridEventKind.GridRemoved, |
| | 56 | 1285 | | AllocateChangeStamp()); |
| | 56 | 1286 | | drainCommittedChanges = EnqueueCommittedChange(new GridCommittedChange(removedGridInfo)); |
| | 56 | 1287 | | } |
| | | 1288 | | } |
| | | 1289 | | finally |
| | | 1290 | | { |
| | 57 | 1291 | | _gridLock.ExitWriteLock(); |
| | 57 | 1292 | | } |
| | | 1293 | | |
| | 56 | 1294 | | Pools.GridPool.Release(gridToRemove!); |
| | 56 | 1295 | | if (drainCommittedChanges) |
| | 55 | 1296 | | DrainCommittedChanges(); |
| | | 1297 | | |
| | 56 | 1298 | | if (ActiveGrids.Count == 0) |
| | 29 | 1299 | | ActiveGrids.TrimExcessCapacity(); |
| | | 1300 | | |
| | 56 | 1301 | | return true; |
| | 1 | 1302 | | } |
| | | 1303 | | |
| | | 1304 | | #endregion |
| | | 1305 | | |
| | | 1306 | | private bool CanAddGrid() |
| | | 1307 | | { |
| | 923 | 1308 | | if (!IsActive) |
| | | 1309 | | { |
| | 2 | 1310 | | GridForgeLogger.Channel.Error($"Grid world not active. Cannot add grids to an inactive world."); |
| | 2 | 1311 | | return false; |
| | | 1312 | | } |
| | | 1313 | | |
| | 921 | 1314 | | if ((uint)ActiveGrids.Count >= MaxGrids) |
| | | 1315 | | { |
| | 2 | 1316 | | GridForgeLogger.Channel.Warn($"No more grids can be added at this time."); |
| | 2 | 1317 | | return false; |
| | | 1318 | | } |
| | | 1319 | | |
| | 919 | 1320 | | return true; |
| | | 1321 | | } |
| | | 1322 | | |
| | | 1323 | | private static bool TryPrepareConfiguredVoxels( |
| | | 1324 | | GridConfiguration configuration, |
| | | 1325 | | GridDimensions dimensions, |
| | | 1326 | | IEnumerable<VoxelIndex>? configuredVoxels, |
| | | 1327 | | bool[,,]? configuredVoxelMask, |
| | | 1328 | | out VoxelIndex[] preparedVoxels) |
| | | 1329 | | { |
| | 938 | 1330 | | preparedVoxels = Array.Empty<VoxelIndex>(); |
| | 938 | 1331 | | if (configuration.StorageKind != GridStorageKind.Sparse) |
| | 801 | 1332 | | return true; |
| | | 1333 | | |
| | 137 | 1334 | | if (configuredVoxelMask != null) |
| | 7 | 1335 | | return TryPrepareConfiguredVoxelMask(configuredVoxelMask, dimensions, out preparedVoxels); |
| | | 1336 | | |
| | 130 | 1337 | | return TryPrepareConfiguredVoxelIndices(configuredVoxels, dimensions, out preparedVoxels); |
| | | 1338 | | } |
| | | 1339 | | |
| | | 1340 | | private static bool TryPrepareConfiguredVoxelMask( |
| | | 1341 | | bool[,,] configuredVoxelMask, |
| | | 1342 | | GridDimensions dimensions, |
| | | 1343 | | out VoxelIndex[] preparedVoxels) |
| | | 1344 | | { |
| | 7 | 1345 | | preparedVoxels = Array.Empty<VoxelIndex>(); |
| | | 1346 | | |
| | 7 | 1347 | | if (configuredVoxelMask.GetLength(0) != dimensions.Width |
| | 7 | 1348 | | || configuredVoxelMask.GetLength(1) != dimensions.Height |
| | 7 | 1349 | | || configuredVoxelMask.GetLength(2) != dimensions.Length) |
| | | 1350 | | { |
| | 5 | 1351 | | GridForgeLogger.Channel.Warn($"Sparse voxel mask dimensions must match normalized grid dimensions."); |
| | 5 | 1352 | | return false; |
| | | 1353 | | } |
| | | 1354 | | |
| | 2 | 1355 | | int configuredCount = 0; |
| | 12 | 1356 | | for (int x = 0; x < dimensions.Width; x++) |
| | | 1357 | | { |
| | 16 | 1358 | | for (int y = 0; y < dimensions.Height; y++) |
| | | 1359 | | { |
| | 24 | 1360 | | for (int z = 0; z < dimensions.Length; z++) |
| | | 1361 | | { |
| | 8 | 1362 | | if (configuredVoxelMask[x, y, z]) |
| | 2 | 1363 | | configuredCount++; |
| | | 1364 | | } |
| | | 1365 | | } |
| | | 1366 | | } |
| | | 1367 | | |
| | 2 | 1368 | | if (configuredCount == 0) |
| | 1 | 1369 | | return true; |
| | | 1370 | | |
| | 1 | 1371 | | preparedVoxels = new VoxelIndex[configuredCount]; |
| | 1 | 1372 | | int index = 0; |
| | 6 | 1373 | | for (int x = 0; x < dimensions.Width; x++) |
| | | 1374 | | { |
| | 8 | 1375 | | for (int y = 0; y < dimensions.Height; y++) |
| | | 1376 | | { |
| | 12 | 1377 | | for (int z = 0; z < dimensions.Length; z++) |
| | | 1378 | | { |
| | 4 | 1379 | | if (configuredVoxelMask[x, y, z]) |
| | 2 | 1380 | | preparedVoxels[index++] = new VoxelIndex(x, y, z); |
| | | 1381 | | } |
| | | 1382 | | } |
| | | 1383 | | } |
| | | 1384 | | |
| | 1 | 1385 | | return true; |
| | | 1386 | | } |
| | | 1387 | | |
| | | 1388 | | private static bool TryPrepareConfiguredVoxelIndices( |
| | | 1389 | | IEnumerable<VoxelIndex>? configuredVoxels, |
| | | 1390 | | GridDimensions dimensions, |
| | | 1391 | | out VoxelIndex[] preparedVoxels) |
| | | 1392 | | { |
| | 130 | 1393 | | preparedVoxels = Array.Empty<VoxelIndex>(); |
| | 130 | 1394 | | if (configuredVoxels == null) |
| | 34 | 1395 | | return true; |
| | | 1396 | | |
| | 96 | 1397 | | SwiftList<VoxelIndex> indices = configuredVoxels is ICollection<VoxelIndex> collection |
| | 96 | 1398 | | ? new SwiftList<VoxelIndex>(collection.Count) |
| | 96 | 1399 | | : new SwiftList<VoxelIndex>(); |
| | | 1400 | | |
| | 469 | 1401 | | foreach (VoxelIndex configuredVoxel in configuredVoxels) |
| | | 1402 | | { |
| | 142 | 1403 | | if (!IsConfiguredVoxelInBounds(configuredVoxel, dimensions)) |
| | | 1404 | | { |
| | 7 | 1405 | | GridForgeLogger.Channel.Warn($"Sparse voxel index {configuredVoxel} is outside normalized grid dimension |
| | 7 | 1406 | | return false; |
| | | 1407 | | } |
| | | 1408 | | |
| | 135 | 1409 | | indices.Add(configuredVoxel); |
| | | 1410 | | } |
| | | 1411 | | |
| | 89 | 1412 | | if (indices.Count == 0) |
| | 8 | 1413 | | return true; |
| | | 1414 | | |
| | 81 | 1415 | | preparedVoxels = indices.ToArray(); |
| | 81 | 1416 | | Array.Sort(preparedVoxels, CompareVoxelIndices); |
| | 81 | 1417 | | CompactPreparedVoxels(ref preparedVoxels); |
| | 81 | 1418 | | return true; |
| | 7 | 1419 | | } |
| | | 1420 | | |
| | | 1421 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1422 | | private static bool IsConfiguredVoxelInBounds(VoxelIndex voxelIndex, GridDimensions dimensions) => |
| | 142 | 1423 | | (uint)voxelIndex.x < (uint)dimensions.Width |
| | 142 | 1424 | | && (uint)voxelIndex.y < (uint)dimensions.Height |
| | 142 | 1425 | | && (uint)voxelIndex.z < (uint)dimensions.Length; |
| | | 1426 | | |
| | | 1427 | | private static void CompactPreparedVoxels(ref VoxelIndex[] preparedVoxels) |
| | | 1428 | | { |
| | 81 | 1429 | | if (preparedVoxels.Length < 2) |
| | 52 | 1430 | | return; |
| | | 1431 | | |
| | 29 | 1432 | | int writeIndex = 1; |
| | 29 | 1433 | | VoxelIndex previous = preparedVoxels[0]; |
| | 166 | 1434 | | for (int readIndex = 1; readIndex < preparedVoxels.Length; readIndex++) |
| | | 1435 | | { |
| | 54 | 1436 | | VoxelIndex current = preparedVoxels[readIndex]; |
| | 54 | 1437 | | if (current == previous) |
| | | 1438 | | continue; |
| | | 1439 | | |
| | 52 | 1440 | | preparedVoxels[writeIndex++] = current; |
| | 52 | 1441 | | previous = current; |
| | | 1442 | | } |
| | | 1443 | | |
| | 29 | 1444 | | if (writeIndex != preparedVoxels.Length) |
| | 2 | 1445 | | Array.Resize(ref preparedVoxels, writeIndex); |
| | 29 | 1446 | | } |
| | | 1447 | | |
| | | 1448 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1449 | | private void UpdateMaxTopologyCellEdge(Fixed64 candidate) |
| | | 1450 | | { |
| | 915 | 1451 | | if (candidate > MaxTopologyCellEdge) |
| | 624 | 1452 | | MaxTopologyCellEdge = candidate; |
| | 915 | 1453 | | } |
| | | 1454 | | |
| | | 1455 | | private void RecalculateMaxTopologyCellEdgeIfNeeded(Fixed64 removedMaxCellEdge) |
| | | 1456 | | { |
| | 56 | 1457 | | if (removedMaxCellEdge < MaxTopologyCellEdge) |
| | 3 | 1458 | | return; |
| | | 1459 | | |
| | 53 | 1460 | | Fixed64 maxCellEdge = Fixed64.Zero; |
| | 164 | 1461 | | foreach (VoxelGrid grid in ActiveGrids) |
| | | 1462 | | { |
| | 29 | 1463 | | if (grid.Topology.MaxCellEdge > maxCellEdge) |
| | 24 | 1464 | | maxCellEdge = grid.Topology.MaxCellEdge; |
| | | 1465 | | } |
| | | 1466 | | |
| | 53 | 1467 | | MaxTopologyCellEdge = maxCellEdge; |
| | 53 | 1468 | | } |
| | | 1469 | | |
| | | 1470 | | private bool TryFindExistingGridUnsafe(GridConfigurationKey boundsKey, out ushort allocatedIndex) |
| | | 1471 | | { |
| | 919 | 1472 | | if (BoundsTracker.TryGetValue(boundsKey, out allocatedIndex)) |
| | | 1473 | | { |
| | 4 | 1474 | | GridForgeLogger.Channel.Warn($"A grid with these bounds has already been allocated."); |
| | 4 | 1475 | | return true; |
| | | 1476 | | } |
| | | 1477 | | |
| | 915 | 1478 | | allocatedIndex = ushort.MaxValue; |
| | 915 | 1479 | | return false; |
| | | 1480 | | } |
| | | 1481 | | |
| | | 1482 | | private void RegisterGrid(VoxelGrid newGrid, ushort allocatedIndex) |
| | | 1483 | | { |
| | 915 | 1484 | | bool hasContactEnvelope = TryCreateBoundaryContactEnvelope( |
| | 915 | 1485 | | newGrid, |
| | 915 | 1486 | | out FixedBoundVolume contactEnvelope); |
| | 915 | 1487 | | _spatialIndex.Insert( |
| | 915 | 1488 | | allocatedIndex, |
| | 915 | 1489 | | new FixedBoundVolume(newGrid.BoundsMin, newGrid.BoundsMax), |
| | 915 | 1490 | | hasContactEnvelope ? contactEnvelope : null); |
| | | 1491 | | |
| | 915 | 1492 | | if (hasContactEnvelope) |
| | | 1493 | | { |
| | 902 | 1494 | | _spatialIndex.CollectContactCandidates(contactEnvelope, _gridCandidates); |
| | 4074 | 1495 | | for (int i = 0; i < _gridCandidates.Count; i++) |
| | | 1496 | | { |
| | 1135 | 1497 | | ushort candidateIndex = _gridCandidates[i]; |
| | 1135 | 1498 | | if (candidateIndex != allocatedIndex) |
| | 233 | 1499 | | InsertBoundaryContactPair(allocatedIndex, candidateIndex); |
| | | 1500 | | } |
| | | 1501 | | } |
| | | 1502 | | |
| | 915 | 1503 | | _spatialIndex.CollectCandidates( |
| | 915 | 1504 | | CreateExpandedBounds( |
| | 915 | 1505 | | newGrid.BoundsMin, |
| | 915 | 1506 | | newGrid.BoundsMax, |
| | 915 | 1507 | | newGrid.Topology.OverlapTolerance), |
| | 915 | 1508 | | ActiveGrids, |
| | 915 | 1509 | | _gridCandidates); |
| | | 1510 | | |
| | 3920 | 1511 | | for (int candidateIndex = 0; candidateIndex < _gridCandidates.Count; candidateIndex++) |
| | | 1512 | | { |
| | 1045 | 1513 | | ushort neighborIndex = _gridCandidates[candidateIndex]; |
| | 1045 | 1514 | | if (neighborIndex == allocatedIndex) |
| | | 1515 | | continue; |
| | | 1516 | | |
| | 130 | 1517 | | VoxelGrid neighborGrid = ActiveGrids[neighborIndex]; |
| | 130 | 1518 | | newGrid.TryAddGridNeighbor(neighborGrid); |
| | 130 | 1519 | | neighborGrid.TryAddGridNeighbor(newGrid); |
| | | 1520 | | } |
| | 915 | 1521 | | } |
| | | 1522 | | |
| | | 1523 | | private void UnregisterGrid(VoxelGrid gridToRemove, ushort removeIndex) |
| | | 1524 | | { |
| | 56 | 1525 | | _spatialIndex.Remove(removeIndex); |
| | 56 | 1526 | | RemoveBoundaryContactPairs(removeIndex); |
| | 56 | 1527 | | UnlinkGridNeighbors(gridToRemove); |
| | 56 | 1528 | | } |
| | | 1529 | | |
| | | 1530 | | private static bool TryCreateBoundaryContactEnvelope( |
| | | 1531 | | VoxelGrid grid, |
| | | 1532 | | out FixedBoundVolume envelope) |
| | | 1533 | | { |
| | 943 | 1534 | | envelope = default; |
| | 943 | 1535 | | if (!GridCellGeometry.TryCreatePrism( |
| | 943 | 1536 | | grid.Configuration.TopologyKind, |
| | 943 | 1537 | | grid.Configuration.TopologyMetrics, |
| | 943 | 1538 | | grid.BoundsMin, |
| | 943 | 1539 | | default, |
| | 943 | 1540 | | out GridCellPrism minimumPrism) |
| | 943 | 1541 | | || !GridCellGeometry.TryCreatePrism( |
| | 943 | 1542 | | grid.Configuration.TopologyKind, |
| | 943 | 1543 | | grid.Configuration.TopologyMetrics, |
| | 943 | 1544 | | grid.BoundsMax, |
| | 943 | 1545 | | default, |
| | 943 | 1546 | | out GridCellPrism maximumPrism)) |
| | | 1547 | | { |
| | 13 | 1548 | | return false; |
| | | 1549 | | } |
| | | 1550 | | |
| | 930 | 1551 | | TopologyVoxelAabb minimum = minimumPrism.GetAabb(); |
| | 930 | 1552 | | TopologyVoxelAabb maximum = maximumPrism.GetAabb(); |
| | 930 | 1553 | | envelope = new FixedBoundVolume( |
| | 930 | 1554 | | new Vector3d( |
| | 930 | 1555 | | FixedMath.Min(minimum.Min.X, maximum.Min.X), |
| | 930 | 1556 | | FixedMath.Min(minimum.Min.Y, maximum.Min.Y), |
| | 930 | 1557 | | FixedMath.Min(minimum.Min.Z, maximum.Min.Z)), |
| | 930 | 1558 | | new Vector3d( |
| | 930 | 1559 | | FixedMath.Max(minimum.Max.X, maximum.Max.X), |
| | 930 | 1560 | | FixedMath.Max(minimum.Max.Y, maximum.Max.Y), |
| | 930 | 1561 | | FixedMath.Max(minimum.Max.Z, maximum.Max.Z))); |
| | 930 | 1562 | | return true; |
| | | 1563 | | } |
| | | 1564 | | |
| | | 1565 | | private void InsertBoundaryContactPair(ushort firstGridIndex, ushort secondGridIndex) |
| | | 1566 | | { |
| | 233 | 1567 | | ushort source = firstGridIndex < secondGridIndex ? firstGridIndex : secondGridIndex; |
| | 233 | 1568 | | ushort target = firstGridIndex < secondGridIndex ? secondGridIndex : firstGridIndex; |
| | 233 | 1569 | | SwiftList<ushort> targets = GetOrCreateBoundaryContactRow( |
| | 233 | 1570 | | _boundaryContactTargetsBySource, |
| | 233 | 1571 | | source, |
| | 233 | 1572 | | out bool addedSourceRow); |
| | 233 | 1573 | | InsertSorted(targets, target); |
| | | 1574 | | |
| | 233 | 1575 | | InsertSorted( |
| | 233 | 1576 | | GetOrCreateBoundaryContactRow(_boundaryContactSourcesByTarget, target, out _), |
| | 233 | 1577 | | source); |
| | 233 | 1578 | | if (addedSourceRow) |
| | 185 | 1579 | | SetBoundaryContactSource(source); |
| | 233 | 1580 | | } |
| | | 1581 | | |
| | | 1582 | | private void RemoveBoundaryContactPairs(ushort gridIndex) |
| | | 1583 | | { |
| | 56 | 1584 | | if (_boundaryContactTargetsBySource.TryGetValue( |
| | 56 | 1585 | | gridIndex, |
| | 56 | 1586 | | out SwiftList<ushort>? targets)) |
| | | 1587 | | { |
| | 44 | 1588 | | for (int i = 0; i < targets.Count; i++) |
| | | 1589 | | { |
| | 15 | 1590 | | RemoveBoundaryContactIncident( |
| | 15 | 1591 | | _boundaryContactSourcesByTarget, |
| | 15 | 1592 | | targets[i], |
| | 15 | 1593 | | gridIndex, |
| | 15 | 1594 | | clearSourceBit: false); |
| | | 1595 | | } |
| | | 1596 | | |
| | 7 | 1597 | | _boundaryContactTargetsBySource.Remove(gridIndex); |
| | 7 | 1598 | | SwiftListPool<ushort>.Shared.Release(targets); |
| | 7 | 1599 | | ClearBoundaryContactSource(gridIndex); |
| | | 1600 | | } |
| | | 1601 | | |
| | 56 | 1602 | | if (_boundaryContactSourcesByTarget.TryGetValue( |
| | 56 | 1603 | | gridIndex, |
| | 56 | 1604 | | out SwiftList<ushort>? sources)) |
| | | 1605 | | { |
| | 60 | 1606 | | for (int i = 0; i < sources.Count; i++) |
| | | 1607 | | { |
| | 16 | 1608 | | RemoveBoundaryContactIncident( |
| | 16 | 1609 | | _boundaryContactTargetsBySource, |
| | 16 | 1610 | | sources[i], |
| | 16 | 1611 | | gridIndex, |
| | 16 | 1612 | | clearSourceBit: true); |
| | | 1613 | | } |
| | | 1614 | | |
| | 14 | 1615 | | _boundaryContactSourcesByTarget.Remove(gridIndex); |
| | 14 | 1616 | | SwiftListPool<ushort>.Shared.Release(sources); |
| | | 1617 | | } |
| | 56 | 1618 | | } |
| | | 1619 | | |
| | | 1620 | | private void RemoveBoundaryContactIncident( |
| | | 1621 | | SwiftDictionary<ushort, SwiftList<ushort>> rows, |
| | | 1622 | | ushort rowIndex, |
| | | 1623 | | ushort incidentIndex, |
| | | 1624 | | bool clearSourceBit) |
| | | 1625 | | { |
| | 31 | 1626 | | bool foundRow = rows.TryGetValue(rowIndex, out SwiftList<ushort>? row); |
| | | 1627 | | Debug.Assert(foundRow && row != null); |
| | 31 | 1628 | | RemoveSorted(row, incidentIndex); |
| | 31 | 1629 | | if (row.Count != 0) |
| | 12 | 1630 | | return; |
| | | 1631 | | |
| | 19 | 1632 | | rows.Remove(rowIndex); |
| | 19 | 1633 | | SwiftListPool<ushort>.Shared.Release(row); |
| | 19 | 1634 | | if (clearSourceBit) |
| | 13 | 1635 | | ClearBoundaryContactSource(rowIndex); |
| | 19 | 1636 | | } |
| | | 1637 | | |
| | | 1638 | | private static SwiftList<ushort> GetOrCreateBoundaryContactRow( |
| | | 1639 | | SwiftDictionary<ushort, SwiftList<ushort>> rows, |
| | | 1640 | | ushort rowIndex, |
| | | 1641 | | out bool added) |
| | | 1642 | | { |
| | 466 | 1643 | | if (rows.TryGetValue(rowIndex, out SwiftList<ushort>? row)) |
| | | 1644 | | { |
| | 97 | 1645 | | added = false; |
| | 97 | 1646 | | return row; |
| | | 1647 | | } |
| | | 1648 | | |
| | 369 | 1649 | | row = SwiftListPool<ushort>.Shared.Rent(); |
| | 369 | 1650 | | rows.Add(rowIndex, row); |
| | 369 | 1651 | | added = true; |
| | 369 | 1652 | | return row; |
| | | 1653 | | } |
| | | 1654 | | |
| | | 1655 | | private static void InsertSorted(SwiftList<ushort> row, ushort value) |
| | | 1656 | | { |
| | 466 | 1657 | | int index = FindSortedIndex(row, value); |
| | 466 | 1658 | | row.Insert(index, value); |
| | 466 | 1659 | | } |
| | | 1660 | | |
| | | 1661 | | private static void RemoveSorted(SwiftList<ushort> row, ushort value) |
| | | 1662 | | { |
| | 31 | 1663 | | int index = FindSortedIndex(row, value); |
| | | 1664 | | Debug.Assert(index < row.Count && row[index] == value); |
| | 31 | 1665 | | row.RemoveAt(index); |
| | 31 | 1666 | | } |
| | | 1667 | | |
| | | 1668 | | private static int FindSortedIndex(SwiftList<ushort> row, ushort value) |
| | | 1669 | | { |
| | 497 | 1670 | | int minimum = 0; |
| | 497 | 1671 | | int maximum = row.Count; |
| | 675 | 1672 | | while (minimum < maximum) |
| | | 1673 | | { |
| | 178 | 1674 | | int middle = minimum + ((maximum - minimum) >> 1); |
| | 178 | 1675 | | if (row[middle] < value) |
| | 117 | 1676 | | minimum = middle + 1; |
| | | 1677 | | else |
| | 61 | 1678 | | maximum = middle; |
| | | 1679 | | } |
| | | 1680 | | |
| | 497 | 1681 | | return minimum; |
| | | 1682 | | } |
| | | 1683 | | |
| | | 1684 | | private void SetBoundaryContactSource(ushort source) |
| | | 1685 | | { |
| | 185 | 1686 | | _boundaryContactSourceWords ??= new ulong[BoundaryContactSourceWordCount]; |
| | 185 | 1687 | | _boundaryContactSourceSummaryWords ??= new ulong[BoundaryContactSourceSummaryWordCount]; |
| | 185 | 1688 | | int wordIndex = source >> 6; |
| | 185 | 1689 | | _boundaryContactSourceWords[wordIndex] |= 1UL << (source & 63); |
| | 185 | 1690 | | _boundaryContactSourceSummaryWords[wordIndex >> 6] |= 1UL << (wordIndex & 63); |
| | 185 | 1691 | | _boundaryContactSourceSummaryLength = Math.Max( |
| | 185 | 1692 | | _boundaryContactSourceSummaryLength, |
| | 185 | 1693 | | (wordIndex >> 6) + 1); |
| | 185 | 1694 | | } |
| | | 1695 | | |
| | | 1696 | | private void ClearBoundaryContactSource(ushort source) |
| | | 1697 | | { |
| | | 1698 | | Debug.Assert(_boundaryContactSourceWords != null && _boundaryContactSourceSummaryWords != null); |
| | 20 | 1699 | | int wordIndex = source >> 6; |
| | 20 | 1700 | | _boundaryContactSourceWords![wordIndex] &= ~(1UL << (source & 63)); |
| | 20 | 1701 | | if (_boundaryContactSourceWords[wordIndex] == 0) |
| | 16 | 1702 | | _boundaryContactSourceSummaryWords![wordIndex >> 6] &= ~(1UL << (wordIndex & 63)); |
| | | 1703 | | |
| | 36 | 1704 | | while (_boundaryContactSourceSummaryLength > 0 |
| | 36 | 1705 | | && _boundaryContactSourceSummaryWords[_boundaryContactSourceSummaryLength - 1] == 0) |
| | | 1706 | | { |
| | 16 | 1707 | | _boundaryContactSourceSummaryLength--; |
| | | 1708 | | } |
| | | 1709 | | |
| | 20 | 1710 | | } |
| | | 1711 | | |
| | | 1712 | | private void ReleaseBoundaryContactPairs() |
| | | 1713 | | { |
| | 1914 | 1714 | | foreach (SwiftList<ushort> row in _boundaryContactTargetsBySource.Values) |
| | 165 | 1715 | | SwiftListPool<ushort>.Shared.Release(row); |
| | 1912 | 1716 | | foreach (SwiftList<ushort> row in _boundaryContactSourcesByTarget.Values) |
| | 164 | 1717 | | SwiftListPool<ushort>.Shared.Release(row); |
| | | 1718 | | |
| | 792 | 1719 | | _boundaryContactTargetsBySource.Clear(); |
| | 792 | 1720 | | _boundaryContactSourcesByTarget.Clear(); |
| | 792 | 1721 | | _boundaryContactSourceWords = null; |
| | 792 | 1722 | | _boundaryContactSourceSummaryWords = null; |
| | 792 | 1723 | | _boundaryContactSourceSummaryLength = 0; |
| | 792 | 1724 | | } |
| | | 1725 | | |
| | | 1726 | | private void UnlinkGridNeighbors(VoxelGrid gridToRemove) |
| | | 1727 | | { |
| | 56 | 1728 | | if (!gridToRemove.IsConjoined) |
| | 44 | 1729 | | return; |
| | | 1730 | | |
| | 12 | 1731 | | var neighborSets = gridToRemove.Neighbors!.DenseValues; |
| | 12 | 1732 | | int neighborSetCount = gridToRemove.Neighbors.Count; |
| | 54 | 1733 | | for (int neighborSetIndex = 0; neighborSetIndex < neighborSetCount; neighborSetIndex++) |
| | | 1734 | | { |
| | 70 | 1735 | | foreach (int neighborIndex in neighborSets[neighborSetIndex]) |
| | | 1736 | | { |
| | 20 | 1737 | | VoxelGrid neighborGrid = ActiveGrids[neighborIndex]; |
| | 20 | 1738 | | neighborGrid.TryRemoveGridNeighbor(gridToRemove); |
| | | 1739 | | } |
| | | 1740 | | } |
| | 12 | 1741 | | } |
| | | 1742 | | |
| | | 1743 | | internal bool CollectGridCandidates( |
| | | 1744 | | Vector3d boundsMin, |
| | | 1745 | | Vector3d boundsMax, |
| | | 1746 | | SwiftList<ushort> candidates, |
| | | 1747 | | int candidateLimit) |
| | | 1748 | | { |
| | 990 | 1749 | | SwiftThrowHelper.ThrowIfNegative(candidateLimit, nameof(candidateLimit)); |
| | 990 | 1750 | | candidates.Clear(); |
| | 990 | 1751 | | if (ActiveGrids.Count == 0) |
| | 6 | 1752 | | return true; |
| | | 1753 | | |
| | 984 | 1754 | | FixedBoundVolume queryBounds = new(boundsMin, boundsMax); |
| | 984 | 1755 | | if (ActiveGrids.Count <= candidateLimit) |
| | | 1756 | | { |
| | 958 | 1757 | | _spatialIndex.CollectCandidates(queryBounds, ActiveGrids, candidates); |
| | 958 | 1758 | | return true; |
| | | 1759 | | } |
| | | 1760 | | |
| | 223 | 1761 | | foreach (VoxelGrid grid in ActiveGrids) |
| | | 1762 | | { |
| | 89 | 1763 | | FixedBoundVolume gridBounds = new(grid.BoundsMin, grid.BoundsMax); |
| | 89 | 1764 | | if (!gridBounds.Intersects(queryBounds)) |
| | | 1765 | | continue; |
| | 69 | 1766 | | if (candidates.Count >= candidateLimit) |
| | 7 | 1767 | | return false; |
| | | 1768 | | |
| | 62 | 1769 | | candidates.Add(grid.GridIndex); |
| | | 1770 | | } |
| | | 1771 | | |
| | 19 | 1772 | | if (candidates.Count > 1) |
| | 18 | 1773 | | candidates.SortInPlace(); |
| | 19 | 1774 | | return true; |
| | 7 | 1775 | | } |
| | | 1776 | | |
| | | 1777 | | private static FixedBoundVolume CreateExpandedBounds( |
| | | 1778 | | Vector3d boundsMin, |
| | | 1779 | | Vector3d boundsMax, |
| | | 1780 | | Fixed64 padding) |
| | | 1781 | | { |
| | 919 | 1782 | | Vector3d expansion = new(padding, padding, padding); |
| | 919 | 1783 | | return new FixedBoundVolume(boundsMin - expansion, boundsMax + expansion); |
| | | 1784 | | } |
| | | 1785 | | |
| | | 1786 | | #region Lookup |
| | | 1787 | | |
| | | 1788 | | /// <summary> |
| | | 1789 | | /// Retrieves a grid by its world-local index. |
| | | 1790 | | /// </summary> |
| | | 1791 | | /// <param name="index">The world-local grid slot to resolve.</param> |
| | | 1792 | | /// <param name="outGrid">The resolved grid, if found.</param> |
| | | 1793 | | /// <returns>True if the grid was resolved; otherwise false.</returns> |
| | | 1794 | | public bool TryGetGrid(int index, out VoxelGrid? outGrid) |
| | | 1795 | | { |
| | 1570 | 1796 | | outGrid = null; |
| | 1570 | 1797 | | if (!CanResolveGrid(index)) |
| | 18 | 1798 | | return false; |
| | | 1799 | | |
| | 1552 | 1800 | | outGrid = ActiveGrids[index]; |
| | 1552 | 1801 | | return true; |
| | | 1802 | | } |
| | | 1803 | | |
| | | 1804 | | /// <summary> |
| | | 1805 | | /// Retrieves the grid containing a given world position. |
| | | 1806 | | /// </summary> |
| | | 1807 | | /// <param name="position">The world position to resolve.</param> |
| | | 1808 | | /// <param name="outGrid">The resolved grid, if found.</param> |
| | | 1809 | | /// <returns>True if a containing grid was found; otherwise false.</returns> |
| | | 1810 | | public bool TryGetGrid(Vector3d position, out VoxelGrid? outGrid) |
| | | 1811 | | { |
| | 154 | 1812 | | outGrid = null; |
| | 154 | 1813 | | if (!CanResolvePosition()) |
| | 2 | 1814 | | return false; |
| | | 1815 | | |
| | 152 | 1816 | | _spatialIndex.CollectPointCandidates(position, _gridCandidates); |
| | 152 | 1817 | | if (TryGetContainingGrid(position, _gridCandidates, out outGrid)) |
| | 64 | 1818 | | return true; |
| | | 1819 | | |
| | 88 | 1820 | | GridForgeLogger.Channel.Info($"No grid contains position {position}."); |
| | 88 | 1821 | | return false; |
| | | 1822 | | } |
| | | 1823 | | |
| | | 1824 | | /// <summary> |
| | | 1825 | | /// Retrieves the grid containing a 2D XZ-plane world position on the default world Y layer. |
| | | 1826 | | /// </summary> |
| | | 1827 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 1828 | | /// <param name="outGrid">The resolved grid, if found.</param> |
| | | 1829 | | /// <returns>True if a containing grid was found; otherwise false.</returns> |
| | | 1830 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1831 | | public bool TryGetGrid(Vector2d position, out VoxelGrid? outGrid) => |
| | 1 | 1832 | | TryGetGrid(position, default, out outGrid); |
| | | 1833 | | |
| | | 1834 | | /// <summary> |
| | | 1835 | | /// Retrieves the grid containing a 2D XZ-plane world position on the supplied world Y layer. |
| | | 1836 | | /// </summary> |
| | | 1837 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 1838 | | /// <param name="layerY">The world Y layer to resolve. Defaults to zero when omitted by paired overloads.</param> |
| | | 1839 | | /// <param name="outGrid">The resolved grid, if found.</param> |
| | | 1840 | | /// <returns>True if a containing grid was found; otherwise false.</returns> |
| | | 1841 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1842 | | public bool TryGetGrid(Vector2d position, Fixed64 layerY, out VoxelGrid? outGrid) => |
| | 3 | 1843 | | TryGetGrid(GridPlane2d.ToWorld(position, layerY), out outGrid); |
| | | 1844 | | |
| | | 1845 | | /// <summary> |
| | | 1846 | | /// Retrieves the active grid whose bounds are nearest to the supplied world position. |
| | | 1847 | | /// </summary> |
| | | 1848 | | /// <param name="position">The world position to resolve.</param> |
| | | 1849 | | /// <param name="outGrid">The closest grid, if found.</param> |
| | | 1850 | | /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are |
| | | 1851 | | /// <returns>True if a closest active grid was resolved; otherwise false.</returns> |
| | | 1852 | | public bool TryGetClosestGrid( |
| | | 1853 | | Vector3d position, |
| | | 1854 | | out VoxelGrid? outGrid, |
| | | 1855 | | GridTopologyKind? topologyKind = null) |
| | | 1856 | | { |
| | 27 | 1857 | | outGrid = null; |
| | 27 | 1858 | | if (!CanResolveActiveGrid()) |
| | 1 | 1859 | | return false; |
| | | 1860 | | |
| | 26 | 1861 | | Fixed64 closestDistanceSquared = Fixed64.MaxValue; |
| | 124 | 1862 | | foreach (VoxelGrid candidateGrid in ActiveGrids) |
| | | 1863 | | { |
| | 36 | 1864 | | if (!candidateGrid.IsActive |
| | 36 | 1865 | | || !MatchesTopologyKind(candidateGrid, topologyKind)) |
| | | 1866 | | { |
| | | 1867 | | continue; |
| | | 1868 | | } |
| | | 1869 | | |
| | 30 | 1870 | | Fixed64 distanceSquared = GetDistanceSquaredToBounds(position, candidateGrid.BoundsMin, candidateGrid.Bounds |
| | 30 | 1871 | | if (outGrid == null || distanceSquared < closestDistanceSquared) |
| | | 1872 | | { |
| | 23 | 1873 | | outGrid = candidateGrid; |
| | 23 | 1874 | | closestDistanceSquared = distanceSquared; |
| | | 1875 | | } |
| | | 1876 | | } |
| | | 1877 | | |
| | 26 | 1878 | | return outGrid != null; |
| | | 1879 | | } |
| | | 1880 | | |
| | | 1881 | | /// <summary> |
| | | 1882 | | /// Retrieves the active grid whose bounds are nearest to a 2D XZ-plane world position on the default world Y layer. |
| | | 1883 | | /// </summary> |
| | | 1884 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 1885 | | /// <param name="outGrid">The closest grid, if found.</param> |
| | | 1886 | | /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are |
| | | 1887 | | /// <returns>True if a closest active grid was resolved; otherwise false.</returns> |
| | | 1888 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1889 | | public bool TryGetClosestGrid( |
| | | 1890 | | Vector2d position, |
| | | 1891 | | out VoxelGrid? outGrid, |
| | | 1892 | | GridTopologyKind? topologyKind = null) => |
| | 1 | 1893 | | TryGetClosestGrid(position, default, out outGrid, topologyKind); |
| | | 1894 | | |
| | | 1895 | | /// <summary> |
| | | 1896 | | /// Retrieves the active grid whose bounds are nearest to a 2D XZ-plane world position on the supplied world Y layer |
| | | 1897 | | /// </summary> |
| | | 1898 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 1899 | | /// <param name="layerY">The world Y layer to resolve. Defaults to zero when omitted by paired overloads.</param> |
| | | 1900 | | /// <param name="outGrid">The closest grid, if found.</param> |
| | | 1901 | | /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are |
| | | 1902 | | /// <returns>True if a closest active grid was resolved; otherwise false.</returns> |
| | | 1903 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1904 | | public bool TryGetClosestGrid( |
| | | 1905 | | Vector2d position, |
| | | 1906 | | Fixed64 layerY, |
| | | 1907 | | out VoxelGrid? outGrid, |
| | | 1908 | | GridTopologyKind? topologyKind = null) => |
| | 3 | 1909 | | TryGetClosestGrid(GridPlane2d.ToWorld(position, layerY), out outGrid, topologyKind); |
| | | 1910 | | |
| | | 1911 | | /// <summary> |
| | | 1912 | | /// Retrieves a grid by a world-scoped voxel identity. |
| | | 1913 | | /// </summary> |
| | | 1914 | | /// <param name="worldVoxelIndex">The voxel identity whose grid should be resolved.</param> |
| | | 1915 | | /// <param name="result">The resolved grid, if found.</param> |
| | | 1916 | | /// <returns>True if the grid was resolved; otherwise false.</returns> |
| | | 1917 | | public bool TryGetGrid(WorldVoxelIndex worldVoxelIndex, out VoxelGrid? result) |
| | | 1918 | | { |
| | 1276 | 1919 | | result = null; |
| | 1276 | 1920 | | if (worldVoxelIndex.WorldSpawnToken != SpawnToken |
| | 1276 | 1921 | | || !TryGetGrid(worldVoxelIndex.GridIndex, out VoxelGrid? resolvedGrid) |
| | 1276 | 1922 | | || worldVoxelIndex.GridSpawnToken != resolvedGrid!.SpawnToken) |
| | | 1923 | | { |
| | 23 | 1924 | | return false; |
| | | 1925 | | } |
| | | 1926 | | |
| | 1253 | 1927 | | result = resolvedGrid; |
| | 1253 | 1928 | | return true; |
| | | 1929 | | } |
| | | 1930 | | |
| | | 1931 | | /// <summary> |
| | | 1932 | | /// Retrieves the grid and voxel containing a given world position. |
| | | 1933 | | /// </summary> |
| | | 1934 | | /// <param name="position">The world position to resolve.</param> |
| | | 1935 | | /// <param name="outGrid">The resolved grid, if found.</param> |
| | | 1936 | | /// <param name="outVoxel">The resolved voxel, if found.</param> |
| | | 1937 | | /// <returns>True if both the grid and voxel were resolved; otherwise false.</returns> |
| | | 1938 | | public bool TryGetGridAndVoxel( |
| | | 1939 | | Vector3d position, |
| | | 1940 | | out VoxelGrid? outGrid, |
| | | 1941 | | out Voxel? outVoxel) |
| | | 1942 | | { |
| | 28 | 1943 | | outVoxel = null; |
| | 28 | 1944 | | return TryGetGrid(position, out outGrid) |
| | 28 | 1945 | | && outGrid!.TryGetVoxel(position, out outVoxel); |
| | | 1946 | | } |
| | | 1947 | | |
| | | 1948 | | /// <summary> |
| | | 1949 | | /// Retrieves the grid and voxel containing a 2D XZ-plane world position on the default world Y layer. |
| | | 1950 | | /// </summary> |
| | | 1951 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 1952 | | /// <param name="outGrid">The resolved grid, if found.</param> |
| | | 1953 | | /// <param name="outVoxel">The resolved voxel, if found.</param> |
| | | 1954 | | /// <returns>True if both the grid and voxel were resolved; otherwise false.</returns> |
| | | 1955 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1956 | | public bool TryGetGridAndVoxel( |
| | | 1957 | | Vector2d position, |
| | | 1958 | | out VoxelGrid? outGrid, |
| | | 1959 | | out Voxel? outVoxel) => |
| | 1 | 1960 | | TryGetGridAndVoxel(position, default, out outGrid, out outVoxel); |
| | | 1961 | | |
| | | 1962 | | /// <summary> |
| | | 1963 | | /// Retrieves the grid and voxel containing a 2D XZ-plane world position on the supplied world Y layer. |
| | | 1964 | | /// </summary> |
| | | 1965 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 1966 | | /// <param name="layerY">The world Y layer to resolve. Defaults to zero when omitted by paired overloads.</param> |
| | | 1967 | | /// <param name="outGrid">The resolved grid, if found.</param> |
| | | 1968 | | /// <param name="outVoxel">The resolved voxel, if found.</param> |
| | | 1969 | | /// <returns>True if both the grid and voxel were resolved; otherwise false.</returns> |
| | | 1970 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 1971 | | public bool TryGetGridAndVoxel( |
| | | 1972 | | Vector2d position, |
| | | 1973 | | Fixed64 layerY, |
| | | 1974 | | out VoxelGrid? outGrid, |
| | | 1975 | | out Voxel? outVoxel) => |
| | 3 | 1976 | | TryGetGridAndVoxel(GridPlane2d.ToWorld(position, layerY), out outGrid, out outVoxel); |
| | | 1977 | | |
| | | 1978 | | /// <summary> |
| | | 1979 | | /// Retrieves the physical voxel whose center is nearest to the supplied world position and the grid that owns it. |
| | | 1980 | | /// Sparse grids only consider configured physical voxels. |
| | | 1981 | | /// </summary> |
| | | 1982 | | /// <param name="position">The world position to resolve.</param> |
| | | 1983 | | /// <param name="outGrid">The grid that owns the closest physical voxel, if found.</param> |
| | | 1984 | | /// <param name="outVoxel">The closest physical voxel, if found.</param> |
| | | 1985 | | /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are |
| | | 1986 | | /// <returns>True if a physical voxel was resolved; otherwise false.</returns> |
| | | 1987 | | public bool TryGetClosestGridAndVoxel( |
| | | 1988 | | Vector3d position, |
| | | 1989 | | out VoxelGrid? outGrid, |
| | | 1990 | | out Voxel? outVoxel, |
| | | 1991 | | GridTopologyKind? topologyKind = null) |
| | | 1992 | | { |
| | 16 | 1993 | | outGrid = null; |
| | 16 | 1994 | | outVoxel = null; |
| | 16 | 1995 | | if (!CanResolveActiveGrid()) |
| | 2 | 1996 | | return false; |
| | | 1997 | | |
| | 14 | 1998 | | Fixed64 closestDistanceSquared = Fixed64.MaxValue; |
| | 14 | 1999 | | if (TryGetClosestGrid(position, out VoxelGrid? closestBoundsGrid, topologyKind) |
| | 14 | 2000 | | && closestBoundsGrid!.ConfiguredVoxelCount != 0) |
| | | 2001 | | { |
| | 10 | 2002 | | bool resolved = closestBoundsGrid.TryGetClosestVoxel( |
| | 10 | 2003 | | position, |
| | 10 | 2004 | | out outVoxel, |
| | 10 | 2005 | | out closestDistanceSquared); |
| | | 2006 | | Debug.Assert(resolved); |
| | 10 | 2007 | | outGrid = closestBoundsGrid; |
| | | 2008 | | } |
| | | 2009 | | |
| | 66 | 2010 | | foreach (VoxelGrid candidateGrid in ActiveGrids) |
| | | 2011 | | { |
| | 19 | 2012 | | if (candidateGrid == null |
| | 19 | 2013 | | || !candidateGrid.IsActive |
| | 19 | 2014 | | || candidateGrid.ConfiguredVoxelCount == 0 |
| | 19 | 2015 | | || !MatchesTopologyKind(candidateGrid, topologyKind)) |
| | | 2016 | | { |
| | | 2017 | | continue; |
| | | 2018 | | } |
| | 14 | 2019 | | if (ReferenceEquals(candidateGrid, outGrid)) |
| | | 2020 | | continue; |
| | | 2021 | | |
| | 5 | 2022 | | Fixed64 boundsDistanceSquared = GetDistanceSquaredToBounds(position, candidateGrid.BoundsMin, candidateGrid. |
| | 5 | 2023 | | if (outVoxel != null && boundsDistanceSquared > closestDistanceSquared) |
| | | 2024 | | continue; |
| | | 2025 | | |
| | 4 | 2026 | | candidateGrid.TryGetClosestVoxel( |
| | 4 | 2027 | | position, |
| | 4 | 2028 | | out Voxel? candidateVoxel, |
| | 4 | 2029 | | out Fixed64 candidateDistanceSquared); |
| | | 2030 | | |
| | 4 | 2031 | | if (IsBetterClosestVoxel( |
| | 4 | 2032 | | candidateDistanceSquared, |
| | 4 | 2033 | | candidateGrid, |
| | 4 | 2034 | | candidateVoxel!, |
| | 4 | 2035 | | closestDistanceSquared, |
| | 4 | 2036 | | outGrid, |
| | 4 | 2037 | | outVoxel)) |
| | | 2038 | | { |
| | 3 | 2039 | | outGrid = candidateGrid; |
| | 3 | 2040 | | outVoxel = candidateVoxel; |
| | 3 | 2041 | | closestDistanceSquared = candidateDistanceSquared; |
| | | 2042 | | } |
| | | 2043 | | } |
| | | 2044 | | |
| | 14 | 2045 | | return outVoxel != null; |
| | | 2046 | | } |
| | | 2047 | | |
| | | 2048 | | /// <summary> |
| | | 2049 | | /// Retrieves the physical voxel whose center is nearest to a 2D XZ-plane world position on the default world Y laye |
| | | 2050 | | /// Sparse grids only consider configured physical voxels. |
| | | 2051 | | /// </summary> |
| | | 2052 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 2053 | | /// <param name="outGrid">The grid that owns the closest physical voxel, if found.</param> |
| | | 2054 | | /// <param name="outVoxel">The closest physical voxel, if found.</param> |
| | | 2055 | | /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are |
| | | 2056 | | /// <returns>True if a physical voxel was resolved; otherwise false.</returns> |
| | | 2057 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 2058 | | public bool TryGetClosestGridAndVoxel( |
| | | 2059 | | Vector2d position, |
| | | 2060 | | out VoxelGrid? outGrid, |
| | | 2061 | | out Voxel? outVoxel, |
| | | 2062 | | GridTopologyKind? topologyKind = null) => |
| | 1 | 2063 | | TryGetClosestGridAndVoxel(position, default, out outGrid, out outVoxel, topologyKind); |
| | | 2064 | | |
| | | 2065 | | /// <summary> |
| | | 2066 | | /// Retrieves the physical voxel whose center is nearest to a 2D XZ-plane world position on the supplied world Y lay |
| | | 2067 | | /// Sparse grids only consider configured physical voxels. |
| | | 2068 | | /// </summary> |
| | | 2069 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 2070 | | /// <param name="layerY">The world Y layer to resolve. Defaults to zero when omitted by paired overloads.</param> |
| | | 2071 | | /// <param name="outGrid">The grid that owns the closest physical voxel, if found.</param> |
| | | 2072 | | /// <param name="outVoxel">The closest physical voxel, if found.</param> |
| | | 2073 | | /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are |
| | | 2074 | | /// <returns>True if a physical voxel was resolved; otherwise false.</returns> |
| | | 2075 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 2076 | | public bool TryGetClosestGridAndVoxel( |
| | | 2077 | | Vector2d position, |
| | | 2078 | | Fixed64 layerY, |
| | | 2079 | | out VoxelGrid? outGrid, |
| | | 2080 | | out Voxel? outVoxel, |
| | | 2081 | | GridTopologyKind? topologyKind = null) => |
| | 3 | 2082 | | TryGetClosestGridAndVoxel(GridPlane2d.ToWorld(position, layerY), out outGrid, out outVoxel, topologyKind); |
| | | 2083 | | |
| | | 2084 | | /// <summary> |
| | | 2085 | | /// Retrieves the grid and voxel for a given voxel identity. |
| | | 2086 | | /// </summary> |
| | | 2087 | | /// <param name="worldVoxelIndex">The voxel identity to resolve.</param> |
| | | 2088 | | /// <param name="outGrid">The resolved grid, if found.</param> |
| | | 2089 | | /// <param name="result">The resolved voxel, if found.</param> |
| | | 2090 | | /// <returns>True if both the grid and voxel were resolved; otherwise false.</returns> |
| | | 2091 | | public bool TryGetGridAndVoxel( |
| | | 2092 | | WorldVoxelIndex worldVoxelIndex, |
| | | 2093 | | out VoxelGrid? outGrid, |
| | | 2094 | | out Voxel? result) |
| | | 2095 | | { |
| | 70 | 2096 | | result = null; |
| | 70 | 2097 | | return TryGetGrid(worldVoxelIndex, out outGrid) |
| | 70 | 2098 | | && outGrid!.TryGetVoxel(worldVoxelIndex.VoxelIndex, out result); |
| | | 2099 | | } |
| | | 2100 | | |
| | | 2101 | | /// <summary> |
| | | 2102 | | /// Retrieves a voxel from a world position. |
| | | 2103 | | /// </summary> |
| | | 2104 | | /// <param name="position">The world position to resolve.</param> |
| | | 2105 | | /// <param name="result">The resolved voxel, if found.</param> |
| | | 2106 | | /// <returns>True if the voxel was resolved; otherwise false.</returns> |
| | | 2107 | | public bool TryGetVoxel( |
| | | 2108 | | Vector3d position, |
| | | 2109 | | out Voxel? result) |
| | | 2110 | | { |
| | 101 | 2111 | | result = null; |
| | 101 | 2112 | | return TryGetGrid(position, out VoxelGrid? grid) |
| | 101 | 2113 | | && grid!.TryGetVoxel(position, out result); |
| | | 2114 | | } |
| | | 2115 | | |
| | | 2116 | | /// <summary> |
| | | 2117 | | /// Retrieves a voxel from a 2D XZ-plane world position on the default world Y layer. |
| | | 2118 | | /// </summary> |
| | | 2119 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 2120 | | /// <param name="result">The resolved voxel, if found.</param> |
| | | 2121 | | /// <returns>True if the voxel was resolved; otherwise false.</returns> |
| | | 2122 | | public bool TryGetVoxel( |
| | | 2123 | | Vector2d position, |
| | | 2124 | | out Voxel? result) |
| | | 2125 | | { |
| | 1 | 2126 | | return TryGetVoxel(position, default, out result); |
| | | 2127 | | } |
| | | 2128 | | |
| | | 2129 | | /// <summary> |
| | | 2130 | | /// Retrieves a voxel from a 2D XZ-plane world position on the supplied world Y layer. |
| | | 2131 | | /// </summary> |
| | | 2132 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 2133 | | /// <param name="layerY">The world Y layer to resolve. Defaults to zero when omitted by paired overloads.</param> |
| | | 2134 | | /// <param name="result">The resolved voxel, if found.</param> |
| | | 2135 | | /// <returns>True if the voxel was resolved; otherwise false.</returns> |
| | | 2136 | | public bool TryGetVoxel( |
| | | 2137 | | Vector2d position, |
| | | 2138 | | Fixed64 layerY, |
| | | 2139 | | out Voxel? result) |
| | | 2140 | | { |
| | 3 | 2141 | | return TryGetVoxel(GridPlane2d.ToWorld(position, layerY), out result); |
| | | 2142 | | } |
| | | 2143 | | |
| | | 2144 | | /// <summary> |
| | | 2145 | | /// Retrieves the physical voxel whose center is nearest to the supplied world position. |
| | | 2146 | | /// Sparse grids only consider configured physical voxels. |
| | | 2147 | | /// </summary> |
| | | 2148 | | /// <param name="position">The world position to resolve.</param> |
| | | 2149 | | /// <param name="result">The closest physical voxel, if found.</param> |
| | | 2150 | | /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are |
| | | 2151 | | /// <returns>True if a physical voxel was resolved; otherwise false.</returns> |
| | | 2152 | | public bool TryGetClosestVoxel( |
| | | 2153 | | Vector3d position, |
| | | 2154 | | out Voxel? result, |
| | | 2155 | | GridTopologyKind? topologyKind = null) |
| | | 2156 | | { |
| | 6 | 2157 | | result = null; |
| | 6 | 2158 | | if (!TryGetClosestGridAndVoxel(position, out _, out Voxel? closestVoxel, topologyKind)) |
| | 2 | 2159 | | return false; |
| | | 2160 | | |
| | 4 | 2161 | | result = closestVoxel; |
| | 4 | 2162 | | return true; |
| | | 2163 | | } |
| | | 2164 | | |
| | | 2165 | | /// <summary> |
| | | 2166 | | /// Retrieves the physical voxel whose center is nearest to a 2D XZ-plane world position on the default world Y laye |
| | | 2167 | | /// Sparse grids only consider configured physical voxels. |
| | | 2168 | | /// </summary> |
| | | 2169 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 2170 | | /// <param name="result">The closest physical voxel, if found.</param> |
| | | 2171 | | /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are |
| | | 2172 | | /// <returns>True if a physical voxel was resolved; otherwise false.</returns> |
| | | 2173 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 2174 | | public bool TryGetClosestVoxel( |
| | | 2175 | | Vector2d position, |
| | | 2176 | | out Voxel? result, |
| | | 2177 | | GridTopologyKind? topologyKind = null) => |
| | 1 | 2178 | | TryGetClosestVoxel(position, default, out result, topologyKind); |
| | | 2179 | | |
| | | 2180 | | /// <summary> |
| | | 2181 | | /// Retrieves the physical voxel whose center is nearest to a 2D XZ-plane world position on the supplied world Y lay |
| | | 2182 | | /// Sparse grids only consider configured physical voxels. |
| | | 2183 | | /// </summary> |
| | | 2184 | | /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param |
| | | 2185 | | /// <param name="layerY">The world Y layer to resolve. Defaults to zero when omitted by paired overloads.</param> |
| | | 2186 | | /// <param name="result">The closest physical voxel, if found.</param> |
| | | 2187 | | /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are |
| | | 2188 | | /// <returns>True if a physical voxel was resolved; otherwise false.</returns> |
| | | 2189 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 2190 | | public bool TryGetClosestVoxel( |
| | | 2191 | | Vector2d position, |
| | | 2192 | | Fixed64 layerY, |
| | | 2193 | | out Voxel? result, |
| | | 2194 | | GridTopologyKind? topologyKind = null) => |
| | 3 | 2195 | | TryGetClosestVoxel(GridPlane2d.ToWorld(position, layerY), out result, topologyKind); |
| | | 2196 | | |
| | | 2197 | | /// <summary> |
| | | 2198 | | /// Retrieves a voxel from a world-scoped voxel identity. |
| | | 2199 | | /// </summary> |
| | | 2200 | | /// <param name="worldVoxelIndex">The voxel identity to resolve.</param> |
| | | 2201 | | /// <param name="result">The resolved voxel, if found.</param> |
| | | 2202 | | /// <returns>True if the voxel was resolved; otherwise false.</returns> |
| | | 2203 | | public bool TryGetVoxel( |
| | | 2204 | | WorldVoxelIndex worldVoxelIndex, |
| | | 2205 | | out Voxel? result) |
| | | 2206 | | { |
| | 3 | 2207 | | result = null; |
| | 3 | 2208 | | return TryGetGrid(worldVoxelIndex, out VoxelGrid? grid) |
| | 3 | 2209 | | && grid!.TryGetVoxel(worldVoxelIndex.VoxelIndex, out result); |
| | | 2210 | | } |
| | | 2211 | | |
| | | 2212 | | #endregion |
| | | 2213 | | |
| | | 2214 | | #region Internal Helpers |
| | | 2215 | | |
| | | 2216 | | /// <summary> |
| | | 2217 | | /// Increments the version of the specified grid and optionally the world version. |
| | | 2218 | | /// </summary> |
| | | 2219 | | public void IncrementGridVersion(int index, bool significant = false) |
| | | 2220 | | { |
| | 5 | 2221 | | if (!IsActive) |
| | | 2222 | | { |
| | 3 | 2223 | | GridForgeLogger.Channel.Warn($"Grid world not active. Cannot increment grid versions."); |
| | 3 | 2224 | | return; |
| | | 2225 | | } |
| | | 2226 | | |
| | 2 | 2227 | | _gridLock.EnterWriteLock(); |
| | | 2228 | | try |
| | | 2229 | | { |
| | 2 | 2230 | | if (significant) |
| | 1 | 2231 | | Version++; |
| | | 2232 | | |
| | 2 | 2233 | | if (ActiveGrids.IsAllocated(index)) |
| | 1 | 2234 | | ActiveGrids[index].IncrementVersion(); |
| | 2 | 2235 | | } |
| | | 2236 | | finally |
| | | 2237 | | { |
| | 2 | 2238 | | _gridLock.ExitWriteLock(); |
| | 2 | 2239 | | } |
| | 2 | 2240 | | } |
| | | 2241 | | |
| | | 2242 | | /// <summary> |
| | | 2243 | | /// Finds active grids in this world that overlap the supplied target grid. |
| | | 2244 | | /// </summary> |
| | | 2245 | | public IEnumerable<VoxelGrid> FindOverlappingGrids(VoxelGrid targetGrid) |
| | | 2246 | | { |
| | 5 | 2247 | | SwiftList<VoxelGrid> overlappingGrids = new(); |
| | 5 | 2248 | | FindOverlappingGridsInto(targetGrid, overlappingGrids); |
| | 5 | 2249 | | return overlappingGrids; |
| | | 2250 | | } |
| | | 2251 | | |
| | | 2252 | | /// <summary> |
| | | 2253 | | /// Clears and fills caller-owned storage with active grids that overlap the supplied target grid. |
| | | 2254 | | /// </summary> |
| | | 2255 | | /// <param name="targetGrid">The grid whose expanded topology bounds define the overlap query.</param> |
| | | 2256 | | /// <param name="results">Caller-owned storage cleared and filled in ascending grid-slot order.</param> |
| | | 2257 | | public void FindOverlappingGridsInto(VoxelGrid targetGrid, SwiftList<VoxelGrid> results) |
| | | 2258 | | { |
| | 7 | 2259 | | SwiftThrowHelper.ThrowIfNull(targetGrid, nameof(targetGrid)); |
| | 7 | 2260 | | SwiftThrowHelper.ThrowIfNull(results, nameof(results)); |
| | | 2261 | | |
| | 7 | 2262 | | results.Clear(); |
| | | 2263 | | |
| | 7 | 2264 | | if (!IsActive) |
| | | 2265 | | { |
| | 3 | 2266 | | GridForgeLogger.Channel.Warn($"Grid world not active. Cannot resolve overlaps."); |
| | 3 | 2267 | | return; |
| | | 2268 | | } |
| | | 2269 | | |
| | 4 | 2270 | | _spatialIndex.CollectCandidates( |
| | 4 | 2271 | | CreateExpandedBounds( |
| | 4 | 2272 | | targetGrid.BoundsMin, |
| | 4 | 2273 | | targetGrid.BoundsMax, |
| | 4 | 2274 | | targetGrid.Topology.OverlapTolerance), |
| | 4 | 2275 | | ActiveGrids, |
| | 4 | 2276 | | _gridCandidates); |
| | 26 | 2277 | | for (int candidateIndex = 0; candidateIndex < _gridCandidates.Count; candidateIndex++) |
| | 9 | 2278 | | TryAddOverlappingGrid(targetGrid, _gridCandidates[candidateIndex], results); |
| | 4 | 2279 | | } |
| | | 2280 | | |
| | | 2281 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 2282 | | private static bool MatchesTopologyKind(VoxelGrid grid, GridTopologyKind? topologyKind) => |
| | 53 | 2283 | | !topologyKind.HasValue || grid.TopologyKind == topologyKind.Value; |
| | | 2284 | | |
| | | 2285 | | private static bool IsBetterClosestVoxel( |
| | | 2286 | | Fixed64 candidateDistanceSquared, |
| | | 2287 | | VoxelGrid candidateGrid, |
| | | 2288 | | Voxel candidateVoxel, |
| | | 2289 | | Fixed64 closestDistanceSquared, |
| | | 2290 | | VoxelGrid? closestGrid, |
| | | 2291 | | Voxel? closestVoxel) |
| | | 2292 | | { |
| | 4 | 2293 | | if (closestVoxel == null || closestGrid == null) |
| | 1 | 2294 | | return true; |
| | | 2295 | | |
| | 3 | 2296 | | if (candidateDistanceSquared != closestDistanceSquared) |
| | 1 | 2297 | | return candidateDistanceSquared < closestDistanceSquared; |
| | | 2298 | | |
| | 2 | 2299 | | return candidateGrid.GridIndex < closestGrid.GridIndex; |
| | | 2300 | | } |
| | | 2301 | | |
| | | 2302 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 2303 | | private static Fixed64 GetDistanceSquaredToBounds(Vector3d position, Vector3d boundsMin, Vector3d boundsMax) |
| | | 2304 | | { |
| | 35 | 2305 | | Fixed64 x = GetAxisDistanceToBounds(position.X, boundsMin.X, boundsMax.X); |
| | 35 | 2306 | | Fixed64 y = GetAxisDistanceToBounds(position.Y, boundsMin.Y, boundsMax.Y); |
| | 35 | 2307 | | Fixed64 z = GetAxisDistanceToBounds(position.Z, boundsMin.Z, boundsMax.Z); |
| | 35 | 2308 | | return x * x + y * y + z * z; |
| | | 2309 | | } |
| | | 2310 | | |
| | | 2311 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 2312 | | private static Fixed64 GetAxisDistanceToBounds(Fixed64 coordinate, Fixed64 min, Fixed64 max) |
| | | 2313 | | { |
| | 105 | 2314 | | if (coordinate < min) |
| | 17 | 2315 | | return min - coordinate; |
| | | 2316 | | |
| | 88 | 2317 | | return coordinate > max ? coordinate - max : Fixed64.Zero; |
| | | 2318 | | } |
| | | 2319 | | |
| | | 2320 | | private bool CanResolveGrid(int index) |
| | | 2321 | | { |
| | 1570 | 2322 | | if (!CanResolveActiveGrid()) |
| | 2 | 2323 | | return false; |
| | | 2324 | | |
| | 1568 | 2325 | | if (!IsGridIndexInActiveRange(index)) |
| | | 2326 | | { |
| | 7 | 2327 | | GridForgeLogger.Channel.Error($"GridIndex '{index}' is out-of-bounds for ActiveGrids."); |
| | 7 | 2328 | | return false; |
| | | 2329 | | } |
| | | 2330 | | |
| | 1561 | 2331 | | return IsGridIndexAllocated(index); |
| | | 2332 | | } |
| | | 2333 | | |
| | | 2334 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 2335 | | private bool CanResolveActiveGrid() |
| | | 2336 | | { |
| | 1613 | 2337 | | if (IsActive) |
| | 1608 | 2338 | | return true; |
| | | 2339 | | |
| | 5 | 2340 | | GridForgeLogger.Channel.Warn($"Grid world not active. Cannot resolve grids."); |
| | 5 | 2341 | | return false; |
| | | 2342 | | } |
| | | 2343 | | |
| | | 2344 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 2345 | | private bool IsGridIndexInActiveRange(int index) => |
| | 1568 | 2346 | | (uint)index < MaxGrids && (uint)index <= ActiveGrids.Count; |
| | | 2347 | | |
| | | 2348 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 2349 | | private bool IsGridIndexAllocated(int index) |
| | | 2350 | | { |
| | 1561 | 2351 | | if (ActiveGrids.IsAllocated(index)) |
| | 1552 | 2352 | | return true; |
| | | 2353 | | |
| | 9 | 2354 | | GridForgeLogger.Channel.Error($"GridIndex '{index}' has not been allocated to ActiveGrids."); |
| | 9 | 2355 | | return false; |
| | | 2356 | | } |
| | | 2357 | | |
| | | 2358 | | private bool CanResolvePosition() |
| | | 2359 | | { |
| | 154 | 2360 | | if (IsActive) |
| | 152 | 2361 | | return true; |
| | | 2362 | | |
| | 2 | 2363 | | GridForgeLogger.Channel.Warn($"Grid world not active. Cannot resolve positions."); |
| | 2 | 2364 | | return false; |
| | | 2365 | | } |
| | | 2366 | | |
| | | 2367 | | private bool TryGetContainingGrid( |
| | | 2368 | | Vector3d position, |
| | | 2369 | | SwiftList<ushort> gridList, |
| | | 2370 | | out VoxelGrid? outGrid) |
| | | 2371 | | { |
| | 152 | 2372 | | outGrid = null; |
| | | 2373 | | |
| | 352 | 2374 | | for (int index = 0; index < gridList.Count; index++) |
| | | 2375 | | { |
| | 88 | 2376 | | ushort candidateIndex = gridList[index]; |
| | 88 | 2377 | | VoxelGrid candidateGrid = ActiveGrids[candidateIndex]; |
| | 88 | 2378 | | if (candidateGrid.IsInBounds(position)) |
| | | 2379 | | { |
| | 64 | 2380 | | outGrid = candidateGrid; |
| | 64 | 2381 | | return true; |
| | | 2382 | | } |
| | | 2383 | | } |
| | | 2384 | | |
| | 88 | 2385 | | return false; |
| | | 2386 | | } |
| | | 2387 | | |
| | | 2388 | | private void TryAddOverlappingGrid( |
| | | 2389 | | VoxelGrid targetGrid, |
| | | 2390 | | ushort neighborIndex, |
| | | 2391 | | SwiftList<VoxelGrid> overlappingGrids) |
| | | 2392 | | { |
| | 9 | 2393 | | if (neighborIndex == targetGrid.GridIndex) |
| | 4 | 2394 | | return; |
| | | 2395 | | |
| | 5 | 2396 | | overlappingGrids.Add(ActiveGrids[neighborIndex]); |
| | 5 | 2397 | | } |
| | | 2398 | | |
| | | 2399 | | #endregion |
| | | 2400 | | |
| | | 2401 | | #region Private Helpers |
| | | 2402 | | |
| | | 2403 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 2404 | | private static int ResolveSpatialGridCellSize(int spatialGridCellSize) |
| | | 2405 | | { |
| | 785 | 2406 | | if (spatialGridCellSize <= 0) |
| | | 2407 | | { |
| | 3 | 2408 | | GridForgeLogger.Channel.Warn($"Spatial grid cell size must be greater than zero. Falling back to default siz |
| | 3 | 2409 | | return DefaultSpatialGridCellSize; |
| | | 2410 | | } |
| | | 2411 | | |
| | 782 | 2412 | | return spatialGridCellSize; |
| | | 2413 | | } |
| | | 2414 | | |
| | | 2415 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 2416 | | private GridEventInfo CreateGridEventInfo( |
| | | 2417 | | VoxelGrid grid, |
| | | 2418 | | GridEventKind changeKind, |
| | | 2419 | | GridChangeStamp changeStamp) |
| | | 2420 | | { |
| | 971 | 2421 | | grid.LastChangeSequence = changeStamp.Sequence; |
| | 971 | 2422 | | return new GridEventInfo( |
| | 971 | 2423 | | SpawnToken, |
| | 971 | 2424 | | grid.GridIndex, |
| | 971 | 2425 | | grid.SpawnToken, |
| | 971 | 2426 | | grid.Configuration, |
| | 971 | 2427 | | grid.Version, |
| | 971 | 2428 | | changeKind, |
| | 971 | 2429 | | default, |
| | 971 | 2430 | | grid.BoundsMin, |
| | 971 | 2431 | | grid.BoundsMax, |
| | 971 | 2432 | | changeStamp); |
| | | 2433 | | } |
| | | 2434 | | |
| | | 2435 | | internal GridEventInfo CreateGridEventInfo( |
| | | 2436 | | VoxelGrid grid, |
| | | 2437 | | GridEventKind changeKind, |
| | | 2438 | | VoxelIndex voxelIndex, |
| | | 2439 | | Vector3d affectedBoundsMin, |
| | | 2440 | | Vector3d affectedBoundsMax, |
| | | 2441 | | GridChangeStamp changeStamp, |
| | | 2442 | | bool hasVoxelState, |
| | | 2443 | | bool isVoxelPresent, |
| | | 2444 | | byte obstacleCount) |
| | | 2445 | | { |
| | 1730 | 2446 | | grid.LastChangeSequence = changeStamp.Sequence; |
| | 1730 | 2447 | | return new GridEventInfo( |
| | 1730 | 2448 | | SpawnToken, |
| | 1730 | 2449 | | grid.GridIndex, |
| | 1730 | 2450 | | grid.SpawnToken, |
| | 1730 | 2451 | | grid.Configuration, |
| | 1730 | 2452 | | grid.Version, |
| | 1730 | 2453 | | changeKind, |
| | 1730 | 2454 | | voxelIndex, |
| | 1730 | 2455 | | affectedBoundsMin, |
| | 1730 | 2456 | | affectedBoundsMax, |
| | 1730 | 2457 | | changeStamp, |
| | 1730 | 2458 | | hasVoxelState, |
| | 1730 | 2459 | | isVoxelPresent, |
| | 1730 | 2460 | | obstacleCount); |
| | | 2461 | | } |
| | | 2462 | | |
| | | 2463 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 2464 | | internal GridChangeStamp AllocateChangeStamp() |
| | | 2465 | | { |
| | | 2466 | | Debug.Assert(Monitor.IsEntered(ChangeSyncRoot)); |
| | 3493 | 2467 | | _changeSequence = checked(_changeSequence + 1); |
| | 3493 | 2468 | | return new GridChangeStamp(_changeSequence, _changeSequence); |
| | | 2469 | | } |
| | | 2470 | | |
| | | 2471 | | internal bool EnqueueCommittedChange(GridCommittedChange change) |
| | | 2472 | | { |
| | | 2473 | | Debug.Assert(Monitor.IsEntered(ChangeSyncRoot)); |
| | 3493 | 2474 | | _committedChanges.Enqueue(change); |
| | 3493 | 2475 | | if (_isPublishingCommittedChanges) |
| | 942 | 2476 | | return false; |
| | | 2477 | | |
| | 2551 | 2478 | | _isPublishingCommittedChanges = true; |
| | 2551 | 2479 | | return true; |
| | | 2480 | | } |
| | | 2481 | | |
| | | 2482 | | internal void DrainCommittedChanges() |
| | | 2483 | | { |
| | 2551 | 2484 | | Volatile.Write(ref _committedPublicationOwnerThreadId, Environment.CurrentManagedThreadId); |
| | | 2485 | | try |
| | | 2486 | | { |
| | | 2487 | | while (true) |
| | | 2488 | | { |
| | | 2489 | | GridCommittedChange change; |
| | 6044 | 2490 | | lock (ChangeSyncRoot) |
| | | 2491 | | { |
| | 6044 | 2492 | | if (!_committedChanges.TryDequeue(out change)) |
| | | 2493 | | { |
| | 2551 | 2494 | | _isPublishingCommittedChanges = false; |
| | 2551 | 2495 | | return; |
| | | 2496 | | } |
| | 3493 | 2497 | | } |
| | | 2498 | | |
| | 3493 | 2499 | | GridObstacleManager.NotifyCommittedExact(change); |
| | 3493 | 2500 | | switch (change.GridEvent.ChangeKind) |
| | | 2501 | | { |
| | | 2502 | | case GridEventKind.GridAdded: |
| | 915 | 2503 | | NotifyActiveGridAdded(change.GridEvent); |
| | 915 | 2504 | | break; |
| | | 2505 | | case GridEventKind.GridRemoved: |
| | 56 | 2506 | | NotifyActiveGridRemoved(change.GridEvent); |
| | 56 | 2507 | | break; |
| | | 2508 | | case GridEventKind.WorldReset: |
| | | 2509 | | break; |
| | | 2510 | | default: |
| | 1730 | 2511 | | NotifyActiveGridChange(change.GridEvent); |
| | | 2512 | | break; |
| | | 2513 | | } |
| | | 2514 | | |
| | 3493 | 2515 | | NotifyChangeCommitted(change.GridEvent); |
| | 3493 | 2516 | | lock (ChangeSyncRoot) |
| | | 2517 | | { |
| | 3493 | 2518 | | _publishedChangeSequence = change.GridEvent.ChangeSequence; |
| | 3493 | 2519 | | Monitor.PulseAll(ChangeSyncRoot); |
| | 3493 | 2520 | | } |
| | | 2521 | | } |
| | | 2522 | | } |
| | | 2523 | | finally |
| | | 2524 | | { |
| | 2551 | 2525 | | Volatile.Write(ref _committedPublicationOwnerThreadId, 0); |
| | 2551 | 2526 | | } |
| | 2551 | 2527 | | } |
| | | 2528 | | |
| | | 2529 | | private void NotifyActiveGridAdded(GridEventInfo eventInfo) |
| | | 2530 | | { |
| | 915 | 2531 | | Action<GridEventInfo>? handlers = _onActiveGridAdded; |
| | 915 | 2532 | | if (handlers == null) |
| | 904 | 2533 | | return; |
| | | 2534 | | |
| | 11 | 2535 | | var handlerDelegates = handlers.GetInvocationList(); |
| | 48 | 2536 | | for (int i = 0; i < handlerDelegates.Length; i++) |
| | | 2537 | | { |
| | | 2538 | | try |
| | | 2539 | | { |
| | 13 | 2540 | | ((Action<GridEventInfo>)handlerDelegates[i])(eventInfo); |
| | 12 | 2541 | | } |
| | 1 | 2542 | | catch (Exception ex) |
| | | 2543 | | { |
| | 1 | 2544 | | GridForgeLogger.Channel.Error($"[Grid {eventInfo.GridIndex}] added notification error: {ex.Message}"); |
| | 1 | 2545 | | } |
| | | 2546 | | } |
| | 11 | 2547 | | } |
| | | 2548 | | |
| | | 2549 | | private void NotifyActiveGridRemoved(GridEventInfo eventInfo) |
| | | 2550 | | { |
| | 56 | 2551 | | Action<GridEventInfo>? handlers = _onActiveGridRemoved; |
| | 56 | 2552 | | if (handlers == null) |
| | 48 | 2553 | | return; |
| | | 2554 | | |
| | 8 | 2555 | | var handlerDelegates = handlers.GetInvocationList(); |
| | 36 | 2556 | | for (int i = 0; i < handlerDelegates.Length; i++) |
| | | 2557 | | { |
| | | 2558 | | try |
| | | 2559 | | { |
| | 10 | 2560 | | ((Action<GridEventInfo>)handlerDelegates[i])(eventInfo); |
| | 9 | 2561 | | } |
| | 1 | 2562 | | catch (Exception ex) |
| | | 2563 | | { |
| | 1 | 2564 | | GridForgeLogger.Channel.Error($"[Grid {eventInfo.GridIndex}] removed notification error: {ex.Message}"); |
| | 1 | 2565 | | } |
| | | 2566 | | } |
| | 8 | 2567 | | } |
| | | 2568 | | |
| | | 2569 | | internal void NotifyActiveGridChange(GridEventInfo eventInfo) |
| | | 2570 | | { |
| | 1730 | 2571 | | Action<GridEventInfo>? handlers = _onActiveGridChange; |
| | 1730 | 2572 | | if (handlers == null) |
| | 907 | 2573 | | return; |
| | | 2574 | | |
| | 823 | 2575 | | var handlerDelegates = handlers.GetInvocationList(); |
| | 61380 | 2576 | | for (int i = 0; i < handlerDelegates.Length; i++) |
| | | 2577 | | { |
| | | 2578 | | try |
| | | 2579 | | { |
| | 29867 | 2580 | | ((Action<GridEventInfo>)handlerDelegates[i])(eventInfo); |
| | 29865 | 2581 | | } |
| | 2 | 2582 | | catch (Exception ex) |
| | | 2583 | | { |
| | 2 | 2584 | | GridForgeLogger.Channel.Error($"[Grid {eventInfo.GridIndex}] change notification error: {ex.Message}"); |
| | 2 | 2585 | | } |
| | | 2586 | | } |
| | 823 | 2587 | | } |
| | | 2588 | | |
| | | 2589 | | private void NotifyChangeCommitted(GridEventInfo eventInfo) |
| | | 2590 | | { |
| | 3493 | 2591 | | Action<GridEventInfo>? handlers = _onChangeCommitted; |
| | 3493 | 2592 | | if (handlers == null) |
| | 3466 | 2593 | | return; |
| | | 2594 | | |
| | 27 | 2595 | | var handlerDelegates = handlers.GetInvocationList(); |
| | 110 | 2596 | | for (int i = 0; i < handlerDelegates.Length; i++) |
| | | 2597 | | { |
| | | 2598 | | try |
| | | 2599 | | { |
| | 28 | 2600 | | ((Action<GridEventInfo>)handlerDelegates[i])(eventInfo); |
| | 27 | 2601 | | } |
| | 1 | 2602 | | catch (Exception ex) |
| | | 2603 | | { |
| | 1 | 2604 | | GridForgeLogger.Channel.Error($"[Change {eventInfo.ChangeSequence}] committed notification error: {ex.Me |
| | 1 | 2605 | | } |
| | | 2606 | | } |
| | 27 | 2607 | | } |
| | | 2608 | | |
| | | 2609 | | #endregion |
| | | 2610 | | } |