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
16 changes: 2 additions & 14 deletions crates/analysis/src/rasterops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -611,21 +611,9 @@ fn dist_m(a: Coord, b: Coord) -> f64 {
rustgis_geom::haversine_m(a, b)
}

/// Elevation (bilinear) at a longitude/latitude point.
/// Elevation (bilinear) at a longitude/latitude point ([`Raster::bilinear`]).
pub fn elevation_at(r: &Raster, b: usize, ll: Coord) -> Option<f64> {
let w = r.transformer().from_lonlat(ll)?;
let (x, y) = r.transform.to_pixel(w);
let (x, y) = (x - 0.5, y - 0.5);
let (c0, r0) = (x.floor() as i64, y.floor() as i64);
let (fx, fy) = (x - c0 as f64, y - r0 as f64);
let v = |c: i64, rr: i64| r.value(b, c, rr).map(f64::from);
let (a, b2, c, d) = (v(c0, r0), v(c0 + 1, r0), v(c0, r0 + 1), v(c0 + 1, r0 + 1));
match (a, b2, c, d) {
(Some(a), Some(b2), Some(c), Some(d)) => {
Some(a * (1.0 - fx) * (1.0 - fy) + b2 * fx * (1.0 - fy) + c * (1.0 - fx) * fy + d * fx * fy)
}
_ => v(x.round() as i64, y.round() as i64),
}
r.bilinear(b, ll)
}

/// An elevation profile along a path: (distance from the start in metres, point, elevation).
Expand Down
33 changes: 33 additions & 0 deletions crates/data/src/raster/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1350,6 +1350,26 @@ impl Raster {
if wrapped < w { wrapped } else { c }
}

/// The value of `band` at a longitude/latitude point, read bilinearly between the four cell
/// centres around it, in the raster's own system: the nearest cell's where one of the four is
/// no-data or off the grid, and `None` where that one is too. A grid stored from 0 to 360° is
/// read at a western longitude in its columns past 180° ([`Raster::wrap_col`]). The elevation profiles read
/// this (`profile.*`, and a layout's profiles beside a map frame, #2863).
pub fn bilinear(&self, band: usize, lonlat: Coord) -> Option<f64> {
let w = self.transformer.from_lonlat(lonlat)?;
let (x, y) = self.transform.to_pixel(w);
let (x, y) = (self.wrap_col(x) - 0.5, y - 0.5);
let (c0, r0) = (x.floor() as i64, y.floor() as i64);
let (fx, fy) = (x - c0 as f64, y - r0 as f64);
let v = |c: i64, r: i64| self.value(band, c, r).map(f64::from);
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
match (v(c0, r0), v(c0 + 1, r0), v(c0, r0 + 1), v(c0 + 1, r0 + 1)) {
(Some(a), Some(b), Some(c), Some(d)) => {
Some(a * (1.0 - fx) * (1.0 - fy) + b * fx * (1.0 - fy) + c * (1.0 - fx) * fy + d * fx * fy)
}
_ => v(x.round() as i64, y.round() as i64),
}
}

