Skip to content
Closed
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
8 changes: 7 additions & 1 deletion crates/data/src/raster/crs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -839,7 +839,13 @@ impl Crs {
/// semi-major axis isn't the Earth's ([`super::planetary`]). Its longitude/latitude are read as
/// they are, on the Earth.
pub fn is_planetary(self) -> bool {
self.custom_def().and_then(|d| super::planetary::proj4_axes(&d.proj4)).is_some_and(|(a, _)| super::planetary::off_earth(a))
self.planetary_semi_major().is_some()
}

/// The semi-major axis, in metres, of another body's system ([`Crs::is_planetary`]), which
/// tells the bodies apart; `None` for the Earth's.
pub fn planetary_semi_major(self) -> Option<f64> {
self.custom_def().and_then(|d| super::planetary::proj4_axes(&d.proj4)).map(|(a, _)| a).filter(|a| super::planetary::off_earth(*a))
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

/// A transformer between this system and WGS 84 longitude/latitude, built once a run per
Expand Down
4 changes: 2 additions & 2 deletions crates/engine/command-surface.txt
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ map.body name? basemap?
map.camera lon? lat? scale?
map.clipping mode distance?
map.colorVision mode
map.convertPosition lon x lat y position? digits?
map.convertPosition lon x lat y crs? position? digits?
map.displayType mode
map.drawingMode mode
map.duplicate map? name?
Expand All @@ -323,7 +323,7 @@ map.exportOrbit path frames? turn? width? height? dpi? speed?
map.extent
map.findPlace query provider? url? limit? go?
map.goToLink url
map.goToXY lon x lat y position? scale? bearing? pitch?
map.goToXY lon x lat y crs? position? scale? bearing? pitch?
map.graticule on? type? crs? onTop? color?
map.import path text data
map.link
Expand Down
107 changes: 99 additions & 8 deletions crates/engine/src/cmd/imagery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ fn first() -> String {
pub fn commands() -> Vec<C> {
vec![
C::new("raster.georeference", "Georeference", "Imagery › Alignment", georeference).inputs(raster_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params(
r#"{"layer": raster, "points"?: [[column, row, lon, lat], …] (two or more; with "transform": [column, row, x, y, on?]), "extent"?: [minLon, minLat, maxLon, maxLat], "transform"?: "similarity"|"affine"|"projective"|"polynomial2"|"polynomial3"|"spline" (fits the points and warps the raster onto a north-up grid covering the warped image; without it the points and extent only shift and scale the grid), "pointsCrs"?: EPSG code or "EPSG:n" of the points' x and y (default 4326), "crs"?: the output's (default pointsCrs), "resampling"?: "nearest"|"bilinear"|"cubic" (default bilinear), "cellSize"?: output units (default about the source pixel's size on the ground), "name"?: new layer for the result (default replaces the layer's raster), "path"?: "*.tif" (also writes the warp as a cloud-optimised GeoTIFF)}"#,
r#"{"layer": raster, "points"?: [[column, row, lon, lat], …] (two or more; with "transform": [column, row, x, y, on?]), "extent"?: [minX, minY, maxX, maxY] in degrees, or in crs when given, | "view" (the map view, in the map's own system on a flat map of the Earth, so the raster fills the view as drawn); not with transform, "transform"?: "similarity"|"affine"|"projective"|"polynomial2"|"polynomial3"|"spline" (fits the points and warps the raster onto a north-up grid covering the warped image; without it the points and extent only shift and scale the grid), "pointsCrs"?: EPSG code or "EPSG:n" of the points' x and y (default 4326; with transform only, not with an extent), "crs"?: the output's (default pointsCrs); with an extent of four numbers, their system and the result's, "resampling"?: "nearest"|"bilinear"|"cubic" (default bilinear), "cellSize"?: output units (default about the source pixel's size on the ground), "name"?: new layer for the result (default replaces the layer's raster), "path"?: "*.tif" (also writes the warp as a cloud-optimised GeoTIFF); resampling, cellSize, name and path with transform only}"#,
),
C::new("raster.project", "Project Raster", "Analyze › Raster", project_raster).inputs(project_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params(
r#"{"layer": raster, "crs"?: EPSG code or "EPSG:n" of the output (default the layer's), "cellSize"?: number or [x, y] in the output's units (default about the layer's pixel there), "origin"?: [x, y] a cell corner falls on (default [0, 0], so grids of the same cellSize line up), "extent"?: polygon layer (its selected or all features' bounds) | [west, south, east, north] in degrees | "view" (default the layer's footprint), "grid"?: raster layer whose coordinate system, cells and extent are taken exactly (instead of crs, cellSize, origin and extent), "resampling"?: "nearest" (default) | "bilinear" | "cubic" | "average" (the mean of the pixels whose centres fall in a cell) | "mode" (their most frequent value, the least of those tied), "name"?: new layer (default "<layer> projected"), "path"?: GeoTIFF to write it to}"#,
Expand Down Expand Up @@ -250,17 +250,61 @@ fn rebuild(r: &Raster, transform: GeoTransform, crs: Crs, bands: Vec<Vec<f32>>)
fn georeference(s: &mut Session, p: &Value) -> CmdResult {
let layer = ps(p, "layer").ok_or("layer is required")?.to_string();
let r = raster(s, p)?;
if p.get("transform").is_some() {
if p.get("transform").is_some_and(|v| !v.is_null()) {
// A transform fits control points: an extent given beside it would be passed over.
if p.get("extent").is_some_and(|e| !e.is_null()) {
return Err("give either a transform with control points or an extent, not both".into());
}
return warp_to_fit(s, p, &layer, &r);
}
let gt = if let Some(e) = p.get("extent").and_then(Value::as_array) {
let n: Vec<f64> = e.iter().filter_map(Value::as_f64).collect();
let [x0, y0, x1, y1] = n.as_slice() else { return Err("extent is [minLon, minLat, maxLon, maxLat]".into()) };
// An extent is placed in crs (or the map's system for "view"): pointsCrs, the control
// points' system, would be passed over.
if p.get("extent").is_some_and(|e| !e.is_null()) && crs_param_read(p, "pointsCrs")?.0.is_some() {
return Err("pointsCrs goes with control points and a transform, not with an extent (one of four numbers takes crs)".into());
}
let mut crs = Crs::LonLat;
let extent = match p.get("extent") {
None | Some(Value::Null) => None,
Some(Value::String(v)) if v == "view" => {
if crs_param_read(p, "crs")?.0.is_some() {
return Err("crs goes with an extent of four numbers; \"view\" is in the map's own system".into());
}
let (e, view_crs) = view_in_map_system(s)?;
crs = view_crs;
Some([e.min_x, e.min_y, e.max_x, e.max_y])
}
Some(Value::Array(e)) => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This branch reads only crs for an extent of four numbers. A pointsCrs given with extent and no transform is still silently ignored, so the "refused, not silently ignored" rule this PR applies to control points is not applied here. The transform path also returns early and ignores an extent without saying so. Suggest refusing pointsCrs when an extent is given, and noting the ignored extent on the transform path, with a test for each.

Category: quality

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 677cd86: pointsCrs given with an extent is refused ("pointsCrs goes with control points and a transform, not with an extent"), and so is an extent beside a transform ("give either a transform with control points or an extent, not both"), each with a test in map_system_places.rs. A "transform": null now counts as none. The parameter text and analysis.md say both.

// Exactly four numbers: an entry that isn't one is refused, not passed over.
let n: Vec<f64> = e.iter().map_while(|v| v.as_f64().filter(|v| v.is_finite())).collect();
let given = crs_param(s, p, "crs")?;
let ([x0, y0, x1, y1], 4) = (n.as_slice(), e.len()) else {
return Err("extent is [minX, minY, maxX, maxY] (degrees, or in crs)".into());
};
crs = given.unwrap_or(Crs::LonLat);
Some([*x0, *y0, *x1, *y1])
}
Some(_) => return Err("extent is [minX, minY, maxX, maxY] (degrees, or in crs) or \"view\"".into()),
};
// An extent places the raster on its own: control points beside it would be passed over.
if extent.is_some() && p.get("points").is_some_and(|v| !v.is_null()) {
return Err("give either an extent or control points, not both".into());
}
// Without a transform the raster is placed where it is, its pixels kept: what only a warp
// uses (a new layer or file for its result, a cell size, a resampling) would be passed over,
// and the layer placed in place of a new one. Refused before anything is copied.
if let Some(key) = ["name", "path", "cellSize", "resampling"].into_iter().find(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
return Err(format!("{key} goes with a transform, which warps the raster into a new grid; without one the layer itself is placed"));
}
let gt = if let Some([x0, y0, x1, y1]) = extent {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: control points are silently dropped when an extent is also given and there is no transform. The extent branch (lines 288-292) places the raster and never reads points, so {"extent": [...], "points": [[c, r, lon, lat], ...]} succeeds with the points ignored and no notice. This PR refuses pointsCrs and an extent beside transform for exactly this reason, so the same refusal should cover this case. The fix is one check before the extent is used, with a test next to fit_to_view_places_the_raster_in_the_maps_system that asserts the refusal and that the layer is unchanged.

Suggested change
let gt = if let Some([x0, y0, x1, y1]) = extent {
if extent.is_some() && p.get("points").is_some_and(|v| !v.is_null()) {
return Err("give either an extent or control points, not both".into());
}
let gt = if let Some([x0, y0, x1, y1]) = extent {

Category: bug

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1459c4c, as suggested: an extent with control points and no transform is refused ("give either an extent or control points, not both"). The test next to the other refusals in map_system_places.rs checks that the layer's grid is unchanged.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On the extent and control-points path (no transform), name, path, cellSize and resampling are never read. The later replace(s, &layer, out) always overwrites the source layer. So {"layer": "scan", "extent": "view", "name": "aligned"} replaces scan's raster and returns layer: "scan", with no new layer and no notice. A path is not written, and cellSize is ignored. The name/path documentation in raster.georeference describes them for the whole command, so this is a silent drop. The PR refuses pointsCrs and crs on this path for exactly that reason, so these keys need the same treatment. This is pre-existing code, but this PR rewrites the branch and adds the refusals beside it.

Suggested direction: refuse name, path, cellSize and resampling on this path with a reason, checked before the raster is copied (here, not after copied(&r) at the rebuild call), and add a test next to fit_to_view_places_the_raster_in_the_maps_system that asserts the refusal and that the layer is unchanged. Alternatively, honour name by creating a new layer.

Category: bug

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in fb6fd02: without transform, name, path, cellSize and resampling are refused ("{key} goes with a transform, which warps the raster into a new grid; without one the layer itself is placed"), before anything changes. The params text and analysis.md say so. The test checks each key and that no aligned layer is made.

if !(x0 < x1 && y0 < y1) {
return Err("extent is [minLon, minLat, maxLon, maxLat]".into());
return Err("extent is [minX, minY, maxX, maxY]: each min below its max".into());
}
GeoTransform { origin_x: *x0, origin_y: *y1, pixel_width: (x1 - x0) / r.width as f64, pixel_height: -(y1 - y0) / r.height as f64 }
GeoTransform { origin_x: x0, origin_y: y1, pixel_width: (x1 - x0) / r.width as f64, pixel_height: -(y1 - y0) / r.height as f64 }
} else {
// Without a transform the points are degrees, placed as such.
if crs_param_read(p, "crs")?.0.is_some() || crs_param_read(p, "pointsCrs")?.0.is_some() {
return Err("control points without a transform are longitude and latitude: give transform to use pointsCrs and crs".into());
}
let pts: Vec<[f64; 4]> = p
.get("points")
.and_then(Value::as_array)
Expand Down Expand Up @@ -300,7 +344,7 @@ fn georeference(s: &mut Session, p: &Value) -> CmdResult {
}
GeoTransform { origin_x: bx, origin_y: by, pixel_width: ax, pixel_height: ay }
};
let mut out = rebuild(&r, gt, Crs::LonLat, copied(&r)?)?;
let mut out = rebuild(&r, gt, crs, copied(&r)?)?;
// The same pixels, so the same values rounded when the file was read.
out.rounded = r.rounded.clone();
out.rounded_some = r.rounded_some.clone();
Expand All @@ -309,6 +353,53 @@ fn georeference(s: &mut Session, p: &Value) -> CmdResult {
Ok(json!({"layer": v["layer"], "extent": [e.min_x, e.min_y, e.max_x, e.max_y]}))
}

/// The map view's rectangle and the system it is in, for fitting a raster to it: on a flat map of
/// the Earth, the view in the map's own units and system (Web Mercator's EPSG:3857, the map's EPSG
/// or ESRI code, or the definition of a preset or local view), so the raster fills the view as
/// drawn; on the globe and another body's map, the longitude and latitude box the view shows.
fn view_in_map_system(s: &Session) -> Result<(rustgis_geom::Extent, Crs), String> {
let m = s.map();
let (w, h) = s.view_size;
// A turned or tilted view isn't a north-up rectangle a raster's grid can fill.
if m.camera.bearing != 0.0 || m.camera.pitch != 0.0 {
return Err("the map is turned or tilted: face north and look straight down (Reset North) to fit a raster to the view".into());
}
let flat_earth = m.body().is_earth() && !m.projection.is_globe();
if flat_earth {
let e = m.camera.extent(w, h);
let crs = match &m.projection {
rustgis_map::Projection::Custom(code) => match rustgis_map::projection::Projector::new(code)?.crs() {
Some(c) => c,
None => Crs::parse(&rustgis_map::projection::lookup(code)?.0)?,
},
_ => Crs::WebMercator,
};
if [e.min_x, e.min_y, e.max_x, e.max_y].iter().any(|v| !v.is_finite()) || e.is_empty() {
return Err("the map view shows no area to fit to".into());
}
// A world copy past the antimeridian is the same place within the world's ±180°; a view
// wider than the world has no single place.
if matches!(m.projection, rustgis_map::Projection::WebMercator) {
let world = 2.0 * std::f64::consts::PI * rustgis_geom::MERCATOR_R;
if e.width() > world || e.height() > world {
return Err("the map view is wider than the world: zoom in to fit a raster to it".into());
}
let shift = ((e.min_x + world / 2.0) / world).floor() * world;
let shift = if e.max_x - shift > world / 2.0 + 1e-6 { shift + world } else { shift };
if e.min_x - shift < -world / 2.0 - 1e-6 {
return Err("the map view crosses the antimeridian: pan it to one side to fit a raster to it".into());
}
return Ok((rustgis_geom::Extent::new(e.min_x - shift, e.min_y, e.max_x - shift, e.max_y), crs));
}
return Ok((e, crs));
}
let e = super::workspace::view_extent_of(m, (w, h));
if e.is_empty() {
return Err("the map view shows no part of the map to fit to".into());
}
Ok((e, Crs::LonLat))
}

/// A coordinate system given as an EPSG code or any text [`Crs::parse`] reads.
fn crs_param(s: &mut Session, p: &Value, key: &str) -> Result<Option<Crs>, String> {
let (crs, warning) = crs_param_read(p, key)?;
Expand Down
Loading
Loading