< Summary

Line coverage
100%
Covered lines: 1329
Uncovered lines: 0
Coverable lines: 1329
Total lines: 3028
Line coverage: 100%
Branch coverage
100%
Covered branches: 556
Total branches: 556
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
File 1: TryBeginCoveredAddresses(...)100%11100%
File 1: TryBeginCoveredAddresses(...)100%11100%
File 1: AdvanceCoveredAddresses(...)100%44100%
File 1: TryBeginCoveredAddressesCore(...)100%22100%
File 1: AdvanceCoveredAddressesCore(...)100%4444100%
File 1: TryBindCoveredAddressGeneration(...)100%2020100%
File 1: IsCoveredAddressCursorCurrent(...)100%66100%
File 1: IsCoveredAddress(...)100%1212100%
File 1: AdvanceCoveredAddress(...)100%66100%
File 1: ConsumeLookupProbe(...)100%22100%
File 1: ConsumeAddressProbe(...)100%22100%
File 2: .cctor()100%11100%
File 2: get_ChangeSequence()100%11100%
File 2: EnterReadLock()100%11100%
File 2: ExitReadLock()100%11100%
File 2: get_IsWriteLockHeld()100%11100%
File 2: .ctor(...)100%11100%
File 2: add_OnActiveGridAdded(...)100%11100%
File 2: remove_OnActiveGridAdded(...)100%11100%
File 2: add_OnActiveGridRemoved(...)100%11100%
File 2: remove_OnActiveGridRemoved(...)100%11100%
File 2: add_OnActiveGridChange(...)100%11100%
File 2: remove_OnActiveGridChange(...)100%11100%
File 2: add_OnChangeCommitted(...)100%11100%
File 2: remove_OnChangeCommitted(...)100%11100%
File 2: add_OnReset(...)100%11100%
File 2: remove_OnReset(...)100%11100%
File 2: Reset(...)100%88100%
File 2: NotifyResetHandlers()100%66100%
File 2: ReleaseActiveGrids()100%22100%
File 2: Dispose()100%11100%
File 2: AllocateObstacleToken()100%22100%
File 2: TryCaptureNavigationBaseline(...)100%44100%
File 2: ExecuteNavigationMaintenanceSnapshot(...)100%22100%
File 2: BeginBoundaryContacts(...)100%22100%
File 2: TryBeginBoundaryContacts(...)100%44100%
File 2: AdvanceBoundaryContacts(...)100%22100%
File 2: AdvanceBoundaryContacts(...)100%22100%
File 2: AdvanceBoundaryContactsUnderGate(...)100%22100%
File 2: AdvanceBoundaryContactsCore(...)100%4848100%
File 2: IsBoundaryContactCursorCurrent(...)100%1616100%
File 2: TryAdvanceFilteredBoundaryContactPair(...)100%2222100%
File 2: BindBoundaryContactPair(...)100%11100%
File 2: ProbeBoundaryContactTarget(...)100%44100%
File 2: AdvanceBoundaryContactAddress(...)100%66100%
File 2: TryCreateTopologyPrism(...)100%11100%
File 2: GetTrailingZeroCount(...)100%22100%
File 2: ConsumeBoundaryContactProbe(...)100%22100%
File 2: ThrowIfNavigationMaintenanceUnavailable()100%11100%
File 2: TryEnterNavigationMaintenanceSnapshot()100%22100%
File 2: ExitNavigationMaintenanceSnapshot()100%11100%
File 2: WaitForPublishedChangePrefix()100%22100%
File 2: TryCaptureNavigationBaselineCore(...)100%88100%
File 2: AreNavigationBaselineAddressesValid(...)100%88100%
File 2: TryAddGrid(...)100%11100%
File 2: TryAddGrid(...)100%11100%
File 2: TryAddGrid(...)100%11100%
File 2: TryAddGridCore(...)100%1212100%
File 2: TryRemoveGrid(...)100%1010100%
File 2: CanAddGrid()100%44100%
File 2: TryPrepareConfiguredVoxels(...)100%44100%
File 2: TryPrepareConfiguredVoxelMask(...)100%2424100%
File 2: TryPrepareConfiguredVoxelIndices(...)100%1212100%
File 2: IsConfiguredVoxelInBounds(...)100%44100%
File 2: CompactPreparedVoxels(...)100%88100%
File 2: UpdateMaxTopologyCellEdge(...)100%22100%
File 2: RecalculateMaxTopologyCellEdgeIfNeeded(...)100%66100%
File 2: TryFindExistingGridUnsafe(...)100%22100%
File 2: RegisterGrid(...)100%1212100%
File 2: UnregisterGrid(...)100%11100%
File 2: TryCreateBoundaryContactEnvelope(...)100%44100%
File 2: InsertBoundaryContactPair(...)100%66100%
File 2: RemoveBoundaryContactPairs(...)100%88100%
File 2: RemoveBoundaryContactIncident(...)100%44100%
File 2: GetOrCreateBoundaryContactRow(...)100%22100%
File 2: InsertSorted(...)100%11100%
File 2: RemoveSorted(...)100%11100%
File 2: FindSortedIndex(...)100%44100%
File 2: SetBoundaryContactSource(...)100%44100%
File 2: ClearBoundaryContactSource(...)100%66100%
File 2: ReleaseBoundaryContactPairs()100%44100%
File 2: UnlinkGridNeighbors(...)100%66100%
File 2: CollectGridCandidates(...)100%1212100%
File 2: CreateExpandedBounds(...)100%11100%
File 2: TryGetGrid(...)100%22100%
File 2: TryGetGrid(...)100%66100%
File 2: TryGetGrid(...)100%11100%
File 2: TryGetGrid(...)100%11100%
File 2: TryGetClosestGrid(...)100%1212100%
File 2: TryGetClosestGrid(...)100%11100%
File 2: TryGetClosestGrid(...)100%11100%
File 2: TryGetGrid(...)100%66100%
File 2: TryGetGridAndVoxel(...)100%22100%
File 2: TryGetGridAndVoxel(...)100%11100%
File 2: TryGetGridAndVoxel(...)100%11100%
File 2: TryGetClosestGridAndVoxel(...)100%2424100%
File 2: TryGetClosestGridAndVoxel(...)100%11100%
File 2: TryGetClosestGridAndVoxel(...)100%11100%
File 2: TryGetGridAndVoxel(...)100%22100%
File 2: TryGetVoxel(...)100%22100%
File 2: TryGetVoxel(...)100%11100%
File 2: TryGetVoxel(...)100%11100%
File 2: TryGetClosestVoxel(...)100%22100%
File 2: TryGetClosestVoxel(...)100%11100%
File 2: TryGetClosestVoxel(...)100%11100%
File 2: TryGetVoxel(...)100%22100%
File 2: IncrementGridVersion(...)100%66100%
File 2: FindOverlappingGrids(...)100%11100%
File 2: FindOverlappingGridsInto(...)100%44100%
File 2: MatchesTopologyKind(...)100%22100%
File 2: IsBetterClosestVoxel(...)100%66100%
File 2: GetDistanceSquaredToBounds(...)100%11100%
File 2: GetAxisDistanceToBounds(...)100%44100%
File 2: CanResolveGrid(...)100%66100%
File 2: CanResolveActiveGrid()100%22100%
File 2: IsGridIndexInActiveRange(...)100%22100%
File 2: IsGridIndexAllocated(...)100%44100%
File 2: CanResolvePosition()100%22100%
File 2: TryGetContainingGrid(...)100%44100%
File 2: TryAddOverlappingGrid(...)100%22100%
File 2: ResolveSpatialGridCellSize(...)100%44100%
File 2: CreateGridEventInfo(...)100%11100%
File 2: CreateGridEventInfo(...)100%11100%
File 2: AllocateChangeStamp()100%11100%
File 2: EnqueueCommittedChange(...)100%22100%
File 2: DrainCommittedChanges()100%88100%
File 2: NotifyActiveGridAdded(...)100%66100%
File 2: NotifyActiveGridRemoved(...)100%66100%
File 2: NotifyActiveGridChange(...)100%66100%
File 2: NotifyChangeCommitted(...)100%66100%

File(s)

/home/runner/work/GridForge/GridForge/src/GridForge/Grids/Managers/GridWorld.CoveredAddresses.cs

