Modern Apps git

← Modern-Apps.git

maps: world.transit v7 is the only transit input; PowerShell world-pack build

Commit
564686682808f1d36f042294def492a7b5b3b82f
Author
vayun-mathur <[email protected]>
When
2026-10-25 20:28 UTC (1 month ago)
Parents
03a2480
- TRIX v7 adds host-only RAIL_LINES (every whole rail shape transit_shapes reads),
  so build_graph derives the transit layer with transit_shapes --pack
- ride-leg shapes stored at full resolution (no 2.5 m simplification)
- mamaps_pack leaves RAIL_LINES out of the app archive
- rail route/shape selection shared in gtfs_ingest::rail
- build_world_transit.ps1: mirror, unzip, merge, prove pack == feeds, install

Diff

library/tilecodec/src/main/rust/src/mamaps/archive/consts.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/archive/consts.rs b/library/tilecodec/src/main/rust/src/mamaps/archive/consts.rsindex d22ff31c83..6037549c7c 100644--- a/library/tilecodec/src/main/rust/src/mamaps/archive/consts.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/archive/consts.rs@@ -52,8 +52,8 @@ pub const GRAPH_VERSION_MIN: u32 = 6; pub const GRAPH_META_LEN: u64 = 40; /// `transit` (`TRIX`) magic, little-endian `u32`. pub const TRANSIT_MAGIC: u32 = 0x5452_4958;-/// Newest transit version accepted.-pub const TRANSIT_VERSION: u32 = 6;+/// Newest transit version accepted. v7 adds a host-only section the app never reads.+pub const TRANSIT_VERSION: u32 = 7; /// Oldest transit version accepted. pub const TRANSIT_VERSION_MIN: u32 = 3; /// POI index record stride.
maps/src/main/rust/src/transit.rs
diff --git a/maps/src/main/rust/src/transit.rs b/maps/src/main/rust/src/transit.rsindex 1701150166..3d726dc20e 100644--- a/maps/src/main/rust/src/transit.rs+++ b/maps/src/main/rust/src/transit.rs@@ -42,8 +42,9 @@ use std::collections::HashMap;  // --- Format constants (mirror scripts/maps/gtfs_ingest/src/index.rs) --- const MAGIC: u32 = 0x5452_4958; // "TRIX"-/// Newest format this reader understands.-const VERSION: u32 = 6;+/// Newest format this reader understands. v7 only adds host-only RAIL_LINES after the+/// sections read here, which the directory loop below ignores.+const VERSION: u32 = 7; /// Oldest format still accepted. Reading both means an app update and a pack /// rebuild can land in either order without offline transit silently degrading /// to the online planner in between.
maps/src/main/rust/src/transit_part8.rs
diff --git a/maps/src/main/rust/src/transit_part8.rs b/maps/src/main/rust/src/transit_part8.rsindex 376e66fe00..06b5e3071d 100644--- a/maps/src/main/rust/src/transit_part8.rs+++ b/maps/src/main/rust/src/transit_part8.rs@@ -189,7 +189,7 @@      #[test]     fn a_feed_with_no_known_prefix_reports_no_motis_stop_id() {-        // build_world_transit.sh mangles feed names, so its packs cannot name a+        // build_world_transit.ps1 mangles feed names, so its packs cannot name a         // Transitous source; those stops must simply have no id.         let mut pack = one_route_pack();         pack.feeds = vec![("sfmuni", "America/Los_Angeles", "")];
scripts/maps/build_graph.ps1
diff --git a/scripts/maps/build_graph.ps1 b/scripts/maps/build_graph.ps1index 20fb8ceff1..346022a0de 100644--- a/scripts/maps/build_graph.ps1+++ b/scripts/maps/build_graph.ps1@@ -7,9 +7,8 @@ #   [2] cargo-build the host tools (road_graph, poi_extract, transit_shapes, #       mamaps_build, mamaps_dump, mamaps_pack) #   [3] build the road graph into a TEMP dir (never the final output)-#   [4] derive the transit-routes layer from the world-transit feeds manifest-#       (build_world_transit.sh --work DIR leaves feeds.manifest + gtfs/ there;-#       -WorldTransit defaults to the manifest beside the pack)+#   [4] derive the transit-routes layer from inputs/world.transit itself+#       (transit_shapes --pack; the raw GTFS feeds are not needed) #   [5] run mamaps_build with pbf + coastline + temp graph + routes + dem into a #       TEMP tiles-only archive ($tmp/tiles.mamaps) -- NO sidecar footer yet #   [6] extract the POI sidecars from the pbf into a TEMP dir, then mamaps_pack@@ -55,7 +54,7 @@ #   inputs/california.osm.pbf -> inputs/caonly.mamaps (only with -Region caonly) #   inputs/north-america.osm.pbf -> inputs/naonly.mamaps (only with -Region naonly) #   plus inputs/coastline.shp, inputs/world.mdem.-#   inputs/world.transit + world_transit_work/feeds.manifest are required+#   inputs/world.transit is required #   unless -NoTransit is passed, which skips GTFS entirely (empty routes + #   no --transit sidecar, as if 0 feeds). #@@ -206,11 +205,6 @@ $BuildRegion = if ($Region -eq "caonly" -or $Region -eq "naonly") { "world" } el $Coastline    = Join-Path $PSScriptRoot "inputs/coastline.shp" $WorldTransit = Join-Path $PSScriptRoot "inputs/world.transit" $Dem          = Join-Path $PSScriptRoot "inputs/world.mdem"-# build_world_transit.sh leaves the feeds manifest + unzipped gtfs/ in its fixed-# work dir (world_transit_work), not in inputs/. Step [3/7] re-runs transit_shapes-# over those to build the transit-line geometry layer.-$TransitManifest = Join-Path $PSScriptRoot "world_transit_work/feeds.manifest"- function Find-Built([string] $crate, [string] $name) {     # The tool crates are root-workspace members (no [workspace] table), so     # `cargo build` links into the WORKSPACE target dir (repo root@@ -260,11 +254,8 @@ $Dem        = (Resolve-Path $Dem).Path $Out        = [System.IO.Path]::GetFullPath($Out) if (-not $NoTransit) {     $WorldTransit = (Resolve-Path $WorldTransit).Path-    if (-not (Test-Path $TransitManifest)) { throw "transit manifest not found: $TransitManifest" }-    $TransitManifest = (Resolve-Path $TransitManifest).Path } else {     $WorldTransit = $null-    $TransitManifest = $null }  # Two things are on disk at once at the deepest zoom: one zoom's tile chunks@@ -372,46 +363,18 @@ if (-not (Test-Path (Join-Path $graphDir "metadata.bin"))) { & $roadOverlay --graph $graphDir | Tee-Object -FilePath $graphLog -Append if ($LASTEXITCODE -ne 0) { throw "road_overlay failed with exit code $LASTEXITCODE" } -# --- [3/7] transit routes from the world-transit feeds --------------------+# --- [3/7] transit routes from the world transit pack --------------------- # -NoTransit skips every feed: an empty routes file, as if 0 feeds existed.+# The lines come out of inputs/world.transit itself (every route's fitted shape,+# colour and type), so the ~80 GB of raw feeds it was built from are not needed. $null = Switch-Phase "transit" $transitLog = Join-Path $tmp "transit.log" if ($NoTransit) {     Write-Host "[3/7] NoTransit: skipping all GTFS feeds (empty transit-routes)"     [System.IO.File]::WriteAllText($routes, "") } else {-Write-Host "[3/7] Deriving transit routes from $TransitManifest"-$manifestDir = Split-Path $TransitManifest -Parent-# build_world_transit.sh runs under WSL and writes absolute /mnt/<drive>/... feed-# paths. This is a Windows build, so translate those back to <drive>:\... . If the-# stored path is gone, fall back to the feed's dir under the manifest's own gtfs/.-function Resolve-FeedDir([string] $dir) {-    if ($dir -match '^/mnt/([a-zA-Z])/(.*)$') {-        $dir = "$($Matches[1].ToUpper()):\" + ($Matches[2] -replace '/', '\')-    }-    if (-not [System.IO.Path]::IsPathRooted($dir)) { $dir = Join-Path $manifestDir $dir }-    if (-not (Test-Path (Join-Path $dir "stops.txt"))) {-        $local = Join-Path (Join-Path $manifestDir "gtfs") (Split-Path $dir -Leaf)-        if (Test-Path (Join-Path $local "stops.txt")) { return $local }-    }-    return $dir-}-$resolvedLines = foreach ($line in (Get-Content $TransitManifest)) {-    if ($line -notmatch '\S') { continue }-    $parts = $line -split '=', 3-    if ($parts.Count -lt 2 -or -not $parts[0] -or -not $parts[1]) { throw "unparsable manifest line: $line" }-    $dir = Resolve-FeedDir $parts[1]-    if (-not (Test-Path (Join-Path $dir "stops.txt"))) {-        throw "feed dir has no stops.txt (stale manifest?): $dir"-    }-    if ($parts.Count -ge 3 -and $parts[2]) { "$($parts[0])=$dir=$($parts[2])" } else { "$($parts[0])=$dir" }-}-if (-not $resolvedLines -or $resolvedLines.Count -eq 0) { throw "no usable feeds in $TransitManifest" }-[System.IO.File]::WriteAllLines((Join-Path $tmp "feeds.resolved.manifest"), $resolvedLines)-# PS1-side subphase: manifest resolution above is orchestration, not tool-# work; the TIMING line below covers transit_shapes itself.-Switch-Subphase "resolve-manifest" | Out-Null-& $shapes $routes --manifest (Join-Path $tmp "feeds.resolved.manifest") | Tee-Object -FilePath $transitLog+Write-Host "[3/7] Deriving transit routes from $WorldTransit"+& $shapes $routes --pack $WorldTransit | Tee-Object -FilePath $transitLog if ($LASTEXITCODE -ne 0) { throw "transit_shapes failed with exit code $LASTEXITCODE" } } @@ -585,7 +548,7 @@ foreach ($pair in @(@("graph", $graphLog), @("transit", $transitLog), @("tiles", } function Get-PhaseSubs([string] $phase) {     # Merged view: Rust subphases in emission order, PS1-owned subphases-    # (tools builds, transit resolve-manifest, verify steps) in capture order,+    # (tools builds, verify steps) in capture order,     # then the closing `other` bucket. Every row sums to the phase wall.     $merged = [ordered]@{}     if ($rustSubs.Contains($phase)) {
scripts/maps/build_world_transit.ps1
diff --git a/scripts/maps/build_world_transit.ps1 b/scripts/maps/build_world_transit.ps1new file mode 100644index 0000000000..cf7f9e7468--- /dev/null+++ b/scripts/maps/build_world_transit.ps1@@ -0,0 +1,165 @@+# build_world_transit.ps1 -- build inputs/world.transit, the single global offline transit pack.+#+# Mirrors Transitous' own published GTFS directory (https://api.transitous.org/gtfs/, its+# already-fetched, already-normalised output; nothing here talks to an agency), unzips every+# feed, and merges them into one TRIX pack with `gtfs_ingest`.+#+# The pack is the build's only transit input: v7 carries RAIL_LINES, the exact shapes+# `transit_shapes` reads from the feeds, so build_graph.ps1 derives the map's transit layer from+# world.transit alone. Before the pack replaces inputs/world.transit this script proves that:+# the layer derived from the pack must be byte-identical to the one derived from the raw feeds.+# Once it has, the work dir (mirror + unzipped feeds, ~80 GB) is not needed again and can be+# deleted; a later run re-downloads it.+#+# THE FEED ID. A zip is `<region>_<Source>.gtfs.zip` and its MOTIS feed id is `<region>-<Source>`.+# Only the FIRST underscore is a separator; the rest keeps its own hyphens and case+# (`us-ca_SF-bayarea` -> `us-ca-SF-bayarea`). Without it the pack carries no MOTIS stop ids and+# live delays cannot be matched to a stop.+#+# Usage (from anywhere):+#   .\scripts\maps\build_world_transit.ps1               # mirror, unzip, merge, verify, install+#   .\scripts\maps\build_world_transit.ps1 -SkipMirror   # reuse the mirror already on disk+#   .\scripts\maps\build_world_transit.ps1 -SkipVerify   # skip the raw-vs-pack layer proof+#+# Work dir: scripts/maps/world_transit_work (transitous/ zips, gtfs/ unzipped, feeds.manifest).+# Output:   scripts/maps/inputs/world.transit (+ .json).++param(+    # Use the zips already in the work dir instead of refreshing the mirror.+    [switch] $SkipMirror,+    # Install the pack without proving the derived transit layer matches the raw feeds.+    [switch] $SkipVerify,+    # Feeds unzipped at once. The download itself is always serial; see below.+    [int] $Jobs = 4+)+$ErrorActionPreference = "Stop"++$Here = $PSScriptRoot+$Repo = (Resolve-Path (Join-Path $Here "../..")).Path+$Work = Join-Path $Here "world_transit_work"+$Mirror = Join-Path $Work "transitous"+$Gtfs = Join-Path $Work "gtfs"+$Manifest = Join-Path $Work "feeds.manifest"+$Staging = Join-Path $Work "pack"+$Inputs = Join-Path $Here "inputs"+$IndexUrl = "https://api.transitous.org/gtfs/"+New-Item -ItemType Directory -Force -Path $Work, $Mirror, $Gtfs, $Inputs | Out-Null++# --- 1. Build the tools --------------------------------------------------------------------+Write-Host "=== [1/5] building gtfs_ingest + transit_shapes (release) ==="+Push-Location $Repo+try {+    cargo build --release -p gtfs_ingest --bin gtfs_ingest --bin transit_shapes+    if ($LASTEXITCODE -ne 0) { throw "cargo build failed" }+    # A workspace member: the binaries land in the workspace's target dir, not the crate's.+    $target = (cargo metadata --format-version 1 --no-deps | ConvertFrom-Json).target_directory+} finally { Pop-Location }+$Ingest = Join-Path $target "release/gtfs_ingest.exe"+$Shapes = Join-Path $target "release/transit_shapes.exe"++# --- 2. Mirror -------------------------------------------------------------------------------+# ONE host, fetched serially at a fixed rate. Do not parallelise: --limit-rate is per process, so+# N downloads at once would put N times the load on a volunteer host. Each zip is re-fetched only+# when upstream is newer than the copy on disk (-z), so a re-run pulls just what changed.+if ($SkipMirror) {+    Write-Host "=== [2/5] -SkipMirror: using the zips in $Mirror ==="+} else {+    Write-Host "=== [2/5] mirroring $IndexUrl -> $Mirror ==="+    $index = curl.exe -sS --fail $IndexUrl+    if ($LASTEXITCODE -ne 0) { throw "cannot read $IndexUrl" }+    $names = [string[]]([regex]::Matches(($index -join "`n"), 'href="([^"/]+\.gtfs\.zip)"') | ForEach-Object { $_.Groups[1].Value } | Select-Object -Unique)+    if (-not $names) { throw "$IndexUrl lists no .gtfs.zip files" }+    $n = 0; $failed = 0+    foreach ($name in $names) {+        $n+++        $dest = Join-Path $Mirror $name+        $curlArgs = @("-sS", "--fail", "-R", "--limit-rate", "30M", "-o", $dest)+        if (Test-Path $dest) { $curlArgs += @("-z", $dest) }+        curl.exe @curlArgs "$IndexUrl$name"+        # One server error must not lose a 2,000-feed build; the feed count below gates it.+        if ($LASTEXITCODE -ne 0) { $failed++; Write-Warning "download failed: $name" }+        Write-Progress -Activity "Mirror" -Status "$n / $($names.Count)" -PercentComplete (100 * $n / $names.Count)+    }+    Write-Progress -Activity "Mirror" -Completed+    Write-Host "  $($names.Count) zip(s) listed, $failed failed"+}++# --- 3. Unzip --------------------------------------------------------------------------------+# lowercase, every run of non-alphanumerics one `_`: gtfs_ingest's registry::safe_name.+function Get-SafeName([string] $s) { ($s.ToLowerInvariant() -replace '[^a-z0-9]+', '_').Trim('_') }++Write-Host "=== [3/5] unzipping into $Gtfs ==="+# Ordinal name order, so the manifest (and the feed order the pack is merged in) is stable.+$zips = [string[]](Get-ChildItem $Mirror -Filter *.gtfs.zip -File | ForEach-Object Name)+[Array]::Sort($zips, [StringComparer]::Ordinal)+$feeds = $zips | ForEach-Object {+    $stem = $_.Substring(0, $_.Length - ".gtfs.zip".Length)+    $cut = $stem.IndexOf('_')+    $safe = Get-SafeName $stem+    if ($cut -lt 1 -or -not $safe) { Write-Warning "'$stem' has no <region>_<source> split; skipped"; return }+    [pscustomobject]@{+        Zip = Join-Path $Mirror $_+        Name = $safe+        Prefix = $stem.Substring(0, $cut) + "-" + $stem.Substring($cut + 1)+        Dir = Join-Path $Gtfs $safe+    }+}+$feeds | ForEach-Object -ThrottleLimit $Jobs -Parallel {+    $f = $_+    # The stamp names the zip a directory was unzipped from, so a zip the mirror refreshed is+    # unzipped again. A directory with tables but no stamp predates stamps and is trusted.+    $stops = Join-Path $f.Dir "stops.txt"+    $stampFile = Join-Path $f.Dir ".unzipped"+    $zip = Get-Item $f.Zip+    $stamp = "$($zip.Length) $($zip.LastWriteTimeUtc.Ticks)"+    if ((Test-Path $stops) -and (-not (Test-Path $stampFile) -or (Get-Content $stampFile) -eq $stamp)) { return }+    if (Test-Path $f.Dir) { Remove-Item -Recurse -Force $f.Dir }+    New-Item -ItemType Directory -Force -Path $f.Dir | Out-Null+    tar.exe -xf $f.Zip -C $f.Dir 2>$null+    if (-not (Test-Path $stops)) {+        # Some feeds nest their tables one directory deep.+        $inner = Get-ChildItem $f.Dir -Recurse -Filter stops.txt -File | Select-Object -First 1+        if ($inner) { Get-ChildItem $inner.DirectoryName | Move-Item -Destination $f.Dir -Force }+    }+    if (Test-Path $stops) {+        Set-Content -Path $stampFile -Value $stamp+    } else {+        Write-Warning "no stops.txt in $(Split-Path $f.Zip -Leaf); skipped"+        Remove-Item -Recurse -Force $f.Dir+    }+}+$usable = $feeds | Where-Object { Test-Path (Join-Path $_.Dir "stops.txt") }+if (-not $usable) { throw "no usable feeds" }+[System.IO.File]::WriteAllLines($Manifest, [string[]]($usable | ForEach-Object { "$($_.Name)=$($_.Dir)=$($_.Prefix)" }))+Write-Host "  $($usable.Count) feed(s) usable of $($feeds.Count), listed in $Manifest"++# --- 4. Merge --------------------------------------------------------------------------------+Write-Host "=== [4/5] merging into one pack ==="+if (Test-Path $Staging) { Remove-Item -Recurse -Force $Staging }+New-Item -ItemType Directory -Force -Path $Staging | Out-Null+& $Ingest $Staging world --manifest $Manifest+if ($LASTEXITCODE -ne 0) { throw "gtfs_ingest failed with exit code $LASTEXITCODE" }+$pack = Join-Path $Staging "world.transit"++# --- 5. Prove the pack stands in for the feeds, then install it -------------------------------+if ($SkipVerify) {+    Write-Host "=== [5/5] -SkipVerify: not checking the derived transit layer ==="+} else {+    Write-Host "=== [5/5] deriving the transit layer from the feeds and from the pack ==="+    $fromFeeds = Join-Path $Staging "layer.feeds.geojsonseq"+    $fromPack = Join-Path $Staging "layer.pack.geojsonseq"+    & $Shapes $fromFeeds --manifest $Manifest+    if ($LASTEXITCODE -ne 0) { throw "transit_shapes over the feeds failed" }+    & $Shapes $fromPack --pack $pack+    if ($LASTEXITCODE -ne 0) { throw "transit_shapes over the pack failed" }+    if ((Get-FileHash $fromFeeds).Hash -ne (Get-FileHash $fromPack).Hash) {+        throw "the pack does not reproduce the feeds' transit layer; inputs/world.transit was NOT replaced"+    }+    Write-Host "  identical: the pack alone rebuilds the transit layer"+    Remove-Item $fromFeeds, $fromPack+}+Move-Item -Force $pack (Join-Path $Inputs "world.transit")+Move-Item -Force "$pack.json" (Join-Path $Inputs "world.transit.json")+Remove-Item -Recurse -Force $Staging+Get-Content (Join-Path $Inputs "world.transit.json") | Select-Object -First 16+Write-Host "Done: $(Join-Path $Inputs 'world.transit'). $Work is no longer needed by build_graph.ps1."
scripts/maps/gtfs_ingest/README.md
diff --git a/scripts/maps/gtfs_ingest/README.md b/scripts/maps/gtfs_ingest/README.mdindex 2ed69a7685..09931cbad2 100644--- a/scripts/maps/gtfs_ingest/README.md+++ b/scripts/maps/gtfs_ingest/README.md@@ -8,7 +8,7 @@ on-device planner that consumes the index is  Merging many feeds into one pack is what makes a single global **`world.transit`** feasible — the app downloads it once on open (mirroring the single global road-graph). See `scripts/maps/build_world_transit.sh` for the world pipeline.+graph). See `scripts/maps/build_world_transit.ps1` for the world pipeline.  ## Why Rust + directory input @@ -283,15 +283,19 @@ whole point of merging feeds into one pack.  ## Building the world pack -`build_world_transit.sh` (repo root: `scripts/maps/`) builds the single global-pack by mirroring Transitous' own published GTFS directory and merging every-zip into one TRX2 pack:+`scripts/maps/build_world_transit.ps1` builds the single global pack by mirroring+Transitous' own published GTFS directory and merging every zip into one TRIX pack,+then proves the pack's RAIL_LINES reproduce the feeds' transit layer before it+replaces `inputs/world.transit`: -```sh-./build_world_transit.sh --region 'us-ca' --out /tmp/wt   # stage: California first-./build_world_transit.sh --work /data/transit --publish  # whole world, then publish+```powershell+.\scripts\maps\build_world_transit.ps1               # mirror, unzip, merge, verify, install+.\scripts\maps\build_world_transit.ps1 -SkipMirror   # reuse the zips already on disk ``` +`build_graph.ps1` reads only the pack, so the work dir this leaves behind+(`scripts/maps/world_transit_work`, ~80 GB) can be deleted afterwards.+ It mirrors rather than resolving the Transitous registry feed-by-feed because the upstreams are third parties in every state of disrepair: 401s, 403s, 404s from dead rehosts, hostname-mismatched TLS certs, broken pipes. Transitous
scripts/maps/gtfs_ingest/src/bin/resolve_feeds.rs
diff --git a/scripts/maps/gtfs_ingest/src/bin/resolve_feeds.rs b/scripts/maps/gtfs_ingest/src/bin/resolve_feeds.rsindex aac6370196..7a27f70999 100644--- a/scripts/maps/gtfs_ingest/src/bin/resolve_feeds.rs+++ b/scripts/maps/gtfs_ingest/src/bin/resolve_feeds.rs@@ -12,7 +12,7 @@ //! and run offline. //! //! The plan is a TSV of `name<TAB>url<TAB>motis_prefix`, which-//! `build_world_transit.sh` downloads and then turns into the three-field manifest+//! `build_world_transit.ps1` downloads and then turns into the three-field manifest //! `manifest.rs::parse_feed_spec` reads. //! //! `--region` and `--max-feeds` are not conveniences. Resolving every `feeds/*.json`
scripts/maps/gtfs_ingest/src/bin/transit_shapes.rs
diff --git a/scripts/maps/gtfs_ingest/src/bin/transit_shapes.rs b/scripts/maps/gtfs_ingest/src/bin/transit_shapes.rsindex c268a1a517..8951b44816 100644--- a/scripts/maps/gtfs_ingest/src/bin/transit_shapes.rs+++ b/scripts/maps/gtfs_ingest/src/bin/transit_shapes.rs@@ -8,7 +8,7 @@ //! //! `<feed>` is `feed_name=gtfs_dir[=motis_prefix]` or a bare `gtfs_dir`, exactly //! as `gtfs_ingest` takes them, so the same `feeds.manifest`-//! `build_world_transit.sh` writes drives every tool in this crate.+//! `build_world_transit.ps1` writes drives every tool in this crate. //! //! # Why GTFS rather than OSM route relations //!@@ -20,13 +20,13 @@ //! when it did not. `routes.txt` carries the agency's official `route_color` and //! `shapes.txt` carries the vehicle's real path with no platforms in it at all. //!-//! # Why not read the `.transit` pack+//! # Reading the `.transit` pack instead (`--pack`) //!-//! `reader.rs` already decodes a built pack host-side, but the pack's geometry is-//! fitted to a stop pattern, simplified at `shapes::SIMPLIFY_TOLERANCE_M` and-//! trimmed to `[first stop, last stop]`. That is right for drawing a journey leg-//! and wrong for a basemap line, which wants the untrimmed, unsimplified-//! alignment. So this reads the raw feeds.+//! The pack's ride geometry is fitted to a stop pattern and trimmed to+//! `[first stop, last stop]`: right for a journey leg, wrong for a basemap line,+//! which wants the whole alignment. So a v7 pack also carries RAIL_LINES, the+//! exact shapes this tool reads from each feed, and `--pack` derives the same+//! layer from it without the raw feeds. //! //! Like the rest of the crate: no serde, the JSON lines are hand-written. @@ -36,12 +36,16 @@ mod extra2; #[path = "transit_shapes_intercity.rs"] mod intercity; +#[path = "transit_shapes_pack.rs"]+mod pack;+ #[path = "transit_shapes_extra.rs"] #[cfg(test)] mod extra;  use gtfs_ingest::bundle; use gtfs_ingest::gtfs::{self, Csv};+use gtfs_ingest::rail::{fallback_color, mode_of, rail_routes, shape_ids_by_route}; use gtfs_ingest::manifest::{parse_feed_spec, read_manifest, FeedSpec}; use gtfs_ingest::timing::PhaseTimer; @@ -72,7 +76,7 @@ const MAX_SERVICES_PER_TRACK: usize = 4; /// under this — the branch is the point of it — while a re-publication with a couple of extra /// stops is well over. const MOSTLY_DRAWN: f64 = 0.95;-use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};+use std::collections::{BTreeMap, HashSet}; use std::io::{BufWriter, Write}; use std::path::{Path, PathBuf}; use std::process::ExitCode;@@ -94,6 +98,21 @@ fn main() -> ExitCode {     let mut timer = PhaseTimer::start("transit");     timer.switch("manifest-resolve"); +    // A built pack stands in for the raw feeds it was made from.+    if args[2] == "--pack" {+        let Some(file) = args.get(3) else {+            eprintln!("ERROR: transit_shapes: --pack requires a world.transit path");+            return ExitCode::from(2);+        };+        return match extra2::run_with_timer(&out, extra2::Inputs::Pack(Path::new(file)), Some(timer)) {+            Ok(()) => ExitCode::SUCCESS,+            Err(e) => {+                eprintln!("ERROR: transit_shapes: {e}");+                ExitCode::FAILURE+            }+        };+    }+     let specs: Vec<FeedSpec> = if args[2] == "--manifest" {         let Some(file) = args.get(3) else {             eprintln!("ERROR: transit_shapes: --manifest requires a file path");@@ -116,7 +135,7 @@ fn main() -> ExitCode {         return ExitCode::from(2);     } -    match extra2::run_with_timer(&out, &specs, Some(timer)) {+    match extra2::run_with_timer(&out, extra2::Inputs::Feeds(&specs), Some(timer)) {         Ok(()) => ExitCode::SUCCESS,         Err(e) => {             eprintln!("ERROR: transit_shapes: {e}");@@ -128,6 +147,7 @@ fn main() -> ExitCode { fn usage() {     eprintln!("usage: transit_shapes <out.geojsonseq> <feed>...");     eprintln!("       transit_shapes <out.geojsonseq> --manifest FILE");+    eprintln!("       transit_shapes <out.geojsonseq> --pack world.transit");     eprintln!("  <feed> = feed_name=gtfs_dir[=motis_prefix]  |  gtfs_dir"); } @@ -168,66 +188,6 @@ struct FeedLines {     shapes_read: usize, } -/// GTFS `route_type` → the basemap's mode vocabulary, or `None` for a mode this-/// layer does not carry (bus, ferry, trolleybus, aerial lift, ...).-///-/// The extended ranges are here because European feeds use them almost-/// exclusively: a feed publishing its metro as 402 rather than 1 would otherwise-/// contribute nothing at all.-fn mode_of(route_type: u32) -> Option<&'static str> {-    Some(match route_type {-        // GTFS 0 is "tram, streetcar, light rail" in one value. `light_rail`-        // rather than `tram` because that is what North American agencies put-        // there — Muni Metro, MAX, Link — and its zoom floor is the shallower of-        // the two, so a street tram filed under 0 surfaces one zoom early rather-        // than a light rail line vanishing until z13.-        0 => "light_rail",-        1 => "subway",-        2 => "train",-        // Cable tram and funicular: short, street-level, and the tram zoom floor.-        5 | 7 => "tram",-        12 => "monorail",-        100..=117 => "train",-        400..=404 => "subway",-        405 => "monorail",-        900..=906 => "tram",-        _ => return None,-    })-}--/// The fallback line colour per mode, as `0xRRGGBB`, for a route naming none.-///-/// **A matched pair with `mamaps_build`'s `schema::transit::MODES`**: the five-/// names above and the five colours here are that table, duplicated because this-/// crate is deliberately detached from the Android workspace and has no-/// dependencies, so the two cannot share code. A change to either is a change to-/// both.-fn fallback_color(mode: &str) -> u32 {-    match mode {-        "subway" => 0xE4002B,-        "light_rail" => 0x00985F,-        "tram" => 0xFFD200,-        "train" => 0x0057A8,-        "monorail" => 0x9D9D9D,-        _ => 0x666666,-    }-}--/// A `route_color` cell as `0xRRGGBB`, or `None` to fall back per mode.-///-/// GTFS spells it as bare `RRGGBB`; a leading `#` is accepted because feeds put-/// one there anyway. Zero is refused rather than emitted: it means "no colour" on-/// the wire, so a route that really is black takes its mode's colour instead.-fn route_color(raw: &str) -> Option<u32> {-    let hex = raw.trim();-    let hex = hex.strip_prefix('#').unwrap_or(hex);-    if hex.len() != 6 || !hex.chars().all(|c| c.is_ascii_hexdigit()) {-        return None;-    }-    let value = u32::from_str_radix(hex, 16).ok()?;-    (value != 0).then_some(value)-}- /// A content hash of one polyline, for dedup. /// /// Rounded to e6 — about 0.1 m — so that two feeds publishing the same alignment@@ -285,7 +245,7 @@ fn read_feed(spec: &FeedSpec) -> Result<FeedLines, String> {      let mut out = FeedLines { routes_kept: rail.len(), ..FeedLines::default() };     for (route_id, shape_ids) in &by_route {-        let (mode, color, fallback, route, long_type) = &rail[route_id.as_str()];+        let (mode, color, fallback, route, route_type) = &rail[route_id.as_str()];         let before = out.lines.len();         // Every distinct shape, whole. What a route publishes is one alignment per         // direction plus a short-turn or a branch variant or two, all of them overlapping,@@ -301,7 +261,7 @@ fn read_feed(spec: &FeedSpec) -> Result<FeedLines, String> {             let points: Vec<(i32, i32)> =                 shape.lat_e7.iter().zip(&shape.lon_e7).map(|(&lat, &lon)| (lat, lon)).collect();             out.lines.push(Line {-                intercity: intercity::is_intercity(*long_type, &points),+                intercity: intercity::is_intercity(intercity::is_long_distance_type(*route_type), &points),                 points,                 color: *color,                 mode,@@ -322,58 +282,6 @@ fn read_feed(spec: &FeedSpec) -> Result<FeedLines, String> {     Ok(out) } -/// `route_id` → `(mode, colour, is a fallback colour, display name, is long-distance by type)`-/// for every rail route in the feed. Everything else, bus included, is dropped here.-fn rail_routes(routes: &Csv) -> HashMap<String, (&'static str, u32, bool, String, bool)> {-    let mut out = HashMap::new();-    for row in &routes.rows {-        let id = routes.get(row, "route_id");-        if id.is_empty() {-            continue;-        }-        let Ok(route_type) = routes.get(row, "route_type").trim().parse::<u32>() else { continue };-        let Some(mode) = mode_of(route_type) else { continue };-        let (color, fallback) = match route_color(routes.get(row, "route_color")) {-            Some(color) => (color, false),-            None => (fallback_color(mode), true),-        };-        let short = routes.get(row, "route_short_name").trim();-        let long = routes.get(row, "route_long_name").trim();-        let name = if short.is_empty() { long } else { short };-        out.insert(-            id.to_string(),-            (mode, color, fallback, name.to_string(), intercity::is_long_distance_type(route_type)),-        );-    }-    out-}--/// The distinct `shape_id`s each rail route's trips reference.-///-/// One line per **distinct polyline**, not per trip and not per RAPTOR route-/// group: a route's trips reference many shapes (one per direction, one per-/// short-turn variant) and every trip carrying its own line would draw the same-/// alignment hundreds of times. `BTreeMap`/`BTreeSet` rather than the hashed-/// pair, because the output has to be byte-identical between runs.-fn shape_ids_by_route(-    trips: &Csv,-    rail: &HashMap<String, (&'static str, u32, bool, String, bool)>,-) -> BTreeMap<String, BTreeSet<String>> {-    let mut out: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();-    for row in &trips.rows {-        let route_id = trips.get(row, "route_id");-        if !rail.contains_key(route_id) {-            continue;-        }-        let shape_id = trips.get(row, "shape_id").trim();-        if shape_id.is_empty() {-            continue;-        }-        out.entry(route_id.to_string()).or_default().insert(shape_id.to_string());-    }-    out-}- /// Cut every line at its corridor boundaries and give each piece its lane, so one line in /// becomes several out — the stretch before a corridor on its own geometry, the stretch /// inside it on the corridor's reference geometry at its lane, and a taper between. Returns
scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra.rs
diff --git a/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra.rs b/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra.rsindex 6e4b011094..2a902a3467 100644--- a/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra.rs+++ b/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra.rs@@ -5,6 +5,7 @@ use super::extra2::run; use super::*; use gtfs_ingest::gtfs::parse_csv;+use gtfs_ingest::rail::route_color; use gtfs_ingest::manifest::FeedSpec; use std::path::PathBuf; 
scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra2.rs
diff --git a/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra2.rs b/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra2.rsindex ff5138c1ad..194c3ed231 100644--- a/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra2.rs+++ b/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra2.rs@@ -5,10 +5,17 @@ use super::*; use rayon::prelude::*; use std::time::Instant; +/// Where the lines come from: raw GTFS feeds, or the `world.transit` pack built from them.+#[derive(Clone, Copy)]+pub(crate) enum Inputs<'a> {+    Feeds(&'a [FeedSpec]),+    Pack(&'a Path),+}+ /// Untimed entry, kept for the unit tests in `transit_shapes_extra`. #[cfg(test)] pub(crate) fn run(out_path: &Path, specs: &[FeedSpec]) -> Result<(), String> {-    run_with_timer(out_path, specs, None)+    run_with_timer(out_path, Inputs::Feeds(specs), None) }  /// Timed pipeline entry: ticks `parse-feeds` over the feed loop below, the@@ -17,7 +24,7 @@ pub(crate) fn run(out_path: &Path, specs: &[FeedSpec]) -> Result<(), String> { /// summary. `None` skips every tick, which is what the tests drive via [`run`]. pub(crate) fn run_with_timer(     out_path: &Path,-    specs: &[FeedSpec],+    inputs: Inputs<'_>,     mut timer: Option<PhaseTimer>, ) -> Result<(), String> {     let mut seen: HashSet<(u64, u32)> = HashSet::new();@@ -59,27 +66,21 @@ pub(crate) fn run_with_timer(     let threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1);     let chunk_size = threads.saturating_mul(2).max(1); -    let total = specs.len();+    let total = match inputs {+        Inputs::Feeds(specs) => specs.len(),+        Inputs::Pack(_) => 1,+    };+    let chunks: Vec<&[FeedSpec]> = match inputs {+        Inputs::Feeds(specs) => specs.chunks(chunk_size).collect(),+        // One pass over the whole pack: it is already one merged, ordered set.+        Inputs::Pack(_) => vec![&[]],+    };     let mut processed = 0usize;-    for chunk in specs.chunks(chunk_size) {-        let next = AtomicUsize::new(0);-        let parsed: Mutex<Vec<(usize, Result<FeedLines, String>)>> =-            Mutex::new(Vec::with_capacity(chunk.len()));-        std::thread::scope(|scope| {-            for _ in 0..threads.min(chunk.len()) {-                scope.spawn(|| loop {-                    let i = next.fetch_add(1, Ordering::Relaxed);-                    if i >= chunk.len() {-                        break;-                    }-                    let read = read_feed(&chunk[i]);-                    parsed.lock().expect("feed reader pool").push((i, read));-                });-            }-        });-        let mut parsed = parsed.into_inner().expect("feed reader pool");-        // Back into spec order, so the fold below sees exactly the sequence it used to.-        parsed.sort_unstable_by_key(|(i, _)| *i);+    for chunk in chunks {+        let parsed = match inputs {+            Inputs::Pack(path) => vec![(0, super::pack::pack_lines(path))],+            Inputs::Feeds(_) => parse_chunk(chunk, threads),+        };          // Feeds unwrapped in spec order and their lines gathered, so the dedup key of every         // line can be computed wide before the sequential fold. Stats accumulate here so an@@ -232,13 +233,36 @@ pub(crate) fn run_with_timer(          {} line(s), {} intercity, {bundled} in a shared corridor, \          {fell_back} on a per-mode fallback colour)",         out_path.display(),-        specs.len(),+        total,         lines.len(),         lines.iter().filter(|l| l.intercity).count(),     );     Ok(()) } +/// Parse one chunk of feeds on `threads` workers, back in spec order, so the fold sees exactly+/// the sequence a sequential read would give it.+fn parse_chunk(chunk: &[FeedSpec], threads: usize) -> Vec<(usize, Result<FeedLines, String>)> {+    let next = AtomicUsize::new(0);+    let parsed: Mutex<Vec<(usize, Result<FeedLines, String>)>> =+        Mutex::new(Vec::with_capacity(chunk.len()));+    std::thread::scope(|scope| {+        for _ in 0..threads.min(chunk.len()) {+            scope.spawn(|| loop {+                let i = next.fetch_add(1, Ordering::Relaxed);+                if i >= chunk.len() {+                    break;+                }+                let read = read_feed(&chunk[i]);+                parsed.lock().expect("feed reader pool").push((i, read));+            });+        }+    });+    let mut parsed = parsed.into_inner().expect("feed reader pool");+    parsed.sort_unstable_by_key(|(i, _)| *i);+    parsed+}+ /// One stderr redraw of the feed-parse meter in the standard shape: /// `\r{label:<28} [{pct:>3}%] {done}/{total}  {elapsed} elapsed, ETA {eta}`. fn print_feed_meter(done: usize, total: usize, start: &Instant) {
scripts/maps/gtfs_ingest/src/bin/transit_shapes_pack.rs
diff --git a/scripts/maps/gtfs_ingest/src/bin/transit_shapes_pack.rs b/scripts/maps/gtfs_ingest/src/bin/transit_shapes_pack.rsnew file mode 100644index 0000000000..7d8ab8f8fc--- /dev/null+++ b/scripts/maps/gtfs_ingest/src/bin/transit_shapes_pack.rs@@ -0,0 +1,144 @@+//! Lines for `transit_shapes` read from a built `world.transit` pack instead of raw GTFS.+//!+//! A v7 pack's RAIL_LINES section holds exactly what [`read_feed`] takes out of each raw feed:+//! every whole, unsimplified shape of every rail route, with its route's type, colour, name and+//! id, in the same order. So the fold, corridor pass and writer downstream produce the same layer+//! from the pack as from the ~80 GB of feeds it was built from.++use super::*;+use gtfs_ingest::reader::Reader;++/// Every RAIL_LINES entry as a candidate line, in pack order.+pub(crate) fn pack_lines(path: &Path) -> Result<FeedLines, String> {+    let pack = Reader::open(path)?;+    let Some(recs) = pack.rail_lines() else {+        return Err(format!(+            "{} is a v{} pack with no RAIL_LINES section; rebuild it with scripts/maps/build_world_transit.ps1",+            path.display(),+            pack.version(),+        ));+    };+    let feeds: Vec<String> = (0..pack.feed_count()).map(|f| pack.feed_name(f)).collect();+    let mut out = FeedLines::default();+    for rec in recs {+        let Some(mode) = mode_of(rec.route_type) else {+            return Err(format!("RAIL_LINES carries route_type {}, which is not rail", rec.route_type));+        };+        let (color, fallback) = match rec.color {+            0 => (fallback_color(mode), true),+            c => (c, false),+        };+        out.shapes_read += 1;+        out.lines.push(Line {+            intercity: intercity::is_intercity(intercity::is_long_distance_type(rec.route_type), &rec.points),+            points: rec.points,+            color,+            mode,+            fallback,+            route: rec.name,+            route_key: format!("{}\u{0}{}", feeds[rec.feed_idx as usize], rec.route_id),+            ordinal: 0,+            lanes: 1,+            taper: 255,+        });+    }+    Ok(out)+}++#[cfg(test)]+mod tests {+    use super::*;+    use gtfs_ingest::index::{FeedDir, IndexBuilder};++    /// Two feeds sharing a rail alignment plus a bus, through the real pack builder: the layer+    /// derived from the pack is byte-identical to the one derived from the feeds.+    #[test]+    fn a_pack_draws_exactly_the_lines_of_the_feeds_it_was_built_from() {+        let root = std::env::temp_dir().join(format!("transit_shapes_pack_{}", std::process::id()));+        let feed = |tag: &str, rail_color: &str, lat: &str| -> PathBuf {+            let dir = root.join(tag);+            std::fs::create_dir_all(&dir).unwrap();+            let w = |f: &str, s: String| std::fs::write(dir.join(f), s).unwrap();+            w("agency.txt", "agency_id,agency_name,agency_url,agency_timezone\nA,A,http://a,America/Los_Angeles\n".into());+            w("stops.txt", format!("stop_id,stop_name,stop_lat,stop_lon\nS1,One,37.700,-122.40\nS2,Two,{lat},-122.40\n"));+            w("routes.txt", format!(+                "route_id,route_short_name,route_long_name,route_type,route_color\nR,Rail,,2,{rail_color}\nB,Bus,,3,FF0000\n"+            ));+            w("trips.txt", "route_id,service_id,trip_id,shape_id\nR,WK,T1,SH1\nR,WK,T2,SH2\nB,WK,T3,SH1\n".into());+            w("stop_times.txt", "trip_id,arrival_time,departure_time,stop_id,stop_sequence\n\+                T1,08:00:00,08:00:00,S1,1\nT1,08:10:00,08:10:00,S2,2\n\+                T2,09:00:00,09:00:00,S2,1\nT2,09:10:00,09:10:00,S1,2\n\+                T3,10:00:00,10:00:00,S1,1\nT3,10:10:00,10:10:00,S2,2\n".into());+            w("calendar.txt", "service_id,monday,tuesday,wednesday,thursday,friday,saturday,sunday,start_date,end_date\nWK,1,1,1,1,1,0,0,20240101,20301231\n".into());+            // A long outbound shape at full precision and a short return with a kink.+            w("shapes.txt", format!(+                "shape_id,shape_pt_lat,shape_pt_lon,shape_pt_sequence\n\+                 SH1,37.6999999,-122.4000001,1\nSH1,37.75,-122.4,2\nSH1,{lat},-122.4,3\n\+                 SH2,{lat},-122.4,1\nSH2,37.75,-122.39,2\nSH2,37.7,-122.4,3\n"+            ));+            dir+        };+        let specs: Vec<FeedSpec> = vec![+            ("a".to_string(), feed("a", "0054A5", "37.800"), String::new()),+            ("b".to_string(), feed("b", "", "39.500"), String::new()),+        ];+        let mut builder = IndexBuilder::new("test");+        for (name, dir, prefix) in &specs {+            let table = |f: &str| gtfs::read_table(dir, f);+            let (stops, routes, trips) =+                (table("stops.txt").unwrap(), table("routes.txt").unwrap(), table("trips.txt").unwrap());+            let (calendar, agency, shapes) = (table("calendar.txt"), table("agency.txt"), gtfs::read_shapes(dir));+            builder+                .add_feed_dir(&FeedDir {+                    name: name.clone(),+                    motis_prefix: prefix.clone(),+                    dir,+                    stops: &stops,+                    routes: &routes,+                    trips: &trips,+                    calendar: calendar.as_ref(),+                    calendar_dates: None,+                    agency: agency.as_ref(),+                    shapes: shapes.as_ref(),+                })+                .unwrap();+        }+        let mut blob = Vec::new();+        builder.finish_to(&mut blob).unwrap();+        let pack = root.join("test.transit");+        std::fs::write(&pack, &blob).unwrap();++        let (from_feeds, from_pack) = (root.join("feeds.geojsonseq"), root.join("pack.geojsonseq"));+        super::super::extra2::run_with_timer(&from_feeds, super::super::extra2::Inputs::Feeds(&specs), None).unwrap();+        super::super::extra2::run_with_timer(&from_pack, super::super::extra2::Inputs::Pack(&pack), None).unwrap();+        let (a, b) = (std::fs::read_to_string(&from_feeds).unwrap(), std::fs::read_to_string(&from_pack).unwrap());+        let stored = Reader::open(&pack).unwrap().rail_lines().expect("a v7 pack");+        let _ = std::fs::remove_dir_all(&root);+        assert!(+            stored.iter().any(|l| l.points.first() == Some(&(376_999_999, -1_224_000_001)) && l.points.len() == 3),+            "every shapes.txt point, at full e7 precision"+        );+        assert_eq!(stored.len(), 4, "two shapes per feed, and no bus");+        assert!(a.contains("\"intercity\":1"), "the 200 km line is intercity");+        assert!(!a.contains("FF0000"), "no bus");+        assert_eq!(a, b, "the pack-derived layer is byte-identical");+    }++    #[test]+    fn a_v6_pack_is_refused_with_a_rebuild_hint() {+        let path = std::env::temp_dir().join(format!("transit_shapes_v6_{}.transit", std::process::id()));+        let mut blob = vec![0u8; gtfs_ingest::index::HEADER_LEN + 27 * 16];+        blob[0..4].copy_from_slice(&gtfs_ingest::index::MAGIC.to_le_bytes());+        blob[4..8].copy_from_slice(&6u32.to_le_bytes());+        blob[8..12].copy_from_slice(&27u32.to_le_bytes());+        let end = (blob.len() as u64).to_le_bytes();+        for i in 0..27 {+            let at = gtfs_ingest::index::HEADER_LEN + i * 16;+            blob[at..at + 8].copy_from_slice(&end);+        }+        std::fs::write(&path, &blob).unwrap();+        let err = pack_lines(&path).err().expect("refused");+        let _ = std::fs::remove_file(&path);+        assert!(err.contains("rebuild"), "{err}");+    }+}
scripts/maps/gtfs_ingest/src/bin/transit_stops.rs
diff --git a/scripts/maps/gtfs_ingest/src/bin/transit_stops.rs b/scripts/maps/gtfs_ingest/src/bin/transit_stops.rsindex 66a64597e8..eb50f6af2a 100644--- a/scripts/maps/gtfs_ingest/src/bin/transit_stops.rs+++ b/scripts/maps/gtfs_ingest/src/bin/transit_stops.rs@@ -7,7 +7,7 @@ //! //! `<feed>` is `feed_name=gtfs_dir[=motis_prefix]` or a bare `gtfs_dir`, exactly //! as `gtfs_ingest` takes them, so the same `feeds.manifest`-//! `build_world_transit.sh` writes drives both tools.+//! `build_world_transit.ps1` writes drives both tools. //! //! This replaces the per-viewport `GET /api/v1/map/stops` fetch: stops are static //! data, so they belong in the basemap rather than behind a network round-trip on
scripts/maps/gtfs_ingest/src/bundle.rs
diff --git a/scripts/maps/gtfs_ingest/src/bundle.rs b/scripts/maps/gtfs_ingest/src/bundle.rsindex a1a19d1f5b..53103feda9 100644--- a/scripts/maps/gtfs_ingest/src/bundle.rs+++ b/scripts/maps/gtfs_ingest/src/bundle.rs@@ -82,9 +82,8 @@ use std::sync::Mutex; /// Two polylines closer than this everywhere are the same line, and two tracks closer than /// this are one corridor. ///-/// Inside the band `shapes.rs` already establishes: well above `SIMPLIFY_TOLERANCE_M`-/// (2.5 m), which is below the disagreement between two agencies' surveys of one track, and-/// well below `MAX_STOP_OFFSET_M` (150 m), which is a shape belonging to another pattern.+/// Well above the few metres two agencies' surveys of one track disagree by, and well below+/// `shapes.rs`' `MAX_STOP_OFFSET_M` (150 m), which is a shape belonging to another pattern. pub const CORRIDOR_M: f64 = 30.0;  /// How close a member's own survey has to come to the reference before it stops drawing its
scripts/maps/gtfs_ingest/src/index.rs
diff --git a/scripts/maps/gtfs_ingest/src/index.rs b/scripts/maps/gtfs_ingest/src/index.rsindex decdc78ced..3033ab22dc 100644--- a/scripts/maps/gtfs_ingest/src/index.rs+++ b/scripts/maps/gtfs_ingest/src/index.rs@@ -42,7 +42,7 @@ //!     one pack without id collisions (ids are namespaced per feed at build). //! //! Header (80 bytes; all u32/i32 little-endian):-//!   u32 magic (MAGIC), u32 version (VERSION=6), u32 section_count,+//!   u32 magic (MAGIC), u32 version (VERSION=7), u32 section_count, //!   u32 stop_count, u32 route_count, u32 trip_count, u32 service_count, //!   u32 profile_count, u32 feed_count, u32 grid_cell_count, u32 feed_name_off, //!   i32 min_lat_e7, i32 min_lon_e7, i32 max_lat_e7, i32 max_lon_e7,@@ -135,6 +135,11 @@ //!                        ROUTE_TRIP_RECS[off[i]..off[i+1]]. Disagreeing with //!                        RouteRec.n_trips makes the reader fall back to the //!                        varint stream rather than index past the table.+//!  27  RAIL_LINES      v7. Host-only: every whole, unsimplified rail shape the+//!                        basemap's transit layer is drawn from, so `transit_shapes`+//!                        can rebuild it from the pack alone. Written last and+//!                        dropped from the app archive by `mamaps_pack`. See+//!                        [`RailLines`].  use crate::gtfs; use crate::gtfs::{parse_gtfs_date, Csv, Shape};@@ -144,12 +149,14 @@ use std::io::Write; use std::path::Path;  pub const MAGIC: u32 = 0x5452_4958; // "TRIX"-pub const VERSION: u32 = 6;+pub const VERSION: u32 = 7; /// Oldest version the device reader still accepts, mirrored from /// `maps/src/main/rust/src/transit.rs` so the host reader agrees on the range. pub const VERSION_MIN: u32 = 3; pub const NONE: u32 = 0xFFFF_FFFF;-pub const SECTION_COUNT: usize = 27;+pub const SECTION_COUNT: usize = 28;+/// Sections in a v6 pack, which has no RAIL_LINES. The host reader still opens one.+pub const SECTION_COUNT_V6: usize = 27; pub const HEADER_LEN: usize = 80;  const MAX_TRANSFER_M: f64 = 400.0;@@ -442,4 +449,5 @@ include!("index_part2.rs"); include!("index_part3.rs"); include!("index_part4.rs"); include!("index_part5.rs");-include!("index_part6.rs");\ No newline at end of file+include!("index_part6.rs");+include!("index_part7.rs");\ No newline at end of file
scripts/maps/gtfs_ingest/src/index_part1.rs
diff --git a/scripts/maps/gtfs_ingest/src/index_part1.rs b/scripts/maps/gtfs_ingest/src/index_part1.rsindex 6639354153..188fd5f11b 100644--- a/scripts/maps/gtfs_ingest/src/index_part1.rs+++ b/scripts/maps/gtfs_ingest/src/index_part1.rs@@ -184,6 +184,7 @@ pub struct IndexBuilder {     sec_stop_route_pos: Vec<u8>,     profiles: ProfileTable,     shape_blobs: ShapeBlobs,+    rail_lines: RailLines,     /// Running STOP_ROUTES entry count, i.e. the next STOP_ROUTES_IDX value.     stop_routes_total: u32, 
scripts/maps/gtfs_ingest/src/index_part2.rs
diff --git a/scripts/maps/gtfs_ingest/src/index_part2.rs b/scripts/maps/gtfs_ingest/src/index_part2.rsindex 6e18f6e335..cfabdb4a23 100644--- a/scripts/maps/gtfs_ingest/src/index_part2.rs+++ b/scripts/maps/gtfs_ingest/src/index_part2.rs@@ -35,6 +35,7 @@ impl IndexBuilder {             sec_stop_route_pos: Vec::new(),             profiles: ProfileTable::new(),             shape_blobs: ShapeBlobs::new(),+            rail_lines: RailLines::new(),             stop_routes_total: 0,             route_count: 0,             trip_total: 0,@@ -372,6 +373,7 @@ impl IndexBuilder {         }          self.finalize_feed(&raptor_routes, &built_trips, &shapes, feed_stop_start)?;+        self.rail_lines.add_feed(feed_idx, feed)?;          // A feed's services are allocated contiguously while it is being added,         // and its exceptions only ever reference them, so sorting this feed's
scripts/maps/gtfs_ingest/src/index_part3.rs
diff --git a/scripts/maps/gtfs_ingest/src/index_part3.rs b/scripts/maps/gtfs_ingest/src/index_part3.rsindex 524a236bb4..98ed8bda25 100644--- a/scripts/maps/gtfs_ingest/src/index_part3.rs+++ b/scripts/maps/gtfs_ingest/src/index_part3.rs@@ -183,6 +183,7 @@ impl IndexBuilder {             sec_stop_route_pos,             profiles,             shape_blobs,+            rail_lines,             stop_routes_total,             route_count,             trip_total,@@ -404,10 +405,12 @@ impl IndexBuilder {             "STOP_GTFS_ID",             "ROUTE_TRIP_RECS",             "ROUTE_TRIP_OFF",+            "RAIL_LINES",         ];         // Close the CSR prefix: one past the last route's trips, i.e. the total. Done         // here because it is only known once every feed's routes have been written.         append_u32(&mut sec_route_trip_off, trip_total as u32);+        let sec_rail_lines = rail_lines.into_section();         let sections: [&[u8]; SECTION_COUNT] = [             &pool.bytes,             &sec_stops,@@ -436,6 +439,7 @@ impl IndexBuilder {             &sec_stop_gtfs_id,             &sec_route_trip_recs,             &sec_route_trip_off,+            &sec_rail_lines,         ];          let dir_len = SECTION_COUNT * 16;
scripts/maps/gtfs_ingest/src/index_part5.rs
diff --git a/scripts/maps/gtfs_ingest/src/index_part5.rs b/scripts/maps/gtfs_ingest/src/index_part5.rsindex fe8a0d38f8..ed62e9b074 100644--- a/scripts/maps/gtfs_ingest/src/index_part5.rs+++ b/scripts/maps/gtfs_ingest/src/index_part5.rs@@ -407,10 +407,10 @@ mod tests {                 "vertex {v} at {vlat},{vlon} is not stop {stop} at {slat},{slon}"             );         }-        // The detour survives simplification, so the drawn ride is not straight.+        // The detour is kept, so the drawn ride is not straight.         assert!(             pts.iter().any(|&(_, lon)| lon > -1_223_950_000),-            "the eastward detour was simplified away: {pts:?}"+            "the eastward detour was dropped: {pts:?}"         );     } 
scripts/maps/gtfs_ingest/src/index_part7.rs
diff --git a/scripts/maps/gtfs_ingest/src/index_part7.rs b/scripts/maps/gtfs_ingest/src/index_part7.rsnew file mode 100644index 0000000000..9dbfbfff70--- /dev/null+++ b/scripts/maps/gtfs_ingest/src/index_part7.rs@@ -0,0 +1,67 @@+/// The RAIL_LINES section: every line the basemap's rail layer draws, as `transit_shapes` reads it+/// out of the raw feeds, so that layer can be rebuilt from the pack alone.+///+/// Host-only. The device never reads it, and `mamaps_pack` writes it out of the app archive, so+/// it is self-contained (its own strings and blobs) rather than adding to STRINGS or SHAPE_COORDS,+/// which ship. Layout:+///+/// ```text+/// u32 line_count+/// line_count x { u32 feed_idx, route_type, color (0 = none), name_off, route_id_off, blob_off }+/// u32 strings_len, strings (NUL-terminated; offsets above index it, NONE = empty)+/// blobs (shapes::encode, deduplicated; blob_off indexes from here)+/// ```+///+/// Lines are in feed order, then route_id, then shape_id ascending: the order the raw path builds+/// them in, which is what its order-dependent dedup needs to reach the same output.+struct RailLines {+    records: Vec<u8>,+    count: u32,+    pool: StringPool,+    blobs: ShapeBlobs,+}++pub const RAIL_LINE_REC_BYTES: usize = 24;++impl RailLines {+    fn new() -> RailLines {+        RailLines { records: Vec::new(), count: 0, pool: StringPool::new(), blobs: ShapeBlobs::new() }+    }++    /// Every whole, unsimplified shape of every rail route in one feed.+    fn add_feed(&mut self, feed_idx: u32, feed: &FeedView) -> Result<(), String> {+        let Some(shapes) = feed.shapes else { return Ok(()) };+        let rail = crate::rail::rail_routes(feed.routes);+        for (route_id, shape_ids) in &crate::rail::shape_ids_by_route(feed.trips, &rail) {+            let (_, color, fallback, name, route_type) = &rail[route_id.as_str()];+            let raw_color = if *fallback { 0 } else { *color };+            for shape_id in shape_ids {+                let Some(shape) = shapes.get(shape_id.as_str()) else { continue };+                if shape.lat_e7.len() < 2 {+                    continue;+                }+                let points: Vec<(i32, i32)> =+                    shape.lat_e7.iter().zip(&shape.lon_e7).map(|(&lat, &lon)| (lat, lon)).collect();+                let blob_off = self.blobs.intern(&shapes::encode(&points))?;+                for v in [feed_idx, *route_type, raw_color, self.pool.intern(name), self.pool.intern(route_id), blob_off] {+                    append_u32(&mut self.records, v);+                }+                self.count += 1;+            }+        }+        if self.pool.overflowed {+            return Err("RAIL_LINES strings passed 4 GiB".to_string());+        }+        Ok(())+    }++    fn into_section(self) -> Vec<u8> {+        let mut out = Vec::with_capacity(8 + self.records.len() + self.pool.bytes.len() + self.blobs.bytes.len());+        append_u32(&mut out, self.count);+        out.extend_from_slice(&self.records);+        append_u32(&mut out, self.pool.bytes.len() as u32);+        out.extend_from_slice(&self.pool.bytes);+        out.extend_from_slice(&self.blobs.bytes);+        out+    }+}
scripts/maps/gtfs_ingest/src/lib.rs
diff --git a/scripts/maps/gtfs_ingest/src/lib.rs b/scripts/maps/gtfs_ingest/src/lib.rsindex 6f81a515e5..e21a326ad7 100644--- a/scripts/maps/gtfs_ingest/src/lib.rs+++ b/scripts/maps/gtfs_ingest/src/lib.rs@@ -18,6 +18,7 @@ pub mod index; pub mod json; pub mod manifest; pub mod par;+pub mod rail; pub mod reader; pub mod reader_extra; pub mod registry;
scripts/maps/gtfs_ingest/src/main.rs
diff --git a/scripts/maps/gtfs_ingest/src/main.rs b/scripts/maps/gtfs_ingest/src/main.rsindex 4382eb8d9e..fca77476f1 100644--- a/scripts/maps/gtfs_ingest/src/main.rs+++ b/scripts/maps/gtfs_ingest/src/main.rs@@ -28,7 +28,7 @@ //! GTFS feeds are sourced from the Transitous feed registry //! (github.com/public-transport/transitous, `feeds/*.json`), which points at //! each agency's official GTFS `.zip` — the same open data behind the P10-//! online boards. See `scripts/maps/build_world_transit.sh`.+//! online boards. See `scripts/maps/build_world_transit.ps1`.  use gtfs_ingest::gtfs; use gtfs_ingest::index;
scripts/maps/gtfs_ingest/src/manifest.rs
diff --git a/scripts/maps/gtfs_ingest/src/manifest.rs b/scripts/maps/gtfs_ingest/src/manifest.rsindex a2103b1fd8..efe120b676 100644--- a/scripts/maps/gtfs_ingest/src/manifest.rs+++ b/scripts/maps/gtfs_ingest/src/manifest.rs@@ -15,7 +15,7 @@ pub type FeedSpec = (String, PathBuf, String); /// /// The third field is the feed's Transitous id namespace, which composes into a /// MOTIS stop id (`<prefix>_<gtfs stop_id>`). Two-field specs stay valid, so-/// `build_world_transit.sh` is unaffected and its packs simply carry no ids.+/// `build_world_transit.ps1` is unaffected and its packs simply carry no ids. /// Fields split on `=`, so neither the directory nor the prefix may contain one. pub fn parse_feed_spec(s: &str) -> FeedSpec {     let mut parts = s.splitn(3, '=');@@ -57,7 +57,7 @@ mod tests {      #[test]     fn a_two_field_spec_carries_no_motis_prefix() {-        // build_world_transit.sh emits these; its packs must keep building.+        // build_world_transit.ps1 emits these; its packs must keep building.         let (name, dir, prefix) = parse_feed_spec("sfmuni=/tmp/gtfs/sfmuni");         assert_eq!(name, "sfmuni");         assert_eq!(dir, PathBuf::from("/tmp/gtfs/sfmuni"));
scripts/maps/gtfs_ingest/src/rail.rs
diff --git a/scripts/maps/gtfs_ingest/src/rail.rs b/scripts/maps/gtfs_ingest/src/rail.rsnew file mode 100644index 0000000000..0750c109ed--- /dev/null+++ b/scripts/maps/gtfs_ingest/src/rail.rs@@ -0,0 +1,120 @@+//! Which GTFS routes and shapes the basemap's rail-line layer is drawn from.+//!+//! Shared by `transit_shapes`, which reads them out of raw feeds, and the pack builder, which+//! stores exactly those shapes in `world.transit`'s RAIL_LINES section so the layer can be+//! rebuilt from the pack alone. One definition, so the two cannot drift apart.++use crate::gtfs::Csv;+use std::collections::{BTreeMap, BTreeSet, HashMap};++/// One rail route: `(mode, colour, is a fallback colour, display name, route_type)`.+pub type RailRoute = (&'static str, u32, bool, String, u32);++/// GTFS `route_type` → the basemap's mode vocabulary, or `None` for a mode this+/// layer does not carry (bus, ferry, trolleybus, aerial lift, ...).+///+/// The extended ranges are here because European feeds use them almost+/// exclusively: a feed publishing its metro as 402 rather than 1 would otherwise+/// contribute nothing at all.+pub fn mode_of(route_type: u32) -> Option<&'static str> {+    Some(match route_type {+        // GTFS 0 is "tram, streetcar, light rail" in one value. `light_rail`+        // rather than `tram` because that is what North American agencies put+        // there — Muni Metro, MAX, Link — and its zoom floor is the shallower of+        // the two, so a street tram filed under 0 surfaces one zoom early rather+        // than a light rail line vanishing until z13.+        0 => "light_rail",+        1 => "subway",+        2 => "train",+        // Cable tram and funicular: short, street-level, and the tram zoom floor.+        5 | 7 => "tram",+        12 => "monorail",+        100..=117 => "train",+        400..=404 => "subway",+        405 => "monorail",+        900..=906 => "tram",+        _ => return None,+    })+}++/// The fallback line colour per mode, as `0xRRGGBB`, for a route naming none.+///+/// **A matched pair with `mamaps_build`'s `schema::transit::MODES`**: the five+/// names above and the five colours here are that table, duplicated because this+/// crate is deliberately detached from the Android workspace and has no+/// dependencies, so the two cannot share code. A change to either is a change to+/// both.+pub fn fallback_color(mode: &str) -> u32 {+    match mode {+        "subway" => 0xE4002B,+        "light_rail" => 0x00985F,+        "tram" => 0xFFD200,+        "train" => 0x0057A8,+        "monorail" => 0x9D9D9D,+        _ => 0x666666,+    }+}++/// A `route_color` cell as `0xRRGGBB`, or `None` to fall back per mode.+///+/// GTFS spells it as bare `RRGGBB`; a leading `#` is accepted because feeds put+/// one there anyway. Zero is refused rather than emitted: it means "no colour" on+/// the wire, so a route that really is black takes its mode's colour instead.+pub fn route_color(raw: &str) -> Option<u32> {+    let hex = raw.trim();+    let hex = hex.strip_prefix('#').unwrap_or(hex);+    if hex.len() != 6 || !hex.chars().all(|c| c.is_ascii_hexdigit()) {+        return None;+    }+    let value = u32::from_str_radix(hex, 16).ok()?;+    (value != 0).then_some(value)+}++/// `route_id` → [`RailRoute`] for every rail route in the feed. Everything else, bus+/// included, is dropped here.+pub fn rail_routes(routes: &Csv) -> HashMap<String, RailRoute> {+    let mut out = HashMap::new();+    for row in &routes.rows {+        let id = routes.get(row, "route_id");+        if id.is_empty() {+            continue;+        }+        let Ok(route_type) = routes.get(row, "route_type").trim().parse::<u32>() else { continue };+        let Some(mode) = mode_of(route_type) else { continue };+        let (color, fallback) = match route_color(routes.get(row, "route_color")) {+            Some(color) => (color, false),+            None => (fallback_color(mode), true),+        };+        let short = routes.get(row, "route_short_name").trim();+        let long = routes.get(row, "route_long_name").trim();+        let name = if short.is_empty() { long } else { short };+        out.insert(id.to_string(), (mode, color, fallback, name.to_string(), route_type));+    }+    out+}++/// The distinct `shape_id`s each rail route's trips reference.+///+/// One line per **distinct polyline**, not per trip and not per RAPTOR route+/// group: a route's trips reference many shapes (one per direction, one per+/// short-turn variant) and every trip carrying its own line would draw the same+/// alignment hundreds of times. `BTreeMap`/`BTreeSet` rather than the hashed+/// pair, because the output has to be byte-identical between runs.+pub fn shape_ids_by_route(+    trips: &Csv,+    rail: &HashMap<String, RailRoute>,+) -> BTreeMap<String, BTreeSet<String>> {+    let mut out: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();+    for row in &trips.rows {+        let route_id = trips.get(row, "route_id");+        if !rail.contains_key(route_id) {+            continue;+        }+        let shape_id = trips.get(row, "shape_id").trim();+        if shape_id.is_empty() {+            continue;+        }+        out.entry(route_id.to_string()).or_default().insert(shape_id.to_string());+    }+    out+}
scripts/maps/gtfs_ingest/src/reader.rs
diff --git a/scripts/maps/gtfs_ingest/src/reader.rs b/scripts/maps/gtfs_ingest/src/reader.rsindex a000c63326..34bf7c3b4b 100644--- a/scripts/maps/gtfs_ingest/src/reader.rs+++ b/scripts/maps/gtfs_ingest/src/reader.rs@@ -9,7 +9,7 @@ //! //! Used by `index`'s tests and by `src/bin/transit_dump.rs`. -use crate::index::{HEADER_LEN, MAGIC, NONE, SECTION_COUNT, VERSION, VERSION_MIN};+use crate::index::{HEADER_LEN, MAGIC, NONE, SECTION_COUNT, SECTION_COUNT_V6, VERSION, VERSION_MIN};  // Section slot numbers. Slot `i` must describe section `i`; the device reader // hardcodes the same numbers.@@ -40,6 +40,7 @@ pub const SEC_FEED_MOTIS_PREFIX: usize = 23; pub const SEC_STOP_GTFS_ID: usize = 24; pub const SEC_ROUTE_TRIP_RECS: usize = 25; pub const SEC_ROUTE_TRIP_OFF: usize = 26;+pub const SEC_RAIL_LINES: usize = 27;  /// Bytes per v6 trip record: `u32 start_time, profile_id, service_idx, headsign_off`. pub const TRIP_REC_BYTES: usize = 16;@@ -108,7 +109,7 @@ impl Reader {             return Err(format!("version {version} outside {VERSION_MIN}..={VERSION}"));         }         let count = ru32(&buf, 8) as usize;-        if count != SECTION_COUNT {+        if count != SECTION_COUNT && count != SECTION_COUNT_V6 {             return Err(format!("section_count {count}, expected {SECTION_COUNT}"));         }         if buf.len() < HEADER_LEN + count * 16 {
scripts/maps/gtfs_ingest/src/reader_extra.rs
diff --git a/scripts/maps/gtfs_ingest/src/reader_extra.rs b/scripts/maps/gtfs_ingest/src/reader_extra.rsindex 8aa7f3c280..d314233060 100644--- a/scripts/maps/gtfs_ingest/src/reader_extra.rs+++ b/scripts/maps/gtfs_ingest/src/reader_extra.rs@@ -29,3 +29,68 @@ pub fn read_uvarint(b: &[u8], pos: &mut usize) -> u64 { pub(crate) fn zigzag(u: u64) -> i64 {     ((u >> 1) as i64) ^ -((u & 1) as i64) }++/// One RAIL_LINES entry: a whole, unsimplified rail shape and the route it draws for.+pub struct RailLineRec {+    pub feed_idx: u32,+    pub route_type: u32,+    /// The feed's own `route_color`, or 0 when it gave none.+    pub color: u32,+    pub name: String,+    pub route_id: String,+    /// `(lat_e7, lon_e7)`, every `shapes.txt` point in sequence order.+    pub points: Vec<(i32, i32)>,+}++impl crate::reader::Reader {+    /// The v7 RAIL_LINES section, in the order it was written (feed, route_id, shape_id).+    /// `None` for a v6 pack, which predates it. Panics on a malformed section: the pack is a+    /// build input written by this crate, not untrusted data.+    pub fn rail_lines(&self) -> Option<Vec<RailLineRec>> {+        use crate::index::{NONE, RAIL_LINE_REC_BYTES};+        if self.section_count() as usize <= crate::reader::SEC_RAIL_LINES {+            return None;+        }+        let s = self.sec_bytes(crate::reader::SEC_RAIL_LINES);+        let count = ru32(s, 0) as usize;+        let recs = 4;+        let strings_at = recs + count * RAIL_LINE_REC_BYTES;+        let strings_len = ru32(s, strings_at) as usize;+        let strings = &s[strings_at + 4..strings_at + 4 + strings_len];+        let blobs = &s[strings_at + 4 + strings_len..];+        let text = |off: u32| -> String {+            if off == NONE {+                return String::new();+            }+            let tail = &strings[off as usize..];+            let end = tail.iter().position(|&b| b == 0).unwrap_or(tail.len());+            String::from_utf8_lossy(&tail[..end]).into_owned()+        };+        let out = (0..count)+            .map(|i| {+                let at = recs + i * RAIL_LINE_REC_BYTES;+                let field = |k: usize| ru32(s, at + k * 4);+                let mut pos = field(5) as usize;+                let n = ru32(blobs, pos) as usize;+                pos += 4;+                let (mut lat, mut lon) = (0i64, 0i64);+                let points = (0..n)+                    .map(|_| {+                        lat += zigzag(read_uvarint(blobs, &mut pos));+                        lon += zigzag(read_uvarint(blobs, &mut pos));+                        (lat as i32, lon as i32)+                    })+                    .collect();+                RailLineRec {+                    feed_idx: field(0),+                    route_type: field(1),+                    color: field(2),+                    name: text(field(3)),+                    route_id: text(field(4)),+                    points,+                }+            })+            .collect();+        Some(out)+    }+}
scripts/maps/gtfs_ingest/src/shapes.rs
diff --git a/scripts/maps/gtfs_ingest/src/shapes.rs b/scripts/maps/gtfs_ingest/src/shapes.rsindex 05fe703fe6..8335501380 100644--- a/scripts/maps/gtfs_ingest/src/shapes.rs+++ b/scripts/maps/gtfs_ingest/src/shapes.rs@@ -6,15 +6,16 @@ //! a polyline plus one vertex index per pattern stop, and those indices must be //! non-decreasing or the slice is meaningless. //!-//! Three things make that work:+//! Two things make that work: //!   * each stop's projection onto the shape is **inserted as a vertex**, so a //!     boarded span begins and ends exactly at its stop rather than at whichever //!     shape point happened to be nearest;-//!   * simplification runs on the spans *between* those pinned vertices, so it-//!     can never move or drop one; //!   * the shape is trimmed to `[first stop, last stop]`, dropping the deadhead //!     prologue/epilogue no ride leg can reach. //!+//! Every `shapes.txt` point in between is kept: the pack is the build's source of+//! truth for transit geometry, so it is stored at full resolution.+//! //! `shape_dist_traveled` is used only to *order* — to pick which segment a stop //! belongs to, which is what disambiguates a loop route that passes a stop //! twice. Its units are feed-defined (km, mi, ft, ...) and are never read as@@ -22,8 +23,7 @@  use crate::gtfs::Shape; -/// Douglas-Peucker tolerance. The lever on pack size: shapes dominate a v4 pack.-const SIMPLIFY_TOLERANCE_M: f64 = 2.5;+/// How far a stop may sit /// How far a stop may sit from the shape before the fit is rejected. A genuine /// mismatch (shape belonging to another pattern, swapped lat/lon) blows past /// this; ordinary stop-to-kerb offsets do not.@@ -105,31 +105,6 @@ pub fn resample(points: &[(i32, i32)], step_m: f64) -> Vec<(i32, i32)> {     out } -/// Douglas-Peucker over `pts[lo..=hi]`, pushing the *interior* indices to keep.-/// Iterative: a world feed's shapes are long enough that recursion is a risk.-fn simplify_span(pts: &[(i32, i32)], lo: usize, hi: usize, keep: &mut Vec<usize>) {-    let mut stack = vec![(lo, hi)];-    while let Some((a, b)) = stack.pop() {-        if b <= a + 1 {-            continue;-        }-        let mut worst = 0.0;-        let mut worst_i = a;-        for i in (a + 1)..b {-            let (_, d) = project(pts[i], pts[a], pts[b], 0.0);-            if d > worst {-                worst = d;-                worst_i = i;-            }-        }-        if worst > SIMPLIFY_TOLERANCE_M {-            keep.push(worst_i);-            stack.push((a, worst_i));-            stack.push((worst_i, b));-        }-    }-}- fn non_decreasing(v: &[f64]) -> bool {     v.windows(2).all(|w| w[1] >= w[0]) }@@ -222,17 +197,13 @@ pub fn fit(shape: &Shape, stops: &[(i32, i32)], stop_dists: Option<&[f64]>) -> O         return None;     } -    // Simplify only between pinned vertices, and trim to the boarded extent.+    // Trim to the boarded extent, keeping every point between pinned vertices.     let mut keep: Vec<usize> = vec![pinned[0]];     let mut stop_vertices: Vec<u32> = vec![0];     for w in pinned.windows(2) {         let (a, b) = (w[0], w[1]);         if b > a {-            let mut interior = Vec::new();-            simplify_span(&pts, a, b, &mut interior);-            interior.sort_unstable();-            keep.extend(interior);-            keep.push(b);+            keep.extend(a + 1..=b);         }         stop_vertices.push((keep.len() - 1) as u32);     }@@ -351,7 +322,7 @@ mod tests {         for (k, &v) in f.stop_vertices.iter().enumerate() {             assert_eq!(f.points[v as usize], stops[k]);         }-        // The detour survives simplification.+        // The detour is kept.         assert!(f.points.iter().any(|&(_, lon)| lon > -1_223_950_000));     } @@ -401,7 +372,7 @@ mod tests {     }      #[test]-    fn simplification_drops_collinear_points_but_keeps_stops() {+    fn every_shape_point_between_the_stops_is_kept() {         let mut pts = Vec::new();         for i in 0..101 {             pts.push((37.700 + i as f64 * 0.0001, -122.400));@@ -409,8 +380,8 @@ mod tests {         let s = shape(&pts, None);         let stops = [e7(37.700, -122.400), e7(37.7100, -122.400)];         let f = fit(&s, &stops, None).expect("fits");-        assert_eq!(f.points.len(), 2, "a straight run collapses to its endpoints");-        assert_eq!(f.stop_vertices, vec![0, 1]);+        assert_eq!(f.points.len(), 101, "full resolution: even a straight run keeps its points");+        assert_eq!(f.stop_vertices, vec![0, 100]);     }      #[test]
scripts/maps/tile_build/src/bin/mamaps_pack.rs
diff --git a/scripts/maps/tile_build/src/bin/mamaps_pack.rs b/scripts/maps/tile_build/src/bin/mamaps_pack.rsindex 5a2fae70b9..0a05a638c0 100644--- a/scripts/maps/tile_build/src/bin/mamaps_pack.rs+++ b/scripts/maps/tile_build/src/bin/mamaps_pack.rs@@ -52,8 +52,67 @@ fn read_file(path: &Path) -> Result<Vec<u8>, String> { struct Staged {     kind: u8,     path: PathBuf,+    /// Bytes this payload occupies in the archive.     len: u64,     extra: u64,+    /// The source file's own length, re-checked at copy time. Larger than `len` only for a+    /// transit pack whose host-only tail is left out (see [`transit_without_host_sections`]).+    file_len: u64,+    /// Bytes written in place of the source's first `head.len()`: the transit pack's header and+    /// directory with the host-only sections emptied. Empty for every other payload.+    head: Vec<u8>,+}++impl Staged {+    fn whole(kind: u8, path: PathBuf, len: u64) -> Staged {+        Staged { kind, path, len, extra: 0, file_len: len, head: Vec::new() }+    }+}++/// TRIX sections from this index on are host-only (v7 RAIL_LINES, the build's own copy of the+/// rail shapes) and never ship: the device reads none of them.+const TRANSIT_HOST_SECTIONS_FROM: usize = 27;+const TRANSIT_HEADER_LEN: usize = 80;++/// The transit pack as the archive carries it: its header and directory with every host-only+/// section set to zero length at the cut, and the file truncated there. Host-only sections are+/// written last, so everything the device reads sits before the cut. Returns `(head, len)`;+/// `head` is empty and `len` the whole file when there is nothing to leave out.+fn transit_without_host_sections(path: &Path, file_len: u64) -> Result<(Vec<u8>, u64), String> {+    let mut f = std::fs::File::open(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?;+    let mut head = vec![0u8; TRANSIT_HEADER_LEN.min(file_len as usize)];+    f.read_exact(&mut head).map_err(|e| format!("cannot read {}: {e}", path.display()))?;+    if head.len() < TRANSIT_HEADER_LEN {+        return Err(format!("{} ends before its TRIX header", path.display()));+    }+    let count = u32::from_le_bytes([head[8], head[9], head[10], head[11]]) as usize;+    if count <= TRANSIT_HOST_SECTIONS_FROM {+        return Ok((Vec::new(), file_len));+    }+    let dir_end = TRANSIT_HEADER_LEN + count * 16;+    if dir_end as u64 > file_len {+        return Err(format!("{}'s section directory runs past the file", path.display()));+    }+    head.resize(dir_end, 0);+    f.read_exact(&mut head[TRANSIT_HEADER_LEN..]).map_err(|e| format!("cannot read {}: {e}", path.display()))?;+    let entry = |head: &[u8], i: usize| {+        let at = TRANSIT_HEADER_LEN + i * 16;+        let u = |o: usize| u64::from_le_bytes(head[o..o + 8].try_into().expect("8 bytes"));+        (u(at), u(at + 8))+    };+    let cut = (TRANSIT_HOST_SECTIONS_FROM..count).map(|i| entry(&head, i).0).min().unwrap_or(file_len);+    for i in 0..TRANSIT_HOST_SECTIONS_FROM {+        let (off, len) = entry(&head, i);+        if off + len > cut {+            return Err(format!("{}: section {i} runs past the host-only sections at {cut}", path.display()));+        }+    }+    for i in TRANSIT_HOST_SECTIONS_FROM..count {+        let at = TRANSIT_HEADER_LEN + i * 16;+        head[at..at + 8].copy_from_slice(&cut.to_le_bytes());+        head[at + 8..at + 16].copy_from_slice(&0u64.to_le_bytes());+    }+    Ok((head, cut)) }  /// The few sidecars small enough to hold: graph metadata, lane index, POI descriptors, and the@@ -89,7 +148,7 @@ fn load_sidecars_impl(         match std::fs::metadata(&path) {             Ok(m) => {                 if required || m.len() > 0 {-                    staged.push(Staged { kind, path, len: m.len(), extra: 0 });+                    staged.push(Staged::whole(kind, path, m.len()));                 }                 Ok(())             }@@ -118,23 +177,26 @@ fn load_sidecars_impl(     timer.switch("read-transit");     let mut transit_prefix = Vec::new();     if let Some(t) = transit {-        let len = std::fs::metadata(t)+        let file_len = std::fs::metadata(t)             .map_err(|e| format!("cannot stat {}: {e}", t.display()))?             .len();-        staged.push(Staged { kind: ARCHIVE_KIND_TRANSIT, path: t.to_path_buf(), len, extra: 0 });-        // The build id hashes only the first 1 KiB (see `derive_build_id`).+        let (head, len) = transit_without_host_sections(t, file_len)?;+        // The build id hashes only the first 1 KiB (see `derive_build_id`), as shipped.         let mut f = std::fs::File::open(t)             .map_err(|e| format!("cannot read {}: {e}", t.display()))?;         let mut buf = vec![0u8; (len.min(1024)) as usize];         f.read_exact(&mut buf)             .map_err(|e| format!("cannot read {}: {e}", t.display()))?;+        let patched = head.len().min(buf.len());+        buf[..patched].copy_from_slice(&head[..patched]);         transit_prefix = buf;+        staged.push(Staged { kind: ARCHIVE_KIND_TRANSIT, path: t.to_path_buf(), len, extra: 0, file_len, head });     }     // The highway overlay (`road_overlay`) is optional and sorts after transit.     let overlay = graph.join("overlay.bin");     match std::fs::metadata(&overlay) {         Ok(m) if m.len() > 0 => {-            staged.push(Staged { kind: ARCHIVE_KIND_GRAPH_OVERLAY, path: overlay, len: m.len(), extra: 0 })+            staged.push(Staged::whole(ARCHIVE_KIND_GRAPH_OVERLAY, overlay, m.len()))         }         Ok(_) => {}         Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}@@ -423,22 +485,26 @@ fn pack_streaming(             .metadata()             .map_err(|e| format!("cannot stat {}: {e}", s.path.display()))?             .len();-        if src_len != s.len {+        if src_len != s.file_len {             return Err(format!(                 "{} changed under the pack (staged {} bytes, now {src_len})",                 s.path.display(),-                s.len,+                s.file_len,             ));         }-        copy_range(&mut src, 0, src_len, &mut writer, &s.path, &tmp)?;+        writer+            .write_all(&s.head)+            .map_err(|e| format!("cannot write {}: {e}", tmp.display()))?;+        let head = s.head.len() as u64;+        copy_range(&mut src, head, s.len - head, &mut writer, &s.path, &tmp)?;         entries.push(ArchiveEntry {             kind: s.kind,             flags: 0,             offset: at,-            len: src_len,+            len: s.len,             extra: s.extra,         });-        at += src_len;+        at += s.len;     }     while at % ARCHIVE_ALIGN != 0 {         writer@@ -754,6 +820,50 @@ mod tests {         out     } +    /// A v7 pack: 27 one-byte device sections, then an 8-byte host-only RAIL_LINES at the end.+    fn transit_pack_v7() -> Vec<u8> {+        let dir_end = 80 + 28 * 16;+        let mut out = vec![0u8; dir_end];+        out[0..4].copy_from_slice(&0x5452_4958u32.to_le_bytes());+        out[4..8].copy_from_slice(&7u32.to_le_bytes());+        out[8..12].copy_from_slice(&28u32.to_le_bytes());+        let mut at = dir_end as u64;+        for i in 0..28 {+            let len: u64 = if i == 27 { 8 } else { 1 };+            let e = 80 + i * 16;+            out[e..e + 8].copy_from_slice(&at.to_le_bytes());+            out[e + 8..e + 16].copy_from_slice(&len.to_le_bytes());+            at += len;+        }+        out.extend((0..27).map(|i| i as u8 + 1));+        out.extend_from_slice(b"RAILRAIL");+        out+    }++    #[test]+    fn the_host_only_rail_lines_stay_out_of_the_archive() {+        let (dir, poi) = overlay_fixture("hostonly");+        let transit_path = dir.join("world.transit");+        let source = transit_pack_v7();+        std::fs::write(&transit_path, &source).expect("fixture transit");+        let validated = load_sidecars(&dir, &poi, Some(&transit_path)).expect("stage fixtures");+        let out = dir.join("packed.mamaps");+        pack_streaming(&dir.join("tiles.mamaps"), &validated, 0xBEEF, &out).expect("pack");+        let packed = std::fs::read(&out).expect("read packed");+        let header = Header::parse(&packed).expect("packed header");+        let view = ArchiveView::parse(&packed, &header).expect("the archive validates");+        let entry = view.entries.iter().find(|e| e.kind == ARCHIVE_KIND_TRANSIT).expect("a transit entry");+        let shipped = &packed[entry.offset as usize..(entry.offset + entry.len) as usize];+        let _ = std::fs::remove_dir_all(&dir);+        assert_eq!(shipped.len(), source.len() - 8, "everything but RAIL_LINES");+        assert!(!shipped.windows(4).any(|w| w == b"RAIL"));+        let (rail_entry, data) = (80 + 27 * 16, 80 + 28 * 16);+        assert_eq!(&shipped[..rail_entry], &source[..rail_entry], "header and device entries unchanged");+        assert_eq!(&shipped[rail_entry..rail_entry + 8], &(shipped.len() as u64).to_le_bytes(), "at the cut");+        assert_eq!(&shipped[rail_entry + 8..data], &[0u8; 8], "and empty");+        assert_eq!(&shipped[data..], &source[data..source.len() - 8], "device sections byte-identical");+    }+     #[test]     fn pack_round_trips_and_rewrites_only_file_len_and_build_id() {         // Through files, like production: tiles + sidecar payloads on disk, packed by