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
120 changes: 118 additions & 2 deletions crates/data/src/raster/crs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,8 +206,9 @@ pub(crate) fn proj_key_refused(key: &str, val: &str) -> bool {

impl Crs {
/// A file's own coordinate system: checked (its PROJ definition must parse, or be a
/// projection RustGIS computes: a sinusoidal one, or an equidistant cylindrical one on an
/// ellipsoid) and added to the run's table, once per definition.
/// projection RustGIS computes: a sinusoidal one, an equidistant cylindrical one on an
/// ellipsoid, or Natural Earth, Winkel Tripel or Eckert IV) and added to the run's table, once
/// per definition.
pub fn custom(def: CustomCrs) -> Result<Crs, String> {
Crs::register(def, false)
}
Expand Down Expand Up @@ -426,6 +427,9 @@ pub(crate) fn transformer_of(def: &str) -> Result<Transformer, String> {
if let Some(eqc) = ellipsoidal_eqc(def) {
return eqc;
}
if let Some(world) = WorldProjection::from_proj4(def) {
return world.and_then(|w| Ok(Transformer { kind: Kind::World { world: Box::new(w), wgs84: Box::new(wgs84()?) } }));
}
let native = proj4rs::Proj::from_proj_string(def).map_err(|e| e.to_string())?;
let geographic = geographic_def(def);
Ok(Transformer { kind: Kind::Proj { native: Box::new(native), wgs84: Box::new(wgs84()?), geographic } })
Expand Down Expand Up @@ -603,13 +607,113 @@ impl EllipsoidalEqc {
}
}

/// A world projection proj4rs lacks (Natural Earth, Winkel Tripel, Eckert IV), computed by
/// `rustgis_geom::world` on a sphere of its datum's semi-major axis (or `+R`), as PROJ does for
/// these spherical projections. Its datum (ellipsoid, shift to WGS 84, prime meridian) is kept for
/// the datum transformation on longitude/latitude, as for [`EllipsoidalEqc`] (#1701).
#[derive(Clone)]
struct WorldProjection {
world: rustgis_geom::world::World,
/// Longitude/latitude on the projection's own datum and prime meridian.
geo: proj4rs::Proj,
/// Metres per unit of its coordinates.
to_meter: f64,
}

impl WorldProjection {
/// The projection a PROJ definition describes when it is `+proj=natearth`, `wintri` or
/// `eck4`: `None` for any other; an error for one it can't compute (axes other than east and
/// north, `+over`, a scale other than 1, an offset that isn't a number, a Winkel Tripel
/// standard parallel that isn't a latitude short of a pole). Winkel Tripel's parallel is
/// `+lat_1`, else 0, as PROJ takes a definition used as a coordinate system (`cs2cs`, GDAL,
/// and WKT without the parameter; verified with PROJ 9.8.1 and 9.9.0). The `proj` program,
/// which runs the bare projection, takes Winkel's own, acos(2/π), for one without `+lat_1`;
/// the map's preset gives that one ([`rustgis_geom::world::winkel_parallel`]). Natural Earth
/// and Eckert IV have no standard parallel: a `+lat_1` is ignored, as in PROJ.
fn from_proj4(def: &str) -> Option<Result<WorldProjection, String>> {
use rustgis_geom::world::Kind as W;
let tokens: Vec<(&str, &str)> =
def.split_whitespace().map(|t| t.trim_start_matches('+')).map(|t| t.split_once('=').unwrap_or((t, ""))).collect();
let name = tokens.iter().find(|(k, _)| *k == "proj").map(|(_, v)| *v)?;
let kind = match name {
"natearth" => W::NaturalEarth,
"wintri" => W::WinkelTripel,
"eck4" => W::EckertIV,
_ => return None,
};
Some((|| {
if tokens.iter().any(|(k, v)| (*k == "k" || *k == "k_0") && v.parse::<f64>().ok() != Some(1.0)) {
return Err("a world projection with a scale other than 1 isn't supported".to_string());
}
let lat1 = match tokens.iter().find(|(k, _)| *k == "lat_1").filter(|_| kind == W::WinkelTripel) {
Some((_, v)) => v
.parse::<f64>()
.ok()
.filter(|v| v.is_finite() && v.abs() < 90.0)
.ok_or_else(|| format!("+lat_1={v} isn't a latitude short of a pole"))?,
None => 0.0,
Comment thread
giswqs marked this conversation as resolved.
Resolved
};
// proj4rs reads what every projection shares (centre, offsets, unit, axes, datum) from
// the same definition with a projection it has, the equidistant cylindrical, in place.
// `+geoc` (latitudes counted from the earth's centre) changes nothing on the sphere
// these are computed on, in PROJ too, so it is kept from the datum's longitude/latitude.
let stand_in: Vec<String> = def
.split_whitespace()
.filter(|t| !t.trim_start_matches('+').starts_with("lat_1=") && t.trim_start_matches('+') != "geoc")
.map(|t| if t.trim_start_matches('+') == format!("proj={name}") { "+proj=eqc".to_string() } else { t.to_string() })
.collect();
let stand_in = stand_in.join(" ");
let native = proj4rs::Proj::from_proj_string(&stand_in).map_err(|e| e.to_string())?;
if !native.is_normalized_axis() || tokens.iter().any(|(k, _)| *k == "over") {
return Err("a world projection takes axes east and north only, with no +over".to_string());
}
let geo = eqc_geographic(&stand_in)?;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
let (a, _) = geo.ellipse_parameters();
let to_meter = native.to_meter();
if !(a.is_finite() && a > 0.0 && to_meter.is_finite() && to_meter > 0.0) {
return Err("its earth or unit isn't usable".to_string());
}
let world = rustgis_geom::world::World {
kind,
lon0: native.longitude_of_origin().to_degrees(),
radius: a,
x0: native.false_easting(),
y0: native.false_northing(),
lat1,
};
// `+x_0=inf` parses: every point of such a system would be nowhere.
if !(world.lon0.is_finite() && world.x0.is_finite() && world.y0.is_finite()) {
return Err("its centre or offset isn't a number".to_string());
}
Ok(WorldProjection { world, geo, to_meter })
})())
}

/// Its coordinates to longitude/latitude on its datum, then to WGS 84.
fn unproject(&self, wgs84: &proj4rs::Proj, c: Coord) -> Option<Coord> {
let own = self.world.inverse(Coord::new(c.x * self.to_meter, c.y * self.to_meter))?;
let mut p = (own.x.to_radians(), own.y.to_radians(), 0.0);
proj4rs::transform::transform(&self.geo, wgs84, &mut p).ok()?;
Some(Coord::new(p.0.to_degrees(), p.1.to_degrees()))
}

/// WGS 84 longitude/latitude to its datum's, then to its coordinates.
fn project(&self, wgs84: &proj4rs::Proj, c: Coord) -> Option<Coord> {
let mut p = (c.x.to_radians(), c.y.to_radians(), 0.0);
proj4rs::transform::transform(wgs84, &self.geo, &mut p).ok()?;
let m = self.world.forward(Coord::new(p.0.to_degrees(), p.1.to_degrees()))?;
Some(Coord::new(m.x / self.to_meter, m.y / self.to_meter))
}
}

#[derive(Clone)]
enum Kind {
LonLat,
Merc,
Proj { native: Box<proj4rs::Proj>, wgs84: Box<proj4rs::Proj>, geographic: bool },
Sinusoidal(rustgis_geom::Sinusoidal),
Eqc { eqc: Box<EllipsoidalEqc>, wgs84: Box<proj4rs::Proj> },
World { world: Box<WorldProjection>, wgs84: Box<proj4rs::Proj> },
}

/// Converts between a raster's coordinates and WGS 84 longitude/latitude.
Expand All @@ -626,6 +730,7 @@ impl std::fmt::Debug for Transformer {
Kind::Proj { .. } => "proj",
Kind::Sinusoidal(_) => "sinusoidal",
Kind::Eqc { .. } => "eqc",
Kind::World { .. } => "world",
};
write!(f, "Transformer({k})")
}
Expand All @@ -644,6 +749,7 @@ impl Transformer {
}
Kind::Sinusoidal(s) => s.inverse(c)?,
Kind::Eqc { eqc, wgs84 } => eqc.unproject(wgs84, c)?,
Kind::World { world, wgs84 } => world.unproject(wgs84, c)?,
};
out.is_finite().then_some(out)
}
Expand Down Expand Up @@ -671,6 +777,7 @@ impl Transformer {
}
Kind::Sinusoidal(s) => s.forward(c)?,
Kind::Eqc { eqc, wgs84 } => eqc.project(wgs84, c)?,
Kind::World { world, wgs84 } => world.project(wgs84, c)?,
};
out.is_finite().then_some(out)
}
Expand All @@ -680,6 +787,15 @@ impl Transformer {
matches!(self.kind, Kind::LonLat | Kind::Proj { geographic: true, .. })
}

