Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions ATTRIBUTION.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ Raster coordinate systems are looked up by EPSG code in the PROJ definitions of
app. The codes it lacks (EPSG 9020–20003, `crates/data/src/raster/epsg_gap.rs`) are from the
[EPSG Geodetic Parameter Dataset](https://epsg.org) v12.029 (© IOGP, under its
[terms of use](https://epsg.org/terms-of-use.html)), written as PROJ definitions by PROJ 9.8.
The map's ESRI codes (`crates/data/src/raster/esri.rs`) are Esri's projected coordinate systems
from Esri's [projection-engine-db-doc](https://github.com/Esri/projection-engine-db-doc)
(Apache-2.0), as imported into the [PROJ](https://proj.org) 9.7.1 database (MIT) and written as
PROJ definitions by PROJ 9.7.1.

The GeoLibre tool suite ([geolibre-rust](https://github.com/opengeos/geolibre-rust), MIT, built
on [whitebox-wasm](https://github.com/opengeos/whitebox-wasm), MIT) is not part of RustGIS: the
Expand Down
33 changes: 33 additions & 0 deletions crates/data/src/raster/crs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,17 @@ pub fn epsg_proj4(code: u16) -> Option<&'static str> {
crs_definitions::from_code(code).map(|d| d.proj4).or_else(|| super::epsg_gap::proj4(code))
}

/// The PROJ definition of one of Esri's projected coordinate systems (`ESRI:102033`, South
/// America Albers), from the built-in table ([`super::esri`]). `None` for a code it lacks.
pub fn esri_proj4(code: u32) -> Option<&'static str> {
super::esri::proj4(code)
}

/// Every ESRI code [`esri_proj4`] knows, in order.
pub fn esri_codes() -> impl Iterator<Item = u32> {
super::esri::DEFS.iter().map(|&(c, _)| c)
}

/// A raster's coordinate system. Saved as its EPSG code, or a custom one as its definition.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(into = "SavedCrs", try_from = "SavedCrs")]
Expand Down Expand Up @@ -338,6 +349,28 @@ mod tests {
assert_eq!(Crs::from_epsg(10622), None);
}

/// The ESRI table (opengeos/RustGIS#213) is in order and holds only projected systems on Earth.
#[test]
fn esri_table_is_sound() {
let defs = super::super::esri::DEFS;
assert!(defs.len() > 1900, "{}", defs.len());
for pair in defs.windows(2) {
assert!(pair[0].0 < pair[1].0, "out of order at ESRI:{}", pair[1].0);
}
for &(code, def) in defs {
assert_eq!(esri_proj4(code), Some(def));
assert!(def.starts_with("+proj=") && !def.contains("+proj=longlat") && !def.contains("+proj=geocent"), "ESRI:{code}");
}
assert_eq!(esri_codes().count(), defs.len());
// South America Albers Equal Area Conic, which opened the issue.
assert!(esri_proj4(102033).is_some_and(|d| d.contains("+proj=aea") && d.contains("+lon_0=-60")));
// Left out: World Miller (RustGIS's sphere is kilometres from PROJ's), a lunar system, a
// Hammer–Aitoff PROJ can't write as a string, and codes that don't exist.
for code in [54003, 103877, 54044, 0, 4326, u32::MAX] {
assert_eq!(esri_proj4(code), None, "ESRI:{code}");
}
}

/// Every entry in the gap table is wanted (upstream still lacks it), in order, and usable.
#[test]
fn gap_table_is_sound() {
Expand Down
2,024 changes: 2,024 additions & 0 deletions crates/data/src/raster/esri.rs

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions crates/data/src/raster/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ pub mod ascii;
pub mod cog;
pub mod crs;
mod epsg_gap;
mod esri;
#[cfg(not(target_arch = "wasm32"))]
pub mod gdal;
pub mod geotiff;
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/navigate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ pub fn commands() -> Vec<C> {
}
Ok(out)
})
.params(r#"{"type"?: "mercator"|"globe"|preset id|"EPSG:<code>" (toggles the globe when omitted)}"#),
.params(r#"{"type"?: "mercator"|"globe"|preset id|"EPSG:<code>"|"ESRI:<code>" (toggles the globe when omitted)}"#),
C::new("map.projections", "Projections", "View › View", |_, _| {
let mut v = vec![json!({"id": "mercator", "label": "Web Mercator"}), json!({"id": "globe", "label": "Globe"})];
v.extend(rustgis_map::projection::PRESETS.iter().map(|(id, label, _)| json!({"id": id, "label": label})));
Expand Down
21 changes: 21 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -580,6 +580,27 @@ fn globe_projection_toggles_renders_and_saves() {
assert!(Project::from_json(&json).unwrap().map().projection == rustgis_map::Projection::Globe);
}

/// `map.projection` takes ESRI codes (#213): South America Albers, the issue's regional map.
#[test]
fn esri_projection_codes() {
let mut s = world();
s.run("map.goToXY", &json!({"lon": -60.0, "lat": -15.0, "scale": 20_000_000})).unwrap();
let r = s.run("map.projection", &json!({"type": "esri:102033"})).unwrap();
assert_eq!(r["projection"], "ESRI:102033");
assert_eq!(r["label"], "ESRI:102033");
let c = s.map().center_lonlat();
assert!((c.x + 60.0).abs() < 1e-6 && (c.y + 15.0).abs() < 1e-6, "{c:?}");
assert!(crate::cmd::share::map_png(&mut s, Some(400.0), Some(300.0), None).unwrap().len() > 1000);
let json = serde_json::to_string(&s.project).unwrap();
assert_eq!(Project::from_json(&json).unwrap().map().projection.code(), "ESRI:102033");
// A code the table leaves out is refused, and the map keeps its projection.
let e = s.run("map.projection", &json!({"type": "ESRI:54003"})).unwrap_err();
assert!(e.contains("ESRI:54003"), "{e}");
assert_eq!(s.map().projection.code(), "ESRI:102033");
// ESRI's Web Mercator is the default map.
assert_eq!(s.run("map.projection", &json!({"type": "ESRI:102100"})).unwrap()["projection"], "mercator");
}

#[test]
fn custom_projections_switch_keep_scale_query_and_render() {
let mut s = with_raster();
Expand Down
28 changes: 18 additions & 10 deletions crates/map/src/globe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ pub enum Projection {
WebMercator,
/// A 3D globe.
Globe,
/// Another flat projection: a preset id (see [`crate::projection::PRESETS`]) or `EPSG:<code>`.
/// Another flat projection: a preset id (see [`crate::projection::PRESETS`]), `EPSG:<code>`,
/// `ESRI:<code>` or `local:lon,lat`.
Custom(String),
}

Expand All @@ -50,28 +51,35 @@ impl Projection {
matches!(self, Projection::Globe)
}

/// A projection by code: `mercator`, `globe`, a preset id or name, or an EPSG code (which
/// must name a projected coordinate system the map can draw).
/// A projection by code: `mercator`, `globe`, a preset id or name, or an EPSG or ESRI code
/// (which must name a projected coordinate system the map can draw).
pub fn from_code(s: &str) -> Result<Projection, String> {
match s.trim().to_ascii_lowercase().replace([' ', '_', '-'], "").as_str() {
"mercator" | "webmercator" | "2d" | "map" | "epsg:3857" | "3857" | "epsg:900913" => return Ok(Projection::WebMercator),
// EPSG:900913, Web Mercator's unofficial code, is in no table.
"mercator" | "webmercator" | "2d" | "map" | "epsg:900913" => return Ok(Projection::WebMercator),
"globe" | "3d" | "scene" | "globalscene" => return Ok(Projection::Globe),
_ => {}
}
let s = s.trim();
// Web Mercator's codes are the default map, however they were typed (`EPSG 3857`, `esri:0102100`).
let named = crate::projection::lookup(s).map(|(_, label)| label);
if named.as_deref().is_ok_and(|l| ["EPSG:3857", "ESRI:102100", "ESRI:102113"].contains(&l)) {
return Ok(Projection::WebMercator);
}
// Build it, not just look it up: a known code whose method has no implementation would
// otherwise be accepted and drawn in Web Mercator under its own name (opengeos/RustGIS#208).
crate::projection::Projector::new(s)?;
// A local view keeps its centre.
if s.starts_with("local:") {
return Ok(Projection::Custom(s.to_string()));
}
// Canonical form: the preset id, or EPSG:<n>.
let canonical = crate::projection::PRESETS
.iter()
.find(|(id, label, _)| id.eq_ignore_ascii_case(s) || label.eq_ignore_ascii_case(s))
.map(|(id, _, _)| id.to_string())
.unwrap_or_else(|| format!("EPSG:{}", s.trim_start_matches(|c: char| !c.is_ascii_digit())));
// Canonical form: the preset id, or the code as `lookup` names it (`EPSG:<n>`, `ESRI:<n>`,
// whatever the spacing and leading zeros typed).
let preset = crate::projection::PRESETS.iter().find(|(id, label, _)| id.eq_ignore_ascii_case(s) || label.eq_ignore_ascii_case(s));
let canonical = match preset {
Some((id, _, _)) => id.to_string(),
None => named?,
};
Ok(Projection::Custom(canonical))
}
}
Expand Down
89 changes: 82 additions & 7 deletions crates/map/src/projection.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! Map projections: how the flat map lays the Earth out (the globe is in [`crate::globe`]).
//!
//! A map is drawn in Web Mercator by default, or in any projected coordinate system: a preset
//! (world and polar projections, regional equal-area grids) or an EPSG code. The camera then
//! (world and polar projections, regional equal-area grids), an EPSG code or an ESRI code. The camera then
//! works in that system's units, so panning, zooming and hit testing are the same for all of
//! them; only conversions between longitude/latitude and map coordinates go through here.

Expand Down Expand Up @@ -40,7 +40,8 @@ pub fn local_views_supported() -> bool {
*SUPPORTED.get_or_init(|| Projector::new("local:0,0").is_ok())
}

/// The PROJ definition and label of a projection code: a preset id or `EPSG:<code>`.
/// The PROJ definition and label of a projection code: a preset id, `EPSG:<code>`, `ESRI:<code>`
/// or `local:lon,lat`.
pub fn lookup(code: &str) -> Result<(String, String), String> {
let code = code.trim();
// `local:lon,lat`: an azimuthal equidistant projection centred on a point (a local scene).
Expand All @@ -59,6 +60,22 @@ pub fn lookup(code: &str) -> Result<(String, String), String> {
}
// `3035`, `EPSG:3035` or `epsg 3035`: an optional prefix, then only digits.
let lower = code.to_ascii_lowercase();
// `ESRI:102033`: one of Esri's projected coordinate systems, from a table checked against PROJ.
// Only `esri`, then a colon, a space or the number: any other name goes on to the end.
if let Some(rest) = lower.strip_prefix("esri").filter(|r| r.starts_with([':', ' ']) || r.starts_with(|c: char| c.is_ascii_digit())) {
let digits = rest.trim_start_matches([':', ' ']);
if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
return Err(format!("unknown coordinate system '{code}'"));
}
let shown = match digits.trim_start_matches('0') {
"" => "0",
d => d,
};
let unknown = || format!("unknown coordinate system ESRI:{shown}");
let n = digits.parse::<u32>().map_err(|_| unknown())?;
let def = rustgis_data::raster::crs::esri_proj4(n).ok_or_else(unknown)?;
return Ok((def.to_string(), format!("ESRI:{n}")));
}
let digits = lower.strip_prefix("epsg").map(|r| r.trim_start_matches([':', ' '])).unwrap_or(&lower);
if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
return Err(format!("unknown projection '{code}'"));
Expand Down Expand Up @@ -264,7 +281,13 @@ impl Projector {
let lon0 = angle(&def, "lon_0").unwrap_or(0.0) + pm;
let lat0 = angle(&def, "lat_0").unwrap_or(0.0);
let domain = Domain::of(preset, &def, (lon0, lat0), pm);
let engine = Engine::World(crate::world::World { kind, lon0 });
// A sphere's radius when the definition gives one (ESRI's Sphere_* systems), else WGS 84's.
let radius = def
.split_whitespace()
.find_map(|t| t.strip_prefix("+R=")?.parse::<f64>().ok())
.filter(|r| r.is_finite() && *r > 0.0)
.unwrap_or(rustgis_geom::MERCATOR_R);
let engine = Engine::World(crate::world::World { kind, lon0, radius });
return Ok(Projector { engine, to_meter: 1.0, domain, lon0, edge: std::sync::OnceLock::new() });
}
let native = proj4rs::Proj::from_proj_string(&def).map_err(|e| match e {
Expand Down Expand Up @@ -530,6 +553,57 @@ mod tests {
}
}

/// ESRI codes (opengeos/RustGIS#213), against pyproj 3.7.2 (PROJ 9.7.1) given the table's
/// definitions.
#[test]
fn esri_codes() {
let check = |code: &str, (lon, lat): (f64, f64), (x, y): (f64, f64), tolerance: f64| {
let p = Projector::new(code).unwrap_or_else(|e| panic!("{code}: {e}"));
let m = p.forward(Coord::new(lon, lat)).unwrap_or_else(|| panic!("{code}"));
assert!((m.x - x).abs() < tolerance && (m.y - y).abs() < tolerance, "{code}: {m:?}, want ({x}, {y})");
let back = p.inverse(m).unwrap_or_else(|| panic!("{code}"));
assert!((back.x - lon).abs() < 1e-6 && (back.y - lat).abs() < 1e-6, "{code}: {back:?}");
};
// South America Albers Equal Area Conic, with its datum shift (South American 1969: the
// first Helmert PROJ lists, 7 m from the regional one PROJ picks for this point).
check("ESRI:102033", (-60.0, -15.0), (46.993, 1_977_375.429), 0.01);
// World Robinson, and Sphere Robinson on its own 6371 km sphere (+R), computed here.
check("ESRI:54030", (20.0, 30.0), (1_813_955.515, 3_208_557.612), 1.0);
check("esri:53030", (20.0, 30.0), (1_811_925.737, 3_204_967.304), 1.0);
// A state plane in US survey feet (deprecated, but what ArcGIS writes): Manhattan.
check("ESRI 102718", (-73.95, 40.75), (998_103.643, 212_525.840), 0.01);
assert_eq!(lookup(" esri:102033 ").map(|(_, label)| label), Ok("ESRI:102033".into()));
assert_eq!(crate::Projection::from_code("esri:102033"), Ok(crate::Projection::Custom("ESRI:102033".into())));
assert_eq!(crate::Projection::from_code("ESRI:102033").map(|p| p.label()), Ok("ESRI:102033".into()));
// One system, one saved code, however it was typed.
for typed in ["ESRI 102033", "esri:0102033", " Esri:102033 "] {
assert_eq!(crate::Projection::from_code(typed), Ok(crate::Projection::Custom("ESRI:102033".into())), "{typed}");
}
assert_eq!(crate::Projection::from_code("epsg:03035"), Ok(crate::Projection::Custom("EPSG:3035".into())));
// ESRI's Web Mercator codes are the default map.
for web in ["ESRI:102100", "esri:102113", "ESRI 102100", "esri:0102100", "EPSG:3857", "3857", "epsg 3857", "EPSG:900913"] {
assert_eq!(crate::Projection::from_code(web), Ok(crate::Projection::WebMercator), "{web}");
}
// Not in the table (World Miller is kilometres off in proj4rs), not a number, too big.
for bad in ["ESRI:54003", "ESRI:", "ESRI:abc", "ESRI:-1", "ESRI:99999999999", "ESRI:1e5"] {
let e = lookup(bad).unwrap_err();
assert!(e.contains("unknown coordinate system") && e.contains("ESRI:"), "{bad}: {e}");
}
// The message names the code as typed, or as the number it read.
assert_eq!(lookup("ESRI:abc").unwrap_err(), "unknown coordinate system 'ESRI:abc'");
assert_eq!(lookup("esri:0").unwrap_err(), "unknown coordinate system ESRI:0");
assert_eq!(lookup("esri:00054003").unwrap_err(), "unknown coordinate system ESRI:54003");
// Any other name starting with "esri" isn't read as a code.
assert_eq!(lookup("esrifoo").unwrap_err(), "unknown projection 'esrifoo'");
// Every code in the table draws (local azimuthal ones only where aeqd is built in).
for n in rustgis_data::raster::crs::esri_codes() {
let code = format!("ESRI:{n}");
let aeqd = lookup(&code).is_ok_and(|(def, _)| def.contains("+proj=aeqd"));
let p = Projector::new(&code);
assert!(p.is_ok() || (aeqd && !local_views_supported()), "{code}: {:?}", p.err());
}
}

#[test]
fn presets_and_epsg_codes() {
for (id, _, _) in PRESETS {
Expand Down Expand Up @@ -678,17 +752,18 @@ mod tests {
// For every EPSG code drawn as a whole-world map, the map jumps sides at `central_meridian() + 180°`:
// just west of it draws on the east, just east of it on the west.
let mut checked = 0;
for n in 1024..=32767u32 {
let epsg = (1024..=32767u32).map(|n| format!("EPSG:{n}"));
for n in epsg.chain(rustgis_data::raster::crs::esri_codes().map(|n| format!("ESRI:{n}"))) {
// Codes with a prime meridian other than Greenwich (+pm) and a datum shift included.
let Ok(p) = Projector::new(&format!("EPSG:{n}")) else { continue };
let Ok(p) = Projector::new(&n) else { continue };
let Some(lon0) = p.central_meridian() else { continue };
let x = |lon: f64| p.forward(Coord::new(lon, 0.0)).map(|m| m.x);
let (Some(west), Some(centre), Some(east)) = (x(lon0 + 179.5), x(lon0), x(lon0 + 180.5)) else { continue };
assert!(west > centre && centre > east, "EPSG:{n}: lon_0 {lon0}: {west} / {centre} / {east}");
assert!(west > centre && centre > east, "{n}: lon_0 {lon0}: {west} / {centre} / {east}");
// With a datum shift the edge is found by search, which must not fall back to the
// nominal edge (no margin) for any of them.
if let Engine::Proj { .. } = p.engine {
assert!(p.find_edge(p.lon0 + 180.0).is_some(), "EPSG:{n}: the edge search fell back");
assert!(p.find_edge(p.lon0 + 180.0).is_some(), "{n}: the edge search fell back");
}
checked += 1;
}
Expand Down
Loading
Loading