OSMServer/Pathfinding/RegionManager.cs
2023-04-09 16:32:02 +02:00

72 lines
2.1 KiB
C#

using System.Text.Json;
using OSMDatastructure;
using OSMDatastructure.Graph;
namespace Pathfinding
{
public class RegionManager
{
private string workingDirectory { get; }
private readonly Dictionary<ulong, Region> _regions = new();
public RegionManager(string workingDirectory)
{
this.workingDirectory = workingDirectory;
}
public Region? GetRegion(Coordinates coordinates)
{
return GetRegion(Coordinates.GetRegionHashCode(coordinates));
}
public Region? GetRegion(ulong id)
{
if(_regions.TryGetValue(id, out Region? value))
return value;
else
{
Region? loadedRegion = RegionFromId(id);
if(loadedRegion is not null)
_regions.Add(loadedRegion!.regionHash, value: loadedRegion);
return loadedRegion;
}
}
public Region[] GetAllRegions()
{
return this._regions.Values.ToArray();
}
private Region? RegionFromFile(string filePath)
{
Region? retRegion = null;
if (File.Exists(filePath))
{
FileStream regionFile = new FileStream(filePath, FileMode.Open);
retRegion = JsonSerializer.Deserialize<Region>(regionFile, Region.serializerOptions)!;
regionFile.Dispose();
}
return retRegion;
}
private Region? RegionFromId(ulong regionId)
{
string filePath = Path.Join(workingDirectory, $"{regionId}.region");
return RegionFromFile(filePath);
}
public OsmNode? GetNode(Coordinates coordinates)
{
Region? regionWithNode = GetRegion(coordinates);
if (regionWithNode is not null)
return regionWithNode.GetNode(coordinates);
return null;
}
public OsmNode? GetNode(ulong nodeId, ulong regionId)
{
Region? r = GetRegion(regionId);
return r?.GetNode(nodeId);
}
}
}