From 2bbd4c4ca1b384a77c269f7ed7bdd4e0c28ba238 Mon Sep 17 00:00:00 2001 From: "vl.arkhangelskii" Date: Mon, 21 Sep 2026 14:00:32 +0300 Subject: [PATCH] fix(graph): add all roads --- README.md | 2 +- ...026-09-21_13-55-00_web-demo-graph-tiles.md | 7 + ...-09-21_14-00-00_graph-polylines-streets.md | 13 + .../Graph/RoadGraphTileService.cs | 4 +- .../Graph/RoadGraphZoomPolicy.cs | 15 +- .../Graph/RoadGraphModels.cs | 5 +- .../Graph/GraphGeometry.cs | 40 +++ .../Graph/OsmSharpRoadGraphBuilder.cs | 29 +- .../Graph/RoadGraphMvtEncoder.cs | 73 ++++- .../Graph/SqliteRoadGraphStore.cs | 24 +- tests/TileServer.UnitTests/RoadGraphTests.cs | 39 ++- web-demo/src/App.tsx | 256 +++++++----------- web-demo/src/access.ts | 25 +- web-demo/src/demo.css | 15 +- web/src/features/graph/GraphPage.tsx | 6 +- web/src/features/guides/GuidesPage.tsx | 7 +- 16 files changed, 361 insertions(+), 199 deletions(-) create mode 100644 context/2026-09-21_13-55-00_web-demo-graph-tiles.md create mode 100644 context/2026-09-21_14-00-00_graph-polylines-streets.md create mode 100644 src/TileServer.Infrastructure/Graph/GraphGeometry.cs diff --git a/README.md b/README.md index cc94ebf..bbd1f8c 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ docker compose up -d --build | `POST` | `/api/v1/sync` | прогнать все extract’ы сейчас | | `POST` | `/api/v1/sync/{id}` | прогнать один extract | -Публичные `/api/v1/tiles` и `/api/v1/styles` закрыты (401). Граф — только по токену. MVT графа: слой `roads`, z 6–14 (на мелком зуме только крупные highway). JSON `bbox=minLon,minLat,maxLon,maxLat`, сторона ≤ 2°. Выключается: `TileServer:BuildRoadGraph=false`. +Публичные `/api/v1/tiles` и `/api/v1/styles` закрыты (401). Граф — только по токену. MVT графа: слой `roads`, z 6–14 (ниже z12 только крупные highway, с z12 все улицы; полилиния после пересборки графа). JSON `bbox=minLon,minLat,maxLon,maxLat`, сторона ≤ 2°. Выключается: `TileServer:BuildRoadGraph=false`. ## Несколько регионов diff --git a/context/2026-09-21_13-55-00_web-demo-graph-tiles.md b/context/2026-09-21_13-55-00_web-demo-graph-tiles.md new file mode 100644 index 0000000..ec5db6e --- /dev/null +++ b/context/2026-09-21_13-55-00_web-demo-graph-tiles.md @@ -0,0 +1,7 @@ +# web-demo tiled graph in style + +Date: 2026-09-21 + +## What + +web-demo no longer waits on JSON bbox / a «Показать граф» click. When the checkbox is on (default), graph MVT sources (`/u/{slug}/graph/{id}/{z}/{x}/{y}.pbf`, layer `roads`) are injected into the MapLibre style JSON the same way OSM tiles are. Toggle reloads the style. `rewriteServiceUrl` keeps `{z}/{x}/{y}` unencoded. Graph tile 404s stay in the graph HUD, not the map banner. diff --git a/context/2026-09-21_14-00-00_graph-polylines-streets.md b/context/2026-09-21_14-00-00_graph-polylines-streets.md new file mode 100644 index 0000000..169fb25 --- /dev/null +++ b/context/2026-09-21_14-00-00_graph-polylines-streets.md @@ -0,0 +1,13 @@ +# Graph polylines + all streets from z12 + +Date: 2026-09-21 + +## Why the overlay looked wrong + +Crooked chords: edges were vertex-to-vertex (intersections only), no OSM shape nodes. +Only highways at z12–13: zoom filter kept residential out until z13, and `ORDER BY length_m DESC LIMIT 8000` dropped short streets even then. + +## Change + +- Builder stores `edges.geom` (lon/lat polyline). Encoder clips that LineString. Old sqlite without `geom` still draws chords — resync required for curves. +- All highway classes from z12 (residential/service included). Cap 40k features, order by id not length. diff --git a/src/TileServer.Application/Graph/RoadGraphTileService.cs b/src/TileServer.Application/Graph/RoadGraphTileService.cs index 4418bb9..d246033 100644 --- a/src/TileServer.Application/Graph/RoadGraphTileService.cs +++ b/src/TileServer.Application/Graph/RoadGraphTileService.cs @@ -63,7 +63,7 @@ public sealed class RoadGraphTileService( try { edges = await store - .QueryEdgesInBoundsAsync(extractId, bounds, highways, RoadGraphZoomPolicy.MaxFeaturesPerTile, ct) + .QueryEdgesInBoundsAsync(extractId, bounds, highways, RoadGraphZoomPolicy.MaxFeaturesForZoom(tile.Z), ct) .ConfigureAwait(false); } catch (Exception ex) @@ -118,7 +118,7 @@ public sealed class RoadGraphTileService( [ new VectorLayerJson( "roads", - "OSM highway segments as vertex-to-vertex edges", + "OSM highway polylines (shape nodes between intersections)", RoadGraphZoomPolicy.MinZoom, RoadGraphZoomPolicy.MaxZoom, fields) diff --git a/src/TileServer.Application/Graph/RoadGraphZoomPolicy.cs b/src/TileServer.Application/Graph/RoadGraphZoomPolicy.cs index d4f6123..21d4fbb 100644 --- a/src/TileServer.Application/Graph/RoadGraphZoomPolicy.cs +++ b/src/TileServer.Application/Graph/RoadGraphZoomPolicy.cs @@ -5,7 +5,6 @@ public static class RoadGraphZoomPolicy public const int MinZoom = 6; public const int MaxZoom = 14; public const int EncodeMaxZoom = 18; - public const int MaxFeaturesPerTile = 8_000; public const double BufferFraction = 0.08; private static readonly string[] Trunk = @@ -22,15 +21,23 @@ public static class RoadGraphZoomPolicy ]; /// - /// Low zooms keep only major highways so a 2°+ tile does not pull the whole graph. - /// Null means no filter (all classes). + /// Low zooms keep only major highways so a large tile does not pull the whole graph. + /// Null means no filter (residential/service included). All streets from z12. /// public static IReadOnlyList? HighwaysForZoom(int z) => z switch { <= 8 => Trunk, <= 10 => Primary, - <= 12 => Secondary, + <= 11 => Secondary, _ => null }; + + public static int MaxFeaturesForZoom(int z) + => z switch + { + <= 10 => 8_000, + <= 11 => 16_000, + _ => 40_000 + }; } diff --git a/src/TileServer.Domain/Graph/RoadGraphModels.cs b/src/TileServer.Domain/Graph/RoadGraphModels.cs index 60f9ea3..16870ea 100644 --- a/src/TileServer.Domain/Graph/RoadGraphModels.cs +++ b/src/TileServer.Domain/Graph/RoadGraphModels.cs @@ -11,6 +11,8 @@ public sealed record RoadGraphMetadata( public sealed record RoadGraphNode(long Id, double Lon, double Lat); +public sealed record RoadGraphPoint(double Lon, double Lat); + public sealed record RoadGraphEdge( long Id, long FromId, @@ -22,6 +24,7 @@ public sealed record RoadGraphEdge( double FromLon, double FromLat, double ToLon, - double ToLat); + double ToLat, + IReadOnlyList? Geometry = null); public sealed record RoadGraphPage(IReadOnlyList Items, long? NextAfter); diff --git a/src/TileServer.Infrastructure/Graph/GraphGeometry.cs b/src/TileServer.Infrastructure/Graph/GraphGeometry.cs new file mode 100644 index 0000000..e2e50e5 --- /dev/null +++ b/src/TileServer.Infrastructure/Graph/GraphGeometry.cs @@ -0,0 +1,40 @@ +using System.Buffers.Binary; +using TileServer.Domain.Graph; + +namespace TileServer.Infrastructure.Graph; + +internal static class GraphGeometry +{ + public static byte[] Pack(IReadOnlyList points) + { + var bytes = new byte[points.Count * 16]; + for (var i = 0; i < points.Count; i++) + { + var span = bytes.AsSpan(i * 16); + BinaryPrimitives.WriteDoubleLittleEndian(span, points[i].Lon); + BinaryPrimitives.WriteDoubleLittleEndian(span[8..], points[i].Lat); + } + + return bytes; + } + + public static IReadOnlyList? Unpack(byte[]? bytes) + { + if (bytes is null || bytes.Length < 32 || bytes.Length % 16 != 0) + { + return null; + } + + var count = bytes.Length / 16; + var points = new RoadGraphPoint[count]; + for (var i = 0; i < count; i++) + { + var span = bytes.AsSpan(i * 16); + points[i] = new RoadGraphPoint( + BinaryPrimitives.ReadDoubleLittleEndian(span), + BinaryPrimitives.ReadDoubleLittleEndian(span[8..])); + } + + return points; + } +} diff --git a/src/TileServer.Infrastructure/Graph/OsmSharpRoadGraphBuilder.cs b/src/TileServer.Infrastructure/Graph/OsmSharpRoadGraphBuilder.cs index 4b12b9f..ceb8e5a 100644 --- a/src/TileServer.Infrastructure/Graph/OsmSharpRoadGraphBuilder.cs +++ b/src/TileServer.Infrastructure/Graph/OsmSharpRoadGraphBuilder.cs @@ -7,12 +7,13 @@ using OsmSharp.Streams; using OsmSharp.Tags; using TileServer.Application.Graph; using TileServer.Domain.Extracts; +using TileServer.Domain.Graph; namespace TileServer.Infrastructure.Graph; /// /// Two-pass PBF scan: highway ways → degree map + packed node refs; nodes → coords; -/// then collapse chains between intersections into edges with Haversine length. +/// then collapse chains between intersections into edges with Haversine length and packed polyline geometry. /// public sealed class OsmSharpRoadGraphBuilder(ILogger logger) : IRoadGraphBuilder { @@ -248,10 +249,12 @@ public sealed class OsmSharpRoadGraphBuilder(ILogger l highway TEXT NOT NULL, name TEXT, oneway INTEGER NOT NULL, - length_m REAL NOT NULL + length_m REAL NOT NULL, + geom BLOB ); CREATE INDEX edges_from ON edges(from_id); CREATE INDEX edges_to ON edges(to_id); + CREATE INDEX edges_highway ON edges(highway); CREATE INDEX nodes_lonlat ON nodes(lon, lat); """; await schema.ExecuteNonQueryAsync(ct).ConfigureAwait(false); @@ -279,8 +282,8 @@ public sealed class OsmSharpRoadGraphBuilder(ILogger l insertEdge.Transaction = outTx; insertEdge.CommandText = """ - INSERT INTO edges (id, from_id, to_id, highway, name, oneway, length_m) - VALUES ($id, $from, $to, $highway, $name, $oneway, $length); + INSERT INTO edges (id, from_id, to_id, highway, name, oneway, length_m, geom) + VALUES ($id, $from, $to, $highway, $name, $oneway, $length, $geom); """; var eId = insertEdge.Parameters.Add("$id", SqliteType.Integer); var eFrom = insertEdge.Parameters.Add("$from", SqliteType.Integer); @@ -289,6 +292,7 @@ public sealed class OsmSharpRoadGraphBuilder(ILogger l var eName = insertEdge.Parameters.Add("$name", SqliteType.Text); var eOneway = insertEdge.Parameters.Add("$oneway", SqliteType.Integer); var eLength = insertEdge.Parameters.Add("$length", SqliteType.Real); + var eGeom = insertEdge.Parameters.Add("$geom", SqliteType.Blob); await using (var readWays = ways.CreateCommand()) { @@ -309,6 +313,7 @@ public sealed class OsmSharpRoadGraphBuilder(ILogger l long? segmentFrom = null; double segmentLength = 0; (double Lon, double Lat)? prevCoord = null; + var shape = new List(8); for (var i = 0; i < nodeIds.Length; i++) { @@ -318,6 +323,7 @@ public sealed class OsmSharpRoadGraphBuilder(ILogger l segmentFrom = null; prevCoord = null; segmentLength = 0; + shape.Clear(); continue; } @@ -333,9 +339,15 @@ public sealed class OsmSharpRoadGraphBuilder(ILogger l { vertexIds.Add(nodeId); ExpandBounds(ref minLon, ref minLat, ref maxLon, ref maxLat, coord.Lon, coord.Lat); - if (segmentFrom is long fromId && fromId != nodeId && segmentLength > 0) + if (segmentFrom is long fromId && fromId != nodeId && segmentLength > 0 && shape.Count >= 1) { + shape.Add(new RoadGraphPoint(coord.Lon, coord.Lat)); var (from, to, onewayFlag) = NormalizeDirection(fromId, nodeId, onewayCode); + if (from != fromId) + { + shape.Reverse(); + } + eId.Value = ++edgeId; eFrom.Value = from; eTo.Value = to; @@ -343,11 +355,18 @@ public sealed class OsmSharpRoadGraphBuilder(ILogger l eName.Value = name is null ? DBNull.Value : name; eOneway.Value = onewayFlag ? 1 : 0; eLength.Value = segmentLength; + eGeom.Value = GraphGeometry.Pack(shape); await insertEdge.ExecuteNonQueryAsync(ct).ConfigureAwait(false); } segmentFrom = nodeId; segmentLength = 0; + shape.Clear(); + shape.Add(new RoadGraphPoint(coord.Lon, coord.Lat)); + } + else if (segmentFrom is not null) + { + shape.Add(new RoadGraphPoint(coord.Lon, coord.Lat)); } prevCoord = coord; diff --git a/src/TileServer.Infrastructure/Graph/RoadGraphMvtEncoder.cs b/src/TileServer.Infrastructure/Graph/RoadGraphMvtEncoder.cs index 115ad27..393dcb6 100644 --- a/src/TileServer.Infrastructure/Graph/RoadGraphMvtEncoder.cs +++ b/src/TileServer.Infrastructure/Graph/RoadGraphMvtEncoder.cs @@ -24,14 +24,8 @@ public sealed class RoadGraphMvtEncoder : IRoadGraphMvtEncoder foreach (var edge in edges) { - var from = tile.ToTilePixels(edge.FromLon, edge.FromLat, Extent); - var to = tile.ToTilePixels(edge.ToLon, edge.ToLat, Extent); - if (!ClipSegment(from, to, out var a, out var b)) - { - continue; - } - - if (a.X == b.X && a.Y == b.Y) + var paths = ProjectAndClip(edge, tile); + if (paths.Count == 0) { continue; } @@ -51,7 +45,7 @@ public sealed class RoadGraphMvtEncoder : IRoadGraphMvtEncoder Id = (ulong)Math.Max(0, edge.Id), Type = MvtCodec.LineString, Tags = tags, - Geometry = MvtCodec.EncodeGeometry([[a, b]], close: false) + Geometry = MvtCodec.EncodeGeometry(paths, close: false) }); } @@ -59,6 +53,67 @@ public sealed class RoadGraphMvtEncoder : IRoadGraphMvtEncoder return MvtCodec.EncodeGzip(mvt); } + internal static IReadOnlyList> ProjectAndClip(RoadGraphEdge edge, TileCoordinate tile) + { + var points = edge.Geometry is { Count: >= 2 } + ? edge.Geometry + : new[] { new RoadGraphPoint(edge.FromLon, edge.FromLat), new RoadGraphPoint(edge.ToLon, edge.ToLat) }; + var pixels = new List<(int X, int Y)>(points.Count); + foreach (var point in points) + { + pixels.Add(tile.ToTilePixels(point.Lon, point.Lat, Extent)); + } + + return ClipPolyline(pixels); + } + + internal static IReadOnlyList> ClipPolyline(IReadOnlyList<(int X, int Y)> pixels) + { + var paths = new List>(); + if (pixels.Count < 2) + { + return paths; + } + + var current = new List<(int X, int Y)>(); + for (var i = 1; i < pixels.Count; i++) + { + if (!ClipSegment(pixels[i - 1], pixels[i], out var a, out var b)) + { + Flush(paths, current); + continue; + } + + if (current.Count == 0) + { + current.Add(a); + } + else if (current[^1] != a) + { + Flush(paths, current); + current.Add(a); + } + + if (current[^1] != b) + { + current.Add(b); + } + } + + Flush(paths, current); + return paths; + } + + private static void Flush(List> paths, List<(int X, int Y)> current) + { + if (current.Count >= 2) + { + paths.Add(current.ToArray()); + } + + current.Clear(); + } + internal static bool ClipSegment( (int X, int Y) from, (int X, int Y) to, diff --git a/src/TileServer.Infrastructure/Graph/SqliteRoadGraphStore.cs b/src/TileServer.Infrastructure/Graph/SqliteRoadGraphStore.cs index ae1a09a..76db864 100644 --- a/src/TileServer.Infrastructure/Graph/SqliteRoadGraphStore.cs +++ b/src/TileServer.Infrastructure/Graph/SqliteRoadGraphStore.cs @@ -193,7 +193,7 @@ public sealed class SqliteRoadGraphStore(IDataPaths paths, ILogger new( + { + IReadOnlyList? geometry = null; + if (reader.FieldCount > 11 && !reader.IsDBNull(11)) + { + geometry = GraphGeometry.Unpack((byte[])reader.GetValue(11)); + } + + return new RoadGraphEdge( id, reader.GetInt64(1), reader.GetInt64(2), @@ -232,7 +239,16 @@ public sealed class SqliteRoadGraphStore(IDataPaths paths, ILogger Assert.Null(RoadGraphZoomPolicy.HighwaysForZoom(13)); + public void HighwaysForZoom_AllClassesFromZ12() + => Assert.Null(RoadGraphZoomPolicy.HighwaysForZoom(12)); } public sealed class RoadGraphMvtTests @@ -105,9 +105,36 @@ public sealed class RoadGraphMvtTests } [Fact] - public void ClipSegment_KeepsCrossingLine() + public void Encode_Polyline_KeepsIntermediateVertex() { - Assert.True(RoadGraphMvtEncoder.ClipSegment((-100, 100), (5000, 2000), out var a, out var b)); - Assert.NotEqual(a, b); + var tile = TileCoordinate.FromLonLat(37.6173, 55.7558, 14); + var edge = new RoadGraphEdge( + 1, 10, 11, "residential", null, false, 180, + 37.6173, 55.7558, 37.6190, 55.7568, + [ + new RoadGraphPoint(37.6173, 55.7558), + new RoadGraphPoint(37.6182, 55.7565), + new RoadGraphPoint(37.6190, 55.7568) + ]); + var data = new RoadGraphMvtEncoder().Encode([edge], tile); + var decoded = MvtCodec.Decode(data); + var feature = Assert.Single(Assert.Single(decoded.Layers).Features); + var paths = MvtCodec.DecodeGeometry(feature.Geometry); + var path = Assert.Single(paths); + Assert.True(path.Count >= 3); + } + + [Fact] + public void ClipPolyline_SplitsWhenLeavingTile() + { + var paths = RoadGraphMvtEncoder.ClipPolyline( + [ + (100, 100), + (200, 200), + (8000, 8000), + (100, 200) + ]); + Assert.NotEmpty(paths); + Assert.All(paths, path => Assert.True(path.Count >= 2)); } } diff --git a/web-demo/src/App.tsx b/web-demo/src/App.tsx index f22bc85..1712135 100644 --- a/web-demo/src/App.tsx +++ b/web-demo/src/App.tsx @@ -88,73 +88,59 @@ function graphLineId(extractId: string): string { return `${GRAPH_PREFIX}-${extractId}-line`; } -function attachGraphTiles(map: MapLibreMap, access: Access, sources: SourceItem[]): string | null { - if (!map.isStyleLoaded()) { - return "Стиль карты ещё грузится — повтори через секунду."; - } +function readyGraphSources(sources: SourceItem[]): SourceItem[] { + return sources.filter((item) => item.graphReady !== false); +} - clearGraphLayers(map); - const ready = sources.filter((item) => item.graphReady !== false); +function styleWithGraph(style: StyleSpecification, access: Access, extracts: SourceItem[]): StyleSpecification { + const ready = readyGraphSources(extracts); if (ready.length === 0) { - return "У выбранных округов граф ещё не собран. Синхронизируй extract."; + return style; } + const sources = { ...style.sources }; + const layers = [...(style.layers ?? [])]; for (const item of ready) { const sourceId = graphSourceId(item.id); - map.addSource(sourceId, { + sources[sourceId] = { type: "vector", tiles: [graphTilesUrl(access, item.id)], minzoom: GRAPH_MIN_ZOOM, maxzoom: GRAPH_MAX_ZOOM - }); - map.addLayer({ - id: graphCasingId(item.id), - type: "line", - source: sourceId, - "source-layer": "roads", - paint: { - "line-color": "#1a1208", - "line-width": ["interpolate", ["linear"], ["zoom"], 6, 1.6, 10, 3.2, 14, 6], - "line-opacity": 0.85 + }; + layers.push( + { + id: graphCasingId(item.id), + type: "line", + source: sourceId, + "source-layer": "roads", + layout: { "line-cap": "round", "line-join": "round" }, + paint: { + "line-color": "#1a1208", + "line-width": ["interpolate", ["linear"], ["zoom"], 6, 1.6, 10, 3.2, 14, 6], + "line-opacity": 0.85 + } + }, + { + id: graphLineId(item.id), + type: "line", + source: sourceId, + "source-layer": "roads", + layout: { "line-cap": "round", "line-join": "round" }, + paint: { + "line-color": "#ffb45a", + "line-width": ["interpolate", ["linear"], ["zoom"], 6, 1, 10, 2, 14, 3.6], + "line-opacity": 1 + } } - }); - map.addLayer({ - id: graphLineId(item.id), - type: "line", - source: sourceId, - "source-layer": "roads", - paint: { - "line-color": "#ffb45a", - "line-width": ["interpolate", ["linear"], ["zoom"], 6, 1, 10, 2, 14, 3.6], - "line-opacity": 1 - } - }); + ); } - return null; + return { ...style, sources, layers }; } -function clearGraphLayers(map: MapLibreMap | null): void { - if (!map) { - return; - } - - const style = map.getStyle(); - if (!style) { - return; - } - - for (const layer of [...(style.layers ?? [])]) { - if (layer.id.startsWith(`${GRAPH_PREFIX}-`)) { - map.removeLayer(layer.id); - } - } - - for (const id of Object.keys(style.sources ?? {})) { - if (id.startsWith(`${GRAPH_PREFIX}-`)) { - map.removeSource(id); - } - } +function isGraphRequestError(message: string): boolean { + return message.includes(GRAPH_PREFIX) || /\/graph\/[\w-]+\/\d+\/\d+\/\d+\.pbf/i.test(message); } export function App() { @@ -175,10 +161,9 @@ export function App() { const [gotoError, setGotoError] = useState(""); const [banner, setBanner] = useState(""); const [syncing, setSyncing] = useState(false); - const [graphLoading, setGraphLoading] = useState(false); const [graphError, setGraphError] = useState(""); const [graphMeta, setGraphMeta] = useState(null); - const [graphEnabled, setGraphEnabled] = useState(false); + const [graphEnabled, setGraphEnabled] = useState(true); const [access, setAccess] = useState(() => { const stored = readAccess(); persistAccess(stored); @@ -188,16 +173,13 @@ export function App() { const [tokenDraft, setTokenDraft] = useState(access.token); const accessRef = useRef(access); accessRef.current = access; - const graphEnabledRef = useRef(graphEnabled); - graphEnabledRef.current = graphEnabled; - const selectedSourcesRef = useRef([]); const personal = isPersonal(access); const selectedSources = sources.filter((item) => selectedSourceIds.includes(item.id)); - selectedSourcesRef.current = selectedSources; const source = selectedSources[0] ?? sources[0]; - const graphSources = selectedSources.filter((item) => item.graphReady !== false); + const graphSources = readyGraphSources(selectedSources); const graphSource = graphSources[0] ?? selectedSources[0] ?? sources[0]; + const graphKey = graphEnabled ? graphSources.map((item) => item.id).join(",") : ""; const updateHud = useCallback((map: MapLibreMap) => { const center = map.getCenter(); @@ -254,12 +236,13 @@ export function App() { return; } - const styleKey = `${access.slug}|${selectedSourceIds.join(",")}|${styleName}|${selectedSources.map((item) => `${item.status}:${item.builtAt ?? ""}`).join(";")}`; + const styleKey = `${access.slug}|${selectedSourceIds.join(",")}|${styleName}|${selectedSources.map((item) => `${item.status}:${item.builtAt ?? ""}`).join(";")}|g:${graphKey}`; if (mapRef.current && styleKeyRef.current === styleKey) { return; } - const style = await fetchJson(styleUrl(access, styleName, selectedSourceIds)); + const baseStyle = await fetchJson(styleUrl(access, styleName, selectedSourceIds)); + const style = graphEnabled ? styleWithGraph(baseStyle, access, selectedSources) : baseStyle; const hashed = cameraFromHash(); const center = hashed ? [hashed.lon, hashed.lat] : (source?.center ?? [37.6173, 55.7558]); const zoom = hashed ? hashed.zoom : 6; @@ -282,38 +265,27 @@ export function App() { map.resize(); updateHud(map); syncGotoFromMap(map); - if (graphEnabledRef.current) { - const err = attachGraphTiles(map, accessRef.current, selectedSourcesRef.current); - if (err) { - setGraphError(err); - } - } }); map.on("error", (event) => { const message = event.error?.message; - if (message) { - setBanner(message); + if (!message) { + return; } + if (isGraphRequestError(message)) { + setGraphError(message); + return; + } + setBanner(message); }); mapRef.current = map; } else { mapRef.current.setStyle(style, { diff: false }); - mapRef.current.once("idle", () => { - const current = mapRef.current; - if (!current || !graphEnabledRef.current) { - return; - } - const err = attachGraphTiles(current, accessRef.current, selectedSourcesRef.current); - if (err) { - setGraphError(err); - } - }); } styleKeyRef.current = styleKey; const pending = selectedSources.find((item) => item.status !== "Ready"); setBanner(pending ? sourceBanner(pending) : ""); - }, [access, personal, selectedSourceIds, sources, source, styleName, syncGotoFromMap, updateHud]); + }, [access, graphEnabled, graphKey, personal, selectedSourceIds, sources, source, styleName, syncGotoFromMap, updateHud]); const refresh = useCallback(async () => { const [sourceList, syncStatus] = await Promise.all([ @@ -351,6 +323,39 @@ export function App() { void loadStyle().catch((err: unknown) => setBanner(err instanceof Error ? err.message : "Ошибка стиля")); }, [loadStyle]); + useEffect(() => { + if (!personal || !graphEnabled) { + setGraphMeta(null); + return; + } + const first = graphSources[0]; + if (!first) { + setGraphMeta(null); + if (selectedSourceIds.length > 0) { + setGraphError("У выбранных округов граф ещё не собран. Синхронизируй extract."); + } + return; + } + + let cancelled = false; + void fetchJson(graphMetaUrl(access, first.id)) + .then((meta) => { + if (!cancelled) { + setGraphMeta(meta); + setGraphError(""); + } + }) + .catch((err: unknown) => { + if (!cancelled) { + setGraphMeta(null); + setGraphError(err instanceof Error ? err.message : "Не удалось прочитать метаданные графа"); + } + }); + return () => { + cancelled = true; + }; + }, [access, graphEnabled, graphKey, personal, selectedSourceIds.length]); + useEffect(() => { return () => { mapRef.current?.remove(); @@ -418,64 +423,6 @@ export function App() { } }; - const clearGraph = () => { - graphEnabledRef.current = false; - setGraphEnabled(false); - clearGraphLayers(mapRef.current); - setGraphMeta(null); - setGraphError(""); - }; - - const loadGraph = async () => { - if (!personal) { - setGraphError("Нужны slug и токен."); - return; - } - const map = mapRef.current; - if (!map) { - setGraphError("Карта ещё не готова."); - return; - } - if (graphSources.length === 0) { - setGraphError("У выбранных округов граф ещё не собран. Синхронизируй extract."); - return; - } - - setGraphLoading(true); - setGraphError(""); - try { - const meta = await fetchJson(graphMetaUrl(access, graphSources[0].id)); - const waitStyle = () => - new Promise((resolve) => { - if (map.isStyleLoaded()) { - resolve(); - return; - } - map.once("idle", () => resolve()); - }); - await waitStyle(); - const err = attachGraphTiles(map, access, selectedSources); - if (err) { - setGraphError(err); - setGraphEnabled(false); - graphEnabledRef.current = false; - return; - } - graphEnabledRef.current = true; - setGraphEnabled(true); - setGraphMeta(meta); - setBanner(""); - } catch (err: unknown) { - clearGraphLayers(map); - setGraphEnabled(false); - graphEnabledRef.current = false; - setGraphMeta(null); - setGraphError(err instanceof Error ? err.message : "Не удалось подключить тайлы графа"); - } finally { - setGraphLoading(false); - } - }; - const mixedStatus = selectedSources.some((item) => item.status === "Failed") ? "Failed" : selectedSources.every((item) => item.status === "Ready") @@ -541,7 +488,8 @@ export function App() { const next = { slug: slugDraft.trim(), token: tokenDraft.trim() }; persistAccess(next); styleKeyRef.current = null; - clearGraph(); + setGraphMeta(null); + setGraphError(""); setAccess(next); }} > @@ -556,7 +504,8 @@ export function App() { setTokenDraft(""); persistAccess({ slug: "", token: "" }); styleKeyRef.current = null; - clearGraph(); + setGraphMeta(null); + setGraphError(""); setAccess({ slug: "", token: "" }); }} > @@ -617,27 +566,24 @@ export function App() { Граф дорог

