| | | 1 | | using FixedMathSharp; |
| | | 2 | | using GridForge.Grids; |
| | | 3 | | using GridForge.Spatial; |
| | | 4 | | using SwiftCollections; |
| | | 5 | | using System; |
| | | 6 | | using System.Linq; |
| | | 7 | | using System.Runtime.CompilerServices; |
| | | 8 | | using System.Threading; |
| | | 9 | | |
| | | 10 | | namespace Trailblazer.Pathing; |
| | | 11 | | |
| | | 12 | | /// <summary> |
| | | 13 | | /// Responsible for generating flow fields using a wavefront flood-fill algorithm. |
| | | 14 | | /// Provides pathfinding data suitable for many agents with shared destinations. |
| | | 15 | | /// </summary> |
| | | 16 | | public class FlowFieldSurveyor |
| | | 17 | | { |
| | 1 | 18 | | private static readonly Vector3d[] _normalizedDirectionByNeighbor = CreateNormalizedDirectionLookup(); |
| | | 19 | | |
| | | 20 | | #region Singleton Instances |
| | | 21 | | |
| | | 22 | | /// <summary> |
| | | 23 | | /// A lazily initialized singleton instance of the pathfinder. |
| | | 24 | | /// </summary> |
| | 1 | 25 | | private static readonly Lazy<FlowFieldSurveyor> _instance = |
| | 1 | 26 | | new(() => new FlowFieldSurveyor(), LazyThreadSafetyMode.ExecutionAndPublication); |
| | | 27 | | |
| | | 28 | | /// <summary> |
| | | 29 | | /// Gets the shared instance of the pathfinder. |
| | | 30 | | /// </summary> |
| | 50 | 31 | | public static FlowFieldSurveyor Shared => _instance.Value; |
| | | 32 | | |
| | | 33 | | #endregion |
| | | 34 | | |
| | 968 | 35 | | private readonly SurveyorLock _scratchLock = new(); |
| | | 36 | | |
| | 968 | 37 | | private readonly PathHeap<SolidChartPartition> _heap = new(); |
| | | 38 | | |
| | 968 | 39 | | private readonly SwiftHashSet<string> _chartKeys = new(); |
| | | 40 | | |
| | 968 | 41 | | private readonly SwiftList<FlowFieldSamplingGrid> _samplingGrids = new(); |
| | | 42 | | |
| | 968 | 43 | | private readonly SwiftList<FlowFieldSamplingGridBuilder> _samplingGridBuilders = new(); |
| | | 44 | | |
| | | 45 | | private FlowFieldPathRequest? _request; |
| | | 46 | | |
| | | 47 | | /// <summary> |
| | | 48 | | /// Attempts to create a shared flow field path from the start to the end voxel specified in the request. |
| | | 49 | | /// </summary> |
| | | 50 | | /// <param name="request">A flow field path request containing the start, end, and search parameters.</param> |
| | | 51 | | /// <returns>A dictionary of flow fields indexed by spawn token.</returns> |
| | | 52 | | public FlowFieldSurveyResult FindPath(FlowFieldPathRequest request) |
| | | 53 | | { |
| | 258 | 54 | | lock (_scratchLock) |
| | | 55 | | { |
| | 258 | 56 | | if (request == null |
| | 258 | 57 | | || request.HasZeroDisplacement |
| | 258 | 58 | | || request.EndNode == null |
| | 258 | 59 | | || !request.EndNode.TryGetPartition(out SolidChartPartition? targetPart) |
| | 258 | 60 | | || targetPart == null) |
| | | 61 | | { |
| | 4 | 62 | | return FlowFieldSurveyResult.Empty; |
| | | 63 | | } |
| | | 64 | | |
| | 254 | 65 | | _request = request; |
| | | 66 | | |
| | 254 | 67 | | ClearWorkingState(); |
| | | 68 | | // Start from the end and move towards the start voxel |
| | 254 | 69 | | _heap.Add(targetPart, pathCost: 0); |
| | 254 | 70 | | ChartOwnerUtility.AddOwners(_chartKeys, targetPart.ChartOwners); |
| | | 71 | | |
| | 254 | 72 | | if (!FloodPath()) |
| | | 73 | | { |
| | 132 | 74 | | ClearWorkingState(); |
| | 132 | 75 | | return FlowFieldSurveyResult.Empty; |
| | | 76 | | } |
| | | 77 | | |
| | 122 | 78 | | SwiftDictionary<WorldVoxelIndex, FlowField> flowFields = GenerateFlowFields(); |
| | 122 | 79 | | string[] chartsUsed = _chartKeys.ToArray(); |
| | 122 | 80 | | FlowFieldSamplingGrid[] samplingGrids = _samplingGrids.Count == 0 |
| | 122 | 81 | | ? Array.Empty<FlowFieldSamplingGrid>() |
| | 122 | 82 | | : _samplingGrids.ToArray(); |
| | 122 | 83 | | FlowFieldSurveyResult result = FlowFieldSurveyResult.Create( |
| | 122 | 84 | | request.Context, |
| | 122 | 85 | | flowFields, |
| | 122 | 86 | | chartsUsed, |
| | 122 | 87 | | request.RequestCacheKey, |
| | 122 | 88 | | samplingGrids); |
| | 122 | 89 | | ClearWorkingState(); |
| | 122 | 90 | | return result; |
| | | 91 | | } |
| | 258 | 92 | | } |
| | | 93 | | |
| | | 94 | | /// <summary> |
| | | 95 | | /// Executes the wavefront expansion (flood fill) phase of the flow field generation algorithm. |
| | | 96 | | /// Starts from the goal and expands outward until the start voxel is reached or search range is exceeded. |
| | | 97 | | /// </summary> |
| | | 98 | | /// <returns><c>true</c> if the start voxel is reached within the maximum range; otherwise <c>false</c>.</returns> |
| | | 99 | | private bool FloodPath() |
| | | 100 | | { |
| | 254 | 101 | | FlowFieldPathRequest request = _request!; |
| | 254 | 102 | | WorldVoxelIndex startIndex = request.StartNode!.WorldIndex; |
| | 254 | 103 | | bool targetReached = false; |
| | | 104 | | |
| | 254 | 105 | | int iterations = 0; |
| | 254 | 106 | | int searchSize = request.MaxPathSearchRange; |
| | 254 | 107 | | int maxFloodRange = 0; |
| | | 108 | | |
| | 2385 | 109 | | while (_heap.RemoveFirst(out SolidChartPartition? current) |
| | 2385 | 110 | | && current != null |
| | 2385 | 111 | | && iterations++ < searchSize) |
| | | 112 | | { |
| | 2132 | 113 | | int currentPathCost = GetPathCost(current); |
| | | 114 | | |
| | | 115 | | // Check if we found our way to the start voxel |
| | 2132 | 116 | | if (!targetReached) |
| | | 117 | | { |
| | 1934 | 118 | | if (current.WorldIndex == startIndex) |
| | | 119 | | { |
| | 122 | 120 | | maxFloodRange = currentPathCost + request.ExtraFloodRange; |
| | 122 | 121 | | targetReached = true; |
| | | 122 | | } |
| | | 123 | | |
| | | 124 | | } |
| | 198 | 125 | | else if (currentPathCost >= maxFloodRange) |
| | | 126 | | break; |
| | | 127 | | |
| | 2131 | 128 | | AnalyzeNeighborDistance(current, currentPathCost); |
| | | 129 | | |
| | 2131 | 130 | | _heap.SetClosed(current); |
| | 2131 | 131 | | } |
| | | 132 | | |
| | 254 | 133 | | return targetReached; |
| | | 134 | | } |
| | | 135 | | |
| | | 136 | | /// <summary> |
| | | 137 | | /// Evaluates each walkable neighbor of the current partition and assigns a heap cost if a shorter path is found. |
| | | 138 | | /// Ensures the wavefront expands in an optimal order. |
| | | 139 | | /// </summary> |
| | | 140 | | /// <param name="current">The current path partition being evaluated.</param> |
| | | 141 | | /// <param name="currentPathCost">The current flood distance stored for the partition.</param> |
| | | 142 | | private void AnalyzeNeighborDistance(SolidChartPartition current, int currentPathCost) |
| | | 143 | | { |
| | 2131 | 144 | | TryProcessDirection(current, SpatialAwareness.PerpendicularDirections, currentPathCost); |
| | 2131 | 145 | | TryProcessDirection(current, SpatialAwareness.DiagonalDirections, currentPathCost, true); |
| | 2131 | 146 | | } |
| | | 147 | | |
| | | 148 | | private void TryProcessDirection( |
| | | 149 | | SolidChartPartition current, |
| | | 150 | | SpatialDirection[] directions, |
| | | 151 | | int currentPathCost, |
| | | 152 | | bool checkEdges = false) |
| | | 153 | | { |
| | 4263 | 154 | | FlowFieldPathRequest request = _request!; |
| | 4263 | 155 | | SolidChartPartition?[]? neighbors = current.Neighbors; |
| | 4263 | 156 | | if (neighbors == null) |
| | 0 | 157 | | return; |
| | | 158 | | |
| | 119340 | 159 | | foreach (SpatialDirection dir in directions) |
| | | 160 | | { |
| | 55407 | 161 | | SolidChartPartition? neighbor = neighbors[(int)dir]; |
| | 55407 | 162 | | if (neighbor is null || _heap.IsClosed(neighbor) || neighbor.IsImpassable(request.UnitSize)) |
| | | 163 | | continue; |
| | | 164 | | |
| | 6524 | 165 | | if (ExceedsMaxClimbHeight(current, neighbor)) |
| | | 166 | | continue; |
| | | 167 | | |
| | 5560 | 168 | | if (checkEdges && !HasValidDiagonalLegs(current, dir)) |
| | | 169 | | continue; |
| | | 170 | | |
| | 3044 | 171 | | int newCost = currentPathCost + 1; |
| | | 172 | | |
| | 3044 | 173 | | if (!_heap.Contains(neighbor)) |
| | | 174 | | { |
| | 1879 | 175 | | _heap.Add(neighbor, newCost); |
| | | 176 | | } |
| | 1165 | 177 | | else if (GetPathCost(neighbor) > newCost) |
| | | 178 | | { |
| | 1 | 179 | | _heap.UpdatePathCost(neighbor, newCost); |
| | 1 | 180 | | _heap.SortUp(neighbor); |
| | | 181 | | } |
| | | 182 | | } |
| | 4263 | 183 | | } |
| | | 184 | | |
| | | 185 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 186 | | private bool ExceedsMaxClimbHeight(SolidChartPartition current, SolidChartPartition neighbor) |
| | | 187 | | { |
| | 16783 | 188 | | FlowFieldPathRequest request = _request!; |
| | 16783 | 189 | | Fixed64 heightDifference = (current.VoxelPosition.y - neighbor.VoxelPosition.y).Abs(); |
| | 16783 | 190 | | return heightDifference > request.MaxClimbHeight; |
| | | 191 | | } |
| | | 192 | | |
| | | 193 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 194 | | private bool HasValidDiagonalLegs(SolidChartPartition current, SpatialDirection diagonal) |
| | | 195 | | { |
| | 7240 | 196 | | (int dx, int dy, int dz) = SpatialAwareness.DirectionOffsets[(int)diagonal]; |
| | | 197 | | |
| | 7240 | 198 | | if (dx != 0 && !IsLegClear(current, DiagonalTraversalLegs.ForXOffset(dx))) |
| | 1949 | 199 | | return false; |
| | | 200 | | |
| | 5291 | 201 | | if (dy != 0 && !IsLegClear(current, DiagonalTraversalLegs.ForYOffset(dy))) |
| | 2 | 202 | | return false; |
| | | 203 | | |
| | 5289 | 204 | | if (dz != 0 && !IsLegClear(current, DiagonalTraversalLegs.ForZOffset(dz))) |
| | 685 | 205 | | return false; |
| | | 206 | | |
| | 4604 | 207 | | return true; |
| | | 208 | | } |
| | | 209 | | |
| | | 210 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 211 | | private bool IsLegClear(SolidChartPartition current, SpatialDirection legDir) |
| | | 212 | | { |
| | 12531 | 213 | | FlowFieldPathRequest request = _request!; |
| | 12531 | 214 | | SolidChartPartition?[]? neighbors = current.Neighbors; |
| | 12531 | 215 | | if (neighbors == null) |
| | 0 | 216 | | return false; |
| | | 217 | | |
| | 12531 | 218 | | SolidChartPartition? leg = neighbors[(int)legDir]; |
| | 12531 | 219 | | return leg != null && _heap.IsClosed(leg) && !leg.IsImpassable(request.UnitSize); |
| | | 220 | | } |
| | | 221 | | |
| | | 222 | | /// <summary> |
| | | 223 | | /// Converts the results of the flood fill phase into directional flow fields pointing toward the goal. |
| | | 224 | | /// Each partition is assigned a direction vector blending shortest path and direct-to-goal direction. |
| | | 225 | | /// </summary> |
| | | 226 | | /// <returns>A dictionary of directional flow field data indexed by voxel spawn tokens.</returns> |
| | | 227 | | private SwiftDictionary<WorldVoxelIndex, FlowField> GenerateFlowFields() |
| | | 228 | | { |
| | 122 | 229 | | FlowFieldPathRequest request = _request!; |
| | 122 | 230 | | WorldVoxelIndex endIndex = request.EndNode!.WorldIndex; |
| | 122 | 231 | | PrepareSamplingGrids(); |
| | | 232 | | |
| | 122 | 233 | | SwiftDictionary<WorldVoxelIndex, FlowField> result = new(_heap.TrackedCount); |
| | | 234 | | // Fixed64 totalDistance = Fixed64.One + _startDistanceMetric; // + 1 for end part |
| | | 235 | | |
| | 3876 | 236 | | foreach (SolidChartPartition current in _heap.EnumerateClosed()) |
| | | 237 | | { |
| | 1816 | 238 | | FlowFieldSamplingGrid samplingGrid = GetSamplingGrid(current.WorldIndex); |
| | | 239 | | |
| | 1816 | 240 | | FlowField currentFlow = new() |
| | 1816 | 241 | | { |
| | 1816 | 242 | | GlobalIndex = current.WorldIndex, |
| | 1816 | 243 | | PathCost = GetPathCostTotal(current) |
| | 1816 | 244 | | }; |
| | | 245 | | |
| | 1816 | 246 | | if (current.WorldIndex == endIndex) |
| | | 247 | | { |
| | | 248 | | // Ensure end voxel is include, it shouldn't point anywhere |
| | 122 | 249 | | currentFlow.IsGoal = true; |
| | 122 | 250 | | AddFlowField(result, samplingGrid, current.WorldIndex, currentFlow); |
| | 122 | 251 | | continue; |
| | | 252 | | } |
| | | 253 | | |
| | | 254 | | // Go through all neighbours and find the one with the lowest distance |
| | 1694 | 255 | | SolidChartPartition? minPartition = null; |
| | 1694 | 256 | | int minCost = int.MaxValue; |
| | 1694 | 257 | | int minDirectionIndex = -1; |
| | 1694 | 258 | | SolidChartPartition?[]? neighbors = current.Neighbors; |
| | 1694 | 259 | | if (neighbors == null) |
| | | 260 | | { |
| | 0 | 261 | | AddFlowField(result, samplingGrid, current.WorldIndex, currentFlow); |
| | 0 | 262 | | ChartOwnerUtility.AddOwners(_chartKeys, current.ChartOwners); |
| | 0 | 263 | | continue; |
| | | 264 | | } |
| | | 265 | | |
| | 91476 | 266 | | for (int i = 0; i < neighbors.Length; i++) |
| | | 267 | | { |
| | 44044 | 268 | | SolidChartPartition? nPart = neighbors[i]; |
| | | 269 | | // check closed heap version to ensure neighbor was part of flood phase |
| | 44044 | 270 | | if (nPart == null || !_heap.IsClosed(nPart)) |
| | | 271 | | continue; |
| | | 272 | | |
| | 10259 | 273 | | if (ExceedsMaxClimbHeight(current, nPart)) |
| | | 274 | | continue; |
| | | 275 | | |
| | 10259 | 276 | | if (SpatialAwareness.IsDiagonalNeighbor((SpatialDirection)i) |
| | 10259 | 277 | | && !HasValidDiagonalLegs(current, (SpatialDirection)i)) |
| | | 278 | | { |
| | | 279 | | continue; |
| | | 280 | | } |
| | | 281 | | |
| | 10140 | 282 | | int cost = GetPathCostTotal(nPart); |
| | 10140 | 283 | | if (cost < minCost) |
| | | 284 | | { |
| | 4214 | 285 | | minPartition = nPart; |
| | 4214 | 286 | | minCost = cost; |
| | 4214 | 287 | | minDirectionIndex = i; |
| | | 288 | | } |
| | | 289 | | } |
| | | 290 | | |
| | | 291 | | // If we found a valid neighbour, point in its direction by applying distance-weighted blending |
| | 1694 | 292 | | if (minPartition != null) |
| | 1694 | 293 | | currentFlow.Direction = _normalizedDirectionByNeighbor[minDirectionIndex]; |
| | | 294 | | |
| | 1694 | 295 | | AddFlowField(result, samplingGrid, current.WorldIndex, currentFlow); |
| | 1694 | 296 | | ChartOwnerUtility.AddOwners(_chartKeys, current.ChartOwners); |
| | | 297 | | } |
| | | 298 | | |
| | 122 | 299 | | return result; |
| | | 300 | | } |
| | | 301 | | |
| | | 302 | | private static void AddFlowField( |
| | | 303 | | SwiftDictionary<WorldVoxelIndex, FlowField> fields, |
| | | 304 | | FlowFieldSamplingGrid samplingGrid, |
| | | 305 | | WorldVoxelIndex index, |
| | | 306 | | FlowField field) |
| | | 307 | | { |
| | 1816 | 308 | | fields.Add(index, field); |
| | 1816 | 309 | | samplingGrid.AddDirection(index, field.Direction); |
| | 1816 | 310 | | } |
| | | 311 | | |
| | | 312 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 313 | | private int GetPathCost(SolidChartPartition partition) |
| | | 314 | | { |
| | 15254 | 315 | | return _heap.TryGetPathCost(partition, out int pathCost) |
| | 15254 | 316 | | ? pathCost |
| | 15254 | 317 | | : int.MaxValue; |
| | | 318 | | } |
| | | 319 | | |
| | | 320 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 321 | | private int GetPathCostTotal(SolidChartPartition partition) |
| | | 322 | | { |
| | 11957 | 323 | | int pathCost = GetPathCost(partition); |
| | 11957 | 324 | | return pathCost == int.MaxValue |
| | 11957 | 325 | | ? int.MaxValue |
| | 11957 | 326 | | : pathCost + partition.PathCostModifier; |
| | | 327 | | } |
| | | 328 | | |
| | | 329 | | private void ClearWorkingState() |
| | | 330 | | { |
| | 508 | 331 | | _heap.FastClear(); |
| | 508 | 332 | | _chartKeys.Clear(); |
| | 508 | 333 | | _samplingGrids.Clear(); |
| | 508 | 334 | | _samplingGridBuilders.Clear(); |
| | 508 | 335 | | } |
| | | 336 | | |
| | | 337 | | private void PrepareSamplingGrids() |
| | | 338 | | { |
| | 122 | 339 | | _samplingGridBuilders.Clear(); |
| | 122 | 340 | | _samplingGrids.Clear(); |
| | | 341 | | |
| | 3876 | 342 | | foreach (SolidChartPartition current in _heap.EnumerateClosed()) |
| | | 343 | | { |
| | 1816 | 344 | | FlowFieldSamplingGridBuilder builder = GetOrAddSamplingGridBuilder(current.WorldIndex, current.VoxelPosition |
| | 1816 | 345 | | builder.Include(current.WorldIndex); |
| | | 346 | | } |
| | | 347 | | |
| | 488 | 348 | | for (int i = 0; i < _samplingGridBuilders.Count; i++) |
| | 122 | 349 | | _samplingGrids.Add(_samplingGridBuilders[i].Create(_request!.Context.VoxelSize)); |
| | 122 | 350 | | } |
| | | 351 | | |
| | | 352 | | private FlowFieldSamplingGridBuilder GetOrAddSamplingGridBuilder(WorldVoxelIndex index, Vector3d worldPosition) |
| | | 353 | | { |
| | 3632 | 354 | | for (int i = 0; i < _samplingGridBuilders.Count; i++) |
| | | 355 | | { |
| | 1694 | 356 | | if (_samplingGridBuilders[i].MatchesGrid(index)) |
| | 1694 | 357 | | return _samplingGridBuilders[i]; |
| | | 358 | | } |
| | | 359 | | |
| | 122 | 360 | | FlowFieldSamplingGridBuilder builder = new(index, worldPosition, _request!.Context.VoxelSize); |
| | 122 | 361 | | _samplingGridBuilders.Add(builder); |
| | 122 | 362 | | return builder; |
| | | 363 | | } |
| | | 364 | | |
| | | 365 | | private FlowFieldSamplingGrid GetSamplingGrid(WorldVoxelIndex index) |
| | | 366 | | { |
| | 3632 | 367 | | for (int i = 0; i < _samplingGrids.Count; i++) |
| | | 368 | | { |
| | 1816 | 369 | | if (_samplingGrids[i].MatchesGrid(index)) |
| | 1816 | 370 | | return _samplingGrids[i]; |
| | | 371 | | } |
| | | 372 | | |
| | 0 | 373 | | throw new InvalidOperationException("Flow-field sampling grid was not prepared for the closed partition."); |
| | | 374 | | } |
| | | 375 | | |
| | | 376 | | private static Vector3d[] CreateNormalizedDirectionLookup() |
| | | 377 | | { |
| | 1 | 378 | | Vector3d[] directions = new Vector3d[SpatialAwareness.DirectionOffsets.Length]; |
| | 54 | 379 | | for (int i = 0; i < directions.Length; i++) |
| | | 380 | | { |
| | 26 | 381 | | (int x, int y, int z) = SpatialAwareness.DirectionOffsets[i]; |
| | 26 | 382 | | directions[i] = new Vector3d((Fixed64)x, (Fixed64)y, (Fixed64)z).Normalize(); |
| | | 383 | | } |
| | | 384 | | |
| | 1 | 385 | | return directions; |
| | | 386 | | } |
| | | 387 | | |
| | | 388 | | /// <summary> |
| | | 389 | | /// Samples an interpolated flow direction from a survey result using direct index arithmetic. |
| | | 390 | | /// </summary> |
| | | 391 | | /// <param name="context">The world context to sample against.</param> |
| | | 392 | | /// <param name="worldPosition">The world-space position to sample from.</param> |
| | | 393 | | /// <param name="result">The flow-field survey result to sample.</param> |
| | | 394 | | /// <returns>An interpolated directional vector.</returns> |
| | | 395 | | public static Vector3d SampleFlowVector( |
| | | 396 | | TrailblazerWorldContext context, |
| | | 397 | | Vector3d worldPosition, |
| | | 398 | | FlowFieldSurveyResult result) |
| | | 399 | | { |
| | 39 | 400 | | if (result == null || !result.HasPath || result.Fields == null) |
| | 1 | 401 | | return Vector3d.Zero; |
| | | 402 | | |
| | 38 | 403 | | PathRequestContextResolver.ThrowIfUnusable(context); |
| | 38 | 404 | | ThrowIfResultOwnedByDifferentContext(result, context); |
| | | 405 | | |
| | 38 | 406 | | return SampleFlowVector(context, worldPosition, result.Fields, result.SamplingGrids); |
| | | 407 | | } |
| | | 408 | | |
| | | 409 | | private static Vector3d SampleFlowVector( |
| | | 410 | | TrailblazerWorldContext context, |
| | | 411 | | Vector3d worldPosition, |
| | | 412 | | SwiftDictionary<WorldVoxelIndex, FlowField> fields, |
| | | 413 | | FlowFieldSamplingGrid[]? samplingGrids) |
| | | 414 | | { |
| | 38 | 415 | | if (fields == null || fields.Count == 0) |
| | 0 | 416 | | return Vector3d.Zero; |
| | | 417 | | |
| | 38 | 418 | | Fixed64 voxelSize = context.VoxelSize; |
| | | 419 | | |
| | | 420 | | // Get bottom-left corner of the square the agent is standing in |
| | 38 | 421 | | Vector3d corner = new( |
| | 38 | 422 | | FixedMath.Floor(worldPosition.x / voxelSize) * voxelSize, |
| | 38 | 423 | | FixedMath.Floor(worldPosition.y / voxelSize) * voxelSize, |
| | 38 | 424 | | FixedMath.Floor(worldPosition.z / voxelSize) * voxelSize |
| | 38 | 425 | | ); |
| | | 426 | | |
| | | 427 | | // Compute normalized offset in cell (0..1) |
| | 38 | 428 | | Fixed64 dx = (worldPosition.x - corner.x) / voxelSize; |
| | 38 | 429 | | Fixed64 dz = (worldPosition.z - corner.z) / voxelSize; |
| | | 430 | | |
| | 38 | 431 | | if (dx == Fixed64.Zero && dz == Fixed64.Zero) |
| | 36 | 432 | | return GetFlowDirection(context, corner, fields, samplingGrids); |
| | | 433 | | |
| | | 434 | | // Sample the 4 surrounding voxel centers |
| | 2 | 435 | | Vector3d bottomLeft = corner; |
| | 2 | 436 | | Vector3d bottomRight = corner + new Vector3d(voxelSize, Fixed64.Zero, Fixed64.Zero); |
| | 2 | 437 | | Vector3d topLeft = corner + new Vector3d(Fixed64.Zero, Fixed64.Zero, voxelSize); |
| | 2 | 438 | | Vector3d topRight = corner + new Vector3d(voxelSize, Fixed64.Zero, voxelSize); |
| | | 439 | | |
| | | 440 | | // Get flow vectors |
| | 2 | 441 | | Vector3d f00 = GetFlowDirection(context, bottomLeft, fields, samplingGrids); |
| | 2 | 442 | | Vector3d f10 = GetFlowDirection(context, bottomRight, fields, samplingGrids); |
| | 2 | 443 | | Vector3d f01 = GetFlowDirection(context, topLeft, fields, samplingGrids); |
| | 2 | 444 | | Vector3d f11 = GetFlowDirection(context, topRight, fields, samplingGrids); |
| | | 445 | | |
| | | 446 | | // Bilinear interpolation |
| | 2 | 447 | | Vector3d zHigh = f00 * (Fixed64.One - dx) + f10 * dx; |
| | 2 | 448 | | Vector3d zLow = f01 * (Fixed64.One - dx) + f11 * dx; |
| | 2 | 449 | | Vector3d blended = zHigh * (Fixed64.One - dz) + zLow * dz; |
| | | 450 | | |
| | 2 | 451 | | blended.Normalize(); |
| | 2 | 452 | | return blended; |
| | | 453 | | } |
| | | 454 | | |
| | | 455 | | /// <summary> |
| | | 456 | | /// Attempts to locate the closest valid voxel from which to begin flow-based movement. |
| | | 457 | | /// Useful for finding an initial entry point to the flow field. |
| | | 458 | | /// </summary> |
| | | 459 | | /// <param name="context">The world context to search against.</param> |
| | | 460 | | /// <param name="origin">The world-space origin to search from.</param> |
| | | 461 | | /// <param name="fields">Flow field data indexed by voxel spawn token.</param> |
| | | 462 | | /// <param name="result">The closest valid voxel, if found.</param> |
| | | 463 | | /// <param name="range">Maximum range to search.</param> |
| | | 464 | | /// <returns><c>true</c> if a nearby flow field anchor is found; otherwise <c>false</c>.</returns> |
| | | 465 | | public static bool TryGetNearestFlowAnchor( |
| | | 466 | | TrailblazerWorldContext context, |
| | | 467 | | Vector3d origin, |
| | | 468 | | SwiftDictionary<WorldVoxelIndex, FlowField> fields, |
| | | 469 | | Fixed64 range, |
| | | 470 | | out Voxel? result) |
| | | 471 | | { |
| | 3 | 472 | | result = null; |
| | 3 | 473 | | PathRequestContextResolver.ThrowIfUnusable(context); |
| | 3 | 474 | | if (fields == null || fields.Count == 0) |
| | 1 | 475 | | return false; |
| | | 476 | | |
| | 2 | 477 | | Fixed64 minDistanceSq = range * range; |
| | 2 | 478 | | bool found = false; |
| | | 479 | | |
| | 12 | 480 | | foreach (FlowField flow in fields.Values) |
| | | 481 | | { |
| | 4 | 482 | | if (!context.World.TryGetGridAndVoxel(flow.GlobalIndex, out _, out Voxel? flowVoxel) |
| | 4 | 483 | | || flowVoxel == null) |
| | | 484 | | continue; |
| | | 485 | | |
| | 2 | 486 | | Fixed64 distSq = Vector3d.SqrDistance(origin, flowVoxel.WorldPosition); |
| | 2 | 487 | | if (distSq <= minDistanceSq) |
| | | 488 | | { |
| | 1 | 489 | | result = flowVoxel; |
| | 1 | 490 | | minDistanceSq = distSq; |
| | 1 | 491 | | found = true; |
| | | 492 | | } |
| | | 493 | | } |
| | | 494 | | |
| | 2 | 495 | | return found; |
| | | 496 | | } |
| | | 497 | | |
| | | 498 | | /// <summary> |
| | | 499 | | /// Retrieves the raw directional flow vector at the given world-space position, if available. |
| | | 500 | | /// </summary> |
| | | 501 | | /// <param name="context">The world context to query against.</param> |
| | | 502 | | /// <param name="position">The position to query within the flow field.</param> |
| | | 503 | | /// <param name="fields">Flow field data indexed by voxel index.</param> |
| | | 504 | | /// <returns>The direction vector, or <c>Vector3d.Zero</c> if no field exists.</returns> |
| | | 505 | | public static Vector3d GetFlowDirection( |
| | | 506 | | TrailblazerWorldContext context, |
| | | 507 | | Vector3d position, |
| | | 508 | | SwiftDictionary<WorldVoxelIndex, FlowField> fields) |
| | | 509 | | { |
| | 3 | 510 | | PathRequestContextResolver.ThrowIfUnusable(context); |
| | 3 | 511 | | if (context.World.TryGetVoxel(position, out Voxel? voxel) |
| | 3 | 512 | | && voxel != null) |
| | | 513 | | { |
| | 3 | 514 | | if (fields.TryGetValue(voxel.WorldIndex, out FlowField field)) |
| | 2 | 515 | | return field.Direction; |
| | | 516 | | } |
| | 1 | 517 | | return Vector3d.Zero; |
| | | 518 | | } |
| | | 519 | | |
| | | 520 | | private static Vector3d GetFlowDirection( |
| | | 521 | | TrailblazerWorldContext context, |
| | | 522 | | Vector3d position, |
| | | 523 | | SwiftDictionary<WorldVoxelIndex, FlowField> fields, |
| | | 524 | | FlowFieldSamplingGrid[]? samplingGrids) |
| | | 525 | | { |
| | 44 | 526 | | if (samplingGrids == null || samplingGrids.Length == 0) |
| | 2 | 527 | | return GetFlowDirection(context, position, fields); |
| | | 528 | | |
| | 90 | 529 | | for (int i = 0; i < samplingGrids.Length; i++) |
| | | 530 | | { |
| | 42 | 531 | | if (samplingGrids[i].TryGetDirection(position, out Vector3d direction)) |
| | 39 | 532 | | return direction; |
| | | 533 | | } |
| | | 534 | | |
| | 3 | 535 | | return Vector3d.Zero; |
| | | 536 | | } |
| | | 537 | | |
| | | 538 | | /// <summary> |
| | | 539 | | /// Retrieves the flow field associated with the specified world position, if available. |
| | | 540 | | /// </summary> |
| | | 541 | | /// <remarks> |
| | | 542 | | /// If the position does not correspond to a valid voxel or no flow field is found for the voxel, |
| | | 543 | | /// the method returns the default value for FlowField. |
| | | 544 | | /// </remarks> |
| | | 545 | | /// <param name="context">The world context to query against.</param> |
| | | 546 | | /// <param name="position">The world position for which to retrieve the corresponding flow field.</param> |
| | | 547 | | /// <param name="fields">A dictionary mapping world voxel indices to their associated flow fields. Must not be null. |
| | | 548 | | /// <returns> |
| | | 549 | | /// The flow field associated with the specified position if found; otherwise, the default value for the FlowField t |
| | | 550 | | /// </returns> |
| | | 551 | | public static FlowField GetFlowField( |
| | | 552 | | TrailblazerWorldContext context, |
| | | 553 | | Vector3d position, |
| | | 554 | | SwiftDictionary<WorldVoxelIndex, FlowField> fields) |
| | | 555 | | { |
| | 4 | 556 | | PathRequestContextResolver.ThrowIfUnusable(context); |
| | 4 | 557 | | if (context.World.TryGetVoxel(position, out Voxel? voxel) |
| | 4 | 558 | | && voxel != null) |
| | | 559 | | { |
| | 4 | 560 | | if (fields.TryGetValue(voxel.WorldIndex, out FlowField field)) |
| | 3 | 561 | | return field; |
| | | 562 | | } |
| | 1 | 563 | | return default; |
| | | 564 | | } |
| | | 565 | | |
| | | 566 | | private static void ThrowIfResultOwnedByDifferentContext( |
| | | 567 | | FlowFieldSurveyResult result, |
| | | 568 | | TrailblazerWorldContext expectedContext) |
| | | 569 | | { |
| | 38 | 570 | | if (result.Context == null || ReferenceEquals(result.Context, expectedContext)) |
| | 38 | 571 | | return; |
| | | 572 | | |
| | 0 | 573 | | throw new InvalidOperationException( |
| | 0 | 574 | | "Flow field survey result belongs to a different owning TrailblazerWorldContext."); |
| | | 575 | | } |
| | | 576 | | |
| | | 577 | | private sealed class FlowFieldSamplingGridBuilder |
| | | 578 | | { |
| | | 579 | | private readonly WorldVoxelIndex _sampleIndex; |
| | | 580 | | private readonly Vector3d _originWorldPosition; |
| | | 581 | | private int _minX; |
| | | 582 | | private int _minY; |
| | | 583 | | private int _minZ; |
| | | 584 | | private int _maxX; |
| | | 585 | | private int _maxY; |
| | | 586 | | private int _maxZ; |
| | | 587 | | |
| | | 588 | | public int Count { get; private set; } |
| | | 589 | | |
| | 122 | 590 | | public FlowFieldSamplingGridBuilder( |
| | 122 | 591 | | WorldVoxelIndex sampleIndex, |
| | 122 | 592 | | Vector3d sampleWorldPosition, |
| | 122 | 593 | | Fixed64 voxelSize) |
| | | 594 | | { |
| | 122 | 595 | | _sampleIndex = sampleIndex; |
| | 122 | 596 | | VoxelIndex localIndex = sampleIndex.VoxelIndex; |
| | 122 | 597 | | _originWorldPosition = new Vector3d( |
| | 122 | 598 | | sampleWorldPosition.x - (voxelSize * (Fixed64)localIndex.x), |
| | 122 | 599 | | sampleWorldPosition.y - (voxelSize * (Fixed64)localIndex.y), |
| | 122 | 600 | | sampleWorldPosition.z - (voxelSize * (Fixed64)localIndex.z)); |
| | 122 | 601 | | } |
| | | 602 | | |
| | | 603 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 604 | | public bool MatchesGrid(WorldVoxelIndex index) |
| | | 605 | | { |
| | 1694 | 606 | | return index.WorldSpawnToken == _sampleIndex.WorldSpawnToken |
| | 1694 | 607 | | && index.GridIndex == _sampleIndex.GridIndex |
| | 1694 | 608 | | && index.GridSpawnToken == _sampleIndex.GridSpawnToken; |
| | | 609 | | } |
| | | 610 | | |
| | | 611 | | public void Include(WorldVoxelIndex index) |
| | | 612 | | { |
| | 1816 | 613 | | VoxelIndex localIndex = index.VoxelIndex; |
| | 1816 | 614 | | if (Count == 0) |
| | | 615 | | { |
| | 122 | 616 | | _minX = _maxX = localIndex.x; |
| | 122 | 617 | | _minY = _maxY = localIndex.y; |
| | 122 | 618 | | _minZ = _maxZ = localIndex.z; |
| | | 619 | | } |
| | | 620 | | else |
| | | 621 | | { |
| | 1967 | 622 | | if (localIndex.x < _minX) _minX = localIndex.x; |
| | 1698 | 623 | | if (localIndex.y < _minY) _minY = localIndex.y; |
| | 1838 | 624 | | if (localIndex.z < _minZ) _minZ = localIndex.z; |
| | 1730 | 625 | | if (localIndex.x > _maxX) _maxX = localIndex.x; |
| | 1696 | 626 | | if (localIndex.y > _maxY) _maxY = localIndex.y; |
| | 1746 | 627 | | if (localIndex.z > _maxZ) _maxZ = localIndex.z; |
| | | 628 | | } |
| | | 629 | | |
| | 1816 | 630 | | Count++; |
| | 1816 | 631 | | } |
| | | 632 | | |
| | | 633 | | public FlowFieldSamplingGrid Create(Fixed64 voxelSize) |
| | | 634 | | { |
| | 122 | 635 | | return new FlowFieldSamplingGrid( |
| | 122 | 636 | | _sampleIndex, |
| | 122 | 637 | | _originWorldPosition, |
| | 122 | 638 | | voxelSize, |
| | 122 | 639 | | _minX, |
| | 122 | 640 | | _minY, |
| | 122 | 641 | | _minZ, |
| | 122 | 642 | | _maxX, |
| | 122 | 643 | | _maxY, |
| | 122 | 644 | | _maxZ, |
| | 122 | 645 | | Count); |
| | | 646 | | } |
| | | 647 | | } |
| | | 648 | | } |