maps: add pmtiles_extract and the base/admin reuse paths
- Commit
300a8f8d39b656f69615d1e4ec508111665d72f5- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-21 06:49 UTC (3 months ago)
- Parents
ea971d8
Diff
scripts/maps/README.md
diff --git a/scripts/maps/README.md b/scripts/maps/README.mdindex 6d7a7116aa..ba6fe1d4b3 100644--- a/scripts/maps/README.md+++ b/scripts/maps/README.md@@ -167,7 +167,7 @@ mutually consistent (same POI set, same coordinates). See | `build_all.ps1` | **Windows twin** of the above. Stages graph/pois/transit are complete; the tiles stage composites only the cargo-only layers onto a `-BaseArchive` (see [Caveats](#caveats--known-limitations)) | | `run_generator.sh` | **Deprecated** thin wrapper over `build_all.sh` (graph + pois + publish) | | `build_v5_pmtiles.sh` | Tile orchestrator: base + safety + maxspeed + transit_lines + ma_pois + admin + transit_stops → merge → `v5.pmtiles` |-| `build_base_layers.sh` | Base tiles (Planetiler build **or** reuse upstream `v4.pmtiles`) |+| `build_base_layers.sh` | Base tiles (Planetiler build **or** reuse a published archive). A `--bbox` reuse extract now uses our own `pmtiles_extract`; `--extractor go-pmtiles` is still accepted, and is the only practical way to clip the 137 GB planet base | | `build_safety_layer.sh` | **`--engine rust`** (default): `osm_ingest` `osm_extract` → geojsonseq → `tile_build` `tile_points` → `safety.pmtiles`, cargo-only. `--engine legacy`: osmium → GeoJSON → `normalize_safety.py` → tippecanoe | | `build_maxspeed_layer.sh` | **`--engine rust`** (default): `osm_extract` → geojsonseq → `tile_lines`, cargo-only. `--engine legacy`: osmium → GeoJSON → `normalize_maxspeed.py` → tippecanoe | | `build_transit_lines_layer.sh` | **`--engine rust`** (default): `osm_extract` reads railway ways **and** route relations straight from the PBF → `tile_lines`, cargo-only, **no GDAL**. `--engine legacy`: osmium + ogr2ogr → GeoJSON → `normalize_transit_lines.py` → tippecanoe |@@ -178,7 +178,7 @@ mutually consistent (same POI set, same coordinates). See | `build_transit_stops_layer.sh` | GTFS dirs → `gtfs_ingest` `transit_stops` → geojsonseq → `tile_build` `tile_points` → `transit_stops.pmtiles`. **No tippecanoe, no osmium** | | `build_transit_stops_layer.ps1` | **Windows** entry point for the same layer (cargo-only) | | `gtfs_ingest/` | Rust GTFS crate (detached): `gtfs_ingest` (the on-device `.transit` pack) and `transit_stops` (the basemap stop layer). TRX2 on-disk format documented in `src/index.rs` |-| `tile_build/` | Rust MVT + PMTiles v3 crate (detached), **replacing tippecanoe and tile-join**. Bins: `tile_points` / `tile_lines` / `tile_polygons` (one per geometry kind), `tile_join` (merge archives), `pmtiles_dump` (canonical text dump, for the differential harness). Library: `geojson` (the shared GeoJSONSeq reader), `geom` (web-mercator projection, tile ranges, quantisation), `clip` (Liang-Barsky for lines, Sutherland-Hodgman for polygons), `simplify` (Douglas-Peucker in integer tile coordinates), `pyramid` (the tile pyramid driver and the drop policy), `mvt` (line and polygon encoders beside the opaque passthrough that keeps `tile_join` lossless). Container layout documented in `src/pmtiles.rs`, the pipeline order in `src/geom.rs`, the drop policy in `src/pyramid.rs` |+| `tile_build/` | Rust MVT + PMTiles v3 crate (detached), **replacing tippecanoe, tile-join and go-pmtiles**. Bins: `tile_points` / `tile_lines` / `tile_polygons` (one per geometry kind), `tile_join` (merge archives), `pmtiles_extract` (subset by bbox, zoom and layer — the `go-pmtiles extract` replacement and the admin layer lift), `pmtiles_dump` (canonical text dump, for the differential harness). Library: `geojson` (the shared GeoJSONSeq reader), `geom` (web-mercator projection, tile ranges, quantisation), `clip` (Liang-Barsky for lines, Sutherland-Hodgman for polygons), `simplify` (Douglas-Peucker in integer tile coordinates), `pyramid` (the tile pyramid driver and the drop policy), `mvt` (line and polygon encoders beside the opaque passthrough that keeps `tile_join` lossless). Container layout documented in `src/pmtiles.rs`, the pipeline order in `src/geom.rs`, the drop policy in `src/pyramid.rs` | | `publish_r2.sh` | Upload built artifacts to Cloudflare R2 (creds from env vars only) | | `normalize_safety.py` | OSM tags → `safety` layer schema (pure stdlib, unit-tested). **Superseded** by `osm_ingest/src/safety.rs`; kept as the contract of record and as `--engine legacy` for the differential harness | | `normalize_maxspeed.py` | OSM maxspeed ways → `maxspeed` layer schema (pure stdlib, unit-tested). **Superseded** by `osm_ingest/src/maxspeed.rs`; kept as the contract of record and as `--engine legacy` |@@ -199,10 +199,34 @@ build is reproducible or cargo-only. ### 1. Planetiler cannot be ported `build_base_layers.sh --mode build` runs Java 21 plus the Protomaps basemap jar.-Nothing here replaces it, so **`--base-mode build` is the one documented Java-exception** and it fails loudly when `java` is absent rather than silently-falling back. The default is `--base-mode reuse`, which fetches a published-archive with `curl` (plus `go-pmtiles` today for a `--bbox` extract).+Nothing here replaces it and nothing is going to: it is a large Java program+*implementing* the Protomaps schema, and reimplementing it would mean owning that+schema rather than consuming it. So **`--mode build` is the one documented Java+exception** and it fails loudly with an explanation when `java` is absent, rather+than quietly becoming a reuse. The default is `--mode reuse`, which needs no JVM.++`--mode reuse` is otherwise cargo-only now. A `--bbox` extract used to shell out to+`go-pmtiles`; it uses `pmtiles_extract` by default instead. One honest caveat: our+extractor works on a **local** archive, so the whole thing has to come down first.+That is fine for a metro base and hopeless for the 137 GB planet, which is why+`--extractor go-pmtiles` remains — it range-requests only the tiles it wants.++### A cargo-only tile build++Putting the reuse paths together, a complete tile archive needs nothing but `cargo`+and `curl`:++```bash+./build_all.sh --pbf california-latest.osm.pbf \+ --base-mode reuse \+ --admin-reuse https://data.vayunmathur.com/v5.pmtiles \+ --gtfs-manifest feeds.manifest --out-dir ./build+```++`--admin-reuse` lifts `admin_country` and `admin_region` out of the published+archive with `pmtiles_extract --layer`, which is what removes the last `ogr2ogr` and+`python3` from the tile path. Those two layers change on Natural Earth's clock, not+OSM's, so carrying them forward is the correct default rather than a shortcut. ### 2. Natural Earth is a third input
scripts/maps/build_all.sh
diff --git a/scripts/maps/build_all.sh b/scripts/maps/build_all.shindex 9340487413..3f59ad4062 100644--- a/scripts/maps/build_all.sh+++ b/scripts/maps/build_all.sh@@ -51,6 +51,12 @@ set -euo pipefail # --work DIR scratch + stamps (default <out-dir>/work) # --base-archive URL published archive to reuse for the base layers # (default: build_base_layers.sh's own)+# --admin-reuse SRC carry admin_country and admin_region forward from an+# existing archive (a local .pmtiles or a URL) instead of+# rebuilding them from Natural Earth. Those two are the only+# layers that still need ogr2ogr and python3, so with this+# and --base-mode reuse the whole tile build is cargo-only+# apart from curl. # --base-mode M build|reuse (default reuse; build needs java 21 + --base-jar) # --base-jar FILE protomaps basemap jar (--base-mode build only) # --base-area A planetiler area (--base-mode build only; default planet)@@ -93,6 +99,7 @@ OUT_DIR="./build_all_out" OUT="" WORK="" BASE_ARCHIVE=""+ADMIN_REUSE="" BASE_MODE="reuse" BASE_JAR="" BASE_AREA="planet"@@ -124,6 +131,7 @@ while [[ $# -gt 0 ]]; do --out) OUT="$2"; shift 2 ;; --work) WORK="$2"; shift 2 ;; --base-archive) BASE_ARCHIVE="$2"; shift 2 ;;+ --admin-reuse) ADMIN_REUSE="$2"; shift 2 ;; --base-mode) BASE_MODE="$2"; shift 2 ;; --base-jar) BASE_JAR="$2"; shift 2 ;; --base-area) BASE_AREA="$2"; shift 2 ;;@@ -143,7 +151,7 @@ while [[ $# -gt 0 ]]; do --engine-admin) ENGINE_ADMIN="$2"; shift 2 ;; --engine-admin-city) ENGINE_ADMIN_CITY="$2"; shift 2 ;; --engine-pois) ENGINE_POIS="$2"; shift 2 ;;- -h|--help) sed -n '4,83p' "$0" | sed 's/^# \?//'; exit 0 ;;+ -h|--help) sed -n '4,89p' "$0" | sed 's/^# \?//'; exit 0 ;; *) echo "Unknown arg: $1" >&2; exit 1 ;; esac done@@ -328,6 +336,7 @@ if want_stage tiles; then V5_ARGS+=(--skip-pois --extra-layer "$POIS_TILE") fi [[ -n "$BASE_ARCHIVE" ]] && V5_ARGS+=(--base-source "$BASE_ARCHIVE")+ [[ -n "$ADMIN_REUSE" ]] && V5_ARGS+=(--admin-reuse "$ADMIN_REUSE") [[ "$BASE_MODE" == "build" ]] && V5_ARGS+=(--base-jar "$BASE_JAR" --base-area "$BASE_AREA") if [[ -f "$EFFECTIVE_GTFS_MANIFEST" ]]; then V5_ARGS+=(--gtfs-manifest "$EFFECTIVE_GTFS_MANIFEST")
scripts/maps/build_base_layers.sh
diff --git a/scripts/maps/build_base_layers.sh b/scripts/maps/build_base_layers.shindex 0ff798d8f3..10976112db 100644--- a/scripts/maps/build_base_layers.sh+++ b/scripts/maps/build_base_layers.sh@@ -19,11 +19,22 @@ set -euo pipefail # verbatim as the base. Fast; identical schema. Use when you only # want to refresh the safety/admin overlays on top of a known base. #+# PLANETILER IS THE ONE DOCUMENTED JAVA EXCEPTION in this pipeline, and it is not+# going to be ported: it is a large Java program implementing the Protomaps schema,+# and reimplementing it would mean owning that schema rather than consuming it. So+# `--mode build` requires `java` and fails loudly when it is absent, and+# `--mode reuse` is the default precisely because it needs no JVM.+#+# `--mode reuse` IS NOW CARGO-ONLY apart from curl. A `--bbox` extract used to shell+# out to `go-pmtiles`; it now uses tile_build's own `pmtiles_extract`. The go tool is+# still accepted with `--extractor go-pmtiles` for comparison, but nothing needs it.+# # Usage: # ./build_base_layers.sh --mode build --area planet --out base.pmtiles \ # --jar protomaps-basemap-HEAD-with-deps.jar # ./build_base_layers.sh --mode build --area california --out base.pmtiles --jar ... # ./build_base_layers.sh --mode reuse --out base.pmtiles+# ./build_base_layers.sh --mode reuse --bbox -122.6,37.2,-121.7,37.9 --out base.pmtiles # # Options: # --mode build|reuse (default: reuse)@@ -31,17 +42,24 @@ set -euo pipefail # --area NAME|FILE Planetiler --area (a geofabrik name like "california", # "planet", or a path to a .osm.pbf). build mode only. # --jar FILE Protomaps basemap planetiler jar. build mode only.-# --source URL upstream base for reuse mode+# --source URL upstream base for reuse mode # (default https://data.vayunmathur.com/v4.pmtiles — the # app's own hosted base; demo-bucket.protomaps.com is dead/404) # --bbox BOX optional metro bbox for a small build/extract dry run+# --extractor E rust|go-pmtiles for a --bbox reuse extract (default rust).+# `rust` downloads the archive and subsets it locally, so it+# needs the disk and RAM for the whole thing; `go-pmtiles`+# range-requests only the tiles it wants, which is the only+# practical way to clip the 137 GB planet base. +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" MODE="reuse" OUT="base.pmtiles" AREA="planet" JAR="" SOURCE_URL="https://data.vayunmathur.com/v4.pmtiles" BBOX=""+EXTRACTOR="rust" while [[ $# -gt 0 ]]; do case "$1" in@@ -51,14 +69,29 @@ while [[ $# -gt 0 ]]; do --jar) JAR="$2"; shift 2 ;; --source) SOURCE_URL="$2"; shift 2 ;; --bbox) BBOX="$2"; shift 2 ;;- -h|--help) sed -n '4,40p' "$0" | sed 's/^# \?//'; exit 0 ;;+ --extractor) EXTRACTOR="$2"; shift 2 ;;+ -h|--help) sed -n '4,53p' "$0" | sed 's/^# \?//'; exit 0 ;; *) echo "Unknown arg: $1" >&2; exit 1 ;; esac done +case "$EXTRACTOR" in+ rust|go-pmtiles) : ;;+ *) echo "ERROR: --extractor must be rust|go-pmtiles (got '$EXTRACTOR')" >&2; exit 1 ;;+esac+ case "$MODE" in build)- command -v java >/dev/null || { echo "ERROR: java (21+) required for build mode" >&2; exit 1; }+ # The one documented Java dependency in this pipeline. Loud, not silent: a+ # missing JVM must not quietly become a reuse.+ command -v java >/dev/null || {+ echo "ERROR: java (21+) is required for --mode build." >&2+ echo " Planetiler is the one part of this pipeline that is NOT ported to" >&2+ echo " Rust and is not going to be -- it implements the Protomaps schema," >&2+ echo " and reimplementing it would mean owning that schema." >&2+ echo " Use --mode reuse (the default), which needs no JVM." >&2+ exit 1+ } [[ -n "$JAR" && -f "$JAR" ]] || { echo "ERROR: --jar protomaps basemap jar required for build mode." >&2 echo " Build it once:" >&2@@ -75,14 +108,33 @@ case "$MODE" in java -Xmx${JAVA_XMX:-8g} -jar "$JAR" "${ARGS[@]}" ;; reuse)- command -v pmtiles >/dev/null || echo "[base] note: install go-pmtiles for --bbox reuse extracts"- if [[ -n "$BBOX" ]]; then- command -v pmtiles >/dev/null || { echo "ERROR: pmtiles CLI required for --bbox reuse" >&2; exit 1; }- echo "[base] reuse+extract $SOURCE_URL bbox=$BBOX -> $OUT"- pmtiles extract "$SOURCE_URL" "$OUT" --bbox="$BBOX"- else+ if [[ -z "$BBOX" ]]; then echo "[base] downloading upstream base $SOURCE_URL -> $OUT (137 GB for planet!)" curl -fL --retry 3 -o "$OUT" "$SOURCE_URL"+ elif [[ "$EXTRACTOR" == "go-pmtiles" ]]; then+ command -v pmtiles >/dev/null || { echo "ERROR: --extractor go-pmtiles needs the pmtiles CLI" >&2; exit 1; }+ echo "[base] reuse+extract (go-pmtiles, range requests) $SOURCE_URL bbox=$BBOX -> $OUT"+ pmtiles extract "$SOURCE_URL" "$OUT" --bbox="$BBOX"+ else+ command -v cargo >/dev/null || { echo "ERROR: cargo not installed (https://rustup.rs)" >&2; exit 1; }+ # Our own extractor works on a LOCAL archive, so the whole thing has to come+ # down first. That is fine for a metro-sized base and hopeless for the 137 GB+ # planet -- say so rather than letting someone discover it after an hour.+ SRC="$SOURCE_URL"+ if [[ "$SOURCE_URL" == http://* || "$SOURCE_URL" == https://* ]]; then+ SRC="$OUT.source"+ if [[ -f "$SRC" ]]; then+ echo "[base] reusing already-downloaded $SRC"+ else+ echo "[base] downloading $SOURCE_URL -> $SRC (the whole archive; see" >&2+ echo " --extractor go-pmtiles if that is the 137 GB planet base)" >&2+ curl -fL --retry 3 -o "$SRC.partial" "$SOURCE_URL"+ mv "$SRC.partial" "$SRC"+ fi+ fi+ echo "[base] reuse+extract (pmtiles_extract) bbox=$BBOX -> $OUT"+ cargo run --release --quiet --manifest-path "$HERE/tile_build/Cargo.toml" \+ --bin pmtiles_extract -- "$SRC" --out "$OUT" --bbox "$BBOX" fi ;; *) echo "ERROR: --mode must be build or reuse" >&2; exit 1 ;;
scripts/maps/build_v5_pmtiles.sh
diff --git a/scripts/maps/build_v5_pmtiles.sh b/scripts/maps/build_v5_pmtiles.shindex 883053a1e4..5bf453977c 100644--- a/scripts/maps/build_v5_pmtiles.sh+++ b/scripts/maps/build_v5_pmtiles.sh@@ -66,6 +66,12 @@ set -euo pipefail # --engine-admin E a silent no-op, so a rollback is always one flag. # --engine-admin-city E `admin-country`/`admin-region` come from Natural # Earth and will never have a rust engine.+# --admin-reuse SRC Carry admin_country and admin_region forward from an existing+# archive (a local .pmtiles or a URL) with pmtiles_extract,+# instead of rebuilding them from Natural Earth. Those two are+# the only layers that still need ogr2ogr and python3, so with+# this and --base-mode reuse the whole tile build is cargo-only+# apart from curl. # --dry-run print each step's command instead of running it # --skip-base don't (re)build base; expects <workdir>/base.pmtiles present # --skip-safety omit safety layer@@ -100,6 +106,7 @@ ENGINE_MAXSPEED="rust" ENGINE_TRANSIT_LINES="rust" ENGINE_ADMIN="legacy" ENGINE_ADMIN_CITY="rust"+ADMIN_REUSE="" DRY_RUN=0 SKIP_BASE=0 SKIP_SAFETY=0@@ -130,6 +137,7 @@ while [[ $# -gt 0 ]]; do --engine-transit-lines) ENGINE_TRANSIT_LINES="$2"; shift 2 ;; --engine-admin) ENGINE_ADMIN="$2"; shift 2 ;; --engine-admin-city) ENGINE_ADMIN_CITY="$2"; shift 2 ;;+ --admin-reuse) ADMIN_REUSE="$2"; shift 2 ;; --dry-run) DRY_RUN=1; shift ;; --skip-base) SKIP_BASE=1; shift ;; --skip-safety) SKIP_SAFETY=1; shift ;;@@ -142,7 +150,7 @@ while [[ $# -gt 0 ]]; do --keep-work) KEEP_WORK=1; shift ;; --publish) PUBLISH=1; shift ;; --publish-key) PUBLISH_KEY="$2"; shift 2 ;;- -h|--help) sed -n '4,85p' "$0" | sed 's/^# \?//'; exit 0 ;;+ -h|--help) sed -n '4,91p' "$0" | sed 's/^# \?//'; exit 0 ;; *) echo "Unknown arg: $1" >&2; exit 1 ;; esac done@@ -245,10 +253,36 @@ if [[ "$SKIP_ADMIN" == "0" ]]; then [[ -n "$PBF" ]] && ADMIN_ARGS+=(--pbf "$PBF") [[ -n "$BBOX" ]] && ADMIN_ARGS+=(--bbox "$BBOX") [[ -z "$PBF" ]] && ADMIN_ARGS+=(--no-city)+ # With --admin-reuse, the Natural Earth levels are lifted out of an existing+ # archive rather than rebuilt, so build_admin_layers.sh only has to do the one+ # level OSM can supply -- and therefore needs no ogr2ogr, tippecanoe or python3.+ [[ -n "$ADMIN_REUSE" ]] && ADMIN_ARGS+=(--only-city) run "$HERE/build_admin_layers.sh" "${ADMIN_ARGS[@]}" for l in admin_country admin_region admin_city; do [[ -f "$WORK/admin/$l.pmtiles" ]] && INPUTS+=("$WORK/admin/$l.pmtiles") done++ if [[ -n "$ADMIN_REUSE" ]]; then+ SRC="$ADMIN_REUSE"+ if [[ "$ADMIN_REUSE" == http://* || "$ADMIN_REUSE" == https://* ]]; then+ SRC="$WORK/admin/reuse_source.pmtiles"+ mkdir -p "$WORK/admin"+ if [[ -f "$SRC" ]]; then+ echo "[v5] reusing already-downloaded $SRC"+ else+ echo "[v5] downloading $ADMIN_REUSE for the admin lift"+ run curl -fL --retry 3 -o "$SRC.partial" "$ADMIN_REUSE"+ run mv "$SRC.partial" "$SRC"+ fi+ fi+ echo "[v5] lifting admin_country + admin_region out of $SRC"+ # One archive holding both, so the merge gains one input rather than two.+ run cargo run --release --quiet --manifest-path "$HERE/tile_build/Cargo.toml" \+ --bin pmtiles_extract -- "$SRC" \+ --out "$WORK/admin/admin_reused.pmtiles" \+ --layer admin_country --layer admin_region+ INPUTS+=("$WORK/admin/admin_reused.pmtiles")+ fi fi # --- 7. transit_stops (GTFS stop pins; cargo-only, takes GTFS dirs not --pbf) ---
scripts/maps/tile_build/Cargo.toml
diff --git a/scripts/maps/tile_build/Cargo.toml b/scripts/maps/tile_build/Cargo.tomlindex 7a3a994aa4..c3e133533f 100644--- a/scripts/maps/tile_build/Cargo.toml+++ b/scripts/maps/tile_build/Cargo.toml@@ -40,6 +40,9 @@ path = "src/bin/tile_join.rs" [[bin]] name = "pmtiles_dump" path = "src/bin/pmtiles_dump.rs"+[[bin]]+name = "pmtiles_extract"+path = "src/bin/pmtiles_extract.rs" [dependencies] miniz_oxide = "0.8" [profile.release]
scripts/maps/tile_build/src/bin/pmtiles_extract.rs
diff --git a/scripts/maps/tile_build/src/bin/pmtiles_extract.rs b/scripts/maps/tile_build/src/bin/pmtiles_extract.rsnew file mode 100644index 0000000000..a90c8668e1--- /dev/null+++ b/scripts/maps/tile_build/src/bin/pmtiles_extract.rs@@ -0,0 +1,379 @@+//! `pmtiles_extract` — subset a PMTiles archive by bbox, zoom range and layer.+//! The `go-pmtiles extract` replacement, plus the layer lift the admin reuse path+//! needs.+//!+//! Usage:+//! pmtiles_extract IN.pmtiles --out OUT.pmtiles+//! [--bbox minlon,minlat,maxlon,maxlat]+//! [--minzoom N] [--maxzoom N] [--layer NAME]...+//!+//! Two jobs, because they are the same walk over the same directory:+//!+//! * **Geographic and zoom subsetting** replaces `pmtiles extract --bbox`, which is+//! what `build_base_layers.sh --mode reuse --bbox` shells out to today. That was+//! the last non-cargo tool in the reuse path.+//! * **Layer selection** (`--layer`, repeatable) lifts named layers out of an+//! archive so they can be carried forward into a `tile_join`. That is how+//! `admin_country` and `admin_region` survive a rebuild: they come from Natural+//! Earth shapefiles, not OSM, so the published archive is the source of record+//! for them and re-deriving them is not an option.+//!+//! ## What is and is not lossless+//!+//! With no `--layer`, tile bodies are copied **byte for byte**: the archive is+//! re-indexed, never re-encoded. With `--layer`, each surviving tile is decoded and+//! re-encoded, which rebuilds its key/value dictionaries in first-use order -- so+//! the bytes differ while the decoded model does not. That is the same contract+//! `tile_join` has, and for the same reason.+//!+//! ## Memory+//!+//! The input is read wholly into memory, like `tile_join`. That is fine for+//! subsetting an overlay and **not** fine for the 1.5 GB published basemap: do that+//! on a machine with the RAM for it. Making it streaming means a random-access+//! reader over the directory tree, which is a different program.++use std::collections::BTreeSet;+use std::process::ExitCode;+use tile_build::mvt::Tile;+use tile_build::pmtiles::{self, Archive, Builder};++fn main() -> ExitCode {+ let argv: Vec<String> = std::env::args().skip(1).collect();+ let mut input: Option<String> = None;+ let mut out: Option<String> = None;+ let mut bbox: Option<[f64; 4]> = None;+ let mut min_zoom: Option<u8> = None;+ let mut max_zoom: Option<u8> = None;+ let mut layers: BTreeSet<String> = BTreeSet::new();++ let mut i = 0;+ while i < argv.len() {+ let value = || argv.get(i + 1).cloned();+ match argv[i].as_str() {+ "--out" => {+ out = value();+ i += 2;+ }+ "--layer" => {+ match value() {+ Some(l) => {+ layers.insert(l);+ }+ None => {+ eprintln!("pmtiles_extract: --layer needs a value");+ return ExitCode::from(2);+ }+ }+ i += 2;+ }+ "--bbox" => {+ let Some(raw) = value() else {+ eprintln!("pmtiles_extract: --bbox needs a value");+ return ExitCode::from(2);+ };+ match parse_bbox(&raw) {+ Ok(b) => bbox = Some(b),+ Err(e) => {+ eprintln!("pmtiles_extract: {e}");+ return ExitCode::from(2);+ }+ }+ i += 2;+ }+ flag @ ("--minzoom" | "--maxzoom") => {+ let Some(raw) = value() else {+ eprintln!("pmtiles_extract: {flag} needs a value");+ return ExitCode::from(2);+ };+ let Ok(z) = raw.parse::<u8>() else {+ eprintln!("pmtiles_extract: {flag} wants a zoom, got '{raw}'");+ return ExitCode::from(2);+ };+ if flag == "--minzoom" {+ min_zoom = Some(z);+ } else {+ max_zoom = Some(z);+ }+ i += 2;+ }+ "-h" | "--help" => {+ usage();+ return ExitCode::SUCCESS;+ }+ other if other.starts_with('-') => {+ eprintln!("pmtiles_extract: unexpected argument '{other}'");+ usage();+ return ExitCode::from(2);+ }+ other => {+ if input.is_some() {+ eprintln!("pmtiles_extract: more than one input archive given");+ return ExitCode::from(2);+ }+ input = Some(other.to_string());+ i += 1;+ }+ }+ }++ let (Some(input), Some(out)) = (input, out) else {+ eprintln!("pmtiles_extract: an input archive and --out are both required");+ usage();+ return ExitCode::from(2);+ };+ if let (Some(lo), Some(hi)) = (min_zoom, max_zoom) {+ if lo > hi {+ eprintln!("pmtiles_extract: --minzoom {lo} is above --maxzoom {hi}");+ return ExitCode::from(2);+ }+ }++ let bytes = match std::fs::read(&input) {+ Ok(b) => b,+ Err(e) => {+ eprintln!("pmtiles_extract: cannot read {input}: {e}");+ return ExitCode::FAILURE;+ }+ };+ let archive = match Archive::parse(&bytes) {+ Ok(a) => a,+ Err(e) => {+ eprintln!("pmtiles_extract: {input} is not a readable PMTiles archive: {e}");+ return ExitCode::FAILURE;+ }+ };+ let tiles = match archive.iter_tiles() {+ Ok(t) => t,+ Err(e) => {+ eprintln!("pmtiles_extract: cannot walk the tile directory: {e}");+ return ExitCode::FAILURE;+ }+ };++ let lo = min_zoom.unwrap_or(archive.header.min_zoom);+ let hi = max_zoom.unwrap_or(archive.header.max_zoom);+ let mut builder = Builder::new();+ builder.min_zoom = lo;+ builder.max_zoom = hi;+ builder.metadata = archive.metadata.clone();+ builder.center_zoom = archive.header.center_zoom.clamp(lo, hi);+ // The bbox, when given, is the truthful extent of what we kept.+ match bbox {+ Some([w, s, e, n]) => {+ builder.min_lon_e7 = e7(w);+ builder.min_lat_e7 = e7(s);+ builder.max_lon_e7 = e7(e);+ builder.max_lat_e7 = e7(n);+ builder.center_lon_e7 = e7((w + e) / 2.0);+ builder.center_lat_e7 = e7((s + n) / 2.0);+ }+ None => {+ builder.min_lon_e7 = archive.header.min_lon_e7;+ builder.min_lat_e7 = archive.header.min_lat_e7;+ builder.max_lon_e7 = archive.header.max_lon_e7;+ builder.max_lat_e7 = archive.header.max_lat_e7;+ builder.center_lon_e7 = archive.header.center_lon_e7;+ builder.center_lat_e7 = archive.header.center_lat_e7;+ }+ }++ let mut kept = 0usize;+ let mut dropped_zoom = 0usize;+ let mut dropped_bbox = 0usize;+ let mut dropped_layer = 0usize;+ let mut seen_layers: BTreeSet<String> = BTreeSet::new();++ for (id, body) in tiles {+ let (z, x, y) = pmtiles::tile_zxy(id);+ if z < lo || z > hi {+ dropped_zoom += 1;+ continue;+ }+ if let Some(b) = &bbox {+ if !tile_in_bbox(z, x, y, b) {+ dropped_bbox += 1;+ continue;+ }+ }+ if layers.is_empty() {+ // Nothing to filter: copy the compressed body straight across, so the+ // subset is byte-identical to the source for every tile it keeps.+ builder.add_tile_raw(id, body.to_vec());+ kept += 1;+ continue;+ }++ let raw = if archive.header.tile_compression == pmtiles::COMPRESSION_GZIP {+ match tile_build::gz::decompress(body) {+ Ok(v) => v,+ Err(e) => {+ eprintln!("pmtiles_extract: z{z}/{x}/{y}: {e}");+ return ExitCode::FAILURE;+ }+ }+ } else {+ body.to_vec()+ };+ let mut tile = match Tile::decode(&raw) {+ Ok(t) => t,+ Err(e) => {+ eprintln!("pmtiles_extract: z{z}/{x}/{y}: {e}");+ return ExitCode::FAILURE;+ }+ };+ for l in &tile.layers {+ seen_layers.insert(l.name.clone());+ }+ tile.layers.retain(|l| layers.contains(&l.name));+ if tile.layers.is_empty() {+ dropped_layer += 1;+ continue;+ }+ builder.add_tile(z, x, y, &tile.encode());+ kept += 1;+ }++ if !layers.is_empty() {+ let missing: Vec<&String> = layers.iter().filter(|l| !seen_layers.contains(*l)).collect();+ if !missing.is_empty() {+ // Loud, and fatal: a silent empty result from a typo'd layer name would+ // quietly drop the borders out of the next published archive.+ eprintln!(+ "pmtiles_extract: no such layer in {input}: {}. Present: {}",+ missing+ .iter()+ .map(|s| s.as_str())+ .collect::<Vec<_>>()+ .join(", "),+ seen_layers.iter().cloned().collect::<Vec<_>>().join(", ")+ );+ return ExitCode::FAILURE;+ }+ }+ if kept == 0 {+ eprintln!(+ "pmtiles_extract: nothing kept ({dropped_zoom} out of zoom range, \+ {dropped_bbox} outside the bbox, {dropped_layer} with no wanted layer)"+ );+ return ExitCode::FAILURE;+ }++ let built = match builder.build() {+ Ok(b) => b,+ Err(e) => {+ eprintln!("pmtiles_extract: {e}");+ return ExitCode::FAILURE;+ }+ };+ if let Err(e) = std::fs::write(&out, &built) {+ eprintln!("pmtiles_extract: cannot write {out}: {e}");+ return ExitCode::FAILURE;+ }+ // Writing something we cannot read back is a bug, not a warning.+ if let Err(e) = Archive::parse(&built) {+ eprintln!("pmtiles_extract: wrote {out} but cannot re-read it: {e}");+ return ExitCode::FAILURE;+ }++ eprintln!(+ "pmtiles_extract: wrote {out} ({:.1} MiB from {:.1} MiB): {kept} tile(s), z{lo}-{hi}",+ built.len() as f64 / (1024.0 * 1024.0),+ bytes.len() as f64 / (1024.0 * 1024.0),+ );+ if !layers.is_empty() {+ eprintln!(+ "pmtiles_extract: kept layer(s) {}",+ layers.iter().cloned().collect::<Vec<_>>().join(", ")+ );+ }+ eprintln!(+ "pmtiles_extract: dropped {dropped_zoom} by zoom, {dropped_bbox} by bbox, \+ {dropped_layer} with no wanted layer"+ );+ ExitCode::SUCCESS+}++fn usage() {+ eprintln!("usage: pmtiles_extract IN.pmtiles --out OUT.pmtiles");+ eprintln!(" [--bbox minlon,minlat,maxlon,maxlat]");+ eprintln!(" [--minzoom N] [--maxzoom N] [--layer NAME]...");+}++fn parse_bbox(s: &str) -> Result<[f64; 4], String> {+ let parts: Vec<&str> = s.split(',').map(str::trim).collect();+ if parts.len() != 4 {+ return Err(format!(+ "--bbox wants minlon,minlat,maxlon,maxlat, got {} field(s)",+ parts.len()+ ));+ }+ let mut v = [0.0f64; 4];+ for (i, p) in parts.iter().enumerate() {+ v[i] = p+ .parse()+ .map_err(|_| format!("--bbox field {} is not a number: {p}", i + 1))?;+ }+ // Reversed rather than silently swapped: a transposed box usually means lat and+ // lon went in the wrong way round, and normalising it would produce a+ // plausible-looking extract of the wrong place.+ if v[0] >= v[2] || v[1] >= v[3] {+ return Err(format!("--bbox is empty or reversed: {s}"));+ }+ Ok(v)+}++/// Does tile `(z, x, y)` overlap the lon/lat box?+///+/// Compared in tile space rather than by un-projecting the tile: the tile grid is+/// what the archive is indexed by, so converting the box once per zoom is both+/// cheaper and free of the rounding a per-tile inverse projection would add.+fn tile_in_bbox(z: u8, x: u64, y: u64, [w, s, e, n]: &[f64; 4]) -> bool {+ let (x0, y0) = tile_build::geom::project(*w, *n, z); // north-west+ let (x1, y1) = tile_build::geom::project(*e, *s, z); // south-east+ let last = ((1u64 << z) - 1) as f64;+ let (tx0, tx1) = (x0.floor().max(0.0), x1.floor().min(last));+ let (ty0, ty1) = (y0.floor().max(0.0), y1.floor().min(last));+ (x as f64) >= tx0 && (x as f64) <= tx1 && (y as f64) >= ty0 && (y as f64) <= ty1+}++fn e7(deg: f64) -> i32 {+ (deg * 1e7).round().clamp(i32::MIN as f64, i32::MAX as f64) as i32+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_bbox_parses_and_rejects_the_transposed_form() {+ assert_eq!(+ parse_bbox("-122.6,37.2,-121.7,37.9").unwrap(),+ [-122.6, 37.2, -121.7, 37.9]+ );+ assert_eq!(parse_bbox(" -1 , -2 , 3 , 4 ").unwrap(), [-1.0, -2.0, 3.0, 4.0]);+ for bad in ["", "1,2,3", "1,2,3,4,5", "a,2,3,4", "3,2,1,4", "1,4,3,2", "1,2,1,4"] {+ assert!(parse_bbox(bad).is_err(), "{bad:?} should not parse");+ }+ }++ #[test]+ fn tile_membership_matches_the_projection() {+ // San Francisco at z11 is tile 327/791.+ let sf = [-122.6, 37.2, -121.7, 37.9];+ assert!(tile_in_bbox(11, 327, 791, &sf));+ // New York is nowhere near it.+ let (nx, ny) = tile_build::geom::project(-74.0, 40.7, 11);+ assert!(!tile_in_bbox(11, nx.floor() as u64, ny.floor() as u64, &sf));+ // At z0 the whole world is one tile, so any box includes it.+ assert!(tile_in_bbox(0, 0, 0, &sf));+ }++ #[test]+ fn a_bbox_at_the_grid_edges_is_clamped_not_wrapped() {+ let world = [-180.0, -85.0, 180.0, 85.0];+ let n = 1u64 << 4;+ assert!(tile_in_bbox(4, 0, 0, &world));+ assert!(tile_in_bbox(4, n - 1, n - 1, &world));+ }+}