/// Cell size in the raster's units (x, y).
pub fn cell_size(&self) -> (f64, f64) {
(self.transform.pixel_width.abs(), self.transform.pixel_height.abs())
Expand Down Expand Up @@ -2767,6 +2787,19 @@ pub(crate) mod tests {
assert!(grid(-0.25, 720, 0.5, Crs::LonLat).wrap_col(f64::NAN).is_nan());
}

/// A grid stored from 0 to 360° is read bilinearly at a western longitude in its columns past
/// 180°, as `pixel_at` finds it (#1109), not as off the grid (#2863).
#[test]
fn a_western_place_on_a_grid_past_180_is_read_bilinearly() {
let gt = GeoTransform { origin_x: -0.25, origin_y: 77.25, pixel_width: 0.5, pixel_height: -0.5 };
let data = (0..720 * 309).map(|i| (i % 720) as f32).collect();
let r = Raster::new("g", 720, 309, vec![data], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap();
let at = |lon: f64| r.bilinear(0, Coord::new(lon, 0.0));
assert!(at(100.0).is_some_and(|v| (v - 200.0).abs() < 1e-6), "{:?}", at(100.0));
assert!(at(-100.0).is_some_and(|v| (v - 520.0).abs() < 1e-6), "260°: {:?}", at(-100.0));
assert!(at(-100.1).is_some_and(|v| (v - 519.8).abs() < 1e-6), "259.9°: {:?}", at(-100.1));
}

#[test]
fn geographic_extent_uses_greenwich_not_the_native_prime_meridian() {
let crs = Crs::parse("+proj=longlat +datum=WGS84 +pm=paris +no_defs").unwrap();
Expand Down
59 changes: 58 additions & 1 deletion crates/engine/src/tests/layout_profiles.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
//! Profiles beside a layout's map frame (#2863 part 2): the commands and what they say.
//! Profiles beside a layout's map frame (#2863 part 2): the commands, what they say, and how a
//! profile agrees with `profile.create`.

use crate::{Session, sample};
use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster};
use rustgis_geom::Coord;
use rustgis_map::layout::{ElementKind, Profile, ProfileSide};
use serde_json::json;

Expand Down Expand Up @@ -46,3 +49,57 @@ fn a_box_given_to_a_profile_is_said_not_kept() {
s.run("layout.update", &json!({"element": frame, "x": 20})).unwrap();
assert!(s.notices_since(mark).is_empty(), "the frame takes its profile along");
}

/// The Mantiqueira of #2863: a vertical section line of a UTM 23S frame through the Pedra da Mina,
/// whose profile `profile.create` gave again within 0.11 m over 1,600 samples of the Copernicus DEM.
/// On a relief of that frame, the profile's samples and `profile.create`'s between the line's ends,
/// as many, agree as closely: a vertical line of a UTM frame strays little from the straight line
/// of longitude and latitude between its ends.
#[test]
fn the_mantiqueira_profile_agrees_with_profile_create() {
let mut s = Session::new(sample::world_project());
s.run("map.projection", &json!({"type": "EPSG:31983"})).unwrap();
let crs = Crs::from_epsg(31983).unwrap();
let to = crs.transformer().unwrap();
let mid = to.from_lonlat(Coord::new(-44.715, -22.412)).unwrap();
let (cols, rows, cell) = (1600usize, 1000usize, 30.0);
let (x0, y0) = (((mid.x - 24_000.0) / cell).round() * cell, ((mid.y + 15_000.0) / cell).round() * cell);
// Ridges and valleys a few kilometres across, some 2,000 m of relief, as the Mantiqueira's.
let z = |e: f64, n: f64| 1500.0 + 600.0 * (e / 2_300.0).sin() * (n / 1_700.0).cos() + 300.0 * ((e + n) / 900.0).sin();
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
let data = (0..rows * cols).map(|i| z(x0 + ((i % cols) as f64 + 0.5) * cell, y0 - ((i / cols) as f64 + 0.5) * cell) as f32).collect();
let gt = GeoTransform { origin_x: x0, origin_y: y0, pixel_width: cell, pixel_height: -cell };
let r = Raster::new("dem", cols as u32, rows as u32, vec![data], gt, crs, None, ColorHint::Gray, "Float32").unwrap();
s.map_mut().add_raster("DEM", rustgis_map::RasterLayer::from_path(r, "dem.tif"));
s.run("layout.new", &json!({"page": "a4", "orientation": "landscape", "template": "blank"})).unwrap();
s.run("layout.addFrame", &json!({})).unwrap();
let frame = s.project.layouts[0].first_frame().unwrap();
s.run(
"layout.update",
&json!({"element": frame, "x": 30, "y": 34, "w": 186, "h": 112, "center": [-44.715, -22.412], "scale": 200_000}),
)
.unwrap();
s.run("layout.addElement", &json!({"kind": "section", "direction": "vertical", "at": [-44.8429, -22.4282]})).unwrap();
let id = put_profile(&mut s, frame, ProfileSide::Right);
let ElementKind::Profile(p) = &s.project.layouts[0].element(id).unwrap().kind else { panic!("a profile") };
let (samples, _) = rustgis_render::layout::profile_samples(&s.project.layouts[0], &s.project.maps, p).unwrap();
// The line's ends on the ground, as the frame shows them.
let map = &s.project.maps[0];
let ElementKind::MapFrame { center, scale, .. } = &s.project.layouts[0].element(frame).unwrap().kind else { panic!("a frame") };
let cam = rustgis_map::layout::frame_camera(map, *center, *scale, 0.0, 0.0);
let (fw, fh) = (186.0 * rustgis_map::layout::PT_PER_MM, 112.0 * rustgis_map::layout::PT_PER_MM);
let (x, _) = cam.try_to_screen(map.to_map(Coord::new(-44.8429, -22.4282)).unwrap(), fw, fh).unwrap();
let ends: Vec<[f64; 2]> =
[0.0, fh].iter().map(|y| map.to_lonlat(cam.try_to_map(x, *y, fw, fh).unwrap()).unwrap()).map(|c| [c.x, c.y]).collect();
let n = samples.values.len();
assert!(n > 700, "a sample a cell: {n}");
let got = s.run("profile.create", &json!({"layer": "DEM", "points": ends, "samples": n})).unwrap();
let theirs: Vec<f64> = got["samples"].as_array().unwrap().iter().map(|r| r["elevation"].as_f64().unwrap()).collect();
assert_eq!(theirs.len(), n);
let off = samples.values.iter().zip(&theirs).map(|(a, b)| (a.unwrap() - b).abs()).fold(0.0, f64::max);
assert!(off < 0.5, "{off} m apart");
// Its length is the frame's height on the ground (112 mm at 1:200,000, the UTM scale factor
// aside) on the ellipsoid; profile.create's, on the sphere, a few tenths of a percent longer.
let (ours, theirs) = (*samples.metres.last().unwrap(), got["length"].as_f64().unwrap());
assert!((ours / 22_400.0 - 1.0).abs() < 0.002, "{ours} m");
assert!((theirs / ours - 1.0).abs() < 0.006, "{theirs} m against {ours} m");
}
8 changes: 5 additions & 3 deletions crates/map/src/layout/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2064,10 +2064,12 @@ fn a_profile_keeps_to_its_frames_side() {
assert_eq!(l.fit_profiles(), 0, "already beside it");
// Saved with only what isn't its default; read back as saved; a repaired one needs nothing more.
let text = serde_json::to_string(&l).unwrap();
let saved = text.split("\"Profile\":").nth(1).unwrap();
for left_out in ["\"band\"", "\"min\"", "\"max\"", "\"units\"", "\"guides\"", "\"color\"", "\"title\"", "\"unit\""] {
assert!(!saved.contains(left_out), "{left_out} in {saved}");
let value: serde_json::Value = serde_json::from_str(&text).unwrap();
let saved = value["elements"].as_array().unwrap().iter().find_map(|e| e["kind"]["Profile"].as_object()).unwrap();
for left_out in ["band", "min", "max", "units", "guides", "color", "title", "unit"] {
assert!(!saved.contains_key(left_out), "{left_out} in {saved:?}");
}
assert!(saved.contains_key("section"), "the profile's own object: {saved:?}");
let back: Layout = serde_json::from_str(&text).unwrap();
assert_eq!(back, l);
assert!(l.clamp().is_empty());
Expand Down
4 changes: 3 additions & 1 deletion crates/render/src/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ mod grid;
mod legend;
mod losses;
mod north;
mod profile;
mod scale_bar;
mod section;
mod swatch;
Expand All @@ -43,6 +44,7 @@ pub use grid::*;
pub use legend::*;
pub use losses::*;
use north::*;
pub use profile::*;
pub use scale_bar::*;
pub use section::*;
use swatch::*;
Expand Down Expand Up @@ -692,7 +694,7 @@ fn draw_page(
None => placeholder(&mut pm, r, "Chart", ppp),
}
}
// What it reads and draws comes in its own steps (#2863 parts 2b to 2d).
// What it reads is worked out from 2b (`profile_samples`); it is said in 2c and drawn in 2d (#2863).
ElementKind::Profile(_) => placeholder(&mut pm, r, "Profile", ppp),
ElementKind::Rectangle { fill, outline, width, radius, dash } => {
// Square corners filled as before, so an existing layout draws to the same pixels.
Expand Down
125 changes: 125 additions & 0 deletions crates/render/src/layout/profile.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
//! A raster's profile beside its map frame (#2863 part 2): its samples along a section line, read
//! at each one's point of the page line through the frame's projection.

use rustgis_map::layout::{MAX_PROFILE_SAMPLES, Profile};

use super::*;

/// What a profile reads along its section line ([`profile_samples`]).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ProfileSamples {
/// Each sample's place along the frame's side, in the frame's points from its left (or top).
pub along: Vec<f64>,
/// Each sample's metres along the ground from the section line's start (its A end), on the
/// WGS 84 ellipsoid, between one sample and the next.
pub metres: Vec<f64>,
/// The band's value at each sample; `None` where it has no data.
pub values: Vec<Option<f64>>,
/// The raster's cells along the section line, when there are more than the samples read
/// ([`MAX_PROFILE_SAMPLES`]).
pub cells: Option<usize>,
}

impl ProfileSamples {
/// The least and most of the values read, if any.
pub fn range(&self) -> Option<(f64, f64)> {
let mut it = self.values.iter().flatten().copied();
let first = it.next()?;
Some(it.fold((first, first), |(lo, hi), v| (lo.min(v), hi.max(v))))
}
}

/// How many points of the line a profile probes to count the raster's cells it crosses.
const CELL_PROBES: usize = 64;

/// A profile's frame, section line and raster in `layout` over `maps`, and what it reads along
/// the line: a sample per cell of the raster it crosses (at most [`MAX_PROFILE_SAMPLES`]), each at
/// its point of the line on the page, taken back through the frame's projection to the ground and
/// read bilinearly there ([`rustgis_data::raster::Raster::bilinear`]), with no smoothing.
/// `Err` says why it draws nothing.
pub fn profile_samples(layout: &Layout, maps: &[Map], p: &Profile) -> Result<(ProfileSamples, Section), String> {
let frame = layout.element(p.frame).ok_or("its map frame is missing")?;
let ElementKind::MapFrame { map, center, scale, bearing, pitch, shape, sections, .. } = &frame.kind else {
return Err("its map frame is missing".into());
};
let map = map_index(maps, map).and_then(|i| maps.get(i)).ok_or("its frame's map is missing")?;
let section = Section::find(sections, &p.section)
.and_then(|i| sections.get(i))
.ok_or_else(|| format!("its frame has no section line '{}'", p.section))?;
if !p.side.suits(section.line) {
return Err(format!(
"a {} section line's profile goes {}, not {}",
section.line.code(),
if p.side.is_horizontal() { "left or right of its frame" } else { "under or over its frame" },
p.side.code()
));
}
let cam = frame_camera(map, *center, *scale, *bearing, *pitch);
if map.projection.is_globe() || cam.pitch.abs() > 1e-9 {
return Err("its frame is tilted or on the globe, where a line straight on the page isn't a section of the ground".into());
}
let layer = map
.layer_by_name(&p.layer)
.filter(|l| l.is_raster())
.ok_or_else(|| format!("the frame's map has no raster layer '{}'", p.layer))?;
let rl = layer.raster.as_ref().ok_or_else(|| format!("the frame's map has no raster layer '{}'", p.layer))?;
if rl.in_place || rl.tiled {
return Err(format!("its layer '{}' is read in place, a part at a time, not held whole", layer.name));
}
let r = rl.data.as_ref().ok_or_else(|| format!("its layer '{}' has no pixels read", layer.name))?;
if r.overview.is_some() {
return Err(format!("its layer '{}' holds only an overview of its file", layer.name));
}
if !r.georeferenced {
return Err(format!("its layer '{}' isn't placed on the ground", layer.name));
}
let band = usize::try_from(p.band).ok().and_then(|b| b.checked_sub(1)).unwrap_or(usize::MAX);
if band >= r.bands.len() {
return Err(format!("its layer '{}' has no band {} (it has {})", layer.name, p.band, r.bands.len()));
}
let (fw, fh) = (frame.w * PT_PER_MM, frame.h * PT_PER_MM);
let [start, end] = section_ends(map, &cam, (fw, fh), shape, section.line)
.map_err(|why| format!("its section line '{}' isn't drawn: {why}", section.name))?;
// Along the line and across it: a vertical line is worked out with the axes swapped.
let vertical = matches!(section.line, SectionLine::Vertical(_));
let swap = |(x, y): (f64, f64)| if vertical { (y, x) } else { (x, y) };
let ((a, across), (b, _)) = (swap(start), swap(end));
let lonlat = |along: f64| {
let (x, y) = swap((along, across));
cam.try_to_map(x, y, fw, fh).and_then(|m| map.to_lonlat(m)).filter(|c| c.x.is_finite() && c.y.is_finite())
};
// The cells the line crosses, counted along it in the raster's own grid.
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
let cell = |c: Coord| r.transformer().from_lonlat(c).map(|w| r.transform.to_pixel(w));
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
let probes: Vec<(f64, f64)> =
(0..=CELL_PROBES).filter_map(|i| lonlat(a + (b - a) * i as f64 / CELL_PROBES as f64).and_then(cell)).collect();
// A geographic grid's columns either side of 180° are a turn apart: a step between them is
// the short way round.
let turn = r.transformer().is_geographic().then(|| 360.0 / r.transform.pixel_width.abs());
let step = |d: f64| turn.map_or(d, |t| (d + t / 2.0).rem_euclid(t) - t / 2.0);
let crossed: f64 = probes.windows(2).map(|w| if let [p, q] = w { step(q.0 - p.0).hypot(q.1 - p.1) } else { 0.0 }).sum();
let cells = if crossed.is_finite() { crossed.ceil() as usize } else { 0 };
let n = cells.saturating_add(1).clamp(2, MAX_PROFILE_SAMPLES);
let mut out = ProfileSamples { cells: (cells.saturating_add(1) > MAX_PROFILE_SAMPLES).then_some(cells), ..ProfileSamples::default() };
let (mut metres, mut last) = (0.0, None);
for i in 0..n {
let along = a + (b - a) * i as f64 / (n - 1) as f64;
// Off the ground there is no distance from A to measure.
let at =
lonlat(along).ok_or_else(|| format!("its section line '{}' runs off the ground of the frame's projection", section.name))?;
if let Some(p) = last {
metres += rustgis_geom::wgs84_distance_m(p, at);
}
last = Some(at);
out.along.push(along);
out.metres.push(metres);
out.values.push(r.bilinear(band, at));
}
if out.values.iter().all(Option::is_none) {
return Err(format!("its layer '{}' has no data along section line '{}'", layer.name, section.name));
}
Ok((out, section.clone()))
}

#[cfg(test)]
#[path = "profile_tests.rs"]
mod tests;
Loading
Loading