- Векторные тайлы graph/{"{source}"}/{"{z}"}/{"{x}"}/{"{y}"}.pbf + Тайлы /graph/{"{source}"}/{"{z}"}/{"{x}"}/{"{y}"}.pbf вшиты в стиль как vector source, + слой roads, z {GRAPH_MIN_ZOOM}–{GRAPH_MAX_ZOOM} {graphSources.length > 0 ? ` — ${graphSources.map((item) => `«${item.name}»`).join(", ")}` : graphSource ? ` («${graphSource.name}»)` : ""} - . Слой roads, z {GRAPH_MIN_ZOOM}–{GRAPH_MAX_ZOOM}. Оранжевые линии поверх OSM. + . Оранжевые линии поверх OSM.

-
- - -
+ {graphError ?

{graphError}

: null} {graphMeta ? (
diff --git a/web-demo/src/access.ts b/web-demo/src/access.ts index 6f8eaa3..54ff8b9 100644 --- a/web-demo/src/access.ts +++ b/web-demo/src/access.ts @@ -76,16 +76,35 @@ export function graphTilesUrl(access: Access, sourceId: string): string { ); } +const TILE_PLACEHOLDERS: Record = { + "{z}": "__TS_Z__", + "{x}": "__TS_X__", + "{y}": "__TS_Y__" +}; + export function rewriteServiceUrl(url: string, access: Access): string { - const resolved = new URL(url, `${API_ORIGIN}/`); + let masked = url; + for (const [token, sentinel] of Object.entries(TILE_PLACEHOLDERS)) { + masked = masked.replaceAll(token, sentinel); + } + + const resolved = new URL(masked, `${API_ORIGIN}/`); const isService = resolved.pathname.startsWith("/u/") || resolved.pathname.startsWith("/api/"); if (!isService) { - return resolved.href; + return restoreTilePlaceholders(resolved.href); } if (isPersonal(access) && resolved.pathname.startsWith("/u/") && !resolved.searchParams.has("token")) { resolved.searchParams.set("token", access.token); } - return `${API_ORIGIN}${resolved.pathname}${resolved.search}`; + return restoreTilePlaceholders(`${API_ORIGIN}${resolved.pathname}${resolved.search}`); +} + +function restoreTilePlaceholders(url: string): string { + let restored = url; + for (const [token, sentinel] of Object.entries(TILE_PLACEHOLDERS)) { + restored = restored.replaceAll(sentinel, token); + } + return restored; } diff --git a/web-demo/src/demo.css b/web-demo/src/demo.css index cf17b08..a288719 100644 --- a/web-demo/src/demo.css +++ b/web-demo/src/demo.css @@ -364,10 +364,19 @@ button:disabled { opacity: 0.55; cursor: wait; } line-height: 1.35; } -.graph-panel__actions { +.graph-panel__toggle { display: flex; - flex-wrap: wrap; - gap: 0.4rem; + align-items: center; + gap: 0.55rem; + font-size: 0.86rem; + color: var(--text); + cursor: pointer; +} + +.graph-panel__toggle input { + width: 1.05rem; + height: 1.05rem; + accent-color: var(--accent); } .graph-panel__bbox { diff --git a/web/src/features/graph/GraphPage.tsx b/web/src/features/graph/GraphPage.tsx index 219441b..ec19675 100644 --- a/web/src/features/graph/GraphPage.tsx +++ b/web/src/features/graph/GraphPage.tsx @@ -272,11 +272,11 @@ export function GraphPage() { >
  • Добавляйте source после load / idle — иначе MapLibre отбросит слой при смене стиля.
  • +
  • С z12 сервер отдаёт все highway, включая residential/service (до 40k рёбер на тайл).
  • - z 6–8: motorway/trunk; z 9–10: + primary; z 11–12: + secondary/tertiary; z 13+: все классы, до 8000 рёбер на - тайл. + После sync геометрия — полилиния OSM между перекрёстками. Старый sqlite без колонки geom рисует хорды — + пересоберите граф.
  • -
  • Геометрия — прямая между вершинами графа, не исходная полилиния OSM.
diff --git a/web/src/features/guides/GuidesPage.tsx b/web/src/features/guides/GuidesPage.tsx index 8e79d04..61e3e07 100644 --- a/web/src/features/guides/GuidesPage.tsx +++ b/web/src/features/guides/GuidesPage.tsx @@ -168,8 +168,8 @@ const map = new maplibregl.Map({ Поля: highway, name, oneway, length_m.
  • - На мелком зуме сервер отдаёт только крупные дороги (z≤8 motorway/trunk, затем primary, secondary). JSON{" "} - /nodes и /edges — точечная выборка, сторона bbox ≤ 2°. + На мелком зуме только крупные дороги (z≤8 motorway/trunk, затем primary, secondary). С z12 — все улицы, + включая residential. JSON /nodes и /edges — точечная выборка, сторона bbox ≤ 2°.
  • Нет файла графа → 404. Дождитесь sync или POST /api/v1/sync/{"{id}"} при{" "} @@ -190,7 +190,8 @@ const map = new maplibregl.Map({

    Граф дорог

    Тайлы графа — как OSM: /graph/{"{source}"}/{"{z}"}/{"{x}"}/{"{y}"}.pbf, слой roads. - Ниже примеры уже с вашим slug, округом и токеном. Геометрия ребра — прямая между вершинами, не полилиния OSM. + Ниже примеры уже с вашим slug, округом и токеном. С z12 — все классы улиц. После пересборки графа + геометрия — полилиния OSM между перекрёстками.