#LineLine coverage
 1//=======================================================================
 2// GridWorld.CoveredAddresses.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
 8using System;
 9using FixedMathSharp;
 10using GridForge.Configuration;
 11using GridForge.Grids.Topology;
 12using GridForge.Spatial;
 13
 14namespace GridForge.Grids;
 15
 16public sealed partial class GridWorld
 17{
 18    /// <summary>
 19    /// Begins a bounded covered-address query for a declared number of exact eligible grid generations.
 20    /// </summary>
 21    /// <param name="cursor">The caller-owned cursor and preallocated generation storage.</param>
 22    /// <param name="boundsMin">One world-space corner of the coverage bounds.</param>
 23    /// <param name="boundsMax">The opposite world-space corner of the coverage bounds.</param>
 24    /// <param name="eligibleGenerationCount">The exact number of canonical generation inputs that will follow.</param>
 25    /// <returns>True when the declared count fits the cursor; otherwise false and the cursor is stale.</returns>
 26    public bool TryBeginCoveredAddresses(
 27        GridCoveredAddressCursor cursor,
 28        Vector3d boundsMin,
 29        Vector3d boundsMax,
 30        int eligibleGenerationCount) =>
 2731        TryBeginCoveredAddressesCore(
 2732            cursor,
 2733            boundsMin,
 2734            boundsMax,
 2735            eligibleGenerationCount,
 2736            hasConfigurationFilter: false,
 2737            default);
 38
 39    /// <summary>
 40    /// Begins a bounded covered-address query filtered to one durable grid configuration before address yield.
 41    /// </summary>
 42    /// <param name="cursor">The caller-owned cursor and preallocated generation storage.</param>
 43    /// <param name="boundsMin">One world-space corner of the coverage bounds.</param>
 44    /// <param name="boundsMax">The opposite world-space corner of the coverage bounds.</param>
 45    /// <param name="eligibleGenerationCount">The exact number of canonical generation inputs that will follow.</param>
 46    /// <param name="configurationFilter">The only configuration eligible to produce addresses.</param>
 47    /// <returns>True when the declared count fits the cursor; otherwise false and the cursor is stale.</returns>
 48    public bool TryBeginCoveredAddresses(
 49        GridCoveredAddressCursor cursor,
 50        Vector3d boundsMin,
 51        Vector3d boundsMax,
 52        int eligibleGenerationCount,
 53        GridConfigurationKey configurationFilter) =>
 254        TryBeginCoveredAddressesCore(
 255            cursor,
 256            boundsMin,
 257            boundsMax,
 258            eligibleGenerationCount,
 259            hasConfigurationFilter: true,
 260            configurationFilter);
 61
 62    /// <summary>
 63    /// Advances generation binding and covered topology-address enumeration under one maintenance snapshot.
 64    /// </summary>
 65    /// <param name="cursor">The cursor previously begun through this world.</param>
 66    /// <param name="generationInputs">The next strictly ascending remaining generation slice, or empty after binding co
 67    /// <param name="results">Caller-owned output storage.</param>
 68    /// <param name="lookupProbeLimit">Maximum generation-validation and spatial lookup probes for this chunk.</param>
 69    /// <param name="addressProbeLimit">Maximum topology-address probes for this chunk.</param>
 70    /// <param name="outputLimit">Maximum covered addresses to write for this chunk.</param>
 71    /// <param name="lookupProbesConsumed">Exact lookup probes consumed by this chunk.</param>
 72    /// <param name="addressProbesConsumed">Exact topology-address probes consumed by this chunk.</param>
 73    /// <param name="generationInputsConsumed">Generation values consumed from the supplied slice.</param>
 74    /// <param name="outputCount">Covered addresses written to <paramref name="results"/>.</param>
 75    /// <returns>The resulting cursor state.</returns>
 76    /// <remarks>
 77    /// No address can be emitted until every declared generation has been validated and copied. A stale
 78    /// result writes no output, clears the run stamp, and requires every prior result from the run to be discarded.
 79    /// Address enumeration does not resolve physical voxel presence or obstacle state. Hex-prism coverage
 80    /// includes cells touching the inclusive query bounds at either vertical face.
 81    /// </remarks>
 82    public GridCoveredAddressCursorStatus AdvanceCoveredAddresses(
 83        GridCoveredAddressCursor cursor,
 84        ReadOnlySpan<GridCoveredAddressGeneration> generationInputs,
 85        Span<GridCoveredAddress> results,
 86        int lookupProbeLimit,
 87        int addressProbeLimit,
 88        int outputLimit,
 89        out int lookupProbesConsumed,
 90        out int addressProbesConsumed,
 91        out int generationInputsConsumed,
 92        out int outputCount)
 93    {
 3494        ChronicleGuard.ThrowIfNull(cursor, nameof(cursor));
 3495        ChronicleGuard.ThrowIfNegative(lookupProbeLimit, nameof(lookupProbeLimit));
 3496        ChronicleGuard.ThrowIfNegative(addressProbeLimit, nameof(addressProbeLimit));
 3497        ChronicleGuard.ThrowIfNegative(outputLimit, nameof(outputLimit));
 3498        if (outputLimit > results.Length)
 199            throw new ArgumentOutOfRangeException(nameof(outputLimit));
 100
 33101        ThrowIfNavigationMaintenanceUnavailable();
 32102        lookupProbesConsumed = 0;
 32103        addressProbesConsumed = 0;
 32104        generationInputsConsumed = 0;
 32105        outputCount = 0;
 1106        while (true)
 107        {
 33108            if (TryEnterNavigationMaintenanceSnapshot())
 109            {
 110                try
 111                {
 32112                    return AdvanceCoveredAddressesCore(
 32113                        cursor,
 32114                        generationInputs,
 32115                        results,
 32116                        lookupProbeLimit,
 32117                        addressProbeLimit,
 32118                        outputLimit,
 32119                        out lookupProbesConsumed,
 32120                        out addressProbesConsumed,
 32121                        out generationInputsConsumed,
 32122                        out outputCount);
 123                }
 124                finally
 125                {
 32126                    ExitNavigationMaintenanceSnapshot();
 32127                }
 128            }
 129
 1130            WaitForPublishedChangePrefix();
 131        }
 32132    }
 133
 134    private bool TryBeginCoveredAddressesCore(
 135        GridCoveredAddressCursor cursor,
 136        Vector3d boundsMin,
 137        Vector3d boundsMax,
 138        int eligibleGenerationCount,
 139        bool hasConfigurationFilter,
 140        GridConfigurationKey configurationFilter)
 141    {
 29142        ChronicleGuard.ThrowIfNull(cursor, nameof(cursor));
 29143        ThrowIfNavigationMaintenanceUnavailable();
 144
 28145        Vector3d queryMinimum = new Vector3d(
 28146            FixedMath.Min(boundsMin.X, boundsMax.X),
 28147            FixedMath.Min(boundsMin.Y, boundsMax.Y),
 28148            FixedMath.Min(boundsMin.Z, boundsMax.Z));
 28149        Vector3d queryMaximum = new Vector3d(
 28150            FixedMath.Max(boundsMin.X, boundsMax.X),
 28151            FixedMath.Max(boundsMin.Y, boundsMax.Y),
 28152            FixedMath.Max(boundsMin.Z, boundsMax.Z));
 153
 1154        while (true)
 155        {
 29156            if (TryEnterNavigationMaintenanceSnapshot())
 157            {
 158                try
 159                {
 28160                    return cursor.Begin(
 28161                        SpawnToken,
 28162                        Version,
 28163                        _changeSequence,
 28164                        queryMinimum,
 28165                        queryMaximum,
 28166                        eligibleGenerationCount,
 28167                        hasConfigurationFilter,
 28168                        configurationFilter);
 169                }
 170                finally
 171                {
 28172                    ExitNavigationMaintenanceSnapshot();
 28173                }
 174            }
 175
 1176            WaitForPublishedChangePrefix();
 177        }
 28178    }
 179
 180    private GridCoveredAddressCursorStatus AdvanceCoveredAddressesCore(
 181        GridCoveredAddressCursor cursor,
 182        ReadOnlySpan<GridCoveredAddressGeneration> generationInputs,
 183        Span<GridCoveredAddress> results,
 184        int lookupProbeLimit,
 185        int addressProbeLimit,
 186        int outputLimit,
 187        out int lookupProbesConsumed,
 188        out int addressProbesConsumed,
 189        out int generationInputsConsumed,
 190        out int outputCount)
 191    {
 32192        lookupProbesConsumed = 0;
 32193        addressProbesConsumed = 0;
 32194        generationInputsConsumed = 0;
 32195        outputCount = 0;
 196
 32197        if (!IsCoveredAddressCursorCurrent(cursor))
 2198            return cursor.MarkStale();
 199
 30200        int remainingInputs = cursor.ExpectedGenerationCount - cursor.BoundGenerationCount;
 30201        if (generationInputs.Length > remainingInputs)
 1202            return cursor.MarkStale();
 29203        if (generationInputs.IsEmpty && remainingInputs != 0)
 1204            return cursor.MarkStale();
 205
 78206        while (generationInputsConsumed < generationInputs.Length)
 207        {
 54208            if (lookupProbesConsumed == lookupProbeLimit)
 1209                return GridCoveredAddressCursorStatus.More;
 210
 53211            GridCoveredAddressGeneration generation = generationInputs[generationInputsConsumed++];
 53212            ConsumeLookupProbe(cursor, ref lookupProbesConsumed);
 53213            if ((cursor.HasLastBoundGeneration
 53214                    && cursor.LastBoundGeneration.CompareTo(generation) >= 0)
 53215                || !TryBindCoveredAddressGeneration(cursor, generation, out GridCoveredAddressCursor.BoundGeneration bou
 216            {
 3217                return cursor.MarkStale();
 218            }
 219
 50220            cursor.LastBoundGeneration = generation;
 50221            cursor.HasLastBoundGeneration = true;
 50222            cursor.BoundGenerationCount++;
 50223            if (bound.HasRange)
 17224                cursor.Generations[cursor.RangeGenerationCount++] = bound;
 225        }
 226
 24227        if (cursor.BoundGenerationCount < cursor.ExpectedGenerationCount)
 2228            return GridCoveredAddressCursorStatus.More;
 229
 22230        if (cursor.CurrentStatus == GridCoveredAddressCursorStatus.Complete)
 1231            return cursor.CurrentStatus;
 232
 26233        while (true)
 234        {
 49235            if (cursor.HasPendingOutput)
 236            {
 27237                if (outputCount == outputLimit)
 1238                    return GridCoveredAddressCursorStatus.More;
 239
 26240                results[outputCount++] = cursor.PendingOutput;
 26241                cursor.PendingOutput = default;
 26242                cursor.HasPendingOutput = false;
 26243                if (cursor.OutputOrdinal != ulong.MaxValue)
 25244                    cursor.OutputOrdinal++;
 26245                if (outputCount == outputLimit)
 246                {
 14247                    if (cursor.GenerationOrdinal >= cursor.RangeGenerationCount)
 248                    {
 11249                        cursor.CurrentStatus = GridCoveredAddressCursorStatus.Complete;
 11250                        return cursor.CurrentStatus;
 251                    }
 252
 3253                    return GridCoveredAddressCursorStatus.More;
 254                }
 255            }
 256
 34257            if (!cursor.HasCurrentAddress)
 258            {
 19259                if (cursor.GenerationOrdinal >= cursor.RangeGenerationCount)
 260                {
 4261                    cursor.CurrentStatus = GridCoveredAddressCursorStatus.Complete;
 4262                    return cursor.CurrentStatus;
 263                }
 264
 15265                cursor.CurrentAddress = cursor.Generations[cursor.GenerationOrdinal].Minimum;
 15266                cursor.HasCurrentAddress = true;
 267            }
 268
 30269            if (addressProbesConsumed == addressProbeLimit)
 2270                return GridCoveredAddressCursorStatus.More;
 271
 28272            GridCoveredAddressCursor.BoundGeneration current =
 28273                cursor.Generations[cursor.GenerationOrdinal];
 28274            VoxelIndex address = cursor.CurrentAddress;
 28275            cursor.HasCurrentAddress = AdvanceCoveredAddress(
 28276                ref cursor.CurrentAddress,
 28277                current.Minimum,
 28278                current.Maximum);
 28279            if (!cursor.HasCurrentAddress)
 15280                cursor.GenerationOrdinal++;
 281
 28282            ConsumeAddressProbe(cursor, ref addressProbesConsumed);
 28283            if (IsCoveredAddress(cursor, current.Generation, address))
 284            {
 26285                cursor.PendingOutput = new GridCoveredAddress(current.Generation, address);
 26286                cursor.HasPendingOutput = true;
 287            }
 288        }
 289    }
 290
 291    private bool TryBindCoveredAddressGeneration(
 292        GridCoveredAddressCursor cursor,
 293        GridCoveredAddressGeneration generation,
 294        out GridCoveredAddressCursor.BoundGeneration bound)
 295    {
 52296        bound = default;
 52297        if (!BoundsTracker.TryGetValue(generation.ConfigurationKey, out ushort gridIndex)
 52298            || gridIndex != generation.GridIndex)
 299        {
 1300            return false;
 301        }
 302
 51303        VoxelGrid grid = ActiveGrids[gridIndex];
 51304        if (grid.SpawnToken != generation.GridSpawnToken
 51305            || grid.LastChangeSequence != generation.GridLastChangeSequence)
 306        {
 1307            return false;
 308        }
 309
 50310        bool eligible = !cursor.HasConfigurationFilter
 50311            || cursor.FilterConfigurationKey == generation.ConfigurationKey;
 50312        VoxelIndex minimum = default;
 50313        VoxelIndex maximum = default;
 50314        Vector3d queryMinimum = cursor.QueryMinimum;
 50315        Vector3d queryMaximum = cursor.QueryMaximum;
 50316        if (eligible && grid.Topology.Kind == GridTopologyKind.HexPrism)
 317        {
 6318            Fixed64 halfLayerHeight = generation.ConfigurationKey.TopologyMetrics.LayerHeight
 6319                * Fixed64.Half;
 6320            queryMinimum = new Vector3d(
 6321                queryMinimum.X,
 6322                queryMinimum.Y - halfLayerHeight,
 6323                queryMinimum.Z);
 6324            queryMaximum = new Vector3d(
 6325                queryMaximum.X,
 6326                queryMaximum.Y + halfLayerHeight,
 6327                queryMaximum.Z);
 328        }
 329
 50330        bool hasRange = eligible && TopologyVoxelRangeUtility.TryGetCandidateRange(
 50331            grid,
 50332            queryMinimum,
 50333            queryMaximum,
 50334            out minimum,
 50335            out maximum);
 50336        bound = new GridCoveredAddressCursor.BoundGeneration(
 50337            generation,
 50338            hasRange ? minimum : default,
 50339            hasRange ? maximum : default,
 50340            hasRange);
 50341        return true;
 342    }
 343
 344    private bool IsCoveredAddressCursorCurrent(GridCoveredAddressCursor cursor) =>
 32345        cursor.CurrentStatus != GridCoveredAddressCursorStatus.Stale
 32346        && cursor.WorldSpawnToken == SpawnToken
 32347        && cursor.WorldVersion == Version
 32348        && cursor.WorldChangeSequence == _changeSequence;
 349
 350    private bool IsCoveredAddress(
 351        GridCoveredAddressCursor cursor,
 352        GridCoveredAddressGeneration generation,
 353        VoxelIndex address)
 354    {
 28355        if (generation.ConfigurationKey.TopologyKind != GridTopologyKind.HexPrism)
 20356            return true;
 357
 8358        VoxelGrid grid = ActiveGrids[generation.GridIndex];
 8359        Vector3d center = grid.GetWorldPosition(address);
 8360        Fixed64 radius = generation.ConfigurationKey.TopologyMetrics.CellRadius;
 8361        Fixed64 halfLayerHeight = generation.ConfigurationKey.TopologyMetrics.LayerHeight
 8362            * Fixed64.Half;
 8363        return center.X >= cursor.QueryMinimum.X - radius
 8364            && center.X <= cursor.QueryMaximum.X + radius
 8365            && center.Y >= cursor.QueryMinimum.Y - halfLayerHeight
 8366            && center.Y <= cursor.QueryMaximum.Y + halfLayerHeight
 8367            && center.Z >= cursor.QueryMinimum.Z - radius
 8368            && center.Z <= cursor.QueryMaximum.Z + radius;
 369    }
 370
 371    private static bool AdvanceCoveredAddress(
 372        ref VoxelIndex address,
 373        VoxelIndex minimum,
 374        VoxelIndex maximum)
 375    {
 28376        if (address.z < maximum.z)
 377        {
 4378            address.z++;
 4379            return true;
 380        }
 381
 24382        address.z = minimum.z;
 24383        if (address.y < maximum.y)
 384        {
 4385            address.y++;
 4386            return true;
 387        }
 388
 20389        address.y = minimum.y;
 20390        if (address.x < maximum.x)
 391        {
 5392            address.x++;
 5393            return true;
 394        }
 395
 15396        return false;
 397    }
 398
 399    private static void ConsumeLookupProbe(
 400        GridCoveredAddressCursor cursor,
 401        ref int lookupProbesConsumed)
 402    {
 53403        lookupProbesConsumed++;
 53404        if (cursor.LookupProbeOrdinal != ulong.MaxValue)
 52405            cursor.LookupProbeOrdinal++;
 53406    }
 407
 408    private static void ConsumeAddressProbe(
 409        GridCoveredAddressCursor cursor,
 410        ref int addressProbesConsumed)
 411    {
 28412        addressProbesConsumed++;
 28413        if (cursor.AddressProbeOrdinal != ulong.MaxValue)
 27414            cursor.AddressProbeOrdinal++;
 28415    }
 416}

/home/runner/work/GridForge/GridForge/src/GridForge/Grids/Managers/GridWorld.cs

#LineLine coverage
 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
 8using System;
 9using System.Collections.Generic;
 10using System.Diagnostics;
 11using System.Runtime.CompilerServices;
 12using System.Threading;
 13using FixedMathSharp;
 14using GridForge.Configuration;
 15using GridForge.Grids.Storage;
 16using GridForge.Grids.Topology;
 17using GridForge.Spatial;
 18using SwiftCollections;
 19using SwiftCollections.Pool;
 20using SwiftCollections.Query;
 21
 22namespace GridForge.Grids;
 23
 24/// <summary>
 25/// Owns the mutable runtime state for one GridForge world.
 26/// </summary>
 27public 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>
 139    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
 155    private static readonly Comparison<VoxelIndex> CompareVoxelIndices =
 156        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 SwiftSlotMap<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        {
 37092            lock (ChangeSyncRoot)
 37093                return _changeSequence;
 37094        }
 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
 2181104    internal void EnterReadLock() => _gridLock.EnterReadLock();
 105
 2180106    internal void ExitReadLock() => _gridLock.ExitReadLock();
 107
 567108    internal bool IsWriteLockHeld => _gridLock.IsWriteLockHeld;
 109
 110    private static long s_worldAllocationCounter;
 111    private static long s_obstacleRegistrationCounter;
 112
 1069113    private readonly ReaderWriterLockSlim _gridLock = new();
 114    internal object ChangeSyncRoot { get; } = new object();
 115    // Published and detached atomically by GridOccupantManager; records use the registry lock.
 116    internal WorldOccupancyRegistry? OccupancyRegistry;
 1069117    private readonly SwiftQueue<GridCommittedChange> _committedChanges = new SwiftQueue<GridCommittedChange>();
 1069118    private readonly SwiftList<ushort> _gridCandidates = new();
 1069119    private readonly SwiftDictionary<ushort, SwiftList<ushort>> _boundaryContactTargetsBySource = new();
 1069120    private readonly SwiftDictionary<ushort, SwiftList<ushort>> _boundaryContactSourcesByTarget = new();
 121    private readonly GridSpatialIndex _spatialIndex;
 122    private ulong[]? _boundaryContactSourceWords;
 123    private ulong[]? _boundaryContactSourceSummaryWords;
 124    private int _boundaryContactSourceSummaryLength;
 125    private long _gridGenerationCounter;
 126    private ulong _changeSequence;
 127    private ulong _publishedChangeSequence;
 128    private bool _isPublishingCommittedChanges;
 129    private volatile bool _isDisposed;
 130    private int _committedPublicationOwnerThreadId;
 131    private int _navigationMaintenanceOwnerThreadId;
 132
 133    #endregion
 134
 135    #region Events
 136
 137    private Action<GridEventInfo>? _onActiveGridAdded;
 138    private Action<GridEventInfo>? _onActiveGridRemoved;
 139    private Action<GridEventInfo>? _onActiveGridChange;
 140    private Action<GridEventInfo>? _onChangeCommitted;
 141    private Action? _onReset;
 142
 143    /// <summary>
 144    /// Event triggered when a new grid is added to this world.
 145    /// </summary>
 146    public event Action<GridEventInfo> OnActiveGridAdded
 147    {
 148        add
 149        {
 171150            lock (ChangeSyncRoot)
 171151                _onActiveGridAdded += value;
 171152        }
 153        remove
 154        {
 168155            lock (ChangeSyncRoot)
 168156                _onActiveGridAdded -= value;
 168157        }
 158    }
 159
 160    /// <summary>
 161    /// Event triggered when a grid is removed from this world.
 162    /// </summary>
 163    public event Action<GridEventInfo> OnActiveGridRemoved
 164    {
 165        add
 166        {
 171167            lock (ChangeSyncRoot)
 171168                _onActiveGridRemoved += value;
 171169        }
 170        remove
 171        {
 168172            lock (ChangeSyncRoot)
 168173                _onActiveGridRemoved -= value;
 168174        }
 175    }
 176
 177    /// <summary>
 178    /// Event triggered when a grid in this world undergoes a significant change.
 179    /// </summary>
 180    public event Action<GridEventInfo> OnActiveGridChange
 181    {
 182        add
 183        {
 175184            lock (ChangeSyncRoot)
 175185                _onActiveGridChange += value;
 175186        }
 187        remove
 188        {
 169189            lock (ChangeSyncRoot)
 169190                _onActiveGridChange -= value;
 169191        }
 192    }
 193
 194    /// <summary>
 195    /// Receives every committed grid lifecycle, sparse-presence, and obstacle mutation in
 196    /// ascending <see cref="GridEventInfo.ChangeSequence"/> order.
 197    /// </summary>
 198    public event Action<GridEventInfo> OnChangeCommitted
 199    {
 200        add
 201        {
 13202            lock (ChangeSyncRoot)
 13203                _onChangeCommitted += value;
 13204        }
 205        remove
 206        {
 7207            lock (ChangeSyncRoot)
 7208                _onChangeCommitted -= value;
 7209        }
 210    }
 211
 212    /// <summary>
 213    /// Event triggered when this world is reset.
 214    /// </summary>
 215    public event Action OnReset
 216    {
 217        add
 218        {
 173219            lock (ChangeSyncRoot)
 173220                _onReset += value;
 173221        }
 222        remove
 223        {
 170224            lock (ChangeSyncRoot)
 170225                _onReset -= value;
 170226        }
 227    }
 228
 229    #endregion
 230
 231    /// <summary>
 232    /// Initializes a new world with optional ordinary-grid lookup tuning.
 233    /// </summary>
 234    /// <param name="spatialGridCellSize">Optional ordinary-grid lookup cell size for this world.</param>
 1069235    public GridWorld(int spatialGridCellSize = DefaultSpatialGridCellSize)
 236    {
 1069237        ActiveGrids = new SwiftSlotMap<VoxelGrid>();
 1069238        BoundsTracker = new SwiftDictionary<GridConfigurationKey, ushort>();
 239
 1069240        SpatialGridCellSize = ResolveSpatialGridCellSize(spatialGridCellSize);
 1069241        _spatialIndex = new GridSpatialIndex(SpatialGridCellSize);
 1069242        SpawnToken = RuntimeIdentityAllocator.Allocate(ref s_worldAllocationCounter);
 1069243        Version = 1;
 1069244        IsActive = true;
 1069245    }
 246
 247    #region Lifecycle
 248
 249    /// <summary>
 250    /// Clears all grids and spatial data owned by this world.
 251    /// </summary>
 252    /// <param name="deactivate">If true, marks the world inactive and releases its event handlers.</param>
 253    public void Reset(bool deactivate = false)
 254    {
 1089255        if (!IsActive)
 256        {
 12257            GridForgeLogger.Channel.Warn($"Grid world not active. Cannot reset an inactive world.");
 12258            return;
 259        }
 260
 1077261        NotifyResetHandlers();
 262        bool drainCommittedChanges;
 1077263        _gridLock.EnterWriteLock();
 264        try
 265        {
 1077266            lock (ChangeSyncRoot)
 267            {
 1077268                bool wasPublishingCommittedChanges = _isPublishingCommittedChanges;
 1077269                ReleaseActiveGrids();
 1077270                GridOccupantManager.ClearTrackedOccupancies(this);
 1077271                Version++;
 272
 1077273                GridEventInfo resetEvent = new GridEventInfo(
 1077274                    SpawnToken,
 1077275                    ushort.MaxValue,
 1077276                    0,
 1077277                    default,
 1077278                    0,
 1077279                    GridEventKind.WorldReset,
 1077280                    changeStamp: AllocateChangeStamp());
 1077281                EnqueueCommittedChange(new GridCommittedChange(resetEvent));
 1077282                drainCommittedChanges = !wasPublishingCommittedChanges;
 283
 1077284                if (deactivate)
 285                {
 1064286                    GridOccupantManager.ReleaseTrackedOccupancies(this);
 1064287                    IsActive = false;
 288                }
 1077289            }
 290        }
 291        finally
 292        {
 1077293            _gridLock.ExitWriteLock();
 1077294        }
 295
 1077296        if (drainCommittedChanges)
 1076297            DrainCommittedChanges();
 298
 1077299        if (!deactivate)
 13300            return;
 301
 1064302        lock (ChangeSyncRoot)
 303        {
 1064304            SpawnToken = 0;
 1064305            _onActiveGridAdded = null;
 1064306            _onActiveGridRemoved = null;
 1064307            _onActiveGridChange = null;
 1064308            _onChangeCommitted = null;
 1064309            _onReset = null;
 1064310        }
 1064311    }
 312
 313    private void NotifyResetHandlers()
 314    {
 1077315        Action? resetHandlers = _onReset;
 1077316        if (resetHandlers == null)
 1053317            return;
 318
 24319        var handlerDelegates = resetHandlers.GetInvocationList();
 320320        for (int i = 0; i < handlerDelegates.Length; i++)
 321        {
 322            try
 323            {
 136324                ((Action)handlerDelegates[i])();
 134325            }
 2326            catch (Exception ex)
 327            {
 2328                GridForgeLogger.Channel.Error($"World reset notification error: {ex.Message}");
 2329            }
 330        }
 24331    }
 332
 333    private void ReleaseActiveGrids()
 334    {
 1077335        _spatialIndex.Clear();
 1077336        ReleaseBoundaryContactPairs();
 337
 4474338        foreach (VoxelGrid grid in ActiveGrids)
 1160339            Pools.GridPool.Release(grid);
 340
 1077341        ActiveGrids.Clear();
 1077342        BoundsTracker.Clear();
 1077343        MaxTopologyCellEdge = Fixed64.Zero;
 1077344    }
 345
 346    /// <inheritdoc />
 347    public void Dispose()
 348    {
 1070349        Reset(deactivate: true);
 1070350        _isDisposed = true;
 1070351        _gridLock.Dispose();
 1070352        GC.SuppressFinalize(this);
 1070353    }
 354
 355    #endregion
 356
 357    #region Grid Management
 358
 359    /// <summary>
 360    /// Allocates a nonzero process-unique identity for one obstacle registration lifetime.
 361    /// </summary>
 362    /// <returns>A fresh opaque obstacle token.</returns>
 363    /// <exception cref="InvalidOperationException">The world is inactive or its token space is exhausted.</exception>
 364    public ObstacleToken AllocateObstacleToken()
 365    {
 461366        if (!IsActive)
 1367            throw new InvalidOperationException("Cannot allocate an obstacle token from an inactive world.");
 368
 460369        return new ObstacleToken(RuntimeIdentityAllocator.Allocate(ref s_obstacleRegistrationCounter));
 370    }
 371
 372    /// <summary>
 373    /// Captures presence and obstacle state for a sorted requested address span without
 374    /// enumerating unrelated grids or unrequested physical voxels.
 375    /// </summary>
 376    /// <param name="configurationKey">The exact normalized configuration identity to resolve.</param>
 377    /// <param name="requestedVoxels">Strictly ascending, unique, in-bounds topology-local addresses.</param>
 378    /// <param name="baseline">The atomic baseline on success.</param>
 379    /// <returns>True when the requested active grid generation was captured; otherwise false.</returns>
 380    public bool TryCaptureNavigationBaseline(
 381        GridConfigurationKey configurationKey,
 382        ReadOnlySpan<VoxelIndex> requestedVoxels,
 383        out GridNavigationBaseline? baseline)
 384    {
 11385        baseline = null;
 11386        if (!IsActive)
 1387            return false;
 388
 10389        if (Volatile.Read(ref _navigationMaintenanceOwnerThreadId)
 10390            == Environment.CurrentManagedThreadId)
 391        {
 1392            return TryCaptureNavigationBaselineCore(configurationKey, requestedVoxels, out baseline);
 393        }
 394
 9395        _gridLock.EnterReadLock();
 396        try
 397        {
 9398            lock (ChangeSyncRoot)
 9399                return TryCaptureNavigationBaselineCore(configurationKey, requestedVoxels, out baseline);
 400        }
 401        finally
 402        {
 9403            _gridLock.ExitReadLock();
 9404        }
 9405    }
 406
 407    /// <summary>
 408    /// Executes one short navigation maintenance snapshot while grid mutations are frozen.
 409    /// Committed-change prefix detachment and all required navigation baseline captures can
 410    /// therefore observe one deterministic world state.
 411    /// </summary>
 412    /// <param name="maintenance">The non-mutating maintenance callback to execute.</param>
 413    /// <remarks>
 414    /// The callback may call <see cref="TryCaptureNavigationBaseline"/> without lock recursion.
 415    /// It must not mutate this world, wait for code that may mutate this world, or retain live
 416    /// grid/voxel references beyond the callback. This method must not be called from a committed-
 417    /// change notification handler. Those handlers remain outside the mutation lock and may enqueue
 418    /// represented events after this snapshot completes.
 419    /// </remarks>
 420    public void ExecuteNavigationMaintenanceSnapshot(Action maintenance)
 421    {
 3422        ChronicleGuard.ThrowIfNull(maintenance, nameof(maintenance));
 3423        ThrowIfNavigationMaintenanceUnavailable();
 424
 1425        while (true)
 426        {
 3427            if (TryEnterNavigationMaintenanceSnapshot())
 428            {
 429                try
 430                {
 2431                    maintenance();
 2432                    return;
 433                }
 434                finally
 435                {
 2436                    ExitNavigationMaintenanceSnapshot();
 2437                }
 438            }
 439
 1440            WaitForPublishedChangePrefix();
 441        }
 2442    }
 443
 444    /// <summary>
 445    /// Begins or restarts a bounded exact boundary-contact query against the current committed world state.
 446    /// </summary>
 447    /// <param name="cursor">The caller-owned cursor to reset and bind.</param>
 448    public void BeginBoundaryContacts(GridBoundaryContactCursor cursor)
 449    {
 26450        ChronicleGuard.ThrowIfNull(cursor, nameof(cursor));
 26451        ThrowIfNavigationMaintenanceUnavailable();
 452
 1453        while (true)
 454        {
 27455            if (TryEnterNavigationMaintenanceSnapshot())
 456            {
 457                try
 458                {
 26459                    cursor.Begin(SpawnToken, Version, _changeSequence);
 26460                    return;
 461                }
 462                finally
 463                {
 26464                    ExitNavigationMaintenanceSnapshot();
 26465                }
 466            }
 467
 1468            WaitForPublishedChangePrefix();
 469        }
 26470    }
 471
 472    /// <summary>
 473    /// Begins or restarts a bounded exact boundary-contact query restricted to one active grid.
 474    /// </summary>
 475    /// <param name="configurationKey">The exact normalized configuration identity to resolve.</param>
 476    /// <param name="cursor">The caller-owned cursor to reset and bind.</param>
 477    /// <returns>True when the requested active grid was bound; otherwise false.</returns>
 478    public bool TryBeginBoundaryContacts(
 479        GridConfigurationKey configurationKey,
 480        GridBoundaryContactCursor cursor)
 481    {
 14482        ChronicleGuard.ThrowIfNull(cursor, nameof(cursor));
 14483        ThrowIfNavigationMaintenanceUnavailable();
 484
 1485        while (true)
 486        {
 15487            if (TryEnterNavigationMaintenanceSnapshot())
 488            {
 489                try
 490                {
 14491                    if (!BoundsTracker.TryGetValue(configurationKey, out ushort gridIndex))
 492                    {
 1493                        cursor.MarkStale();
 1494                        return false;
 495                    }
 496
 13497                    VoxelGrid grid = ActiveGrids[gridIndex];
 13498                    cursor.BeginFiltered(
 13499                        SpawnToken,
 13500                        Version,
 13501                        _changeSequence,
 13502                        gridIndex,
 13503                        grid.SpawnToken,
 13504                        grid.LastChangeSequence);
 13505                    return true;
 506                }
 507                finally
 508                {
 14509                    ExitNavigationMaintenanceSnapshot();
 14510                }
 511            }
 512
 1513            WaitForPublishedChangePrefix();
 514        }
 14515    }
 516
 517    /// <summary>
 518    /// Advances a bounded exact boundary-contact query under one short navigation-maintenance snapshot.
 519    /// </summary>
 520    /// <param name="cursor">The caller-owned cursor previously begun through this world.</param>
 521    /// <param name="results">Caller-owned storage for contacts emitted by this chunk.</param>
 522    /// <param name="candidateProbeLimit">The maximum pair, source-address, and target probes for this chunk.</param>
 523    /// <param name="outputLimit">The maximum contacts to write during this chunk.</param>
 524    /// <param name="candidateProbesConsumed">The exact number of candidate probes consumed by this chunk.</param>
 525    /// <param name="outputCount">The number of contacts written to <paramref name="results"/>.</param>
 526    /// <returns>The resulting cursor state.</returns>
 527    /// <remarks>
 528    /// A <see cref="GridBoundaryContactCursorStatus.Stale"/> result writes no contacts and resets the
 529    /// cursor ordinal. The caller must discard every contact returned since the preceding begin.
 530    /// Completed cursors remain bound and are revalidated on every later call, including zero-budget calls.
 531    /// </remarks>
 532    public GridBoundaryContactCursorStatus AdvanceBoundaryContacts(
 533        GridBoundaryContactCursor cursor,
 534        Span<VoxelContactManifold> results,
 535        int candidateProbeLimit,
 536        int outputLimit,
 537        out int candidateProbesConsumed,
 538        out int outputCount)
 539    {
 107540        ChronicleGuard.ThrowIfNull(cursor, nameof(cursor));
 107541        ChronicleGuard.ThrowIfNegative(candidateProbeLimit, nameof(candidateProbeLimit));
 107542        ChronicleGuard.ThrowIfNegative(outputLimit, nameof(outputLimit));
 107543        if (outputLimit > results.Length)
 1544            throw new ArgumentOutOfRangeException(nameof(outputLimit));
 545
 106546        return AdvanceBoundaryContactsUnderGate(
 106547            cursor,
 106548            results,
 106549            default,
 106550            includeConfigurationKeys: false,
 106551            candidateProbeLimit,
 106552            outputLimit,
 106553            out candidateProbesConsumed,
 106554            out outputCount);
 555    }
 556
 557    /// <summary>
 558    /// Advances a bounded exact boundary-contact query and emits durable grid identities with each contact.
 559    /// </summary>
 560    /// <param name="cursor">The caller-owned cursor previously begun through this world.</param>
 561    /// <param name="results">Caller-owned storage for contacts and their normalized grid identities.</param>
 562    /// <param name="candidateProbeLimit">The maximum pair, source-address, and target probes for this chunk.</param>
 563    /// <param name="outputLimit">The maximum contacts to write during this chunk.</param>
 564    /// <param name="candidateProbesConsumed">The exact number of candidate probes consumed by this chunk.</param>
 565    /// <param name="outputCount">The number of contacts written to <paramref name="results"/>.</param>
 566    /// <returns>The resulting cursor state.</returns>
 567    /// <remarks>
 568    /// Every emitted identity belongs to <see cref="GridBoundaryContactCursor.RunStamp"/>.
 569    /// A stale result writes no contacts and resets that stamp to its default value.
 570    /// </remarks>
 571    public GridBoundaryContactCursorStatus AdvanceBoundaryContacts(
 572        GridBoundaryContactCursor cursor,
 573        Span<GridBoundaryContact> results,
 574        int candidateProbeLimit,
 575        int outputLimit,
 576        out int candidateProbesConsumed,
 577        out int outputCount)
 578    {
 9579        ChronicleGuard.ThrowIfNull(cursor, nameof(cursor));
 9580        ChronicleGuard.ThrowIfNegative(candidateProbeLimit, nameof(candidateProbeLimit));
 9581        ChronicleGuard.ThrowIfNegative(outputLimit, nameof(outputLimit));
 9582        if (outputLimit > results.Length)
 1583            throw new ArgumentOutOfRangeException(nameof(outputLimit));
 584
 8585        return AdvanceBoundaryContactsUnderGate(
 8586            cursor,
 8587            default,
 8588            results,
 8589            includeConfigurationKeys: true,
 8590            candidateProbeLimit,
 8591            outputLimit,
 8592            out candidateProbesConsumed,
 8593            out outputCount);
 594    }
 595
 596    private GridBoundaryContactCursorStatus AdvanceBoundaryContactsUnderGate(
 597        GridBoundaryContactCursor cursor,
 598        Span<VoxelContactManifold> manifoldResults,
 599        Span<GridBoundaryContact> boundResults,
 600        bool includeConfigurationKeys,
 601        int candidateProbeLimit,
 602        int outputLimit,
 603        out int candidateProbesConsumed,
 604        out int outputCount)
 605    {
 114606        ThrowIfNavigationMaintenanceUnavailable();
 114607        candidateProbesConsumed = 0;
 114608        outputCount = 0;
 1609        while (true)
 610        {
 115611            if (TryEnterNavigationMaintenanceSnapshot())
 612            {
 613                try
 614                {
 114615                    return AdvanceBoundaryContactsCore(
 114616                        cursor,
 114617                        manifoldResults,
 114618                        boundResults,
 114619                        includeConfigurationKeys,
 114620                        candidateProbeLimit,
 114621                        outputLimit,
 114622                        out candidateProbesConsumed,
 114623                        out outputCount);
 624                }
 625                finally
 626                {
 114627                    ExitNavigationMaintenanceSnapshot();
 114628                }
 629            }
 630
 1631            WaitForPublishedChangePrefix();
 632        }
 114633    }
 634
 635    private GridBoundaryContactCursorStatus AdvanceBoundaryContactsCore(
 636        GridBoundaryContactCursor cursor,
 637        Span<VoxelContactManifold> manifoldResults,
 638        Span<GridBoundaryContact> boundResults,
 639        bool includeConfigurationKeys,
 640        int candidateProbeLimit,
 641        int outputLimit,
 642        out int candidateProbesConsumed,
 643        out int outputCount)
 644    {
 114645        candidateProbesConsumed = 0;
 114646        outputCount = 0;
 114647        if (!IsBoundaryContactCursorCurrent(cursor))
 10648            return cursor.MarkStale();
 649
 104650        if (cursor.CurrentStatus == GridBoundaryContactCursorStatus.Complete)
 2651            return cursor.CurrentStatus;
 652
 653        while (true)
 654        {
 320655            if (cursor.HasPendingContact)
 656            {
 52657                if (outputCount == outputLimit)
 1658                    return GridBoundaryContactCursorStatus.More;
 659
 51660                if (includeConfigurationKeys)
 661                {
 8662                    boundResults[outputCount++] = new GridBoundaryContact(
 8663                        cursor.SourceConfigurationKey,
 8664                        cursor.TargetConfigurationKey,
 8665                        cursor.PendingContact);
 666                }
 667                else
 668                {
 43669                    manifoldResults[outputCount++] = cursor.PendingContact;
 670                }
 51671                cursor.PendingContact = default;
 51672                cursor.HasPendingContact = false;
 51673                if (outputCount == outputLimit)
 40674                    return GridBoundaryContactCursorStatus.More;
 675            }
 676
 279677            switch (cursor.Stage)
 678            {
 679                case GridBoundaryContactCursor.TraversalStage.Pair:
 122680                    if (cursor.IsFiltered)
 681                    {
 23682                        if (!TryAdvanceFilteredBoundaryContactPair(
 23683                                cursor,
 23684                                candidateProbeLimit,
 23685                                ref candidateProbesConsumed,
 23686                                out ushort filteredSource,
 23687                                out ushort filteredTarget))
 688                        {
 12689                            return cursor.CurrentStatus;
 690                        }
 691
 11692                        BindBoundaryContactPair(cursor, filteredSource, filteredTarget);
 11693                        cursor.Stage = GridBoundaryContactCursor.TraversalStage.Source;
 11694                        continue;
 695                    }
 696
 99697                    if (!cursor.HasPairSource)
 698                    {
 69699                        if (cursor.PairSourceWord != 0)
 700                        {
 17701                            int sourceBit = GetTrailingZeroCount(cursor.PairSourceWord);
 17702                            cursor.PairSourceWord &= cursor.PairSourceWord - 1UL;
 17703                            cursor.PairSourceGridIndex = (ushort)(
 17704                                (cursor.PairSourceWordIndex << 6) + sourceBit);
 17705                            cursor.PairTargetOrdinal = 0;
 17706                            cursor.HasPairSource = true;
 17707                            continue;
 708                        }
 709
 52710                        if (cursor.PairSourceSummaryWord != 0)
 711                        {
 19712                            if (candidateProbesConsumed == candidateProbeLimit)
 2713                                return GridBoundaryContactCursorStatus.More;
 714
 17715                            int wordBit = GetTrailingZeroCount(cursor.PairSourceSummaryWord);
 17716                            cursor.PairSourceSummaryWord &= cursor.PairSourceSummaryWord - 1UL;
 17717                            cursor.PairSourceWordIndex =
 17718                                ((cursor.PairSourceSummaryWordIndex - 1) << 6) + wordBit;
 17719                            cursor.PairSourceWord = _boundaryContactSourceWords![cursor.PairSourceWordIndex];
 17720                            ConsumeBoundaryContactProbe(cursor, ref candidateProbesConsumed);
 17721                            continue;
 722                        }
 723
 33724                        if (_boundaryContactSourceSummaryWords == null
 33725                            || cursor.PairSourceSummaryWordIndex
 33726                                >= _boundaryContactSourceSummaryLength)
 727                        {
 14728                            cursor.CurrentStatus = GridBoundaryContactCursorStatus.Complete;
 14729                            return cursor.CurrentStatus;
 730                        }
 731
 19732                        if (candidateProbesConsumed == candidateProbeLimit)
 1733                            return GridBoundaryContactCursorStatus.More;
 734
 18735                        cursor.PairSourceSummaryWord = _boundaryContactSourceSummaryWords[
 18736                            cursor.PairSourceSummaryWordIndex++];
 18737                        ConsumeBoundaryContactProbe(cursor, ref candidateProbesConsumed);
 18738                        continue;
 739                    }
 740
 30741                    bool foundPairTargets = _boundaryContactTargetsBySource.TryGetValue(
 30742                        cursor.PairSourceGridIndex,
 30743                        out SwiftList<ushort>? pairTargets);
 744                    Debug.Assert(foundPairTargets && pairTargets != null);
 30745                    if (cursor.PairTargetOrdinal >= pairTargets.Count)
 746                    {
 12747                        cursor.HasPairSource = false;
 12748                        continue;
 749                    }
 750
 18751                    if (candidateProbesConsumed == candidateProbeLimit)
 1752                        return GridBoundaryContactCursorStatus.More;
 753
 17754                    ushort pairTarget = pairTargets[cursor.PairTargetOrdinal++];
 17755                    ConsumeBoundaryContactProbe(cursor, ref candidateProbesConsumed);
 17756                    BindBoundaryContactPair(cursor, cursor.PairSourceGridIndex, pairTarget);
 17757                    cursor.Stage = GridBoundaryContactCursor.TraversalStage.Source;
 17758                    continue;
 759
 760                case GridBoundaryContactCursor.TraversalStage.Source:
 77761                    VoxelGrid sourceGrid = ActiveGrids[cursor.SourceGridIndex];
 77762                    VoxelGrid targetGrid = ActiveGrids[cursor.TargetGridIndex];
 77763                    if (!cursor.HasSourceRange)
 764                    {
 22765                        cursor.ClearPairProgress();
 22766                        continue;
 767                    }
 768
 55769                    if (candidateProbesConsumed == candidateProbeLimit)
 4770                        return GridBoundaryContactCursorStatus.More;
 771
 51772                    VoxelIndex sourceIndex = cursor.SourceAddress;
 51773                    cursor.HasSourceRange = AdvanceBoundaryContactAddress(
 51774                        ref cursor.SourceAddress,
 51775                        cursor.SourceMinimum,
 51776                        cursor.SourceMaximum);
 51777                    ConsumeBoundaryContactProbe(cursor, ref candidateProbesConsumed);
 51778                    if (!TryCreateTopologyPrism(sourceGrid, sourceIndex, out cursor.SourcePrism)
 51779                        || !TopologyVoxelRangeUtility.TryGetCandidateRange(
 51780                            targetGrid,
 51781                            cursor.SourcePrism.GetAabb().Expand(targetGrid.Topology.MaxCellEdge),
 51782                            out cursor.TargetMinimum,
 51783                            out cursor.TargetMaximum))
 784                    {
 785                        continue;
 786                    }
 787
 51788                    cursor.TargetAddress = cursor.TargetMinimum;
 51789                    cursor.Stage = GridBoundaryContactCursor.TraversalStage.Target;
 51790                    continue;
 791
 792                default:
 80793                    if (candidateProbesConsumed == candidateProbeLimit)
 27794                        return GridBoundaryContactCursorStatus.More;
 795
 53796                    ProbeBoundaryContactTarget(cursor, ref candidateProbesConsumed);
 53797                    continue;
 798            }
 799        }
 800    }
 801
 802    private bool IsBoundaryContactCursorCurrent(GridBoundaryContactCursor cursor)
 803    {
 114804        if (cursor.CurrentStatus == GridBoundaryContactCursorStatus.Stale
 114805            || cursor.WorldSpawnToken != SpawnToken
 114806            || cursor.WorldVersion != Version
 114807            || cursor.WorldChangeSequence != _changeSequence)
 808        {
 7809            return false;
 810        }
 811
 107812        if (cursor.IsFiltered
 107813            && ActiveGrids[cursor.FilterGridIndex].LastChangeSequence
 107814                != cursor.FilterGridLastChangeSequence)
 815        {
 1816            return false;
 817        }
 818
 106819        if (cursor.SourceGridSpawnToken == 0)
 36820            return true;
 821
 70822        return ActiveGrids[cursor.SourceGridIndex].LastChangeSequence
 70823                == cursor.SourceGridLastChangeSequence
 70824            && ActiveGrids[cursor.TargetGridIndex].LastChangeSequence
 70825                == cursor.TargetGridLastChangeSequence;
 826    }
 827
 828    private bool TryAdvanceFilteredBoundaryContactPair(
 829        GridBoundaryContactCursor cursor,
 830        int candidateProbeLimit,
 831        ref int candidateProbesConsumed,
 832        out ushort sourceGridIndex,
 833        out ushort targetGridIndex)
 834    {
 23835        sourceGridIndex = 0;
 23836        targetGridIndex = 0;
 45837        while (cursor.FilteredPairPhase < 2)
 838        {
 36839            SwiftDictionary<ushort, SwiftList<ushort>> rows = cursor.FilteredPairPhase == 0
 36840                ? _boundaryContactSourcesByTarget
 36841                : _boundaryContactTargetsBySource;
 36842            if (!cursor.HasFilteredPairRow)
 843            {
 21844                if (candidateProbesConsumed == candidateProbeLimit)
 1845                    return false;
 846
 20847                cursor.FilteredPairRowCount = rows.TryGetValue(
 20848                    cursor.FilterGridIndex,
 20849                    out SwiftList<ushort>? row)
 20850                    ? row.Count
 20851                    : 0;
 20852                cursor.FilteredPairRowOrdinal = 0;
 20853                if (cursor.FilteredPairRowCount != 0)
 854                {
 8855                    cursor.PendingFilteredGridIndex = row![0];
 8856                    cursor.FilteredPairRowOrdinal = 1;
 8857                    cursor.HasPendingFilteredPair = true;
 858                }
 20859                cursor.HasFilteredPairRow = true;
 20860                ConsumeBoundaryContactProbe(cursor, ref candidateProbesConsumed);
 861            }
 862
 35863            if (cursor.HasPendingFilteredPair)
 864            {
 12865                if (candidateProbesConsumed == candidateProbeLimit)
 1866                    return false;
 867
 11868                ushort incidentGridIndex = cursor.PendingFilteredGridIndex;
 11869                cursor.PendingFilteredGridIndex = 0;
 11870                cursor.HasPendingFilteredPair = false;
 11871                ConsumeBoundaryContactProbe(cursor, ref candidateProbesConsumed);
 11872                if (cursor.FilteredPairPhase == 0)
 873                {
 3874                    sourceGridIndex = incidentGridIndex;
 3875                    targetGridIndex = cursor.FilterGridIndex;
 876                }
 877                else
 878                {
 8879                    sourceGridIndex = cursor.FilterGridIndex;
 8880                    targetGridIndex = incidentGridIndex;
 881                }
 882
 11883                return true;
 884            }
 885
 23886            if (cursor.FilteredPairRowOrdinal < cursor.FilteredPairRowCount)
 887            {
 4888                if (candidateProbesConsumed == candidateProbeLimit)
 1889                    return false;
 890
 3891                bool foundRow = rows.TryGetValue(
 3892                    cursor.FilterGridIndex,
 3893                    out SwiftList<ushort>? row);
 894                Debug.Assert(foundRow && row != null);
 3895                cursor.PendingFilteredGridIndex = row[cursor.FilteredPairRowOrdinal++];
 3896                cursor.HasPendingFilteredPair = true;
 3897                ConsumeBoundaryContactProbe(cursor, ref candidateProbesConsumed);
 3898                continue;
 899            }
 900
 19901            cursor.FilteredPairPhase++;
 19902            cursor.FilteredPairRowCount = 0;
 19903            cursor.FilteredPairRowOrdinal = 0;
 19904            cursor.HasFilteredPairRow = false;
 905        }
 906
 9907        cursor.CurrentStatus = GridBoundaryContactCursorStatus.Complete;
 9908        return false;
 909    }
 910
 911    private void BindBoundaryContactPair(
 912        GridBoundaryContactCursor cursor,
 913        ushort sourceGridIndex,
 914        ushort targetGridIndex)
 915    {
 28916        VoxelGrid sourceGrid = ActiveGrids[sourceGridIndex];
 28917        VoxelGrid targetGrid = ActiveGrids[targetGridIndex];
 28918        cursor.SourceGridIndex = sourceGridIndex;
 28919        cursor.TargetGridIndex = targetGridIndex;
 28920        cursor.SourceGridSpawnToken = sourceGrid.SpawnToken;
 28921        cursor.TargetGridSpawnToken = targetGrid.SpawnToken;
 28922        cursor.SourceGridLastChangeSequence = sourceGrid.LastChangeSequence;
 28923        cursor.TargetGridLastChangeSequence = targetGrid.LastChangeSequence;
 28924        cursor.SourceConfigurationKey = sourceGrid.Configuration.ToGridKey();
 28925        cursor.TargetConfigurationKey = targetGrid.Configuration.ToGridKey();
 926
 28927        bool createdEnvelope = TryCreateBoundaryContactEnvelope(
 28928            targetGrid,
 28929            out FixedBoundVolume targetEnvelope);
 28930        bool createdSourcePrism = TryCreateTopologyPrism(
 28931            sourceGrid,
 28932            default,
 28933            out GridCellPrism firstSourcePrism);
 934        Debug.Assert(createdEnvelope && createdSourcePrism);
 935
 28936        TopologyVoxelAabb firstSourceBounds = firstSourcePrism.GetAabb();
 28937        Vector3d lowerExtent = sourceGrid.BoundsMin - firstSourceBounds.Min;
 28938        Vector3d upperExtent = firstSourceBounds.Max - sourceGrid.BoundsMin;
 28939        var sourceCandidateBounds = new TopologyVoxelAabb(
 28940            targetEnvelope.Min - upperExtent,
 28941            targetEnvelope.Max + lowerExtent);
 28942        cursor.HasSourceRange = TopologyVoxelRangeUtility.TryGetCandidateRange(
 28943            sourceGrid,
 28944            sourceCandidateBounds,
 28945            out cursor.SourceMinimum,
 28946            out cursor.SourceMaximum);
 28947        cursor.SourceAddress = cursor.SourceMinimum;
 28948    }
 949
 950    private void ProbeBoundaryContactTarget(
 951        GridBoundaryContactCursor cursor,
 952        ref int candidateProbesConsumed)
 953    {
 53954        VoxelGrid targetGrid = ActiveGrids[cursor.TargetGridIndex];
 53955        VoxelIndex targetIndex = cursor.TargetAddress;
 53956        if (!AdvanceBoundaryContactAddress(
 53957                ref cursor.TargetAddress,
 53958                cursor.TargetMinimum,
 53959                cursor.TargetMaximum))
 960        {
 51961            cursor.Stage = GridBoundaryContactCursor.TraversalStage.Source;
 962        }
 53963        ConsumeBoundaryContactProbe(cursor, ref candidateProbesConsumed);
 964
 53965        bool createdTargetPrism = TryCreateTopologyPrism(
 53966            targetGrid,
 53967            targetIndex,
 53968            out GridCellPrism targetPrism);
 969        Debug.Assert(createdTargetPrism);
 970
 53971        VoxelContactManifold contact = GridCellGeometry.GetContact(cursor.SourcePrism, targetPrism);
 53972        if (contact.Kind != VoxelContactKind.Separated)
 973        {
 51974            cursor.PendingContact = contact;
 51975            cursor.HasPendingContact = true;
 976        }
 53977    }
 978
 979    private static bool AdvanceBoundaryContactAddress(
 980        ref VoxelIndex address,
 981        VoxelIndex minimum,
 982        VoxelIndex maximum)
 983    {
 104984        if (address.z < maximum.z)
 985        {
 18986            address.z++;
 18987            return true;
 988        }
 989
 86990        address.z = minimum.z;
 86991        if (address.y < maximum.y)
 992        {
 6993            address.y++;
 6994            return true;
 995        }
 996
 80997        address.y = minimum.y;
 80998        if (address.x < maximum.x)
 999        {
 41000            address.x++;
 41001            return true;
 1002        }
 1003
 761004        return false;
 1005    }
 1006
 1007    private bool TryCreateTopologyPrism(
 1008        VoxelGrid grid,
 1009        VoxelIndex index,
 1010        out GridCellPrism prism)
 1011    {
 1321012        return GridCellGeometry.TryCreatePrism(
 1321013            grid.Configuration.TopologyKind,
 1321014            grid.Configuration.TopologyMetrics,
 1321015            grid.GetWorldPosition(index),
 1321016            new WorldVoxelIndex(SpawnToken, grid.GridIndex, grid.SpawnToken, index),
 1321017            out prism);
 1018    }
 1019
 1020    private static int GetTrailingZeroCount(ulong value)
 1021    {
 341022        int count = 0;
 661023        while ((value & 1UL) == 0)
 1024        {
 321025            value >>= 1;
 321026            count++;
 1027        }
 1028
 341029        return count;
 1030    }
 1031
 1032    private static void ConsumeBoundaryContactProbe(
 1033        GridBoundaryContactCursor cursor,
 1034        ref int candidateProbesConsumed)
 1035    {
 1901036        candidateProbesConsumed++;
 1901037        if (cursor.CandidateOrdinal != ulong.MaxValue)
 1891038            cursor.CandidateOrdinal++;
 1901039    }
 1040
 1041    private void ThrowIfNavigationMaintenanceUnavailable()
 1042    {
 2191043        ChronicleGuard.ThrowIfTrue(
 2191044            !IsActive,
 2191045            message: "Cannot capture navigation maintenance state from an inactive world.");
 2171046        ChronicleGuard.ThrowIfTrue(
 2171047            Volatile.Read(ref _committedPublicationOwnerThreadId)
 2171048                == Environment.CurrentManagedThreadId,
 2171049            message: "Cannot enter navigation maintenance from a committed-change notification handler.");
 2161050    }
 1051
 1052    private bool TryEnterNavigationMaintenanceSnapshot()
 1053    {
 2221054        _gridLock.EnterReadLock();
 2221055        Monitor.Enter(ChangeSyncRoot);
 2221056        if (_publishedChangeSequence != _changeSequence)
 1057        {
 61058            Monitor.Exit(ChangeSyncRoot);
 61059            _gridLock.ExitReadLock();
 61060            return false;
 1061        }
 1062
 2161063        _navigationMaintenanceOwnerThreadId = Environment.CurrentManagedThreadId;
 2161064        return true;
 1065    }
 1066
 1067    private void ExitNavigationMaintenanceSnapshot()
 1068    {
 2161069        _navigationMaintenanceOwnerThreadId = 0;
 2161070        Monitor.Exit(ChangeSyncRoot);
 2161071        _gridLock.ExitReadLock();
 2161072    }
 1073
 1074    private void WaitForPublishedChangePrefix()
 1075    {
 1076        // A committed handler may legally perform a reentrant structural mutation. Never
 1077        // wait for that handler while holding the read lock it needs to promote past.
 61078        lock (ChangeSyncRoot)
 1079        {
 121080            while (_publishedChangeSequence != _changeSequence)
 61081                Monitor.Wait(ChangeSyncRoot);
 61082        }
 61083    }
 1084
 1085    private bool TryCaptureNavigationBaselineCore(
 1086        GridConfigurationKey configurationKey,
 1087        ReadOnlySpan<VoxelIndex> requestedVoxels,
 1088        out GridNavigationBaseline? baseline)
 1089    {
 1090        Debug.Assert(Monitor.IsEntered(ChangeSyncRoot));
 101091        baseline = null;
 101092        if (!BoundsTracker.TryGetValue(configurationKey, out ushort gridIndex))
 1093        {
 11094            return false;
 1095        }
 1096
 91097        VoxelGrid grid = ActiveGrids[gridIndex];
 91098        if (!AreNavigationBaselineAddressesValid(grid, requestedVoxels))
 1099        {
 31100            return false;
 1101        }
 1102
 61103        NavigationBaselineVoxelState[] states = new NavigationBaselineVoxelState[requestedVoxels.Length];
 281104        for (int i = 0; i < requestedVoxels.Length; i++)
 1105        {
 81106            VoxelIndex requestedVoxel = requestedVoxels[i];
 81107            bool isPresent = grid.TryGetVoxel(requestedVoxel, out Voxel? voxel);
 81108            states[i] = new NavigationBaselineVoxelState(
 81109                requestedVoxel,
 81110                isPresent,
 81111                isPresent ? voxel!.ObstacleCount : (byte)0);
 1112        }
 1113
 61114        baseline = new GridNavigationBaseline(
 61115            _changeSequence,
 61116            SpawnToken,
 61117            grid.SpawnToken,
 61118            grid.LastChangeSequence,
 61119            grid.GridIndex,
 61120            configurationKey,
 61121            states);
 61122        return true;
 1123    }
 1124
 1125    private static bool AreNavigationBaselineAddressesValid(
 1126        VoxelGrid grid,
 1127        ReadOnlySpan<VoxelIndex> requestedVoxels)
 1128    {
 381129        for (int i = 0; i < requestedVoxels.Length; i++)
 1130        {
 131131            VoxelIndex requestedVoxel = requestedVoxels[i];
 131132            if (!grid.IsValidVoxelIndex(requestedVoxel.x, requestedVoxel.y, requestedVoxel.z)
 131133                || (i > 0 && requestedVoxels[i - 1].CompareTo(requestedVoxel) >= 0))
 1134            {
 31135                return false;
 1136            }
 1137        }
 1138
 61139        return true;
 1140    }
 1141
 1142    /// <summary>
 1143    /// Adds a new grid to this world and registers it in the spatial index.
 1144    /// </summary>
 1145    /// <param name="configuration">The grid configuration to normalize and register.</param>
 1146    /// <param name="allocatedIndex">The allocated world-local grid slot on success.</param>
 1147    /// <returns>True if the grid was added; otherwise false.</returns>
 1148    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1149    public bool TryAddGrid(GridConfiguration configuration, out ushort allocatedIndex) =>
 10501150        TryAddGridCore(configuration, null, null, out allocatedIndex);
 1151
 1152    /// <summary>
 1153    /// Adds a new grid to this world and materializes the supplied sparse voxel indices when sparse storage is configur
 1154    /// Dense grids ignore the configured voxel input and materialize every in-bounds voxel.
 1155    /// </summary>
 1156    /// <param name="configuration">The grid configuration to normalize and register.</param>
 1157    /// <param name="configuredVoxels">Grid-local voxel indices to materialize for sparse storage.</param>
 1158    /// <param name="allocatedIndex">The allocated world-local grid slot on success.</param>
 1159    /// <returns>True if the grid was added; otherwise false.</returns>
 1160    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1161    public bool TryAddGrid(
 1162        GridConfiguration configuration,
 1163        IEnumerable<VoxelIndex>? configuredVoxels,
 1164        out ushort allocatedIndex) =>
 1941165        TryAddGridCore(configuration, configuredVoxels, null, out allocatedIndex);
 1166
 1167    /// <summary>
 1168    /// Adds a new grid to this world and materializes true cells from the supplied sparse voxel mask when sparse storag
 1169    /// Dense grids ignore the configured voxel input and materialize every in-bounds voxel.
 1170    /// </summary>
 1171    /// <param name="configuration">The grid configuration to normalize and register.</param>
 1172    /// <param name="configuredVoxels">A [x, y, z] mask whose true values identify sparse voxels to materialize. Sparse 
 1173    /// <param name="allocatedIndex">The allocated world-local grid slot on success.</param>
 1174    /// <returns>True if the grid was added; otherwise false.</returns>
 1175    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1176    public bool TryAddGrid(
 1177        GridConfiguration configuration,
 1178        bool[,,]? configuredVoxels,
 1179        out ushort allocatedIndex) =>
 71180        TryAddGridCore(configuration, null, configuredVoxels, out allocatedIndex);
 1181
 1182    private bool TryAddGridCore(
 1183        GridConfiguration configuration,
 1184        IEnumerable<VoxelIndex>? configuredVoxels,
 1185        bool[,,]? configuredVoxelMask,
 1186        out ushort allocatedIndex)
 1187    {
 12511188        allocatedIndex = ushort.MaxValue;
 1189
 12511190        if (!configuration.TryNormalize(out NormalizedGridConfiguration descriptor))
 61191            return false;
 1192
 12451193        GridConfiguration normalizedConfiguration = descriptor.Configuration;
 12451194        IGridTopology topology = descriptor.Topology!;
 12451195        GridDimensions dimensions = descriptor.Dimensions;
 1196
 12451197        if (!TryPrepareConfiguredVoxels(
 12451198            normalizedConfiguration,
 12451199            dimensions,
 12451200            configuredVoxels,
 12451201            configuredVoxelMask,
 12451202            out VoxelIndex[] preparedVoxels))
 1203        {
 121204            return false;
 1205        }
 1206
 12331207        if (_isDisposed)
 1208        {
 31209            GridForgeLogger.Channel.Error($"Grid world not active. Cannot add grids to an inactive world.");
 31210            return false;
 1211        }
 1212
 12301213        GridConfigurationKey boundsKey = descriptor.Key;
 12301214        VoxelGrid? newGrid = null;
 12301215        GridEventInfo addedGridInfo = default;
 1216        bool drainCommittedChanges;
 1217
 12301218        _gridLock.EnterWriteLock();
 1219        try
 1220        {
 12301221            lock (ChangeSyncRoot)
 1222            {
 12301223                if (!CanAddGrid() || TryFindExistingGridUnsafe(boundsKey, out allocatedIndex))
 81224                    return false;
 1225
 12221226                long gridGeneration = RuntimeIdentityAllocator.Allocate(ref _gridGenerationCounter);
 12221227                newGrid = Pools.GridPool.Rent();
 1228
 12221229                allocatedIndex = (ushort)ActiveGrids.Add(newGrid);
 12221230                BoundsTracker.Add(boundsKey, allocatedIndex);
 1231
 12221232                newGrid.Initialize(this, allocatedIndex, gridGeneration, normalizedConfiguration, topology, preparedVoxe
 12221233                UpdateMaxTopologyCellEdge(newGrid.Topology.MaxCellEdge);
 12221234                RegisterGrid(newGrid, allocatedIndex);
 1235
 12221236                Version++;
 12221237                addedGridInfo = CreateGridEventInfo(
 12221238                    newGrid,
 12221239                    GridEventKind.GridAdded,
 12221240                    AllocateChangeStamp());
 12221241                drainCommittedChanges = EnqueueCommittedChange(new GridCommittedChange(addedGridInfo));
 12221242            }
 1243        }
 1244        finally
 1245        {
 12301246            _gridLock.ExitWriteLock();
 12301247        }
 1248
 12221249        if (drainCommittedChanges)
 12211250            DrainCommittedChanges();
 12221251        return true;
 81252    }
 1253
 1254    /// <summary>
 1255    /// Removes a grid from this world and updates all references to ensure integrity.
 1256    /// </summary>
 1257    /// <param name="removeIndex">The world-local grid slot to remove.</param>
 1258    /// <returns>True if the grid was removed; otherwise false.</returns>
 1259    public bool TryRemoveGrid(ushort removeIndex)
 1260    {
 641261        if (!IsActive)
 11262            return false;
 1263
 631264        VoxelGrid? gridToRemove = null;
 631265        GridEventInfo removedGridInfo = default;
 1266        bool drainCommittedChanges;
 1267
 631268        _gridLock.EnterWriteLock();
 1269        try
 1270        {
 631271            lock (ChangeSyncRoot)
 1272            {
 631273                if (!IsActive || !ActiveGrids.IsAllocated(removeIndex))
 11274                    return false;
 1275
 621276                gridToRemove = ActiveGrids[removeIndex];
 621277                Fixed64 removedMaxCellEdge = gridToRemove.Topology.MaxCellEdge;
 621278                UnregisterGrid(gridToRemove, removeIndex);
 621279                BoundsTracker.Remove(gridToRemove.Configuration.ToGridKey());
 621280                ActiveGrids.RemoveAt(removeIndex);
 621281                RecalculateMaxTopologyCellEdgeIfNeeded(removedMaxCellEdge);
 1282
 621283                Version++;
 621284                removedGridInfo = CreateGridEventInfo(
 621285                    gridToRemove,
 621286                    GridEventKind.GridRemoved,
 621287                    AllocateChangeStamp());
 621288                drainCommittedChanges = EnqueueCommittedChange(new GridCommittedChange(removedGridInfo));
 621289            }
 1290        }
 1291        finally
 1292        {
 631293            _gridLock.ExitWriteLock();
 631294        }
 1295
 621296        Pools.GridPool.Release(gridToRemove!);
 621297        if (drainCommittedChanges)
 611298            DrainCommittedChanges();
 1299
 621300        if (ActiveGrids.Count == 0)
 331301            ActiveGrids.TrimExcessCapacity();
 1302
 621303        return true;
 11304    }
 1305
 1306    #endregion
 1307
 1308    private bool CanAddGrid()
 1309    {
 12301310        if (!IsActive)
 1311        {
 21312            GridForgeLogger.Channel.Error($"Grid world not active. Cannot add grids to an inactive world.");
 21313            return false;
 1314        }
 1315
 12281316        if ((uint)ActiveGrids.Count >= MaxGrids)
 1317        {
 21318            GridForgeLogger.Channel.Warn($"No more grids can be added at this time.");
 21319            return false;
 1320        }
 1321
 12261322        return true;
 1323    }
 1324
 1325    private static bool TryPrepareConfiguredVoxels(
 1326        GridConfiguration configuration,
 1327        GridDimensions dimensions,
 1328        IEnumerable<VoxelIndex>? configuredVoxels,
 1329        bool[,,]? configuredVoxelMask,
 1330        out VoxelIndex[] preparedVoxels)
 1331    {
 12451332        preparedVoxels = Array.Empty<VoxelIndex>();
 12451333        if (configuration.StorageKind != GridStorageKind.Sparse)
 10501334            return true;
 1335
 1951336        if (configuredVoxelMask != null)
 71337            return TryPrepareConfiguredVoxelMask(configuredVoxelMask, dimensions, out preparedVoxels);
 1338
 1881339        return TryPrepareConfiguredVoxelIndices(configuredVoxels, dimensions, out preparedVoxels);
 1340    }
 1341
 1342    private static bool TryPrepareConfiguredVoxelMask(
 1343        bool[,,] configuredVoxelMask,
 1344        GridDimensions dimensions,
 1345        out VoxelIndex[] preparedVoxels)
 1346    {
 71347        preparedVoxels = Array.Empty<VoxelIndex>();
 1348
 71349        if (configuredVoxelMask.GetLength(0) != dimensions.Width
 71350            || configuredVoxelMask.GetLength(1) != dimensions.Height
 71351            || configuredVoxelMask.GetLength(2) != dimensions.Length)
 1352        {
 51353            GridForgeLogger.Channel.Warn($"Sparse voxel mask dimensions must match normalized grid dimensions.");
 51354            return false;
 1355        }
 1356
 21357        int configuredCount = 0;
 121358        for (int x = 0; x < dimensions.Width; x++)
 1359        {
 161360            for (int y = 0; y < dimensions.Height; y++)
 1361            {
 241362                for (int z = 0; z < dimensions.Length; z++)
 1363                {
 81364                    if (configuredVoxelMask[x, y, z])
 21365                        configuredCount++;
 1366                }
 1367            }
 1368        }
 1369
 21370        if (configuredCount == 0)
 11371            return true;
 1372
 11373        preparedVoxels = new VoxelIndex[configuredCount];
 11374        int index = 0;
 61375        for (int x = 0; x < dimensions.Width; x++)
 1376        {
 81377            for (int y = 0; y < dimensions.Height; y++)
 1378            {
 121379                for (int z = 0; z < dimensions.Length; z++)
 1380                {
 41381                    if (configuredVoxelMask[x, y, z])
 21382                        preparedVoxels[index++] = new VoxelIndex(x, y, z);
 1383                }
 1384            }
 1385        }
 1386
 11387        return true;
 1388    }
 1389
 1390    private static bool TryPrepareConfiguredVoxelIndices(
 1391        IEnumerable<VoxelIndex>? configuredVoxels,
 1392        GridDimensions dimensions,
 1393        out VoxelIndex[] preparedVoxels)
 1394    {
 1881395        preparedVoxels = Array.Empty<VoxelIndex>();
 1881396        if (configuredVoxels == null)
 501397            return true;
 1398
 1381399        SwiftList<VoxelIndex> indices = configuredVoxels is ICollection<VoxelIndex> collection
 1381400            ? new SwiftList<VoxelIndex>(collection.Count)
 1381401            : new SwiftList<VoxelIndex>();
 1402
 7611403        foreach (VoxelIndex configuredVoxel in configuredVoxels)
 1404        {
 2461405            if (!IsConfiguredVoxelInBounds(configuredVoxel, dimensions))
 1406            {
 71407                GridForgeLogger.Channel.Warn($"Sparse voxel index {configuredVoxel} is outside normalized grid dimension
 71408                return false;
 1409            }
 1410
 2391411            indices.Add(configuredVoxel);
 1412        }
 1413
 1311414        if (indices.Count == 0)
 91415            return true;
 1416
 1221417        preparedVoxels = indices.ToArray();
 1221418        Array.Sort(preparedVoxels, CompareVoxelIndices);
 1221419        CompactPreparedVoxels(ref preparedVoxels);
 1221420        return true;
 71421    }
 1422
 1423    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1424    private static bool IsConfiguredVoxelInBounds(VoxelIndex voxelIndex, GridDimensions dimensions) =>
 2461425        (uint)voxelIndex.x < (uint)dimensions.Width
 2461426        && (uint)voxelIndex.y < (uint)dimensions.Height
 2461427        && (uint)voxelIndex.z < (uint)dimensions.Length;
 1428
 1429    private static void CompactPreparedVoxels(ref VoxelIndex[] preparedVoxels)
 1430    {
 1221431        if (preparedVoxels.Length < 2)
 671432            return;
 1433
 551434        int writeIndex = 1;
 551435        VoxelIndex previous = preparedVoxels[0];
 3441436        for (int readIndex = 1; readIndex < preparedVoxels.Length; readIndex++)
 1437        {
 1171438            VoxelIndex current = preparedVoxels[readIndex];
 1171439            if (current == previous)
 1440                continue;
 1441
 1151442            preparedVoxels[writeIndex++] = current;
 1151443            previous = current;
 1444        }
 1445
 551446        if (writeIndex != preparedVoxels.Length)
 21447            Array.Resize(ref preparedVoxels, writeIndex);
 551448    }
 1449
 1450    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1451    private void UpdateMaxTopologyCellEdge(Fixed64 candidate)
 1452    {
 12221453        if (candidate > MaxTopologyCellEdge)
 8991454            MaxTopologyCellEdge = candidate;
 12221455    }
 1456
 1457    private void RecalculateMaxTopologyCellEdgeIfNeeded(Fixed64 removedMaxCellEdge)
 1458    {
 621459        if (removedMaxCellEdge < MaxTopologyCellEdge)
 31460            return;
 1461
 591462        Fixed64 maxCellEdge = Fixed64.Zero;
 1801463        foreach (VoxelGrid grid in ActiveGrids)
 1464        {
 311465            if (grid.Topology.MaxCellEdge > maxCellEdge)
 261466                maxCellEdge = grid.Topology.MaxCellEdge;
 1467        }
 1468
 591469        MaxTopologyCellEdge = maxCellEdge;
 591470    }
 1471
 1472    private bool TryFindExistingGridUnsafe(GridConfigurationKey boundsKey, out ushort allocatedIndex)
 1473    {
 12261474        if (BoundsTracker.TryGetValue(boundsKey, out allocatedIndex))
 1475        {
 41476            GridForgeLogger.Channel.Warn($"A grid with these bounds has already been allocated.");
 41477            return true;
 1478        }
 1479
 12221480        allocatedIndex = ushort.MaxValue;
 12221481        return false;
 1482    }
 1483
 1484    private void RegisterGrid(VoxelGrid newGrid, ushort allocatedIndex)
 1485    {
 12221486        bool hasContactEnvelope = TryCreateBoundaryContactEnvelope(
 12221487            newGrid,
 12221488            out FixedBoundVolume contactEnvelope);
 12221489        _spatialIndex.Insert(
 12221490            allocatedIndex,
 12221491            new FixedBoundVolume(newGrid.BoundsMin, newGrid.BoundsMax),
 12221492            hasContactEnvelope ? contactEnvelope : null);
 1493
 12221494        if (hasContactEnvelope)
 1495        {
 12031496            _spatialIndex.CollectContactCandidates(contactEnvelope, _gridCandidates);
 53141497            for (int i = 0; i < _gridCandidates.Count; i++)
 1498            {
 14541499                ushort candidateIndex = _gridCandidates[i];
 14541500                if (candidateIndex != allocatedIndex)
 2511501                    InsertBoundaryContactPair(allocatedIndex, candidateIndex);
 1502            }
 1503        }
 1504
 12221505        _spatialIndex.CollectCandidates(
 12221506            CreateExpandedBounds(
 12221507                newGrid.BoundsMin,
 12221508                newGrid.BoundsMax,
 12221509                newGrid.Topology.OverlapTolerance),
 12221510            ActiveGrids,
 12221511            _gridCandidates);
 1512
 51801513        for (int candidateIndex = 0; candidateIndex < _gridCandidates.Count; candidateIndex++)
 1514        {
 13681515            ushort neighborIndex = _gridCandidates[candidateIndex];
 13681516            if (neighborIndex == allocatedIndex)
 1517                continue;
 1518
 1461519            VoxelGrid neighborGrid = ActiveGrids[neighborIndex];
 1461520            newGrid.TryAddGridNeighbor(neighborGrid);
 1461521            neighborGrid.TryAddGridNeighbor(newGrid);
 1522        }
 12221523    }
 1524
 1525    private void UnregisterGrid(VoxelGrid gridToRemove, ushort removeIndex)
 1526    {
 621527        _spatialIndex.Remove(removeIndex);
 621528        RemoveBoundaryContactPairs(removeIndex);
 621529        UnlinkGridNeighbors(gridToRemove);
 621530    }
 1531
 1532    private static bool TryCreateBoundaryContactEnvelope(
 1533        VoxelGrid grid,
 1534        out FixedBoundVolume envelope)
 1535    {
 12501536        envelope = default;
 12501537        if (!GridCellGeometry.TryCreatePrism(
 12501538                grid.Configuration.TopologyKind,
 12501539                grid.Configuration.TopologyMetrics,
 12501540                grid.BoundsMin,
 12501541                default,
 12501542                out GridCellPrism minimumPrism)
 12501543            || !GridCellGeometry.TryCreatePrism(
 12501544                grid.Configuration.TopologyKind,
 12501545                grid.Configuration.TopologyMetrics,
 12501546                grid.BoundsMax,
 12501547                default,
 12501548                out GridCellPrism maximumPrism))
 1549        {
 191550            return false;
 1551        }
 1552
 12311553        TopologyVoxelAabb minimum = minimumPrism.GetAabb();
 12311554        TopologyVoxelAabb maximum = maximumPrism.GetAabb();
 12311555        envelope = new FixedBoundVolume(
 12311556            new Vector3d(
 12311557                FixedMath.Min(minimum.Min.X, maximum.Min.X),
 12311558                FixedMath.Min(minimum.Min.Y, maximum.Min.Y),
 12311559                FixedMath.Min(minimum.Min.Z, maximum.Min.Z)),
 12311560            new Vector3d(
 12311561                FixedMath.Max(minimum.Max.X, maximum.Max.X),
 12311562                FixedMath.Max(minimum.Max.Y, maximum.Max.Y),
 12311563                FixedMath.Max(minimum.Max.Z, maximum.Max.Z)));
 12311564        return true;
 1565    }
 1566
 1567    private void InsertBoundaryContactPair(ushort firstGridIndex, ushort secondGridIndex)
 1568    {
 2511569        ushort source = firstGridIndex < secondGridIndex ? firstGridIndex : secondGridIndex;
 2511570        ushort target = firstGridIndex < secondGridIndex ? secondGridIndex : firstGridIndex;
 2511571        SwiftList<ushort> targets = GetOrCreateBoundaryContactRow(
 2511572            _boundaryContactTargetsBySource,
 2511573            source,
 2511574            out bool addedSourceRow);
 2511575        InsertSorted(targets, target);
 1576
 2511577        InsertSorted(
 2511578            GetOrCreateBoundaryContactRow(_boundaryContactSourcesByTarget, target, out _),
 2511579            source);
 2511580        if (addedSourceRow)
 2031581            SetBoundaryContactSource(source);
 2511582    }
 1583
 1584    private void RemoveBoundaryContactPairs(ushort gridIndex)
 1585    {
 621586        if (_boundaryContactTargetsBySource.TryGetValue(
 621587                gridIndex,
 621588                out SwiftList<ushort>? targets))
 1589        {
 441590            for (int i = 0; i < targets.Count; i++)
 1591            {
 151592                RemoveBoundaryContactIncident(
 151593                    _boundaryContactSourcesByTarget,
 151594                    targets[i],
 151595                    gridIndex,
 151596                    clearSourceBit: false);
 1597            }
 1598
 71599            _boundaryContactTargetsBySource.Remove(gridIndex);
 71600            SwiftListPool<ushort>.Shared.Release(targets);
 71601            ClearBoundaryContactSource(gridIndex);
 1602        }
 1603
 621604        if (_boundaryContactSourcesByTarget.TryGetValue(
 621605                gridIndex,
 621606                out SwiftList<ushort>? sources))
 1607        {
 681608            for (int i = 0; i < sources.Count; i++)
 1609            {
 181610                RemoveBoundaryContactIncident(
 181611                    _boundaryContactTargetsBySource,
 181612                    sources[i],
 181613                    gridIndex,
 181614                    clearSourceBit: true);
 1615            }
 1616
 161617            _boundaryContactSourcesByTarget.Remove(gridIndex);
 161618            SwiftListPool<ushort>.Shared.Release(sources);
 1619        }
 621620    }
 1621
 1622    private void RemoveBoundaryContactIncident(
 1623        SwiftDictionary<ushort, SwiftList<ushort>> rows,
 1624        ushort rowIndex,
 1625        ushort incidentIndex,
 1626        bool clearSourceBit)
 1627    {
 331628        bool foundRow = rows.TryGetValue(rowIndex, out SwiftList<ushort>? row);
 1629        Debug.Assert(foundRow && row != null);
 331630        RemoveSorted(row, incidentIndex);
 331631        if (row.Count != 0)
 121632            return;
 1633
 211634        rows.Remove(rowIndex);
 211635        SwiftListPool<ushort>.Shared.Release(row);
 211636        if (clearSourceBit)
 151637            ClearBoundaryContactSource(rowIndex);
 211638    }
 1639
 1640    private static SwiftList<ushort> GetOrCreateBoundaryContactRow(
 1641        SwiftDictionary<ushort, SwiftList<ushort>> rows,
 1642        ushort rowIndex,
 1643        out bool added)
 1644    {
 5021645        if (rows.TryGetValue(rowIndex, out SwiftList<ushort>? row))
 1646        {
 971647            added = false;
 971648            return row;
 1649        }
 1650
 4051651        row = SwiftListPool<ushort>.Shared.Rent();
 4051652        rows.Add(rowIndex, row);
 4051653        added = true;
 4051654        return row;
 1655    }
 1656
 1657    private static void InsertSorted(SwiftList<ushort> row, ushort value)
 1658    {
 5021659        int index = FindSortedIndex(row, value);
 5021660        row.Insert(index, value);
 5021661    }
 1662
 1663    private static void RemoveSorted(SwiftList<ushort> row, ushort value)
 1664    {
 331665        int index = FindSortedIndex(row, value);
 1666        Debug.Assert(index < row.Count && row[index] == value);
 331667        row.RemoveAt(index);
 331668    }
 1669
 1670    private static int FindSortedIndex(SwiftList<ushort> row, ushort value)
 1671    {
 5351672        int minimum = 0;
 5351673        int maximum = row.Count;
 7151674        while (minimum < maximum)
 1675        {
 1801676            int middle = minimum + ((maximum - minimum) >> 1);
 1801677            if (row[middle] < value)
 1171678                minimum = middle + 1;
 1679            else
 631680                maximum = middle;
 1681        }
 1682
 5351683        return minimum;
 1684    }
 1685
 1686    private void SetBoundaryContactSource(ushort source)
 1687    {
 2031688        _boundaryContactSourceWords ??= new ulong[BoundaryContactSourceWordCount];
 2031689        _boundaryContactSourceSummaryWords ??= new ulong[BoundaryContactSourceSummaryWordCount];
 2031690        int wordIndex = source >> 6;
 2031691        _boundaryContactSourceWords[wordIndex] |= 1UL << (source & 63);
 2031692        _boundaryContactSourceSummaryWords[wordIndex >> 6] |= 1UL << (wordIndex & 63);
 2031693        _boundaryContactSourceSummaryLength = Math.Max(
 2031694            _boundaryContactSourceSummaryLength,
 2031695            (wordIndex >> 6) + 1);
 2031696    }
 1697
 1698    private void ClearBoundaryContactSource(ushort source)
 1699    {
 1700        Debug.Assert(_boundaryContactSourceWords != null && _boundaryContactSourceSummaryWords != null);
 221701        int wordIndex = source >> 6;
 221702        _boundaryContactSourceWords![wordIndex] &= ~(1UL << (source & 63));
 221703        if (_boundaryContactSourceWords[wordIndex] == 0)
 181704            _boundaryContactSourceSummaryWords![wordIndex >> 6] &= ~(1UL << (wordIndex & 63));
 1705
 401706        while (_boundaryContactSourceSummaryLength > 0
 401707            && _boundaryContactSourceSummaryWords[_boundaryContactSourceSummaryLength - 1] == 0)
 1708        {
 181709            _boundaryContactSourceSummaryLength--;
 1710        }
 1711
 221712    }
 1713
 1714    private void ReleaseBoundaryContactPairs()
 1715    {
 25161716        foreach (SwiftList<ushort> row in _boundaryContactTargetsBySource.Values)
 1811717            SwiftListPool<ushort>.Shared.Release(row);
 25141718        foreach (SwiftList<ushort> row in _boundaryContactSourcesByTarget.Values)
 1801719            SwiftListPool<ushort>.Shared.Release(row);
 1720
 10771721        _boundaryContactTargetsBySource.Clear();
 10771722        _boundaryContactSourcesByTarget.Clear();
 10771723        _boundaryContactSourceWords = null;
 10771724        _boundaryContactSourceSummaryWords = null;
 10771725        _boundaryContactSourceSummaryLength = 0;
 10771726    }
 1727
 1728    private void UnlinkGridNeighbors(VoxelGrid gridToRemove)
 1729    {
 621730        if (!gridToRemove.IsConjoined)
 481731            return;
 1732
 141733        var neighborSets = gridToRemove.Neighbors!.DenseValues;
 141734        int neighborSetCount = gridToRemove.Neighbors.Count;
 621735        for (int neighborSetIndex = 0; neighborSetIndex < neighborSetCount; neighborSetIndex++)
 1736        {
 781737            foreach (int neighborIndex in neighborSets[neighborSetIndex])
 1738            {
 221739                VoxelGrid neighborGrid = ActiveGrids[neighborIndex];
 221740                neighborGrid.TryRemoveGridNeighbor(gridToRemove);
 1741            }
 1742        }
 141743    }
 1744
 1745    internal bool CollectGridCandidates(
 1746        Vector3d boundsMin,
 1747        Vector3d boundsMax,
 1748        SwiftList<ushort> candidates,
 1749        int candidateLimit)
 1750    {
 12681751        ChronicleGuard.ThrowIfNegative(candidateLimit, nameof(candidateLimit));
 12681752        candidates.Clear();
 12681753        if (ActiveGrids.Count == 0)
 61754            return true;
 1755
 12621756        FixedBoundVolume queryBounds = new(boundsMin, boundsMax);
 12621757        if (ActiveGrids.Count <= candidateLimit)
 1758        {
 12261759            _spatialIndex.CollectCandidates(queryBounds, ActiveGrids, candidates);
 12261760            return true;
 1761        }
 1762
 2591763        foreach (VoxelGrid grid in ActiveGrids)
 1764        {
 1011765            FixedBoundVolume gridBounds = new(grid.BoundsMin, grid.BoundsMax);
 1011766            if (!gridBounds.Intersects(queryBounds))
 1767                continue;
 791768            if (candidates.Count >= candidateLimit)
 151769                return false;
 1770
 641771            candidates.Add(grid.GridIndex);
 1772        }
 1773
 211774        if (candidates.Count > 1)
 181775            candidates.SortInPlace();
 211776        return true;
 151777    }
 1778
 1779    private static FixedBoundVolume CreateExpandedBounds(
 1780        Vector3d boundsMin,
 1781        Vector3d boundsMax,
 1782        Fixed64 padding)
 1783    {
 12261784        Vector3d expansion = new(padding, padding, padding);
 12261785        return new FixedBoundVolume(boundsMin - expansion, boundsMax + expansion);
 1786    }
 1787
 1788    #region Lookup
 1789
 1790    /// <summary>
 1791    /// Retrieves a grid by its world-local index.
 1792    /// </summary>
 1793    /// <param name="index">The world-local grid slot to resolve.</param>
 1794    /// <param name="outGrid">The resolved grid, if found.</param>
 1795    /// <returns>True if the grid was resolved; otherwise false.</returns>
 1796    public bool TryGetGrid(int index, out VoxelGrid? outGrid)
 1797    {
 19901798        outGrid = null;
 19901799        if (!CanResolveGrid(index))
 191800            return false;
 1801
 19711802        outGrid = ActiveGrids[index];
 19711803        return true;
 1804    }
 1805
 1806    /// <summary>
 1807    /// Retrieves the grid containing a given world position.
 1808    /// </summary>
 1809    /// <param name="position">The world position to resolve.</param>
 1810    /// <param name="outGrid">The resolved grid, if found.</param>
 1811    /// <returns>True if a containing grid was found; otherwise false.</returns>
 1812    public bool TryGetGrid(Vector3d position, out VoxelGrid? outGrid)
 1813    {
 1541814        outGrid = null;
 1541815        if (!CanResolvePosition())
 21816            return false;
 1817
 1521818        _spatialIndex.CollectPointCandidates(position, _gridCandidates);
 1521819        if (TryGetContainingGrid(position, _gridCandidates, out outGrid))
 641820            return true;
 1821
 881822        GridForgeLogger.Channel.Info($"No grid contains position {position}.");
 881823        return false;
 1824    }
 1825
 1826    /// <summary>
 1827    /// Retrieves the grid containing a 2D XZ-plane world position on the default world Y layer.
 1828    /// </summary>
 1829    /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param
 1830    /// <param name="outGrid">The resolved grid, if found.</param>
 1831    /// <returns>True if a containing grid was found; otherwise false.</returns>
 1832    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1833    public bool TryGetGrid(Vector2d position, out VoxelGrid? outGrid) =>
 11834         TryGetGrid(position, default, out outGrid);
 1835
 1836    /// <summary>
 1837    /// Retrieves the grid containing a 2D XZ-plane world position on the supplied world Y layer.
 1838    /// </summary>
 1839    /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param
 1840    /// <param name="layerY">The world Y layer to resolve. Defaults to zero when omitted by paired overloads.</param>
 1841    /// <param name="outGrid">The resolved grid, if found.</param>
 1842    /// <returns>True if a containing grid was found; otherwise false.</returns>
 1843    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1844    public bool TryGetGrid(Vector2d position, Fixed64 layerY, out VoxelGrid? outGrid) =>
 31845        TryGetGrid(GridPlane2d.ToWorld(position, layerY), out outGrid);
 1846
 1847    /// <summary>
 1848    /// Retrieves the active grid whose bounds are nearest to the supplied world position.
 1849    /// </summary>
 1850    /// <param name="position">The world position to resolve.</param>
 1851    /// <param name="outGrid">The closest grid, if found.</param>
 1852    /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are 
 1853    /// <returns>True if a closest active grid was resolved; otherwise false.</returns>
 1854    public bool TryGetClosestGrid(
 1855        Vector3d position,
 1856        out VoxelGrid? outGrid,
 1857        GridTopologyKind? topologyKind = null)
 1858    {
 311859        outGrid = null;
 311860        if (!CanResolveActiveGrid())
 11861            return false;
 1862
 301863        Fixed64 closestDistanceSquared = Fixed64.MaxValue;
 1481864        foreach (VoxelGrid candidateGrid in ActiveGrids)
 1865        {
 441866            if (!candidateGrid.IsActive
 441867                || !MatchesTopologyKind(candidateGrid, topologyKind))
 1868            {
 1869                continue;
 1870            }
 1871
 381872            Fixed64 distanceSquared = GetDistanceSquaredToBounds(position, candidateGrid.BoundsMin, candidateGrid.Bounds
 381873            if (outGrid == null || distanceSquared < closestDistanceSquared)
 1874            {
 271875                outGrid = candidateGrid;
 271876                closestDistanceSquared = distanceSquared;
 1877            }
 1878        }
 1879
 301880        return outGrid != null;
 1881    }
 1882
 1883    /// <summary>
 1884    /// Retrieves the active grid whose bounds are nearest to a 2D XZ-plane world position on the default world Y layer.
 1885    /// </summary>
 1886    /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param
 1887    /// <param name="outGrid">The closest grid, if found.</param>
 1888    /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are 
 1889    /// <returns>True if a closest active grid was resolved; otherwise false.</returns>
 1890    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1891    public bool TryGetClosestGrid(
 1892        Vector2d position,
 1893        out VoxelGrid? outGrid,
 1894        GridTopologyKind? topologyKind = null) =>
 11895        TryGetClosestGrid(position, default, out outGrid, topologyKind);
 1896
 1897    /// <summary>
 1898    /// Retrieves the active grid whose bounds are nearest to a 2D XZ-plane world position on the supplied world Y layer
 1899    /// </summary>
 1900    /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param
 1901    /// <param name="layerY">The world Y layer to resolve. Defaults to zero when omitted by paired overloads.</param>
 1902    /// <param name="outGrid">The closest grid, if found.</param>
 1903    /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are 
 1904    /// <returns>True if a closest active grid was resolved; otherwise false.</returns>
 1905    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1906    public bool TryGetClosestGrid(
 1907        Vector2d position,
 1908        Fixed64 layerY,
 1909        out VoxelGrid? outGrid,
 1910        GridTopologyKind? topologyKind = null) =>
 31911        TryGetClosestGrid(GridPlane2d.ToWorld(position, layerY), out outGrid, topologyKind);
 1912
 1913    /// <summary>
 1914    /// Retrieves a grid by a world-scoped voxel identity.
 1915    /// </summary>
 1916    /// <param name="worldVoxelIndex">The voxel identity whose grid should be resolved.</param>
 1917    /// <param name="result">The resolved grid, if found.</param>
 1918    /// <returns>True if the grid was resolved; otherwise false.</returns>
 1919    public bool TryGetGrid(WorldVoxelIndex worldVoxelIndex, out VoxelGrid? result)
 1920    {
 13301921        result = null;
 13301922        if (worldVoxelIndex.WorldSpawnToken != SpawnToken
 13301923            || !TryGetGrid(worldVoxelIndex.GridIndex, out VoxelGrid? resolvedGrid)
 13301924            || worldVoxelIndex.GridSpawnToken != resolvedGrid!.SpawnToken)
 1925        {
 231926            return false;
 1927        }
 1928
 13071929        result = resolvedGrid;
 13071930        return true;
 1931    }
 1932
 1933    /// <summary>
 1934    /// Retrieves the grid and voxel containing a given world position.
 1935    /// </summary>
 1936    /// <param name="position">The world position to resolve.</param>
 1937    /// <param name="outGrid">The resolved grid, if found.</param>
 1938    /// <param name="outVoxel">The resolved voxel, if found.</param>
 1939    /// <returns>True if both the grid and voxel were resolved; otherwise false.</returns>
 1940    public bool TryGetGridAndVoxel(
 1941        Vector3d position,
 1942        out VoxelGrid? outGrid,
 1943        out Voxel? outVoxel)
 1944    {
 281945        outVoxel = null;
 281946        return TryGetGrid(position, out outGrid)
 281947            && outGrid!.TryGetVoxel(position, out outVoxel);
 1948    }
 1949
 1950    /// <summary>
 1951    /// Retrieves the grid and voxel containing a 2D XZ-plane world position on the default world Y layer.
 1952    /// </summary>
 1953    /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param
 1954    /// <param name="outGrid">The resolved grid, if found.</param>
 1955    /// <param name="outVoxel">The resolved voxel, if found.</param>
 1956    /// <returns>True if both the grid and voxel were resolved; otherwise false.</returns>
 1957    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1958    public bool TryGetGridAndVoxel(
 1959        Vector2d position,
 1960        out VoxelGrid? outGrid,
 1961        out Voxel? outVoxel) =>
 11962         TryGetGridAndVoxel(position, default, out outGrid, out outVoxel);
 1963
 1964    /// <summary>
 1965    /// Retrieves the grid and voxel containing a 2D XZ-plane world position on the supplied world Y layer.
 1966    /// </summary>
 1967    /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param
 1968    /// <param name="layerY">The world Y layer to resolve. Defaults to zero when omitted by paired overloads.</param>
 1969    /// <param name="outGrid">The resolved grid, if found.</param>
 1970    /// <param name="outVoxel">The resolved voxel, if found.</param>
 1971    /// <returns>True if both the grid and voxel were resolved; otherwise false.</returns>
 1972    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1973    public bool TryGetGridAndVoxel(
 1974        Vector2d position,
 1975        Fixed64 layerY,
 1976        out VoxelGrid? outGrid,
 1977        out Voxel? outVoxel) =>
 31978         TryGetGridAndVoxel(GridPlane2d.ToWorld(position, layerY), out outGrid, out outVoxel);
 1979
 1980    /// <summary>
 1981    /// Retrieves the physical voxel whose center is nearest to the supplied world position and the grid that owns it.
 1982    /// Sparse grids only consider configured physical voxels.
 1983    /// </summary>
 1984    /// <param name="position">The world position to resolve.</param>
 1985    /// <param name="outGrid">The grid that owns the closest physical voxel, if found.</param>
 1986    /// <param name="outVoxel">The closest physical voxel, if found.</param>
 1987    /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are 
 1988    /// <returns>True if a physical voxel was resolved; otherwise false.</returns>
 1989    public bool TryGetClosestGridAndVoxel(
 1990        Vector3d position,
 1991        out VoxelGrid? outGrid,
 1992        out Voxel? outVoxel,
 1993        GridTopologyKind? topologyKind = null)
 1994    {
 181995        outGrid = null;
 181996        outVoxel = null;
 181997        if (!CanResolveActiveGrid())
 21998            return false;
 1999
 162000        Fixed64 closestDistanceSquared = Fixed64.MaxValue;
 162001        if (TryGetClosestGrid(position, out VoxelGrid? closestBoundsGrid, topologyKind)
 162002            && closestBoundsGrid!.ConfiguredVoxelCount != 0)
 2003        {
 122004            bool resolved = closestBoundsGrid.TryGetClosestVoxel(
 122005                position,
 122006                out outVoxel,
 122007                out closestDistanceSquared);
 2008            Debug.Assert(resolved);
 122009            outGrid = closestBoundsGrid;
 2010        }
 2011
 782012        foreach (VoxelGrid candidateGrid in ActiveGrids)
 2013        {
 232014            if (candidateGrid == null
 232015                || !candidateGrid.IsActive
 232016                || candidateGrid.ConfiguredVoxelCount == 0
 232017                || !MatchesTopologyKind(candidateGrid, topologyKind))
 2018            {
 2019                continue;
 2020            }
 182021            if (ReferenceEquals(candidateGrid, outGrid))
 2022                continue;
 2023
 72024            Fixed64 boundsDistanceSquared = GetDistanceSquaredToBounds(position, candidateGrid.BoundsMin, candidateGrid.
 72025            if (outVoxel != null && boundsDistanceSquared > closestDistanceSquared)
 2026                continue;
 2027
 62028            candidateGrid.TryGetClosestVoxel(
 62029                position,
 62030                out Voxel? candidateVoxel,
 62031                out Fixed64 candidateDistanceSquared);
 2032
 62033            if (IsBetterClosestVoxel(
 62034                candidateDistanceSquared,
 62035                candidateGrid,
 62036                candidateVoxel!,
 62037                closestDistanceSquared,
 62038                outGrid,
 62039                outVoxel))
 2040            {
 52041                outGrid = candidateGrid;
 52042                outVoxel = candidateVoxel;
 52043                closestDistanceSquared = candidateDistanceSquared;
 2044            }
 2045        }
 2046
 162047        return outVoxel != null;
 2048    }
 2049
 2050    /// <summary>
 2051    /// Retrieves the physical voxel whose center is nearest to a 2D XZ-plane world position on the default world Y laye
 2052    /// Sparse grids only consider configured physical voxels.
 2053    /// </summary>
 2054    /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param
 2055    /// <param name="outGrid">The grid that owns the closest physical voxel, if found.</param>
 2056    /// <param name="outVoxel">The closest physical voxel, if found.</param>
 2057    /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are 
 2058    /// <returns>True if a physical voxel was resolved; otherwise false.</returns>
 2059    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 2060    public bool TryGetClosestGridAndVoxel(
 2061        Vector2d position,
 2062        out VoxelGrid? outGrid,
 2063        out Voxel? outVoxel,
 2064        GridTopologyKind? topologyKind = null) =>
 12065        TryGetClosestGridAndVoxel(position, default, out outGrid, out outVoxel, topologyKind);
 2066
 2067    /// <summary>
 2068    /// Retrieves the physical voxel whose center is nearest to a 2D XZ-plane world position on the supplied world Y lay
 2069    /// Sparse grids only consider configured physical voxels.
 2070    /// </summary>
 2071    /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param
 2072    /// <param name="layerY">The world Y layer to resolve. Defaults to zero when omitted by paired overloads.</param>
 2073    /// <param name="outGrid">The grid that owns the closest physical voxel, if found.</param>
 2074    /// <param name="outVoxel">The closest physical voxel, if found.</param>
 2075    /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are 
 2076    /// <returns>True if a physical voxel was resolved; otherwise false.</returns>
 2077    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 2078    public bool TryGetClosestGridAndVoxel(
 2079        Vector2d position,
 2080        Fixed64 layerY,
 2081        out VoxelGrid? outGrid,
 2082        out Voxel? outVoxel,
 2083        GridTopologyKind? topologyKind = null) =>
 32084        TryGetClosestGridAndVoxel(GridPlane2d.ToWorld(position, layerY), out outGrid, out outVoxel, topologyKind);
 2085
 2086    /// <summary>
 2087    /// Retrieves the grid and voxel for a given voxel identity.
 2088    /// </summary>
 2089    /// <param name="worldVoxelIndex">The voxel identity to resolve.</param>
 2090    /// <param name="outGrid">The resolved grid, if found.</param>
 2091    /// <param name="result">The resolved voxel, if found.</param>
 2092    /// <returns>True if both the grid and voxel were resolved; otherwise false.</returns>
 2093    public bool TryGetGridAndVoxel(
 2094        WorldVoxelIndex worldVoxelIndex,
 2095        out VoxelGrid? outGrid,
 2096        out Voxel? result)
 2097    {
 742098        result = null;
 742099        return TryGetGrid(worldVoxelIndex, out outGrid)
 742100            && outGrid!.TryGetVoxel(worldVoxelIndex.VoxelIndex, out result);
 2101    }
 2102
 2103    /// <summary>
 2104    /// Retrieves a voxel from a world position.
 2105    /// </summary>
 2106    /// <param name="position">The world position to resolve.</param>
 2107    /// <param name="result">The resolved voxel, if found.</param>
 2108    /// <returns>True if the voxel was resolved; otherwise false.</returns>
 2109    public bool TryGetVoxel(
 2110        Vector3d position,
 2111        out Voxel? result)
 2112    {
 1012113        result = null;
 1012114        return TryGetGrid(position, out VoxelGrid? grid)
 1012115            && grid!.TryGetVoxel(position, out result);
 2116    }
 2117
 2118    /// <summary>
 2119    /// Retrieves a voxel from a 2D XZ-plane world position on the default world Y layer.
 2120    /// </summary>
 2121    /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param
 2122    /// <param name="result">The resolved voxel, if found.</param>
 2123    /// <returns>True if the voxel was resolved; otherwise false.</returns>
 2124    public bool TryGetVoxel(
 2125        Vector2d position,
 2126        out Voxel? result)
 2127    {
 12128        return TryGetVoxel(position, default, out result);
 2129    }
 2130
 2131    /// <summary>
 2132    /// Retrieves a voxel from a 2D XZ-plane world position on the supplied world Y layer.
 2133    /// </summary>
 2134    /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param
 2135    /// <param name="layerY">The world Y layer to resolve. Defaults to zero when omitted by paired overloads.</param>
 2136    /// <param name="result">The resolved voxel, if found.</param>
 2137    /// <returns>True if the voxel was resolved; otherwise false.</returns>
 2138    public bool TryGetVoxel(
 2139        Vector2d position,
 2140        Fixed64 layerY,
 2141        out Voxel? result)
 2142    {
 32143        return TryGetVoxel(GridPlane2d.ToWorld(position, layerY), out result);
 2144    }
 2145
 2146    /// <summary>
 2147    /// Retrieves the physical voxel whose center is nearest to the supplied world position.
 2148    /// Sparse grids only consider configured physical voxels.
 2149    /// </summary>
 2150    /// <param name="position">The world position to resolve.</param>
 2151    /// <param name="result">The closest physical voxel, if found.</param>
 2152    /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are 
 2153    /// <returns>True if a physical voxel was resolved; otherwise false.</returns>
 2154    public bool TryGetClosestVoxel(
 2155        Vector3d position,
 2156        out Voxel? result,
 2157        GridTopologyKind? topologyKind = null)
 2158    {
 62159        result = null;
 62160        if (!TryGetClosestGridAndVoxel(position, out _, out Voxel? closestVoxel, topologyKind))
 22161            return false;
 2162
 42163        result = closestVoxel;
 42164        return true;
 2165    }
 2166
 2167    /// <summary>
 2168    /// Retrieves the physical voxel whose center is nearest to a 2D XZ-plane world position on the default world Y laye
 2169    /// Sparse grids only consider configured physical voxels.
 2170    /// </summary>
 2171    /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param
 2172    /// <param name="result">The closest physical voxel, if found.</param>
 2173    /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are 
 2174    /// <returns>True if a physical voxel was resolved; otherwise false.</returns>
 2175    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 2176    public bool TryGetClosestVoxel(
 2177        Vector2d position,
 2178        out Voxel? result,
 2179        GridTopologyKind? topologyKind = null) =>
 12180        TryGetClosestVoxel(position, default, out result, topologyKind);
 2181
 2182    /// <summary>
 2183    /// Retrieves the physical voxel whose center is nearest to a 2D XZ-plane world position on the supplied world Y lay
 2184    /// Sparse grids only consider configured physical voxels.
 2185    /// </summary>
 2186    /// <param name="position">The 2D position whose X component maps to world X and Y component maps to world Z.</param
 2187    /// <param name="layerY">The world Y layer to resolve. Defaults to zero when omitted by paired overloads.</param>
 2188    /// <param name="result">The closest physical voxel, if found.</param>
 2189    /// <param name="topologyKind">Optional topology filter. When supplied, only grids using the requested topology are 
 2190    /// <returns>True if a physical voxel was resolved; otherwise false.</returns>
 2191    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 2192    public bool TryGetClosestVoxel(
 2193        Vector2d position,
 2194        Fixed64 layerY,
 2195        out Voxel? result,
 2196        GridTopologyKind? topologyKind = null) =>
 32197        TryGetClosestVoxel(GridPlane2d.ToWorld(position, layerY), out result, topologyKind);
 2198
 2199    /// <summary>
 2200    /// Retrieves a voxel from a world-scoped voxel identity.
 2201    /// </summary>
 2202    /// <param name="worldVoxelIndex">The voxel identity to resolve.</param>
 2203    /// <param name="result">The resolved voxel, if found.</param>
 2204    /// <returns>True if the voxel was resolved; otherwise false.</returns>
 2205    public bool TryGetVoxel(
 2206        WorldVoxelIndex worldVoxelIndex,
 2207        out Voxel? result)
 2208    {
 32209        result = null;
 32210        return TryGetGrid(worldVoxelIndex, out VoxelGrid? grid)
 32211            && grid!.TryGetVoxel(worldVoxelIndex.VoxelIndex, out result);
 2212    }
 2213
 2214    #endregion
 2215
 2216    #region Internal Helpers
 2217
 2218    /// <summary>
 2219    /// Increments the version of the specified grid and optionally the world version.
 2220    /// </summary>
 2221    public void IncrementGridVersion(int index, bool significant = false)
 2222    {
 52223        if (!IsActive)
 2224        {
 32225            GridForgeLogger.Channel.Warn($"Grid world not active. Cannot increment grid versions.");
 32226            return;
 2227        }
 2228
 22229        _gridLock.EnterWriteLock();
 2230        try
 2231        {
 22232            if (significant)
 12233                Version++;
 2234
 22235            if (ActiveGrids.IsAllocated(index))
 12236                ActiveGrids[index].IncrementVersion();
 22237        }
 2238        finally
 2239        {
 22240            _gridLock.ExitWriteLock();
 22241        }
 22242    }
 2243
 2244    /// <summary>
 2245    /// Finds active grids in this world that overlap the supplied target grid.
 2246    /// </summary>
 2247    public IEnumerable<VoxelGrid> FindOverlappingGrids(VoxelGrid targetGrid)
 2248    {
 52249        SwiftList<VoxelGrid> overlappingGrids = new();
 52250        FindOverlappingGridsInto(targetGrid, overlappingGrids);
 52251        return overlappingGrids;
 2252    }
 2253
 2254    /// <summary>
 2255    /// Clears and fills caller-owned storage with active grids that overlap the supplied target grid.
 2256    /// </summary>
 2257    /// <param name="targetGrid">The grid whose expanded topology bounds define the overlap query.</param>
 2258    /// <param name="results">Caller-owned storage cleared and filled in ascending grid-slot order.</param>
 2259    public void FindOverlappingGridsInto(VoxelGrid targetGrid, SwiftList<VoxelGrid> results)
 2260    {
 72261        ChronicleGuard.ThrowIfNull(targetGrid, nameof(targetGrid));
 72262        ChronicleGuard.ThrowIfNull(results, nameof(results));
 2263
 72264        results.Clear();
 2265
 72266        if (!IsActive)
 2267        {
 32268            GridForgeLogger.Channel.Warn($"Grid world not active. Cannot resolve overlaps.");
 32269            return;
 2270        }
 2271
 42272        _spatialIndex.CollectCandidates(
 42273            CreateExpandedBounds(
 42274                targetGrid.BoundsMin,
 42275                targetGrid.BoundsMax,
 42276                targetGrid.Topology.OverlapTolerance),
 42277            ActiveGrids,
 42278            _gridCandidates);
 262279        for (int candidateIndex = 0; candidateIndex < _gridCandidates.Count; candidateIndex++)
 92280            TryAddOverlappingGrid(targetGrid, _gridCandidates[candidateIndex], results);
 42281    }
 2282
 2283    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 2284    private static bool MatchesTopologyKind(VoxelGrid grid, GridTopologyKind? topologyKind) =>
 652285        !topologyKind.HasValue || grid.TopologyKind == topologyKind.Value;
 2286
 2287    private static bool IsBetterClosestVoxel(
 2288        Fixed64 candidateDistanceSquared,
 2289        VoxelGrid candidateGrid,
 2290        Voxel candidateVoxel,
 2291        Fixed64 closestDistanceSquared,
 2292        VoxelGrid? closestGrid,
 2293        Voxel? closestVoxel)
 2294    {
 62295        if (closestVoxel == null || closestGrid == null)
 12296            return true;
 2297
 52298        if (candidateDistanceSquared != closestDistanceSquared)
 32299            return candidateDistanceSquared < closestDistanceSquared;
 2300
 22301        return candidateGrid.GridIndex < closestGrid.GridIndex;
 2302    }
 2303
 2304    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 2305    private static Fixed64 GetDistanceSquaredToBounds(Vector3d position, Vector3d boundsMin, Vector3d boundsMax)
 2306    {
 452307        Fixed64 x = GetAxisDistanceToBounds(position.X, boundsMin.X, boundsMax.X);
 452308        Fixed64 y = GetAxisDistanceToBounds(position.Y, boundsMin.Y, boundsMax.Y);
 452309        Fixed64 z = GetAxisDistanceToBounds(position.Z, boundsMin.Z, boundsMax.Z);
 452310        return x * x + y * y + z * z;
 2311    }
 2312
 2313    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 2314    private static Fixed64 GetAxisDistanceToBounds(Fixed64 coordinate, Fixed64 min, Fixed64 max)
 2315    {
 1352316        if (coordinate < min)
 172317            return min - coordinate;
 2318
 1182319        return coordinate > max ? coordinate - max : Fixed64.Zero;
 2320    }
 2321
 2322    private bool CanResolveGrid(int index)
 2323    {
 19902324        if (!CanResolveActiveGrid())
 22325            return false;
 2326
 19882327        if (!IsGridIndexInActiveRange(index))
 2328        {
 82329            GridForgeLogger.Channel.Error($"GridIndex '{index}' is out-of-bounds for ActiveGrids.");
 82330            return false;
 2331        }
 2332
 19802333        return IsGridIndexAllocated(index);
 2334    }
 2335
 2336    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 2337    private bool CanResolveActiveGrid()
 2338    {
 20392339        if (IsActive)
 20342340            return true;
 2341
 52342        GridForgeLogger.Channel.Warn($"Grid world not active. Cannot resolve grids.");
 52343        return false;
 2344    }
 2345
 2346    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 2347    private bool IsGridIndexInActiveRange(int index) =>
 19882348         (uint)index < MaxGrids && (uint)index <= ActiveGrids.Count;
 2349
 2350    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 2351    private bool IsGridIndexAllocated(int index)
 2352    {
 19802353        if (ActiveGrids.IsAllocated(index))
 19712354            return true;
 2355
 92356        GridForgeLogger.Channel.Error($"GridIndex '{index}' has not been allocated to ActiveGrids.");
 92357        return false;
 2358    }
 2359
 2360    private bool CanResolvePosition()
 2361    {
 1542362        if (IsActive)
 1522363            return true;
 2364
 22365        GridForgeLogger.Channel.Warn($"Grid world not active. Cannot resolve positions.");
 22366        return false;
 2367    }
 2368
 2369    private bool TryGetContainingGrid(
 2370        Vector3d position,
 2371        SwiftList<ushort> gridList,
 2372        out VoxelGrid? outGrid)
 2373    {
 1522374        outGrid = null;
 2375
 3522376        for (int index = 0; index < gridList.Count; index++)
 2377        {
 882378            ushort candidateIndex = gridList[index];
 882379            VoxelGrid candidateGrid = ActiveGrids[candidateIndex];
 882380            if (candidateGrid.IsInBounds(position))
 2381            {
 642382                outGrid = candidateGrid;
 642383                return true;
 2384            }
 2385        }
 2386
 882387        return false;
 2388    }
 2389
 2390    private void TryAddOverlappingGrid(
 2391        VoxelGrid targetGrid,
 2392        ushort neighborIndex,
 2393        SwiftList<VoxelGrid> overlappingGrids)
 2394    {
 92395        if (neighborIndex == targetGrid.GridIndex)
 42396            return;
 2397
 52398        overlappingGrids.Add(ActiveGrids[neighborIndex]);
 52399    }
 2400
 2401    #endregion
 2402
 2403    #region Private Helpers
 2404
 2405    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 2406    private static int ResolveSpatialGridCellSize(int spatialGridCellSize)
 2407    {
 10692408        if (spatialGridCellSize <= 0)
 2409        {
 32410            GridForgeLogger.Channel.Warn($"Spatial grid cell size must be greater than zero. Falling back to default siz
 32411            return DefaultSpatialGridCellSize;
 2412        }
 2413
 10662414        return spatialGridCellSize;
 2415    }
 2416
 2417    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 2418    private GridEventInfo CreateGridEventInfo(
 2419        VoxelGrid grid,
 2420        GridEventKind changeKind,
 2421        GridChangeStamp changeStamp)
 2422    {
 12842423        grid.LastChangeSequence = changeStamp.Sequence;
 12842424        return new GridEventInfo(
 12842425            SpawnToken,
 12842426            grid.GridIndex,
 12842427            grid.SpawnToken,
 12842428            grid.Configuration,
 12842429            grid.Version,
 12842430            changeKind,
 12842431            default,
 12842432            grid.BoundsMin,
 12842433            grid.BoundsMax,
 12842434            changeStamp);
 2435    }
 2436
 2437    internal GridEventInfo CreateGridEventInfo(
 2438        VoxelGrid grid,
 2439        GridEventKind changeKind,
 2440        VoxelIndex voxelIndex,
 2441        Vector3d affectedBoundsMin,
 2442        Vector3d affectedBoundsMax,
 2443        GridChangeStamp changeStamp,
 2444        bool hasVoxelState,
 2445        bool isVoxelPresent,
 2446        byte obstacleCount)
 2447    {
 19962448        grid.LastChangeSequence = changeStamp.Sequence;
 19962449        return new GridEventInfo(
 19962450            SpawnToken,
 19962451            grid.GridIndex,
 19962452            grid.SpawnToken,
 19962453            grid.Configuration,
 19962454            grid.Version,
 19962455            changeKind,
 19962456            voxelIndex,
 19962457            affectedBoundsMin,
 19962458            affectedBoundsMax,
 19962459            changeStamp,
 19962460            hasVoxelState,
 19962461            isVoxelPresent,
 19962462            obstacleCount);
 2463    }
 2464
 2465    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 2466    internal GridChangeStamp AllocateChangeStamp()
 2467    {
 2468        Debug.Assert(Monitor.IsEntered(ChangeSyncRoot));
 43572469        _changeSequence = checked(_changeSequence + 1);
 43572470        return new GridChangeStamp(_changeSequence, _changeSequence);
 2471    }
 2472
 2473    internal bool EnqueueCommittedChange(GridCommittedChange change)
 2474    {
 2475        Debug.Assert(Monitor.IsEntered(ChangeSyncRoot));
 43572476        _committedChanges.Enqueue(change);
 43572477        if (_isPublishingCommittedChanges)
 9562478            return false;
 2479
 34012480        _isPublishingCommittedChanges = true;
 34012481        return true;
 2482    }
 2483
 2484    internal void DrainCommittedChanges()
 2485    {
 34012486        Volatile.Write(ref _committedPublicationOwnerThreadId, Environment.CurrentManagedThreadId);
 2487        try
 2488        {
 2489            while (true)
 2490            {
 2491                GridCommittedChange change;
 77582492                lock (ChangeSyncRoot)
 2493                {
 77582494                    if (!_committedChanges.TryDequeue(out change))
 2495                    {
 34012496                        _isPublishingCommittedChanges = false;
 34012497                        return;
 2498                    }
 43572499                }
 2500
 43572501                GridObstacleManager.NotifyCommittedExact(change);
 43572502                switch (change.GridEvent.ChangeKind)
 2503                {
 2504                    case GridEventKind.GridAdded:
 12222505                        NotifyActiveGridAdded(change.GridEvent);
 12222506                        break;
 2507                    case GridEventKind.GridRemoved:
 622508                        NotifyActiveGridRemoved(change.GridEvent);
 622509                        break;
 2510                    case GridEventKind.WorldReset:
 2511                        break;
 2512                    default:
 19962513                        NotifyActiveGridChange(change.GridEvent);
 2514                        break;
 2515                }
 2516
 43572517                NotifyChangeCommitted(change.GridEvent);
 43572518                lock (ChangeSyncRoot)
 2519                {
 43572520                    _publishedChangeSequence = change.GridEvent.ChangeSequence;
 43572521                    Monitor.PulseAll(ChangeSyncRoot);
 43572522                }
 2523            }
 2524        }
 2525        finally
 2526        {
 34012527            Volatile.Write(ref _committedPublicationOwnerThreadId, 0);
 34012528        }
 34012529    }
 2530
 2531    private void NotifyActiveGridAdded(GridEventInfo eventInfo)
 2532    {
 12222533        Action<GridEventInfo>? handlers = _onActiveGridAdded;
 12222534        if (handlers == null)
 12112535            return;
 2536
 112537        var handlerDelegates = handlers.GetInvocationList();
 482538        for (int i = 0; i < handlerDelegates.Length; i++)
 2539        {
 2540            try
 2541            {
 132542                ((Action<GridEventInfo>)handlerDelegates[i])(eventInfo);
 122543            }
 12544            catch (Exception ex)
 2545            {
 12546                GridForgeLogger.Channel.Error($"[Grid {eventInfo.GridIndex}] added notification error: {ex.Message}");
 12547            }
 2548        }
 112549    }
 2550
 2551    private void NotifyActiveGridRemoved(GridEventInfo eventInfo)
 2552    {
 622553        Action<GridEventInfo>? handlers = _onActiveGridRemoved;
 622554        if (handlers == null)
 542555            return;
 2556
 82557        var handlerDelegates = handlers.GetInvocationList();
 362558        for (int i = 0; i < handlerDelegates.Length; i++)
 2559        {
 2560            try
 2561            {
 102562                ((Action<GridEventInfo>)handlerDelegates[i])(eventInfo);
 92563            }
 12564            catch (Exception ex)
 2565            {
 12566                GridForgeLogger.Channel.Error($"[Grid {eventInfo.GridIndex}] removed notification error: {ex.Message}");
 12567            }
 2568        }
 82569    }
 2570
 2571    internal void NotifyActiveGridChange(GridEventInfo eventInfo)
 2572    {
 19962573        Action<GridEventInfo>? handlers = _onActiveGridChange;
 19962574        if (handlers == null)
 11732575            return;
 2576
 8232577        var handlerDelegates = handlers.GetInvocationList();
 591762578        for (int i = 0; i < handlerDelegates.Length; i++)
 2579        {
 2580            try
 2581            {
 287652582                ((Action<GridEventInfo>)handlerDelegates[i])(eventInfo);
 287632583            }
 22584            catch (Exception ex)
 2585            {
 22586                GridForgeLogger.Channel.Error($"[Grid {eventInfo.GridIndex}] change notification error: {ex.Message}");
 22587            }
 2588        }
 8232589    }
 2590
 2591    private void NotifyChangeCommitted(GridEventInfo eventInfo)
 2592    {
 43572593        Action<GridEventInfo>? handlers = _onChangeCommitted;
 43572594        if (handlers == null)
 43302595            return;
 2596
 272597        var handlerDelegates = handlers.GetInvocationList();
 1102598        for (int i = 0; i < handlerDelegates.Length; i++)
 2599        {
 2600            try
 2601            {
 282602                ((Action<GridEventInfo>)handlerDelegates[i])(eventInfo);
 272603            }
 12604            catch (Exception ex)
 2605            {
 12606                GridForgeLogger.Channel.Error($"[Change {eventInfo.ChangeSequence}] committed notification error: {ex.Me
 12607            }
 2608        }
 272609    }
 2610
 2611    #endregion
 2612}

Methods/Properties

TryBeginCoveredAddresses(GridForge.Grids.Topology.GridCoveredAddressCursor,FixedMathSharp.Vector3d,FixedMathSharp.Vector3d,System.Int32)
TryBeginCoveredAddresses(GridForge.Grids.Topology.GridCoveredAddressCursor,FixedMathSharp.Vector3d,FixedMathSharp.Vector3d,System.Int32,GridForge.Configuration.GridConfigurationKey)
AdvanceCoveredAddresses(GridForge.Grids.Topology.GridCoveredAddressCursor,System.ReadOnlySpan`1<GridForge.Grids.Topology.GridCoveredAddressGeneration>,System.Span`1<GridForge.Grids.Topology.GridCoveredAddress>,System.Int32,System.Int32,System.Int32,System.Int32&,System.Int32&,System.Int32&,System.Int32&)
TryBeginCoveredAddressesCore(GridForge.Grids.Topology.GridCoveredAddressCursor,FixedMathSharp.Vector3d,FixedMathSharp.Vector3d,System.Int32,System.Boolean,GridForge.Configuration.GridConfigurationKey)
AdvanceCoveredAddressesCore(GridForge.Grids.Topology.GridCoveredAddressCursor,System.ReadOnlySpan`1<GridForge.Grids.Topology.GridCoveredAddressGeneration>,System.Span`1<GridForge.Grids.Topology.GridCoveredAddress>,System.Int32,System.Int32,System.Int32,System.Int32&,System.Int32&,System.Int32&,System.Int32&)
TryBindCoveredAddressGeneration(GridForge.Grids.Topology.GridCoveredAddressCursor,GridForge.Grids.Topology.GridCoveredAddressGeneration,GridForge.Grids.Topology.GridCoveredAddressCursor/BoundGeneration&)
IsCoveredAddressCursorCurrent(GridForge.Grids.Topology.GridCoveredAddressCursor)
IsCoveredAddress(GridForge.Grids.Topology.GridCoveredAddressCursor,GridForge.Grids.Topology.GridCoveredAddressGeneration,GridForge.Spatial.VoxelIndex)
AdvanceCoveredAddress(GridForge.Spatial.VoxelIndex&,GridForge.Spatial.VoxelIndex,GridForge.Spatial.VoxelIndex)
ConsumeLookupProbe(GridForge.Grids.Topology.GridCoveredAddressCursor,System.Int32&)
ConsumeAddressProbe(GridForge.Grids.Topology.GridCoveredAddressCursor,System.Int32&)
.cctor()
get_ChangeSequence()
EnterReadLock()
ExitReadLock()
get_IsWriteLockHeld()
.ctor(System.Int32)
add_OnActiveGridAdded(System.Action`1<GridForge.Grids.GridEventInfo>)
remove_OnActiveGridAdded(System.Action`1<GridForge.Grids.GridEventInfo>)
add_OnActiveGridRemoved(System.Action`1<GridForge.Grids.GridEventInfo>)
remove_OnActiveGridRemoved(System.Action`1<GridForge.Grids.GridEventInfo>)
add_OnActiveGridChange(System.Action`1<GridForge.Grids.GridEventInfo>)
remove_OnActiveGridChange(System.Action`1<GridForge.Grids.GridEventInfo>)
add_OnChangeCommitted(System.Action`1<GridForge.Grids.GridEventInfo>)
remove_OnChangeCommitted(System.Action`1<GridForge.Grids.GridEventInfo>)
add_OnReset(System.Action)
remove_OnReset(System.Action)
Reset(System.Boolean)
NotifyResetHandlers()
ReleaseActiveGrids()
Dispose()
AllocateObstacleToken()
TryCaptureNavigationBaseline(GridForge.Configuration.GridConfigurationKey,System.ReadOnlySpan`1<GridForge.Spatial.VoxelIndex>,GridForge.Grids.GridNavigationBaseline&)
ExecuteNavigationMaintenanceSnapshot(System.Action)
BeginBoundaryContacts(GridForge.Grids.Topology.GridBoundaryContactCursor)
TryBeginBoundaryContacts(GridForge.Configuration.GridConfigurationKey,GridForge.Grids.Topology.GridBoundaryContactCursor)
AdvanceBoundaryContacts(GridForge.Grids.Topology.GridBoundaryContactCursor,System.Span`1<GridForge.Grids.Topology.VoxelContactManifold>,System.Int32,System.Int32,System.Int32&,System.Int32&)
AdvanceBoundaryContacts(GridForge.Grids.Topology.GridBoundaryContactCursor,System.Span`1<GridForge.Grids.Topology.GridBoundaryContact>,System.Int32,System.Int32,System.Int32&,System.Int32&)
AdvanceBoundaryContactsUnderGate(GridForge.Grids.Topology.GridBoundaryContactCursor,System.Span`1<GridForge.Grids.Topology.VoxelContactManifold>,System.Span`1<GridForge.Grids.Topology.GridBoundaryContact>,System.Boolean,System.Int32,System.Int32,System.Int32&,System.Int32&)
AdvanceBoundaryContactsCore(GridForge.Grids.Topology.GridBoundaryContactCursor,System.Span`1<GridForge.Grids.Topology.VoxelContactManifold>,System.Span`1<GridForge.Grids.Topology.GridBoundaryContact>,System.Boolean,System.Int32,System.Int32,System.Int32&,System.Int32&)
IsBoundaryContactCursorCurrent(GridForge.Grids.Topology.GridBoundaryContactCursor)
TryAdvanceFilteredBoundaryContactPair(GridForge.Grids.Topology.GridBoundaryContactCursor,System.Int32,System.Int32&,System.UInt16&,System.UInt16&)
BindBoundaryContactPair(GridForge.Grids.Topology.GridBoundaryContactCursor,System.UInt16,System.UInt16)
ProbeBoundaryContactTarget(GridForge.Grids.Topology.GridBoundaryContactCursor,System.Int32&)
AdvanceBoundaryContactAddress(GridForge.Spatial.VoxelIndex&,GridForge.Spatial.VoxelIndex,GridForge.Spatial.VoxelIndex)
TryCreateTopologyPrism(GridForge.Grids.VoxelGrid,GridForge.Spatial.VoxelIndex,GridForge.Grids.Topology.GridCellPrism&)
GetTrailingZeroCount(System.UInt64)
ConsumeBoundaryContactProbe(GridForge.Grids.Topology.GridBoundaryContactCursor,System.Int32&)
ThrowIfNavigationMaintenanceUnavailable()
TryEnterNavigationMaintenanceSnapshot()
ExitNavigationMaintenanceSnapshot()
WaitForPublishedChangePrefix()
TryCaptureNavigationBaselineCore(GridForge.Configuration.GridConfigurationKey,System.ReadOnlySpan`1<GridForge.Spatial.VoxelIndex>,GridForge.Grids.GridNavigationBaseline&)
AreNavigationBaselineAddressesValid(GridForge.Grids.VoxelGrid,System.ReadOnlySpan`1<GridForge.Spatial.VoxelIndex>)
TryAddGrid(GridForge.Configuration.GridConfiguration,System.UInt16&)
TryAddGrid(GridForge.Configuration.GridConfiguration,System.Collections.Generic.IEnumerable`1<GridForge.Spatial.VoxelIndex>,System.UInt16&)
TryAddGrid(GridForge.Configuration.GridConfiguration,System.Boolean[0...,0...,0...],System.UInt16&)
TryAddGridCore(GridForge.Configuration.GridConfiguration,System.Collections.Generic.IEnumerable`1<GridForge.Spatial.VoxelIndex>,System.Boolean[0...,0...,0...],System.UInt16&)
TryRemoveGrid(System.UInt16)
CanAddGrid()
TryPrepareConfiguredVoxels(GridForge.Configuration.GridConfiguration,GridForge.Grids.Topology.GridDimensions,System.Collections.Generic.IEnumerable`1<GridForge.Spatial.VoxelIndex>,System.Boolean[0...,0...,0...],GridForge.Spatial.VoxelIndex[]&)
TryPrepareConfiguredVoxelMask(System.Boolean[0...,0...,0...],GridForge.Grids.Topology.GridDimensions,GridForge.Spatial.VoxelIndex[]&)
TryPrepareConfiguredVoxelIndices(System.Collections.Generic.IEnumerable`1<GridForge.Spatial.VoxelIndex>,GridForge.Grids.Topology.GridDimensions,GridForge.Spatial.VoxelIndex[]&)
IsConfiguredVoxelInBounds(GridForge.Spatial.VoxelIndex,GridForge.Grids.Topology.GridDimensions)
CompactPreparedVoxels(GridForge.Spatial.VoxelIndex[]&)
UpdateMaxTopologyCellEdge(FixedMathSharp.Fixed64)
RecalculateMaxTopologyCellEdgeIfNeeded(FixedMathSharp.Fixed64)
TryFindExistingGridUnsafe(GridForge.Configuration.GridConfigurationKey,System.UInt16&)
RegisterGrid(GridForge.Grids.VoxelGrid,System.UInt16)
UnregisterGrid(GridForge.Grids.VoxelGrid,System.UInt16)
TryCreateBoundaryContactEnvelope(GridForge.Grids.VoxelGrid,SwiftCollections.Query.FixedBoundVolume&)
InsertBoundaryContactPair(System.UInt16,System.UInt16)
RemoveBoundaryContactPairs(System.UInt16)
RemoveBoundaryContactIncident(SwiftCollections.SwiftDictionary`2<System.UInt16,SwiftCollections.SwiftList`1<System.UInt16>>,System.UInt16,System.UInt16,System.Boolean)
GetOrCreateBoundaryContactRow(SwiftCollections.SwiftDictionary`2<System.UInt16,SwiftCollections.SwiftList`1<System.UInt16>>,System.UInt16,System.Boolean&)
InsertSorted(SwiftCollections.SwiftList`1<System.UInt16>,System.UInt16)
RemoveSorted(SwiftCollections.SwiftList`1<System.UInt16>,System.UInt16)
FindSortedIndex(SwiftCollections.SwiftList`1<System.UInt16>,System.UInt16)
SetBoundaryContactSource(System.UInt16)
ClearBoundaryContactSource(System.UInt16)
ReleaseBoundaryContactPairs()
UnlinkGridNeighbors(GridForge.Grids.VoxelGrid)
CollectGridCandidates(FixedMathSharp.Vector3d,FixedMathSharp.Vector3d,SwiftCollections.SwiftList`1<System.UInt16>,System.Int32)
CreateExpandedBounds(FixedMathSharp.Vector3d,FixedMathSharp.Vector3d,FixedMathSharp.Fixed64)
TryGetGrid(System.Int32,GridForge.Grids.VoxelGrid&)
TryGetGrid(FixedMathSharp.Vector3d,GridForge.Grids.VoxelGrid&)
TryGetGrid(FixedMathSharp.Vector2d,GridForge.Grids.VoxelGrid&)
TryGetGrid(FixedMathSharp.Vector2d,FixedMathSharp.Fixed64,GridForge.Grids.VoxelGrid&)
TryGetClosestGrid(FixedMathSharp.Vector3d,GridForge.Grids.VoxelGrid&,System.Nullable`1<GridForge.Grids.Topology.GridTopologyKind>)
TryGetClosestGrid(FixedMathSharp.Vector2d,GridForge.Grids.VoxelGrid&,System.Nullable`1<GridForge.Grids.Topology.GridTopologyKind>)
TryGetClosestGrid(FixedMathSharp.Vector2d,FixedMathSharp.Fixed64,GridForge.Grids.VoxelGrid&,System.Nullable`1<GridForge.Grids.Topology.GridTopologyKind>)
TryGetGrid(GridForge.Spatial.WorldVoxelIndex,GridForge.Grids.VoxelGrid&)
TryGetGridAndVoxel(FixedMathSharp.Vector3d,GridForge.Grids.VoxelGrid&,GridForge.Grids.Voxel&)
TryGetGridAndVoxel(FixedMathSharp.Vector2d,GridForge.Grids.VoxelGrid&,GridForge.Grids.Voxel&)
TryGetGridAndVoxel(FixedMathSharp.Vector2d,FixedMathSharp.Fixed64,GridForge.Grids.VoxelGrid&,GridForge.Grids.Voxel&)
TryGetClosestGridAndVoxel(FixedMathSharp.Vector3d,GridForge.Grids.VoxelGrid&,GridForge.Grids.Voxel&,System.Nullable`1<GridForge.Grids.Topology.GridTopologyKind>)
TryGetClosestGridAndVoxel(FixedMathSharp.Vector2d,GridForge.Grids.VoxelGrid&,GridForge.Grids.Voxel&,System.Nullable`1<GridForge.Grids.Topology.GridTopologyKind>)
TryGetClosestGridAndVoxel(FixedMathSharp.Vector2d,FixedMathSharp.Fixed64,GridForge.Grids.VoxelGrid&,GridForge.Grids.Voxel&,System.Nullable`1<GridForge.Grids.Topology.GridTopologyKind>)
TryGetGridAndVoxel(GridForge.Spatial.WorldVoxelIndex,GridForge.Grids.VoxelGrid&,GridForge.Grids.Voxel&)
TryGetVoxel(FixedMathSharp.Vector3d,GridForge.Grids.Voxel&)
TryGetVoxel(FixedMathSharp.Vector2d,GridForge.Grids.Voxel&)
TryGetVoxel(FixedMathSharp.Vector2d,FixedMathSharp.Fixed64,GridForge.Grids.Voxel&)
TryGetClosestVoxel(FixedMathSharp.Vector3d,GridForge.Grids.Voxel&,System.Nullable`1<GridForge.Grids.Topology.GridTopologyKind>)
TryGetClosestVoxel(FixedMathSharp.Vector2d,GridForge.Grids.Voxel&,System.Nullable`1<GridForge.Grids.Topology.GridTopologyKind>)
TryGetClosestVoxel(FixedMathSharp.Vector2d,FixedMathSharp.Fixed64,GridForge.Grids.Voxel&,System.Nullable`1<GridForge.Grids.Topology.GridTopologyKind>)
TryGetVoxel(GridForge.Spatial.WorldVoxelIndex,GridForge.Grids.Voxel&)
IncrementGridVersion(System.Int32,System.Boolean)
FindOverlappingGrids(GridForge.Grids.VoxelGrid)
FindOverlappingGridsInto(GridForge.Grids.VoxelGrid,SwiftCollections.SwiftList`1<GridForge.Grids.VoxelGrid>)
MatchesTopologyKind(GridForge.Grids.VoxelGrid,System.Nullable`1<GridForge.Grids.Topology.GridTopologyKind>)
IsBetterClosestVoxel(FixedMathSharp.Fixed64,GridForge.Grids.VoxelGrid,GridForge.Grids.Voxel,FixedMathSharp.Fixed64,GridForge.Grids.VoxelGrid,GridForge.Grids.Voxel)
GetDistanceSquaredToBounds(FixedMathSharp.Vector3d,FixedMathSharp.Vector3d,FixedMathSharp.Vector3d)
GetAxisDistanceToBounds(FixedMathSharp.Fixed64,FixedMathSharp.Fixed64,FixedMathSharp.Fixed64)
CanResolveGrid(System.Int32)
CanResolveActiveGrid()
IsGridIndexInActiveRange(System.Int32)
IsGridIndexAllocated(System.Int32)
CanResolvePosition()
TryGetContainingGrid(FixedMathSharp.Vector3d,SwiftCollections.SwiftList`1<System.UInt16>,GridForge.Grids.VoxelGrid&)
TryAddOverlappingGrid(GridForge.Grids.VoxelGrid,System.UInt16,SwiftCollections.SwiftList`1<GridForge.Grids.VoxelGrid>)
ResolveSpatialGridCellSize(System.Int32)
CreateGridEventInfo(GridForge.Grids.VoxelGrid,GridForge.Grids.GridEventKind,GridForge.Grids.GridChangeStamp)
CreateGridEventInfo(GridForge.Grids.VoxelGrid,GridForge.Grids.GridEventKind,GridForge.Spatial.VoxelIndex,FixedMathSharp.Vector3d,FixedMathSharp.Vector3d,GridForge.Grids.GridChangeStamp,System.Boolean,System.Boolean,System.Byte)
AllocateChangeStamp()
EnqueueCommittedChange(GridForge.Grids.GridCommittedChange)
DrainCommittedChanges()
NotifyActiveGridAdded(GridForge.Grids.GridEventInfo)
NotifyActiveGridRemoved(GridForge.Grids.GridEventInfo)
NotifyActiveGridChange(GridForge.Grids.GridEventInfo)
NotifyChangeCommitted(GridForge.Grids.GridEventInfo)