OSMServer/Pathfinding/RegionManager.cs

82 lines
3.0 KiB
C#

using OSMDatastructure;
namespace OSMImporter
{
public class RegionManager
{
private string workingDirectory { get; }
private readonly Dictionary<ulong, Region> _regions = new();
public RegionManager(string workingDirectory)
{
this.workingDirectory = workingDirectory;
}
/// <summary>
/// Checks wether the Region is already loaded and returns the Region, or tries to load the Region from file in workingDirectory
/// </summary>
/// <param name="coordinates">Coordinates of the Region (or within the Region) to load</param>
/// <returns>The Region at the specified Coordinates containing Nodes and Connections</returns>
/// <exception cref="FileNotFoundException">If the Regionfile can not be found.</exception>
public Region GetRegion(Coordinates coordinates)
{
if(this._regions.ContainsKey(coordinates.GetRegionHash()))
return this._regions[coordinates.GetRegionHash()];
else
{
Region loadedRegion = LoadRegion(coordinates);
this._regions.Add(loadedRegion.regionHash, value: loadedRegion);
return loadedRegion;
}
}
public Region[] GetAllRegions()
{
return this._regions.Values.ToArray();
}
/// <summary>
///
/// </summary>
/// <param name="coordinates">Coordinates of the Region (or within the Region) to load</param>
/// <returns>The Region at the specified Coordinates containing Nodes and Connections</returns>
/// <exception cref="FileNotFoundException">If the Regionfile can not be found.</exception>
private Region LoadRegion(Coordinates coordinates)
{
string fullPath = Path.Combine(workingDirectory, coordinates.GetRegionHash().ToString());
Console.WriteLine("Loading {0}", fullPath);
if (!File.Exists(fullPath))
{
throw new FileNotFoundException(string.Format("Region does not exist: {0}", fullPath));
}
FileStream fileStream = new FileStream(fullPath, FileMode.Open);
byte[] regionBytes = new byte[fileStream.Length];
int _ = fileStream.Read(regionBytes, 0, regionBytes.Length);
fileStream.Close();
return ByteConverter.ToRegion(regionBytes);
}
public Node? GetNode(ulong id)
{
foreach (Region region in this._regions.Values)
{
Node? node = region.GetNode(id);
if (node != null)
return node;
}
return null;
}
public Node? GetNode(Coordinates coordinates)
{
Region? regionWithNode = GetRegion(coordinates);
if (regionWithNode == null)
return null;//TODO null handling
return regionWithNode.GetNode(coordinates);
}
}
}