| | | 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 | | internal struct AStarVoxelMeta |
| | | 13 | | { |
| | | 14 | | /// <summary> |
| | | 15 | | /// The movement penalty cost of this voxel. |
| | | 16 | | /// </summary> |
| | | 17 | | public int MovementCost; |
| | | 18 | | |
| | | 19 | | /// <summary> |
| | | 20 | | /// The total survey path cost recorded for this voxel. |
| | | 21 | | /// </summary> |
| | | 22 | | public int PathCost; |
| | | 23 | | |
| | | 24 | | /// <summary> |
| | | 25 | | /// The next voxel in the trail path. |
| | | 26 | | /// </summary> |
| | | 27 | | public WorldVoxelIndex? NextTrailIndex; |
| | | 28 | | } |
| | | 29 | | |
| | | 30 | | /// <summary> |
| | | 31 | | /// Executes A* pathfinding logic using partitioned grids to find viable navigation paths for agents. |
| | | 32 | | /// Supports climb height constraints and optional spline smoothing of the final path. |
| | | 33 | | /// </summary> |
| | | 34 | | public class AStarSurveyor |
| | | 35 | | { |
| | | 36 | | #region Constants |
| | | 37 | | |
| | | 38 | | /// <summary> |
| | | 39 | | /// Cost applied for straight (orthogonal) pathfinding moves. |
| | | 40 | | /// </summary> |
| | | 41 | | public const int StraightCost = 100; |
| | | 42 | | |
| | | 43 | | /// <summary> |
| | | 44 | | /// Cost applied for diagonal pathfinding moves. |
| | | 45 | | /// </summary> |
| | | 46 | | public const int DiagonalCost = 141; |
| | | 47 | | |
| | | 48 | | #endregion |
| | | 49 | | |
| | | 50 | | #region Singleton Instances |
| | | 51 | | |
| | | 52 | | /// <summary> |
| | | 53 | | /// A lazily initialized singleton instance of the pathfinder. |
| | | 54 | | /// </summary> |
| | 1 | 55 | | private static readonly Lazy<AStarSurveyor> _instance = |
| | 1 | 56 | | new(() => new AStarSurveyor(), LazyThreadSafetyMode.ExecutionAndPublication); |
| | | 57 | | |
| | | 58 | | /// <summary> |
| | | 59 | | /// Gets the shared instance of the pathfinder. |
| | | 60 | | /// </summary> |
| | 11 | 61 | | public static AStarSurveyor Shared => _instance.Value; |
| | | 62 | | |
| | | 63 | | #endregion |
| | | 64 | | |
| | 964 | 65 | | private readonly SurveyorLock _scratchLock = new(); |
| | | 66 | | |
| | 964 | 67 | | private readonly PathHeap<SolidChartPartition> _heap = new(); |
| | | 68 | | |
| | | 69 | | // Key by stable voxel index so reconstruction is independent of GridForge voxel wrapper identity. |
| | 964 | 70 | | private readonly SwiftDictionary<WorldVoxelIndex, AStarVoxelMeta> _meta = new(); |
| | | 71 | | |
| | 964 | 72 | | private readonly SwiftList<SolidChartPartition> _rawPath = new(); |
| | | 73 | | |
| | 964 | 74 | | private readonly SwiftList<AStarWaypoint> _waypoints = new(); |
| | | 75 | | |
| | 964 | 76 | | private readonly SwiftHashSet<string> _chartKeys = new(); |
| | | 77 | | |
| | | 78 | | private AStarPathRequest? _request; |
| | | 79 | | |
| | | 80 | | /// <summary> |
| | | 81 | | /// Attempts to find a path between the start and end points provided in the request. |
| | | 82 | | /// Returns true if a valid path was found and outputs the resulting waypoint list. |
| | | 83 | | /// </summary> |
| | | 84 | | /// <param name="request">The pathfinding request containing start/end info and constraints.</param> |
| | | 85 | | /// <returns>The list of path waypoints if successful; otherwise null.</returns> |
| | | 86 | | public AStarSurveyResult FindPath(AStarPathRequest request) |
| | | 87 | | { |
| | 458 | 88 | | lock (_scratchLock) |
| | | 89 | | { |
| | 458 | 90 | | if (request == null |
| | 458 | 91 | | || request.HasZeroDisplacement |
| | 458 | 92 | | || request.StartNode!.TryGetPartition(out SolidChartPartition? startPartition) != true) |
| | | 93 | | { |
| | 1 | 94 | | return AStarSurveyResult.Empty; |
| | | 95 | | } |
| | | 96 | | |
| | 457 | 97 | | _request = request; |
| | | 98 | | |
| | 457 | 99 | | ClearWorkingState(); |
| | | 100 | | // Trace path from the start to the end |
| | 457 | 101 | | _meta[_request.StartNode.WorldIndex] = new AStarVoxelMeta |
| | 457 | 102 | | { |
| | 457 | 103 | | PathCost = 0 |
| | 457 | 104 | | }; |
| | 457 | 105 | | _heap.Add(startPartition!, pathCost: 0); |
| | | 106 | | |
| | 457 | 107 | | if (!TracePath()) |
| | | 108 | | { |
| | 307 | 109 | | ClearWorkingState(); |
| | 307 | 110 | | return AStarSurveyResult.Empty; |
| | | 111 | | } |
| | | 112 | | |
| | 150 | 113 | | BuildRawPath(); |
| | 150 | 114 | | BuildWaypoints(); |
| | | 115 | | |
| | 150 | 116 | | AStarWaypoint[] waypoints = _waypoints.ToArray(); |
| | 150 | 117 | | string[] chartKeys = _chartKeys.ToArray(); |
| | 150 | 118 | | AStarSurveyResult result = AStarSurveyResult.Create(request.Context, waypoints, chartKeys, request.RequestCa |
| | 150 | 119 | | ClearWorkingState(); |
| | 150 | 120 | | return result; |
| | | 121 | | } |
| | 458 | 122 | | } |
| | | 123 | | |
| | | 124 | | /// <summary> |
| | | 125 | | /// Executes the core A* loop to find a valid trail between the start and end voxels. |
| | | 126 | | /// </summary> |
| | | 127 | | /// <returns>True if the path to the target was found; false otherwise.</returns> |
| | | 128 | | private bool TracePath() |
| | | 129 | | { |
| | 457 | 130 | | int iterations = 0; |
| | 457 | 131 | | int searchSize = _request!.MaxPathSearchRange; |
| | 1273 | 132 | | while (_heap.RemoveFirst(out SolidChartPartition? currentPartition) |
| | 1273 | 133 | | && currentPartition != null |
| | 1273 | 134 | | && iterations++ < searchSize) |
| | | 135 | | { |
| | 966 | 136 | | if (ProcessNeighbors(currentPartition)) |
| | 150 | 137 | | return true; |
| | | 138 | | |
| | 816 | 139 | | _heap.SetClosed(currentPartition); |
| | 816 | 140 | | } |
| | | 141 | | |
| | 307 | 142 | | return false; |
| | | 143 | | } |
| | | 144 | | |
| | | 145 | | /// <summary> |
| | | 146 | | /// Indicates whether straight and diagonal neighbor voxels should be processed during pathfinding. |
| | | 147 | | /// </summary> |
| | | 148 | | /// <returns>True if any neighbor is the target destination.</returns> |
| | | 149 | | private bool ProcessNeighbors(SolidChartPartition current) |
| | | 150 | | { |
| | 967 | 151 | | if (!_meta.TryGetValue(current.WorldIndex, out AStarVoxelMeta data)) |
| | 1 | 152 | | return false; |
| | | 153 | | |
| | 966 | 154 | | if (TryProcessDirection(current, SpatialAwareness.PerpendicularDirections, data.MovementCost + StraightCost)) |
| | 128 | 155 | | return true; |
| | 838 | 156 | | if (TryProcessDirection(current, SpatialAwareness.DiagonalDirections, data.MovementCost + DiagonalCost, true)) |
| | 22 | 157 | | return true; |
| | | 158 | | |
| | 816 | 159 | | return false; |
| | | 160 | | } |
| | | 161 | | |
| | | 162 | | private bool TryProcessDirection(SolidChartPartition current, SpatialDirection[] directions, int cost, bool checkEdg |
| | | 163 | | { |
| | 47106 | 164 | | foreach (SpatialDirection dir in directions) |
| | | 165 | | { |
| | 21824 | 166 | | SolidChartPartition? neighbor = current.Neighbors?[(int)dir] ?? null; |
| | 21824 | 167 | | if (neighbor is null || _heap.IsClosed(neighbor) || neighbor.IsImpassable(_request!.UnitSize)) |
| | | 168 | | continue; |
| | | 169 | | |
| | 2889 | 170 | | if (checkEdges && !HasValidDiagonalLegs(current, dir)) |
| | | 171 | | continue; |
| | | 172 | | |
| | 1585 | 173 | | if (ProcessNeighbor(current, neighbor, cost)) |
| | 150 | 174 | | return true; |
| | | 175 | | } |
| | | 176 | | |
| | 1654 | 177 | | return false; |
| | | 178 | | } |
| | | 179 | | |
| | | 180 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 181 | | private bool HasValidDiagonalLegs(SolidChartPartition current, SpatialDirection diagonal) |
| | | 182 | | { |
| | 1618 | 183 | | (int dx, int dy, int dz) = SpatialAwareness.DirectionOffsets[(int)diagonal]; |
| | | 184 | | |
| | 1618 | 185 | | if (dx != 0 && !IsLegClear(current, DiagonalTraversalLegs.ForXOffset(dx))) |
| | 611 | 186 | | return false; |
| | | 187 | | |
| | 1007 | 188 | | if (dy != 0 && !IsLegClear(current, DiagonalTraversalLegs.ForYOffset(dy))) |
| | 418 | 189 | | return false; |
| | | 190 | | |
| | 589 | 191 | | if (dz != 0 && !IsLegClear(current, DiagonalTraversalLegs.ForZOffset(dz))) |
| | 275 | 192 | | return false; |
| | | 193 | | |
| | 314 | 194 | | return true; |
| | | 195 | | } |
| | | 196 | | |
| | | 197 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 198 | | private bool IsLegClear(SolidChartPartition current, SpatialDirection legDir) |
| | | 199 | | { |
| | 2625 | 200 | | SolidChartPartition? leg = current.Neighbors?[(int)legDir] ?? null; |
| | | 201 | | // Diagonal legality is a topology check, not a search-order check. Requiring closed legs |
| | | 202 | | // makes admissible heuristics flood open planes before diagonal routes can form. |
| | 2625 | 203 | | return leg != null && !leg.IsImpassable(_request!.UnitSize); |
| | | 204 | | } |
| | | 205 | | |
| | | 206 | | /// <summary> |
| | | 207 | | /// Determines whether a given neighbor voxel should be considered for path expansion. |
| | | 208 | | /// </summary> |
| | | 209 | | /// <returns>True if the neighbor is the target destination.</returns> |
| | | 210 | | private bool ProcessNeighbor( |
| | | 211 | | SolidChartPartition current, |
| | | 212 | | SolidChartPartition neighbor, |
| | | 213 | | int cost) |
| | | 214 | | { |
| | | 215 | | // Skip neighbors that have a height difference greater than the allowed maximum |
| | 1586 | 216 | | Fixed64 heightDifference = (current.VoxelPosition.y - neighbor.VoxelPosition.y).Abs(); |
| | 1586 | 217 | | if (heightDifference > _request!.MaxClimbHeight) |
| | 275 | 218 | | return false; |
| | | 219 | | |
| | 1311 | 220 | | if (neighbor.Voxel == _request.EndNode) |
| | | 221 | | { |
| | 150 | 222 | | int endPathCost = CalculatePathCost(neighbor, cost); |
| | 150 | 223 | | SetPathPartitionData(neighbor, current.WorldIndex, cost, endPathCost); |
| | 150 | 224 | | return true; |
| | | 225 | | } |
| | | 226 | | |
| | 1161 | 227 | | int pathCost = CalculatePathCost(neighbor, cost, out int heuristicCost); |
| | 1161 | 228 | | if (!_heap.Contains(neighbor)) |
| | | 229 | | { |
| | 939 | 230 | | SetPathPartitionData(neighbor, current.WorldIndex, cost, pathCost); |
| | 939 | 231 | | _heap.Add(neighbor, pathCost, heuristicCost); |
| | | 232 | | } |
| | 222 | 233 | | else if (_meta.TryGetValue(neighbor.WorldIndex, out AStarVoxelMeta neighborData) |
| | 222 | 234 | | && neighborData.MovementCost > cost) |
| | | 235 | | { |
| | 1 | 236 | | SetPathPartitionData(neighbor, current.WorldIndex, cost, pathCost); |
| | 1 | 237 | | _heap.UpdatePathCost(neighbor, pathCost, heuristicCost); |
| | 1 | 238 | | _heap.SortUp(neighbor); |
| | | 239 | | } |
| | | 240 | | |
| | 1161 | 241 | | return false; |
| | | 242 | | } |
| | | 243 | | |
| | | 244 | | /// <summary> |
| | | 245 | | /// Assigns pathfinding data to a path partition, including cost and direction toward the next trail voxel. |
| | | 246 | | /// </summary> |
| | | 247 | | /// <param name="partition">The path partition being updated.</param> |
| | | 248 | | /// <param name="nextTrailCoordinates">The coordinates of the parent partition leading to this one.</param> |
| | | 249 | | /// <param name="movementCost">The cumulative movement cost to this partition.</param> |
| | | 250 | | /// <param name="pathCost">The total survey path cost recorded for this partition.</param> |
| | | 251 | | private void SetPathPartitionData( |
| | | 252 | | SolidChartPartition partition, |
| | | 253 | | WorldVoxelIndex nextTrailCoordinates, |
| | | 254 | | int movementCost, |
| | | 255 | | int pathCost) |
| | | 256 | | { |
| | 1090 | 257 | | _meta[partition.WorldIndex] = new AStarVoxelMeta |
| | 1090 | 258 | | { |
| | 1090 | 259 | | MovementCost = movementCost, |
| | 1090 | 260 | | NextTrailIndex = nextTrailCoordinates, |
| | 1090 | 261 | | PathCost = pathCost |
| | 1090 | 262 | | }; |
| | 1090 | 263 | | } |
| | | 264 | | |
| | | 265 | | /// <summary> |
| | | 266 | | /// Reconstructs the raw voxel-based path from the destination to the origin by walking backwards through trail link |
| | | 267 | | /// </summary> |
| | | 268 | | /// <returns>A list of voxels from start to end representing the raw path.</returns> |
| | | 269 | | private void BuildRawPath() |
| | | 270 | | { |
| | 150 | 271 | | Voxel? current = _request!.EndNode; |
| | 518 | 272 | | while (current != null && current != _request.StartNode) |
| | | 273 | | { |
| | 368 | 274 | | SolidChartPartition? currentPartition = current.GetPartitionOrDefault<SolidChartPartition>(); |
| | 368 | 275 | | if (currentPartition == null) |
| | | 276 | | break; |
| | | 277 | | |
| | 368 | 278 | | _rawPath.Insert(0, currentPartition); |
| | | 279 | | |
| | 368 | 280 | | if (!_meta.TryGetValue(current.WorldIndex, out AStarVoxelMeta data) || !data.NextTrailIndex.HasValue) |
| | | 281 | | break; // break in the trail! |
| | | 282 | | |
| | 368 | 283 | | if (!_request.Context.World.TryGetGridAndVoxel(data.NextTrailIndex.Value, out _, out Voxel? nextTrailVoxel)) |
| | | 284 | | break; // break in the trail! |
| | | 285 | | |
| | 368 | 286 | | current = nextTrailVoxel; |
| | | 287 | | } |
| | | 288 | | |
| | | 289 | | // Ensure start position is included |
| | 150 | 290 | | SolidChartPartition? startPartition = _request!.StartNode!.GetPartitionOrDefault<SolidChartPartition>(); |
| | 150 | 291 | | if (startPartition != null) |
| | 150 | 292 | | _rawPath.Insert(0, startPartition); |
| | 150 | 293 | | } |
| | | 294 | | |
| | | 295 | | /// <summary> |
| | | 296 | | /// Constructs a smoothed version of the path using direction changes and optional spline smoothing. |
| | | 297 | | /// </summary> |
| | | 298 | | /// <returns>A smoothed list of world positions.</returns> |
| | | 299 | | private void BuildWaypoints() |
| | | 300 | | { |
| | 150 | 301 | | _waypoints.EnsureCapacity(_rawPath.Count); |
| | 150 | 302 | | SolidChartPartition start = _rawPath[0]; |
| | 150 | 303 | | _waypoints.Add(new() |
| | 150 | 304 | | { |
| | 150 | 305 | | Position = start.VoxelPosition, |
| | 150 | 306 | | PathCost = GetPathCost(start.Voxel), |
| | 150 | 307 | | GlobalIndex = start.WorldIndex |
| | 150 | 308 | | }); |
| | 150 | 309 | | ChartOwnerUtility.AddOwners(_chartKeys, start.ChartOwners); |
| | | 310 | | |
| | 150 | 311 | | Vector3d lastDirection = Vector3d.Zero; |
| | | 312 | | |
| | | 313 | | // add 1 to ensure we preserve unwalkable voxels that are close enough to matter for the unit size |
| | 150 | 314 | | byte scaledUnitSize = (byte)((_request!.UnitSize / _request.Context.VoxelSize).CeilToInt() + 1); |
| | 736 | 315 | | for (int i = 1; i < _rawPath.Count - 1; i++) |
| | | 316 | | { |
| | 218 | 317 | | Vector3d direction = (_rawPath[i + 1].VoxelPosition - _rawPath[i].VoxelPosition).Normalize(); |
| | | 318 | | |
| | | 319 | | |
| | 218 | 320 | | bool preserveUnwalkable = _rawPath[i].GetNeighborClearance() <= scaledUnitSize; |
| | 218 | 321 | | bool directionChanged = !lastDirection.FuzzyEqual(direction); |
| | | 322 | | |
| | 218 | 323 | | if (preserveUnwalkable || directionChanged) |
| | | 324 | | { |
| | 162 | 325 | | _waypoints.Add(new() |
| | 162 | 326 | | { |
| | 162 | 327 | | Position = _rawPath[i].VoxelPosition, |
| | 162 | 328 | | PathCost = GetPathCost(_rawPath[i].Voxel), |
| | 162 | 329 | | GlobalIndex = _rawPath[i].WorldIndex |
| | 162 | 330 | | }); |
| | | 331 | | } |
| | | 332 | | |
| | 218 | 333 | | lastDirection = direction; |
| | 218 | 334 | | ChartOwnerUtility.AddOwners(_chartKeys, _rawPath[i].ChartOwners); |
| | | 335 | | } |
| | | 336 | | |
| | 150 | 337 | | SolidChartPartition end = _rawPath.FromEnd(1); |
| | 150 | 338 | | _waypoints.Add(new() |
| | 150 | 339 | | { |
| | 150 | 340 | | Position = end.VoxelPosition, |
| | 150 | 341 | | PathCost = GetPathCost(end.Voxel), |
| | 150 | 342 | | GlobalIndex = end.WorldIndex, |
| | 150 | 343 | | IsGoal = true |
| | 150 | 344 | | }); |
| | 150 | 345 | | ChartOwnerUtility.AddOwners(_chartKeys, end.ChartOwners); |
| | 150 | 346 | | } |
| | | 347 | | |
| | | 348 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 349 | | private int CalculatePathCost(SolidChartPartition partition, int movementCost) => |
| | 150 | 350 | | CalculatePathCost(partition, movementCost, out _); |
| | | 351 | | |
| | | 352 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 353 | | private int CalculatePathCost( |
| | | 354 | | SolidChartPartition partition, |
| | | 355 | | int movementCost, |
| | | 356 | | out int heuristicCost) |
| | | 357 | | { |
| | 1311 | 358 | | heuristicCost = CalculateHeuristic( |
| | 1311 | 359 | | partition.VoxelPosition, |
| | 1311 | 360 | | _request!.EndNode!.WorldPosition, |
| | 1311 | 361 | | _request.Heuristic); |
| | | 362 | | |
| | 1311 | 363 | | return partition.PathCostModifier + movementCost + heuristicCost; |
| | | 364 | | } |
| | | 365 | | |
| | | 366 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 367 | | private int GetPathCost(Voxel voxel) |
| | | 368 | | { |
| | 462 | 369 | | return _meta[voxel.WorldIndex].PathCost; |
| | | 370 | | } |
| | | 371 | | |
| | | 372 | | private void ClearWorkingState() |
| | | 373 | | { |
| | 914 | 374 | | _heap.FastClear(); |
| | 914 | 375 | | _meta.Clear(); |
| | 914 | 376 | | _rawPath.FastClear(); |
| | 914 | 377 | | _waypoints.FastClear(); |
| | 914 | 378 | | _chartKeys.Clear(); |
| | 914 | 379 | | } |
| | | 380 | | |
| | | 381 | | /// <summary> |
| | | 382 | | /// Calculates the heuristic cost for the current voxel based on the target voxel and the heuristic method used. |
| | | 383 | | /// This implementation takes into account the X, Y, and Z axes for pathfinding. |
| | | 384 | | /// </summary> |
| | | 385 | | public static int CalculateHeuristic( |
| | | 386 | | Vector3d currentPosition, |
| | | 387 | | Vector3d targetPosition, |
| | | 388 | | HeuristicMethod heuristicMethod) |
| | | 389 | | { |
| | 1915 | 390 | | Fixed64 heuristicCost = Fixed64.MAX_VALUE; |
| | | 391 | | |
| | | 392 | | // Calculate the absolute distance in each axis |
| | 1915 | 393 | | Vector3d dst = Vector3d.Abs(currentPosition - targetPosition); |
| | | 394 | | |
| | | 395 | | switch (heuristicMethod) |
| | | 396 | | { |
| | | 397 | | case HeuristicMethod.Manhattan: |
| | | 398 | | // Sum the distances and multiply by 100 for the heuristic cost |
| | 1044 | 399 | | heuristicCost = (dst.x + dst.y + dst.z) * StraightCost; |
| | 1044 | 400 | | break; |
| | | 401 | | case HeuristicMethod.Octile: |
| | 7 | 402 | | Fixed64 maxXY = FixedMath.Max(dst.x, dst.y); |
| | 7 | 403 | | Fixed64 max = FixedMath.Max(maxXY, dst.z); |
| | 7 | 404 | | Fixed64 minXY = FixedMath.Min(dst.x, dst.y); |
| | 7 | 405 | | Fixed64 min = FixedMath.Min(minXY, dst.z); |
| | 7 | 406 | | Fixed64 middle = dst.x + dst.y + dst.z - max - min; |
| | 7 | 407 | | heuristicCost = (middle * DiagonalCost) + ((max - middle) * StraightCost); |
| | 7 | 408 | | break; |
| | | 409 | | case HeuristicMethod.Euclidean: |
| | | 410 | | // Calculate the squared distance and find the square root |
| | 863 | 411 | | Fixed64 d = dst.x * dst.x + dst.y * dst.y + dst.z * dst.z; |
| | 863 | 412 | | d = FixedMath.Sqrt(d); |
| | | 413 | | // Multiply the result by 100 for the heuristic cost |
| | 863 | 414 | | heuristicCost = d * StraightCost; |
| | | 415 | | break; |
| | | 416 | | default: |
| | | 417 | | break; |
| | | 418 | | } |
| | | 419 | | |
| | 1915 | 420 | | return heuristicCost.CeilToInt(); |
| | | 421 | | } |
| | | 422 | | |
| | | 423 | | /// <summary> |
| | | 424 | | /// Applies Catmull-Rom spline smoothing to a set of input path points to produce a smoother curve. |
| | | 425 | | /// </summary> |
| | | 426 | | /// <param name="input">The input path of waypoints.</param> |
| | | 427 | | /// <param name="resolutionPerSegment">The number of interpolated points per segment.</param> |
| | | 428 | | /// <returns>A smoothed path using Catmull-Rom spline interpolation.</returns> |
| | | 429 | | public static AStarWaypoint[] CatmullSmooth(AStarWaypoint[] input, int resolutionPerSegment = 3) |
| | | 430 | | { |
| | 6 | 431 | | if (input.Length < 4) return input; |
| | | 432 | | |
| | | 433 | | // size = smoothing points + 2 for start/end points |
| | 4 | 434 | | AStarWaypoint[] output = new AStarWaypoint[((input.Length - 3) * resolutionPerSegment) + 2]; |
| | | 435 | | |
| | | 436 | | // Add the starting point |
| | 4 | 437 | | output[0] = input[0]; |
| | | 438 | | |
| | 4 | 439 | | int outputIndex = 1; // Start at 1 because output[0] = input[0] |
| | 26 | 440 | | for (int i = 0; i < input.Length - 3; i++) |
| | | 441 | | { |
| | 9 | 442 | | Vector3d p0 = input[i].Position; |
| | 9 | 443 | | Vector3d p1 = input[i + 1].Position; |
| | 9 | 444 | | Vector3d p2 = input[i + 2].Position; |
| | 9 | 445 | | Vector3d p3 = input[i + 3].Position; |
| | | 446 | | |
| | | 447 | | // j starts at 1 to skip duplicate of first point |
| | 72 | 448 | | for (int j = 1; j <= resolutionPerSegment; j++) |
| | | 449 | | { |
| | 27 | 450 | | Fixed64 t = new(j / (double)resolutionPerSegment); |
| | | 451 | | |
| | | 452 | | // You should create a new waypoint here: |
| | 27 | 453 | | output[outputIndex] = new AStarWaypoint |
| | 27 | 454 | | { |
| | 27 | 455 | | Position = CatmullRom(p0, p1, p2, p3, t), |
| | 27 | 456 | | GlobalIndex = input[i + 1].GlobalIndex, |
| | 27 | 457 | | PathCost = input[i + 1].PathCost, |
| | 27 | 458 | | IsGoal = false |
| | 27 | 459 | | }; |
| | | 460 | | |
| | 27 | 461 | | outputIndex++; |
| | | 462 | | } |
| | | 463 | | } |
| | | 464 | | |
| | | 465 | | // Add the final point |
| | 4 | 466 | | output[outputIndex] = input[^1]; |
| | 4 | 467 | | return output; |
| | | 468 | | } |
| | | 469 | | |
| | | 470 | | /// <summary> |
| | | 471 | | /// Computes the interpolated point along a Catmull-Rom spline given four control points. |
| | | 472 | | /// </summary> |
| | | 473 | | /// <param name="p0">The first control point.</param> |
| | | 474 | | /// <param name="p1">The second control point.</param> |
| | | 475 | | /// <param name="p2">The third control point.</param> |
| | | 476 | | /// <param name="p3">The fourth control point.</param> |
| | | 477 | | /// <param name="t">Interpolation factor between 0 and 1.</param> |
| | | 478 | | /// <returns>The interpolated point on the spline.</returns> |
| | | 479 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 480 | | private static Vector3d CatmullRom(Vector3d p0, Vector3d p1, Vector3d p2, Vector3d p3, Fixed64 t) |
| | | 481 | | { |
| | | 482 | | // Classic Catmull-Rom basis matrix |
| | 27 | 483 | | Fixed64 t2 = t * t; |
| | 27 | 484 | | Fixed64 t3 = t2 * t; |
| | | 485 | | |
| | 27 | 486 | | return |
| | 27 | 487 | | ((-t3 + 2 * t2 - t) * p0 + |
| | 27 | 488 | | (3 * t3 - 5 * t2 + 2) * p1 + |
| | 27 | 489 | | (-3 * t3 + 4 * t2 + t) * p2 + |
| | 27 | 490 | | (t3 - t2) * p3) / 2; |
| | | 491 | | } |
| | | 492 | | } |