/// The WGS 84 longitude of its central meridian, when its projection is a world projection
/// RustGIS computes (Natural Earth, Winkel Tripel, Eckert IV): its outline's east and west
/// edges are the meridian opposite (#1701).
pub(super) fn world_central_meridian(&self) -> Option<f64> {
let Kind::World { world, wgs84 } = &self.kind else { return None };
let centre = Coord::new(world.world.x0 / world.to_meter, world.world.y0 / world.to_meter);
world.unproject(wgs84, centre).map(|c| c.x).filter(|lon| lon.is_finite())
}

/// Web Mercator to native coordinates (the renderer's direction).
pub fn from_merc(&self, c: Coord) -> Option<Coord> {
match &self.kind {
Expand Down
5 changes: 3 additions & 2 deletions crates/data/src/raster/esri.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@
//! systems are candidates to add), and the NAD27 ones whose grids proj4rs can't load: 167;
//! - six world systems RustGIS computes on a sphere where PROJ uses the ellipsoid or other
//! parameters, kilometres apart: World Miller (54003), the WGS 84 Equal Earths (54035–54037)
//! and the Winkel Tripel NGS pair (53042, 54042), whose `lat_1` RustGIS doesn't read. The
//! presets, and EPSG:8857, stay the way to draw these;
//! and the Winkel Tripel NGS pair (53042, 54042), whose `lat_1` the map didn't read then (it
//! does since #1701, so they are candidates to add). The presets, and EPSG:8857, stay the way
//! to draw these;
//! - 44 systems whose datum PROJ shifts to WGS 84 by something other than one Helmert step
//! (Molodensky–Badekas for Korean 1985, a chain of operations for NGO 1948 …), and the 11
//! planetary ones (Moon, Mars), whose bodies the map can't hold;
Expand Down
90 changes: 90 additions & 0 deletions crates/data/src/raster/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -890,6 +890,37 @@ impl Raster {
let (lo, hi) = (e.min_x - shift, e.max_x - shift);
(e.min_x, e.max_x) = if lo >= -180.0 && hi <= 180.0 { (lo, hi) } else { (-180.0, 180.0) };
}
// A whole world in a world projection RustGIS computes reaches the antimeridian and the
// poles at its outline's edge, which samples miss when the grid's edges are a little past
// it (its corners are off the outline): whatever of them is in the grid is in its extent
// (#1701).
if let Some(centre) = self.transformer.world_central_meridian().filter(|_| !e.is_empty()) {
let inside = |lon: f64, lat: f64| {
self.transformer.from_lonlat(Coord::new(lon, lat)).is_some_and(|m| {
let (col, row) = self.transform.to_pixel(m);
(-1e-6..=w + 1e-6).contains(&col) && (-1e-6..=h + 1e-6).contains(&row)
})
};
let along = |i: usize| -180.0 + 360.0 * i as f64 / steps as f64;
if (0..=steps).any(|i| inside(180.0, along(i) / 2.0)) {
e.max_x = 180.0;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
if (0..=steps).any(|i| inside(-180.0, along(i) / 2.0)) {
e.min_x = -180.0;
}
if (0..=steps).any(|i| inside(along(i), 90.0)) {
e.max_y = 90.0;
}
if (0..=steps).any(|i| inside(along(i), -90.0)) {
e.min_y = -90.0;
}
// Centred elsewhere than on 0°, the outline's edges are another meridian than the
// antimeridian: the one opposite its centre, on either side of it.
let edge = (centre + 360.0).rem_euclid(360.0) - 180.0;
if edge.abs() < 180.0 - 1e-6 && (0..=steps).any(|i| [-1e-9, 1e-9].iter().any(|d| inside(edge + d, along(i) / 2.0))) {
(e.min_x, e.max_x) = (e.min_x.min(edge), e.max_x.max(edge));
}
}
e
}

Expand Down Expand Up @@ -1783,6 +1814,65 @@ pub(crate) mod tests {
assert!(e.contains(Coord::new(179.9, 0.0)) && e.contains(Coord::new(-179.9, 0.0)));
}

/// A whole world in Natural Earth, Winkel Tripel or Eckert IV reaches both sides of the
/// antimeridian and both poles, with its edges on the outline or a little past it, as a warp
/// leaves them; its east half reaches 180° and not -180°, and Europe stays Europe (#1701).
#[test]
fn a_whole_world_in_a_world_projection_has_a_world_wide_extent() {
for def in [
"+proj=natearth +lon_0=0 +datum=WGS84 +units=m +no_defs",
"+proj=wintri +lon_0=0 +lat_1=50.459776252189805 +datum=WGS84 +units=m +no_defs",
"+proj=eck4 +lon_0=0 +datum=WGS84 +units=m +no_defs",
] {
let crs = Crs::parse(def).unwrap();
let t = crs.transformer().unwrap();
let at = |lon: f64, lat: f64| t.from_lonlat(Coord::new(lon, lat)).unwrap();
let (east, north) = (at(180.0, 0.0).x, at(0.0, 90.0).y);
let raster = |(west, south, east, north): (f64, f64, f64, f64)| {
let (w, h) = (64, 32);
let gt = GeoTransform {
origin_x: west,
origin_y: north,
pixel_width: (east - west) / w as f64,
pixel_height: (south - north) / h as f64,
};
Raster::new("w", w, h, vec![vec![1.0; (w * h) as usize]], gt, crs, None, ColorHint::Gray, "Float32").unwrap()
};
for past in [1.0, 1.001, 1.01] {
let e = raster((-east * past, -north * past, east * past, north * past)).extent();
assert_eq!((e.min_x, e.max_x, e.min_y, e.max_y), (-180.0, 180.0, -90.0, 90.0), "{def} {past}: {e:?}");
// The east half: 0° to 180°.
let e = raster((0.0, -north * past, east * past, north * past)).extent();
assert!(e.min_x.abs() < 1e-6 && e.max_x == 180.0, "{def} {past}: {e:?}");
}
let (sw, ne) = (at(-10.0, 35.0), at(30.0, 70.0));
let e = raster((sw.x, sw.y, ne.x, ne.y)).extent();
assert!(e.min_x > -40.0 && e.max_x < 60.0 && e.min_y > 30.0 && e.max_y < 75.0, "{def}: {e:?}");
// Centred on 150°E, the outline's edges are 30°W: the west half is 30°W to 150°E, a
// whole world all of it, and the east half, across the antimeridian, all of it too.
let crs = Crs::parse(&def.replace("+lon_0=0", "+lon_0=150")).unwrap();
let raster = |(west, south, east, north): (f64, f64, f64, f64)| {
let (w, h) = (64, 32);
let gt = GeoTransform {
origin_x: west,
origin_y: north,
pixel_width: (east - west) / w as f64,
pixel_height: (south - north) / h as f64,
};
Raster::new("w", w, h, vec![vec![1.0; (w * h) as usize]], gt, crs, None, ColorHint::Gray, "Float32").unwrap()
};
for past in [1.0, 1.001, 1.01] {
let e = raster((-east * past, -north * past, 0.0, north * past)).extent();
assert!((e.min_x + 30.0).abs() < 1e-6 && (e.max_x - 150.0).abs() < 1e-6, "{def} at 150°E, west half, {past}: {e:?}");
assert_eq!((e.min_y, e.max_y), (-90.0, 90.0), "{def} at 150°E, west half, {past}: {e:?}");
for west in [-east * past, 0.0] {
let e = raster((west, -north * past, east * past, north * past)).extent();
assert_eq!((e.min_x, e.max_x), (-180.0, 180.0), "{def} at 150°E from {west}, {past}: {e:?}");
}
}
}
}

#[test]
fn rejects_bad_shapes() {
let gt = GeoTransform { origin_x: 0.0, origin_y: 0.0, pixel_width: 1.0, pixel_height: -1.0 };
Expand Down
Loading
Loading