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
61 changes: 48 additions & 13 deletions crates/analysis/src/sketch_edit.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
//! Editing a feature with a drawn line: cutting polygons in pieces, reshaping a boundary or a
//! line, and tracing along a feature's edge. Computed in Web Mercator metres, as the other
//! editing tools are; vertices an edit doesn't move keep their exact longitude and latitude.
//! editing tools are; vertices an edit doesn't move keep their exact longitude and latitude. In a
//! run in a projected system's own plane ([`crate::convert::Plane::Own`], #2032 C2f-7) the
//! geometry and the line are in that system's coordinates, and the work is in its own plane, in
//! metres east and north of its grid: a cut or a reshape meets the layer's segments where they
//! run straight, in the layer's own coordinates.

use std::collections::HashMap;

Expand All @@ -24,21 +28,50 @@ fn within_work(a: usize, b: usize) -> Result<(), String> {
/// Why an edit past [`MAX_WORK`] is refused.
const TOO_MUCH: &str = "the shapes and the line have too many vertices to edit together";

/// A point in Web Mercator metres and the longitude/latitude it came from.
/// Whether the run is in a projected system's own plane, rather than in longitude/latitude.
fn own() -> bool {
crate::convert::plane() == crate::convert::Plane::Own
}

/// A place in the plane the work is in, in metres: Web Mercator's for longitude/latitude; east and
/// north of a projected system's grid, by the order and direction of its axes, in its own plane.
fn to_m(c: Coord) -> Coord {
if !own() {
return lonlat_to_merc(c);
}
let u = crate::convert::run_plane().unit_m;
let (e, n) = crate::convert::own_east_north(c.x, c.y);
Coord::new(e * u, n * u)
}

/// [`to_m`] undone.
fn from_m(m: Coord) -> Coord {
if !own() {
return merc_to_lonlat(m);
}
let r = crate::convert::run_plane();
let [(xe, xn), (ye, yn)] = r.axes;
let (e, n) = (m.x / r.unit_m, m.y / r.unit_m);
let det = xe * yn - ye * xn;
Coord::new((e * yn - n * ye) / det, (xe * n - xn * e) / det)
}

/// A point in metres ([`to_m`]) and the coordinates it came from: longitude/latitude, or a
/// projected system's own in its plane.
#[derive(Clone, Copy, Debug)]
struct Pt {
m: Coord,
ll: Coord,
}

impl Pt {
/// An input vertex: its longitude/latitude kept as given.
/// An input vertex: its coordinates kept as given.
fn of(ll: Coord) -> Pt {
Pt { m: lonlat_to_merc(ll), ll }
Pt { m: to_m(ll), ll }
}
/// A new point worked out in metres.
fn at(m: Coord) -> Pt {
Pt { m, ll: merc_to_lonlat(m) }
Pt { m, ll: from_m(m) }
}
}

Expand All @@ -47,12 +80,13 @@ fn dist(a: Coord, b: Coord) -> f64 {
(a.x - b.x).hypot(a.y - b.y)
}

/// The input as metres, refusing coordinates that don't project (a pole, NaN).
/// Longitudes beyond ±360° (as `edit.vertex` takes, for features unwrapped across the
/// antimeridian) aren't coordinates on the Earth.
/// The input as metres ([`to_m`]), refusing coordinates that don't project (a pole, NaN). In
/// longitude/latitude, longitudes beyond ±360° (as `edit.vertex` takes, for features unwrapped
/// across the antimeridian) aren't coordinates on the Earth; in a projected system's own plane
/// any finite coordinate is one.
fn project(path: &[Coord]) -> Result<Vec<Pt>, String> {
let pts: Vec<Pt> = path.iter().map(|c| Pt::of(*c)).collect();
if pts.iter().all(|p| p.m.is_finite() && p.ll.x.abs() <= 360.0 && p.ll.y.abs() <= 90.0) {
if pts.iter().all(|p| p.m.is_finite() && (own() || (p.ll.x.abs() <= 360.0 && p.ll.y.abs() <= 90.0))) {
Ok(pts)
} else {
Err("the shape has coordinates that can't be drawn on the map".into())
Expand All @@ -76,7 +110,7 @@ fn area2(ring: &[Pt]) -> f64 {
ring.windows(2).filter_map(|w| Some((w.first()?.m, w.get(1)?.m))).map(|(a, b)| a.x * b.y - b.x * a.y).sum()
}

/// [`area2`] of a ring in longitude/latitude.
/// [`area2`] of a ring in its coordinates (longitude/latitude, or a projected system's own).
fn area2_ll(ring: &[Coord]) -> f64 {
area2(&ring.iter().map(|c| Pt::of(*c)).collect::<Vec<_>>())
}
Expand Down Expand Up @@ -445,7 +479,7 @@ fn valid(rings: &[Vec<Coord>]) -> bool {

/// A polygon (outer ring, then holes) as a `geo` polygon in metres.
fn geo_polygon(rings: &[Vec<Coord>]) -> Option<geo::Polygon<f64>> {
let ring = |r: &Vec<Coord>| geo::LineString::new(r.iter().map(|c| lonlat_to_merc(*c)).map(|m| geo::coord! {x: m.x, y: m.y}).collect());
let ring = |r: &Vec<Coord>| geo::LineString::new(r.iter().map(|c| to_m(*c)).map(|m| geo::coord! {x: m.x, y: m.y}).collect());
let mut it = rings.iter();
let outer = it.next()?;
Some(geo::Polygon::new(ring(outer), it.map(ring).collect()))
Expand Down Expand Up @@ -799,7 +833,8 @@ pub struct Reshaped {
}

/// A path traced along a feature's edge, and how far (Web Mercator metres, which exceed ground
/// metres by 1/cos(latitude)) its ends were from the points asked for.
/// metres by 1/cos(latitude); in a projected system's own plane, metres of its grid) its ends were
/// from the points asked for.
#[derive(Clone, Debug, PartialEq)]
pub struct Traced {
pub path: Vec<Coord>,
Expand All @@ -825,7 +860,7 @@ fn nearest(path: &[Pt], c: Coord) -> Option<(f64, f64, Coord)> {
/// `part`, when given, is the line part or polygon ring to follow (polygons' rings numbered in
/// order, holes after their outer ring), as already chosen on the map.
pub fn trace(g: &Geometry, from: Coord, to: Coord, part: Option<usize>) -> Result<Traced, String> {
let (f, t) = (lonlat_to_merc(from), lonlat_to_merc(to));
let (f, t) = (to_m(from), to_m(to));
let closed = matches!(g, Geometry::Polygon(_));
if !matches!(g, Geometry::Line(_) | Geometry::Polygon(_)) {
return Err("only lines and polygons can be traced".into());
Expand Down
148 changes: 130 additions & 18 deletions crates/engine/src/cmd/design.rs
Original file line number Diff line number Diff line change
Expand Up @@ -681,7 +681,7 @@ pub fn commands() -> Vec<C> {
.when(need_editable_selection)
.params(r#"{"line": GeoJSON LineString (lon/lat) drawn across the selected line or polygon's boundary}"#),
C::new("edit.trace", "Trace Edge Path", "Edit › Features", sketch::trace).roles(&[]).effects(crate::policy::Effects::NONE).view().params(
r#"{"from": [lon, lat], "to": [lon, lat], "layer"?, "row"?: number (else the nearest edge within the tolerance), "tolerancePx"?: number (default: the snapping tolerance)}"#,
r#"{"from": [lon, lat], "to": [lon, lat], "layer"?, "row"?: number (else the nearest edge within the tolerance), "tolerancePx"?: number (default: the snapping tolerance)} (fromOffM and toOffM in Web Mercator metres, or metres of the grid of a layer held in a projected system)"#,
),
C::new("edit.traverse", "Traverse", "Edit › Features › Modify", traverse).roles(&[]).effects(crate::policy::Effects::NONE).when(need_editable).params(
r#"{"layer"?, "start": [lon, lat], "units"?: "Meters" (default)|"Feet"|"Kilometers"|"Miles", "legs": [{"distance": number, "bearing": degrees from north}]} (closed in a polygon layer, open in a line layer)"#,
Expand Down Expand Up @@ -750,18 +750,18 @@ fn distance_unit_metres(p: &Json) -> Result<f64, String> {
/// longitude/latitude, Web Mercator, another world projection or a geographic system has none,
/// and is edited in Web Mercator or on the ground, as before.
#[derive(Clone, Copy)]
struct OwnGrid {
pub(super) struct OwnGrid {
/// The system.
crs: rustgis_data::raster::Crs,
pub(super) crs: rustgis_data::raster::Crs,
/// Metres per unit of its coordinates.
unit_m: f64,
pub(super) unit_m: f64,
/// The (east, north) of a step of one along x, then along y.
axes: [(f64, f64); 2],
}

impl OwnGrid {
/// The grid layer `l` is edited in, if any.
fn of(l: &rustgis_map::Layer) -> Option<Self> {
pub(super) fn of(l: &rustgis_map::Layer) -> Option<Self> {
let crs = l.dataset.coord_crs();
// Graphics are edited as before: their shapes share no places with features.
if l.is_raster() || l.graphics || !rustgis_analysis::works_in(crs) {
Expand Down Expand Up @@ -1479,7 +1479,9 @@ pub(crate) fn held_places(s: &Session, id: u32, originals: &[&Geometry], edited:
// Only what an edited place still lacks is held from here on.
held.want_only(edited);
let system = l.dataset.coord_crs();
let Ok(to_own) = rustgis_data::raster::Crs::LonLat.to(system) else { return held };
// Through the map's system when the layer is shown through it: the route its stored places
// are read by, so a place snapped to one lands within the box looked in.
let Ok(to_own) = l.dataset.shown_from_lonlat() else { return held };
// The places not held yet, each in the layer's coordinates, and the box they are in there,
// padded by what a round trip moves a place: a stored place reading as one lies within it.
let mut within = rustgis_geom::Extent::EMPTY;
Expand Down Expand Up @@ -1509,6 +1511,23 @@ pub(crate) fn held_places(s: &Session, id: u32, originals: &[&Geometry], edited:
held
}

/// A line drawn on the map, in longitude/latitude, in the coordinates of layer `id`, held in a
/// projected system, for an edit worked out there (#2032 C2f-7): a point snapped to a stored place
/// of a layer in that system is that place, as stored ([`held_places`]); any other is converted
/// as the layer is drawn ([`rustgis_data::Dataset::shown_from_lonlat`]).
pub(super) fn line_in_own(s: &Session, id: u32, line: &[Coord]) -> Result<Vec<Coord>, String> {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
let held = held_places(s, id, &[], &[&Geometry::Line(vec![line.to_vec()])]);
// Through the map's system when the layer is shown through it, as its features are drawn.
let to = s.map().layer(id).ok_or("no such layer")?.dataset.shown_from_lonlat()?;
line.iter()
.map(|c| {
held.get(*c)
.or_else(|| to.point(*c))
.ok_or_else(|| "a point of the line is no place in the layer's coordinate system".to_string())
})
.collect()
}

/// How far a round trip through longitude/latitude may move place `c`, in its own units, with
/// room to spare: a millionth of its size.
fn round_trip_reach(c: Coord) -> f64 {
Expand Down Expand Up @@ -1565,15 +1584,20 @@ fn merge(s: &mut Session, _: &Json) -> CmdResult {
if sel.len() < 2 {
return Err("select two or more features to merge".into());
}
// Merged in longitude/latitude, from the layer's own coordinates, and written back in them, the
// places it keeps as stored.
// A feature with a place that can't be given there refuses the merge, naming it: the merged
// shape would lose that place.
// Held in a projected system, merged in its own coordinates, as they are: the shapes are
// unioned where their segments run straight there (#2032 C2f-7), and nothing is converted.
// Otherwise merged in longitude/latitude, from the layer's own coordinates, and written back
// in them, the places it keeps as stored; a feature with a place that can't be given there
// refuses the merge, naming it: the merged shape would lose that place.
let own = OwnGrid::of(l).is_some();
let with_ids: Vec<(u64, &Geometry)> =
sel.iter().filter_map(|r| l.dataset.features.row(*r)).filter_map(|f| Some((f.id(), f.geometry()?))).collect();
let originals: Vec<&Geometry> = with_ids.iter().map(|(_, g)| *g).collect();
let geoms: Vec<Geometry> =
with_ids.iter().map(|(fid, g)| l.dataset.feature_to_lonlat(*fid, g).map(std::borrow::Cow::into_owned)).collect::<Result<_, _>>()?;
let geoms: Vec<Geometry> = if own {
originals.iter().map(|g| (*g).clone()).collect()
} else {
with_ids.iter().map(|(fid, g)| l.dataset.feature_to_lonlat(*fid, g).map(std::borrow::Cow::into_owned)).collect::<Result<_, _>>()?
};
let kind = |g: &Geometry| match g {
Geometry::Point(_) | Geometry::MultiPoint(_) => 0,
Geometry::Line(_) => 1,
Expand All @@ -1582,12 +1606,19 @@ fn merge(s: &mut Session, _: &Json) -> CmdResult {
if geoms.len() != sel.len() || geoms.windows(2).any(|w| w.first().map(kind) != w.get(1).map(kind)) {
return Err("merge features of one kind (all points, all lines or all polygons), each with a shape".into());
}
let merged = rustgis_analysis::topology::merge(&geoms).ok_or("these features can't be merged")?;
let mut held = rustgis_data::HeldPlaces::default();
for g in &originals {
l.dataset.hold_places(g, None, &mut held);
}
let merged = l.dataset.edit_from_lonlat(merged, &held)?;
let merged = {
let _plane = own.then(|| rustgis_analysis::convert::install(rustgis_analysis::convert::run_plane_for(l.dataset.coord_crs())));
rustgis_analysis::topology::merge(&geoms).ok_or("these features can't be merged")?
};
let merged = if own {
merged
} else {
let mut held = rustgis_data::HeldPlaces::default();
for g in &originals {
l.dataset.hold_places(g, None, &mut held);
}
l.dataset.edit_from_lonlat(merged, &held)?
};
let keep = sel.first().copied().ok_or("nothing selected")?;
let mut changes = Vec::new();
for r in sel.iter().skip(1).rev() {
Expand Down Expand Up @@ -1648,6 +1679,9 @@ fn split(s: &mut Session, p: &Json) -> CmdResult {
return Err("lon and lat are degrees".into());
}
let id = selection_layer(s)?;
if let Some(grid) = s.map().layer(id).and_then(OwnGrid::of) {
return split_own(s, id, grid, at);
}
let l = s.map_mut().layer_mut(id).ok_or("no such layer")?;
// A vertex past ±90° is no place: the search would take it for the pole, so the lines are
// refused up front, before any is split.
Expand Down Expand Up @@ -1829,6 +1863,84 @@ fn split(s: &mut Session, p: &Json) -> CmdResult {
Ok(json!({"split": true}))
}

/// [`split`] of the selected lines of layer `id`, held in `grid`'s projected system, in its own
/// coordinates (#2032 C2f-7): at the point nearest `at` (longitude/latitude) on its segments as they run straight there, measured flat in its

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 doc line runs past the 140-column max_width in rustfmt.toml. rustfmt leaves comments alone, so cargo fmt --check won't flag it, but it should be rewrapped with the rest of the paragraph.

Category: quality

/// grid. Every place of the line stays as stored; only the point it is split at is new.
fn split_own(s: &mut Session, id: u32, grid: OwnGrid, at: Coord) -> CmdResult {
// Converted as the layer is drawn; the split point is projected onto a segment anyway, so
// stored places aren't looked up for it.
let to_own = s.map().layer(id).ok_or("no such layer")?.dataset.shown_from_lonlat()?;
let at = to_own.point(at).ok_or("the point to split at is no place in the layer's coordinate system")?;
// A millimetre and a centimetre of the grid, in its units.
let (mm, cm) = (0.001 / grid.unit_m, 0.01 / grid.unit_m);
let l = s.map_mut().layer_mut(id).ok_or("no such layer")?;
let (mut changes, mut unmeasured) = (Vec::new(), 0usize);
for r in l.selection.clone() {
let Some(Geometry::Line(parts)) = l.dataset.features.geometry(r) else { continue };
let parts = parts.clone();
let mut best: Option<(f64, usize, usize, Coord)> = None;
for (pi, part) in parts.iter().enumerate() {
for (si, w) in part.windows(2).enumerate() {
let (a, b) = (w[0], w[1]);
if !(a.is_finite() && b.is_finite()) {
unmeasured += 1;
continue;
}
let (dx, dy) = (b.x - a.x, b.y - a.y);
let len2 = dx * dx + dy * dy;
let t = if len2 > 0.0 { (((at.x - a.x) * dx + (at.y - a.y) * dy) / len2).clamp(0.0, 1.0) } else { 0.0 };
let q = Coord::new(a.x + t * dx, a.y + t * dy);
let d = (q.x - at.x).hypot(q.y - at.y);
// A segment too long to measure (its distance not a number) is passed over.
if !d.is_finite() {
unmeasured += 1;
} else if best.is_none_or(|b| d < b.0) {
best = Some((d, pi, si, q));
}
}
}
let Some((_, pi, si, q)) = best else { continue };
let Some(part) = parts.get(pi) else { continue };
let apart = |a: &Coord, b: Coord| (a.x - b.x).hypot(a.y - b.y);
// At a vertex (to within a millimetre), the parts meet there, without it repeated.
let q = [part.get(si), part.get(si + 1)].into_iter().flatten().find(|v| apart(v, q) < mm).copied().unwrap_or(q);
let mut first: Vec<Coord> = part.iter().take(si + 1).copied().collect();
if first.last() != Some(&q) {
first.push(q);
}
let mut second = vec![q];
second.extend(part.iter().skip(si + 1).copied().skip_while(|c| *c == q));
// At (or within a centimetre of) the line's ends isn't a split.
let near = |a: Option<&Coord>| a.is_some_and(|a| apart(a, q) < cm);
if first.len() < 2 || second.len() < 2 || near(first.first()) || near(second.last()) {
continue;
}
let mut a_parts: Vec<Vec<Coord>> = parts.iter().take(pi).cloned().collect();
a_parts.push(first);
let mut b_parts = vec![second];
b_parts.extend(parts.iter().skip(pi + 1).cloned());
let Some(f) = l.dataset.features.get(r).cloned() else { continue };
l.dataset.features.set_geometry(r, Some(Geometry::Line(a_parts)));
l.dataset.push(Some(Geometry::Line(b_parts)), f.attrs.clone());
changes.push(Change { before: Some(f), row: Some(r) });
changes.push(Change { before: None, row: Some(l.dataset.features.len() - 1) });
}
if changes.is_empty() {
if unmeasured > 0 {
return Err(format!(
"no line could be split away from its ends; {unmeasured} segment(s) could not be measured because of invalid coordinates"
));
}
return Err("select a line to split (away from its ends)".into());
}
l.touch_geometry();
apply(s, id, changes)?;
if unmeasured > 0 {
s.warn(format!("{unmeasured} segment(s) of the selected lines could not be measured because of invalid coordinates; the split search skipped them, so the point found may not be the nearest"));

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 is a new notice on the own-grid Split path, and nothing tests it either way. AGENTS.md asks for a lossy input to give the notice and a clean input to give none. own_segments.rs has no notice assertions. Please add one test with a segment that has a non-finite coordinate (expects this warning, with its count) and one clean split (expects no warning).

Category: agents-md

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 4b537a7: a_split_says_how_many_segments_it_couldnt_measure_and_a_clean_one_says_nothing covers both. A line with a vertex missing a coordinate gives the warning with its count, 2 segments; a clean line gives none.

}
Ok(json!({"split": true}))
}

/// How many ground distances one split may work out along segments (a million, as its notices
/// say); past them, a segment counts as near as the nearest point found on it so far, its nearer
/// end at first.
Expand Down
Loading
Loading