|
| 1 | +using NetTopologySuite.Geometries; |
| 2 | + |
| 3 | +namespace Alidade.Osm.Services; |
| 4 | + |
| 5 | +/// <inheritdoc /> |
| 6 | +internal sealed class OsmCacheService : IOsmCacheService |
| 7 | +{ |
| 8 | + // TODO: Replace the O(n) linear scans in GetGeometryFromBbox with three |
| 9 | + // NTS Quadtree<long> spatial indexes (one per element type) if profiling |
| 10 | + // shows the scan becoming a bottleneck during long panning sessions. |
| 11 | + // Quadtree supports incremental inserts; STRtree is bulk-load only. |
| 12 | + private Geometry? _cachedArea; |
| 13 | + private readonly Dictionary<long, OsmNode> _nodes = []; |
| 14 | + private readonly Dictionary<long, OsmWay> _ways = []; |
| 15 | + private readonly Dictionary<long, OsmRelation> _relations = []; |
| 16 | + |
| 17 | + private static readonly GeometryFactory _geomFactory = new(new PrecisionModel(), 4326); |
| 18 | + |
| 19 | + /// <inheritdoc /> |
| 20 | + public List<CacheBounds> GetGeometryMissBboxes(CacheBounds request) |
| 21 | + { |
| 22 | + if (_cachedArea is null) |
| 23 | + { |
| 24 | + return [request]; |
| 25 | + } |
| 26 | + |
| 27 | + Geometry requestGeom = BoundsToGeometry(request); |
| 28 | + Geometry diff = requestGeom.Difference(_cachedArea); |
| 29 | + |
| 30 | + if (diff.IsEmpty) |
| 31 | + { |
| 32 | + return []; |
| 33 | + } |
| 34 | + |
| 35 | + return DecomposeToBboxes(diff); |
| 36 | + } |
| 37 | + |
| 38 | + /// <inheritdoc /> |
| 39 | + public void AddToCache(CacheBounds bounds, OsmCacheData data) |
| 40 | + { |
| 41 | + Geometry newGeom = BoundsToGeometry(bounds); |
| 42 | + _cachedArea = _cachedArea is null |
| 43 | + ? newGeom |
| 44 | + : _cachedArea.Union(newGeom); |
| 45 | + |
| 46 | + foreach (OsmNode n in data.Nodes) |
| 47 | + { |
| 48 | + _nodes[n.Id] = n; |
| 49 | + } |
| 50 | + |
| 51 | + foreach (OsmWay w in data.Ways) |
| 52 | + { |
| 53 | + _ways[w.Id] = w; |
| 54 | + } |
| 55 | + |
| 56 | + foreach (OsmRelation r in data.Relations) |
| 57 | + { |
| 58 | + _relations[r.Id] = r; |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + /// <inheritdoc /> |
| 63 | + public OsmCacheData GetGeometryFromBbox(CacheBounds bounds) |
| 64 | + { |
| 65 | + Geometry requestGeom = BoundsToGeometry(bounds); |
| 66 | + |
| 67 | + if (_cachedArea is null || !_cachedArea.Covers(requestGeom)) |
| 68 | + { |
| 69 | + throw new InvalidOperationException( |
| 70 | + $"Requested bbox ({bounds}) includes area outside the OSM cache."); |
| 71 | + } |
| 72 | + |
| 73 | + List<OsmNode> nodesInBbox = [.. _nodes.Values |
| 74 | + .Where(n => n.Lat <= bounds.North |
| 75 | + && n.Lon <= bounds.East |
| 76 | + && n.Lat >= bounds.South |
| 77 | + && n.Lon >= bounds.West)]; |
| 78 | + |
| 79 | + HashSet<long> nodeIdsInBbox = nodesInBbox.Select(n => n.Id).ToHashSet(); |
| 80 | + |
| 81 | + List<OsmWay> ways = [.. _ways.Values.Where(w => w.NodeIds.Any(id => nodeIdsInBbox.Contains(id)))]; |
| 82 | + |
| 83 | + // Include out-of-bbox nodes referenced by included ways so that rendering |
| 84 | + // doesn't break for ways that cross the viewport boundary — the OSM API |
| 85 | + // always returns full way geometry including nodes outside the requested bbox. |
| 86 | + HashSet<long> allNodeIds = [..nodeIdsInBbox]; |
| 87 | + List<OsmNode> allNodes = [..nodesInBbox]; |
| 88 | + |
| 89 | + foreach (OsmWay way in ways) |
| 90 | + { |
| 91 | + foreach (long nodeId in way.NodeIds) |
| 92 | + { |
| 93 | + if (allNodeIds.Add(nodeId) && _nodes.TryGetValue(nodeId, out OsmNode? extraNode)) |
| 94 | + { |
| 95 | + allNodes.Add(extraNode); |
| 96 | + } |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + HashSet<long> wayIds = [.. ways.Select(w => w.Id)]; |
| 101 | + |
| 102 | + List<OsmRelation> relations = [.. _relations.Values |
| 103 | + .Where(r => r.Members.Any(m => |
| 104 | + (m.Type == OsmElementTypes.Node && allNodeIds.Contains(m.Ref)) |
| 105 | + || (m.Type == OsmElementTypes.Way && wayIds.Contains(m.Ref))) |
| 106 | + )]; |
| 107 | + |
| 108 | + return new OsmCacheData(allNodes, ways, relations); |
| 109 | + } |
| 110 | + |
| 111 | + /// <inheritdoc /> |
| 112 | + public void Clear() |
| 113 | + { |
| 114 | + _cachedArea = null; |
| 115 | + _nodes.Clear(); |
| 116 | + _ways.Clear(); |
| 117 | + _relations.Clear(); |
| 118 | + } |
| 119 | + |
| 120 | + private static Geometry BoundsToGeometry(CacheBounds b) |
| 121 | + => _geomFactory.ToGeometry(new Envelope(b.West, b.East, b.South, b.North)); |
| 122 | + |
| 123 | + private static CacheBounds EnvelopeToCacheBounds(Envelope env) |
| 124 | + => new(env.MinX, env.MinY, env.MaxX, env.MaxY); |
| 125 | + |
| 126 | + /// <summary> |
| 127 | + /// Decomposes an orthogonal difference polygon (or multipolygon) into a minimal |
| 128 | + /// set of axis-aligned bboxes using horizontal strip decomposition. Each consecutive |
| 129 | + /// pair of unique latitude values in the geometry defines a horizontal band; the |
| 130 | + /// intersection of the diff with that band yields one or more bboxes for that strip. |
| 131 | + /// An L-shaped diff (typical single-pan case) produces exactly two bboxes. |
| 132 | + /// </summary> |
| 133 | + private static List<CacheBounds> DecomposeToBboxes(Geometry diff) |
| 134 | + { |
| 135 | + double[] ys = [.. diff.Coordinates |
| 136 | + .Select(c => c.Y) |
| 137 | + .Distinct() |
| 138 | + .OrderBy(y => y)]; |
| 139 | + |
| 140 | + List<CacheBounds> result = []; |
| 141 | + Envelope diffEnv = diff.EnvelopeInternal; |
| 142 | + |
| 143 | + for (int i = 0; i < ys.Length - 1; i++) |
| 144 | + { |
| 145 | + double yLow = ys[i]; |
| 146 | + double yHigh = ys[i + 1]; |
| 147 | + |
| 148 | + // Horizontal slab spanning the band, extended past diff's X extent so the |
| 149 | + // intersection clips cleanly against the diff's actual X boundary. |
| 150 | + Envelope slabEnv = new(diffEnv.MinX - 1.0, diffEnv.MaxX + 1.0, yLow, yHigh); |
| 151 | + Geometry slab = _geomFactory.ToGeometry(slabEnv); |
| 152 | + Geometry band = diff.Intersection(slab); |
| 153 | + |
| 154 | + if (band.IsEmpty) |
| 155 | + { |
| 156 | + continue; |
| 157 | + } |
| 158 | + |
| 159 | + if (band is GeometryCollection gc) |
| 160 | + { |
| 161 | + for (int j = 0; j < gc.NumGeometries; j++) |
| 162 | + { |
| 163 | + Geometry part = gc.GetGeometryN(j); |
| 164 | + if (!part.IsEmpty) |
| 165 | + { |
| 166 | + result.Add(EnvelopeToCacheBounds(part.EnvelopeInternal)); |
| 167 | + } |
| 168 | + } |
| 169 | + } |
| 170 | + else |
| 171 | + { |
| 172 | + result.Add(EnvelopeToCacheBounds(band.EnvelopeInternal)); |
| 173 | + } |
| 174 | + } |
| 175 | + |
| 176 | + return result; |
| 177 | + } |
| 178 | +} |
0 commit comments