using System.Runtime.Serialization.Formatters.Binary; using OSMDatastructure; using OSMDatastructure.Graph; namespace Server; public class RegionLoader { private string path { get; } private Dictionary regionIdsDict; public RegionLoader(string path) { this.path = path; this.regionIdsDict = new(); } public HashSet GetNodes(ulong regionHash) { Region r = GetRegion(regionHash); return r.nodes; } public HashSet GetWays(ulong regionHash) { Region r = GetRegion(regionHash); return r.ways; } public TagManager GetTags(ulong regionHash) { Region r = GetRegion(regionHash); return r.tagManager; } public HashSet? GetTagsForWay(ulong regionHash, ulong wayId) { Region r = GetRegion(regionHash); return r.tagManager.GetTagsForWayId(wayId); } public Region GetRegion(ulong regionHash) { if (regionIdsDict.ContainsKey(regionHash)) return regionIdsDict[regionHash]; else return LoadRegion(regionHash); } private Region LoadRegion(ulong regionHash) { Region newRegion = new Region(regionHash); BinaryFormatter bFormatter = new BinaryFormatter(); if (regionIdsDict.ContainsKey(regionHash)) throw new Exception("Region already loaded"); if (!Directory.Exists(Path.Join(path, regionHash.ToString()))) throw new FileNotFoundException("Region does not exist"); #pragma warning disable SYSLIB0011 using (FileStream wayFileStream = new FileStream(Path.Join(path, regionHash.ToString(), RegionConverter.WaysFileName), FileMode.Open)) { while (wayFileStream.Position < wayFileStream.Length) { OsmEdge deserializedEdge = (OsmEdge)bFormatter.Deserialize(wayFileStream); newRegion.ways.Add(deserializedEdge); } } using (FileStream nodeFileStream = new FileStream(Path.Join(path, regionHash.ToString(), RegionConverter.NodesFileName), FileMode.Open)) { while (nodeFileStream.Position < nodeFileStream.Length) { OsmNode deserializedNode = (OsmNode)bFormatter.Deserialize(nodeFileStream); newRegion.nodes.Add(deserializedNode); } } using (FileStream tagsFileStream = new FileStream(Path.Join(path, regionHash.ToString(), RegionConverter.tagsFileName), FileMode.Open)) { while (tagsFileStream.Position < tagsFileStream.Length) { TagManager tm = (TagManager)bFormatter.Deserialize(tagsFileStream); ulong id = (ulong)tm.wayTagSets.First()!.Value.First(tag => tag.key == Tag.TagType.id)!.value; foreach(Tag tag in tm.wayTagSets.First()!.Value) newRegion.tagManager.AddTag(id, tag); } } #pragma warning restore SYSLIB0011 regionIdsDict.Add(regionHash, newRegion); return newRegion; } }