diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index 91eedf510f..548e134dfe 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -161,7 +161,7 @@ gpkg.addLayer path table? limit? name? gpkg.discardEdits layer? gpkg.pendingEdits layer? gpkg.saveEdits layer? -graphics.add shape points layer? text? fill? outline? width? size? fontSize? bold? italic? align? letterSpacing? image? path? +graphics.add shape points layer? text? fill? outline? width? size? fontSize? bold? italic? align? letterSpacing? image? path? frame? graphics.edit layer row points? text? fontSize? bold? italic? align? letterSpacing? fill? outline? width? size? graphics.keepTool on? graphics.newLayer name? diff --git a/crates/engine/src/cmd/graphics.rs b/crates/engine/src/cmd/graphics.rs index 34e6be67bd..7259f51bca 100644 --- a/crates/engine/src/cmd/graphics.rs +++ b/crates/engine/src/cmd/graphics.rs @@ -27,7 +27,7 @@ pub fn commands() -> Vec { }).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"name"?: string}"#), C::new("graphics.add", "Add Graphic", "Edit › Graphics", add).roles(&[]).effects(crate::policy::Effects::NONE).params( - r##"{"shape": "point"|"text"|"line"|"curve"|"freehand"|"polygon"|"lasso"|"rectangle"|"circle"|"ellipse"|"picture", "points": [[lon, lat], …] (rectangle, ellipse, picture: two corners; circle: centre and a point on the edge), "layer"?: graphics layer, "text"?: string (dynamic tokens: {map} {scale} {date} {time} {crs} {layers} {center}), "fill"?: "#RRGGBBAA", "outline"?: "#RRGGBBAA", "width"?: number, "size"?: number, "fontSize"?: number, "bold"?: bool, "italic"?: bool, "align"?: "left"|"center"|"right" (a text's lines in their block, which stays centred on its point), "letterSpacing"?: points, -5 to 50, "image"?: base64 PNG/JPEG, "path"?: picture file}"##, + r##"{"shape": "point"|"text"|"line"|"curve"|"freehand"|"polygon"|"lasso"|"rectangle"|"circle"|"ellipse"|"picture", "points": [[lon, lat], …] (rectangle, ellipse, picture: two corners; circle: centre and a point on the edge), "layer"?: graphics layer, "text"?: string (dynamic tokens: {map} {scale} {date} {time} {crs} {layers} {center}), "fill"?: "#RRGGBBAA", "outline"?: "#RRGGBBAA", "width"?: number, "size"?: number, "fontSize"?: number, "bold"?: bool, "italic"?: bool, "align"?: "left"|"center"|"right" (a text's lines in their block, which stays centred on its point), "letterSpacing"?: points, -5 to 50, "image"?: base64 PNG/JPEG, "path"?: picture file, "frame"?: "mercator" (default: a rectangle a box of longitudes and latitudes, a circle, ellipse or curve round in Web Mercator)|"view" (built in the map's own coordinates as the view faces, as a drag on the map previews it; a picture stays a box of longitudes and latitudes)}"##, ), C::new("graphics.style", "Graphic Style", "Edit › Graphics", style).roles(&[]).effects(crate::policy::Effects::NONE) .when(super::need_selection) @@ -84,21 +84,56 @@ fn target(s: &mut Session, p: &Value) -> Result { }) } -fn points(p: &Value) -> Result, String> { +impl Plane { + /// The latitude a graphic's points are kept within: 85° in Web Mercator (the default plane, + /// or a view of a Web Mercator map), where a pole is infinitely far; 90° in a view of a map + /// in another projection, which may show a pole. + fn lat_max(&self) -> f64 { + if matches!(self, Plane::View { flat: rustgis_map::projection::Flat::Custom(_), .. }) { 90.0 } else { 85.0 } + } + + /// `pts` kept within [`Plane::lat_max`], and how many were moved to it. + fn clamped(&self, pts: impl IntoIterator) -> (Vec, usize) { + let m = self.lat_max(); + let mut moved = 0; + let pts = pts + .into_iter() + .map(|c| { + let y = c.y.clamp(-m, m); + moved += usize::from(y != c.y); + Coord::new(c.x, y) + }) + .collect(); + (pts, moved) + } +} + +/// The points given, in longitude/latitude, kept within `plane`'s latitude +/// ([`Plane::clamped`]), and how many were moved to it. +fn points(p: &Value, plane: &Plane) -> Result<(Vec, usize), String> { let arr = p.get("points").and_then(Value::as_array).ok_or("points is required")?; if arr.len() > MAX_POINTS { return Err(format!("a graphic takes at most {MAX_POINTS} points")); } - arr.iter() + let given = arr + .iter() .map(|v| { let x = v.get(0).and_then(Value::as_f64).filter(|x| x.is_finite() && x.abs() <= 540.0); let y = v.get(1).and_then(Value::as_f64).filter(|y| y.is_finite() && y.abs() <= 90.0); match (x, y) { - (Some(x), Some(y)) => Ok(Coord::new(x, y.clamp(-85.0, 85.0))), + (Some(x), Some(y)) => Ok(Coord::new(x, y)), _ => Err("each point is [lon, lat]".to_string()), } }) - .collect() + .collect::, _>>()?; + Ok(plane.clamped(given)) +} + +/// Says that `n` points of a graphic were placed at 85°, where a Web Mercator map stops. +fn say_clamped(s: &mut Session, n: usize) { + if n > 0 { + s.notify(format!("{n} point(s) of the graphic past 85° latitude were placed at 85°: a Web Mercator map can't show a pole"), false); + } } fn need(pts: &[Coord], n: usize, shape: &str) -> Result<(), String> { @@ -121,9 +156,88 @@ fn ring(mut pts: Vec) -> Vec { pts } -/// A smooth curve through the points (Catmull-Rom). -fn curve(pts: &[Coord]) -> Vec { - let m: Vec = pts.iter().map(|c| lonlat_to_merc(*c)).collect(); +/// The plane a graphic's rectangle, circle, ellipse or curve is built in. Web Mercator facing +/// north is what a command builds in unless told otherwise, as every release did; the view's +/// (`"frame": "view"`) is the map's own coordinates turned to the camera's bearing, the plane a +/// shape dragged on the map is previewed in, so what is drawn is what was dragged on any map: on +/// one in UTM a rectangle has the view's square corners, not a box of longitudes and latitudes, +/// and a circle is round there, not round in Web Mercator. +pub enum Plane { + Mercator, + View { flat: rustgis_map::projection::Flat, cos: f64, sin: f64 }, +} + +impl Plane { + /// The plane `"frame"` names: absent or `"mercator"`, Web Mercator; `"view"`, the map's view. + fn of(s: &Session, p: &Value) -> Result { + match p.get("frame") { + None | Some(Value::Null) => Ok(Plane::Mercator), + Some(Value::String(f)) if f == "mercator" => Ok(Plane::Mercator), + Some(Value::String(f)) if f == "view" => Ok(Plane::view(s)), + Some(other) => Err(format!("frame {other} is neither \"view\" nor \"mercator\"")), + } + } + + /// The map's view: its own coordinates, x to the right and y up as the camera faces. + pub fn view(s: &Session) -> Self { + let map = s.map(); + let b = map.camera.bearing; + // Exactly 1 and 0 facing north, as the camera turns it. + let (sin, cos) = if b == 0.0 || !b.is_finite() { (0.0, 1.0) } else { b.to_radians().sin_cos() }; + Plane::View { flat: map.flat(), cos, sin } + } + + /// A place in longitude/latitude in the plane; `None` where the map doesn't show it. + fn to(&self, c: Coord) -> Option { + match self { + Plane::Mercator => Some(lonlat_to_merc(c)), + Plane::View { flat, cos, sin } => { + let m = flat.forward_checked(c)?; + Some(Coord::new(m.x * cos - m.y * sin, m.x * sin + m.y * cos)) + } + } + } + + /// A place in the plane in longitude/latitude; `None` past the map's projection: where the + /// place read back isn't one the map shows at that same place (outside a limited projection's + /// area, or folded over), as [`Plane::to`] refuses it. + fn back(&self, v: Coord) -> Option { + match self { + Plane::Mercator => Some(merc_to_lonlat(v)), + Plane::View { flat, cos, sin } => { + let m = Coord::new(v.x * cos + v.y * sin, v.y * cos - v.x * sin); + let c = flat.inverse(m)?; + // Web Mercator reads every place back where it is (past 85° it is clamped as it + // is drawn). + if matches!(flat, rustgis_map::projection::Flat::Mercator) { + return Some(c); + } + let again = flat.forward_checked(c)?; + // A millionth of its size, and at least a millimetre: what a round trip moves a + // place, with room to spare. + let reach = (1e-6 * m.x.abs().max(m.y.abs())).max(1e-3); + ((again.x - m.x).abs() <= reach && (again.y - m.y).abs() <= reach).then_some(c) + } + } + } + + #[cfg(test)] + pub(crate) fn back_for_tests(&self, v: Coord) -> Option { + self.back(v) + } + + fn all_to(&self, pts: &[Coord], shape: &str) -> Result, String> { + pts.iter().map(|c| self.to(*c).ok_or_else(|| format!("a point of the {shape} isn't on the map"))).collect() + } + + fn all_back(&self, pts: impl IntoIterator, shape: &str) -> Result, String> { + pts.into_iter().map(|v| self.back(v).ok_or_else(|| format!("the {shape} reaches past the map's projection"))).collect() + } +} + +/// A smooth curve through the points (Catmull-Rom), in the plane. +fn curve(pts: &[Coord], plane: &Plane) -> Result, String> { + let m = plane.all_to(pts, "curve")?; let n = m.len(); let at = |i: isize| m.get(i.clamp(0, n as isize - 1) as usize).copied().unwrap_or_default(); let mut out = Vec::new(); @@ -141,25 +255,35 @@ fn curve(pts: &[Coord]) -> Vec { if let Some(l) = m.last() { out.push(*l); } - out.into_iter().map(merc_to_lonlat).collect() + plane.all_back(out, "curve") } -/// An ellipse inscribed in the box between two corners, drawn round on the flat map. -fn ellipse(a: Coord, b: Coord) -> Vec { - let (a, b) = (lonlat_to_merc(a), lonlat_to_merc(b)); +/// An ellipse inscribed in the box between two corners in the plane, drawn round there. +fn ellipse(a: Coord, b: Coord, plane: &Plane, shape: &str) -> Result, String> { let (cx, cy) = ((a.x + b.x) / 2.0, (a.y + b.y) / 2.0); let (rx, ry) = ((a.x - b.x).abs() / 2.0, (a.y - b.y).abs() / 2.0); - ring( - (0..72) - .map(|i| { - let t = i as f64 / 72.0 * std::f64::consts::TAU; - merc_to_lonlat(Coord::new(cx + rx * t.cos(), cy + ry * t.sin())) - }) - .collect(), - ) + let around = (0..72).map(|i| { + let t = i as f64 / 72.0 * std::f64::consts::TAU; + Coord::new(cx + rx * t.cos(), cy + ry * t.sin()) + }); + Ok(ring(plane.all_back(around, shape)?)) } -fn geometry(shape: &str, pts: Vec) -> Result { +/// Two corners in the plane, refused when they share a side. +fn corners(pts: &[Coord], plane: &Plane, shape: &str) -> Result<(Coord, Coord), String> { + let (a, b) = ends(pts, shape)?; + let (a, b) = (plane.to(a), plane.to(b)); + let (a, b) = a.zip(b).ok_or_else(|| format!("a corner of the {shape} isn't on the map"))?; + if a.x == b.x || a.y == b.y { + return Err(format!("a{} {shape} needs two different corners", if shape == "ellipse" { "n" } else { "" })); + } + Ok((a, b)) +} + +/// The shape a graphic of `shape` through `pts` (longitude/latitude) takes, built in `plane`. +/// A picture is a box of longitudes and latitudes in every plane: it is drawn upright on the +/// map over its box there. +pub fn geometry(shape: &str, pts: Vec, plane: &Plane) -> Result { Ok(match shape { "point" | "text" => Geometry::Point(*pts.first().ok_or("a point needs a location")?), "line" | "freehand" => { @@ -168,12 +292,18 @@ fn geometry(shape: &str, pts: Vec) -> Result { } "curve" => { need(&pts, 2, shape)?; - Geometry::Line(vec![curve(&pts)]) + Geometry::Line(vec![curve(&pts, plane)?]) } "polygon" | "lasso" => { need(&pts, 3, shape)?; Geometry::Polygon(vec![vec![ring(pts)]]) } + "rectangle" if matches!(plane, Plane::View { .. }) => { + let (a, b) = corners(&pts, plane, shape)?; + let (x0, x1, y0, y1) = (a.x.min(b.x), a.x.max(b.x), a.y.min(b.y), a.y.max(b.y)); + let around = [Coord::new(x0, y0), Coord::new(x1, y0), Coord::new(x1, y1), Coord::new(x0, y1)]; + Geometry::Polygon(vec![vec![ring(plane.all_back(around, shape)?)]]) + } "rectangle" | "picture" => { let (a, b) = ends(&pts, shape)?; if a.x == b.x || a.y == b.y { @@ -190,27 +320,33 @@ fn geometry(shape: &str, pts: Vec) -> Result { } "circle" => { let (c, e) = ends(&pts, shape)?; - let (c, e) = (lonlat_to_merc(c), lonlat_to_merc(e)); + let (c, e) = plane.to(c).zip(plane.to(e)).ok_or("the circle's centre or edge isn't on the map")?; let r = ((e.x - c.x).powi(2) + (e.y - c.y).powi(2)).sqrt(); if r <= 0.0 { return Err("a circle needs a radius".into()); } - Geometry::Polygon(vec![vec![ellipse( - merc_to_lonlat(Coord::new(c.x - r, c.y - r)), - merc_to_lonlat(Coord::new(c.x + r, c.y + r)), - )]]) + Geometry::Polygon(vec![vec![ellipse(Coord::new(c.x - r, c.y - r), Coord::new(c.x + r, c.y + r), plane, shape)?]]) } "ellipse" => { - let (a, b) = ends(&pts, shape)?; - if a.x == b.x || a.y == b.y { - return Err("an ellipse needs two different corners".into()); - } - Geometry::Polygon(vec![vec![ellipse(a, b)]]) + let (a, b) = corners(&pts, plane, shape)?; + Geometry::Polygon(vec![vec![ellipse(a, b, plane, shape)?]]) } other => return Err(format!("unknown shape '{other}'")), }) } +/// The outline a shape dragged between `pts` takes on the map (`"frame": "view"`), in +/// longitude/latitude: what the drag previews, so the preview is the graphic it adds. +pub fn dragged_outline(s: &Session, shape: &str, pts: &[Coord]) -> Option> { + // Kept within the latitude the graphic will be added within, so the outline is the one added. + let plane = Plane::view(s); + let (pts, _) = plane.clamped(pts.iter().copied()); + match geometry(shape, pts, &plane).ok()? { + Geometry::Polygon(p) => p.into_iter().next()?.into_iter().next(), + _ => None, + } +} + /// The italic, alignment and letter spacing a command gives a text (#535): `None` where not given. #[derive(Default)] struct TextStyle { @@ -345,7 +481,9 @@ fn add(s: &mut Session, p: &Value) -> CmdResult { if !graphics::SHAPES.contains(&shape.as_str()) { return Err(format!("unknown shape '{shape}'")); } - let g = geometry(&shape, points(p)?)?; + let plane = Plane::of(s, p)?; + let (pts, clamped) = points(p, &plane)?; + let g = geometry(&shape, pts, &plane)?; let text = ps(p, "text").map(|t| super::within("text", "a graphic's text", t, 2000)).transpose()?; if shape == "text" && text.as_deref().is_none_or(|t| t.trim().is_empty()) { return Err("text is required".into()); @@ -387,6 +525,7 @@ fn add(s: &mut Session, p: &Value) -> CmdResult { } } l.touch_geometry(); + say_clamped(s, clamped); Ok(json!({"layer": id, "row": row, "shape": shape})) } @@ -420,11 +559,14 @@ fn edit(s: &mut Session, p: &Value) -> CmdResult { if !matches!(kind.as_str(), "point" | "text") { return Err("only a point or a text graphic is placed again by its points".into()); } - Some(geometry(&kind, points(p)?)?) + // As the map shows it: a point at 88° on a polar map stays there. + let plane = Plane::view(s); + let (pts, clamped) = points(p, &plane)?; + Some((geometry(&kind, pts, &plane)?, clamped)) } None => None, }; - if let Some(g) = placed { + if let Some((g, clamped)) = placed { let held = super::design::held_places(s, id, &[], &[&g]); let l = s.map_mut().layer_mut(id).ok_or("no such layer")?; // Placed in longitude/latitude, written in the layer's own coordinates. @@ -433,6 +575,7 @@ fn edit(s: &mut Session, p: &Value) -> CmdResult { ft.geometry = Some(g); } l.touch_geometry(); + say_clamped(s, clamped); // A null is no style, as `restyle` reads it: placed with only nulls, it is just placed. let styled = ["text", "fill", "outline", "width", "size", "fontSize", "bold", "italic", "align", "letterSpacing"] .iter() diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f8d2991106..8366e6ad32 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5,6 +5,8 @@ use crate::{Project, Session, sample}; #[path = "tests/formats_out.rs"] mod formats_out; +#[path = "tests/graphics_frames.rs"] +mod graphics_frames; #[cfg(not(target_arch = "wasm32"))] #[path = "tests/held_databases.rs"] mod held_databases; diff --git a/crates/engine/src/tests/graphics_frames.rs b/crates/engine/src/tests/graphics_frames.rs new file mode 100644 index 0000000000..3da4f08d24 --- /dev/null +++ b/crates/engine/src/tests/graphics_frames.rs @@ -0,0 +1,214 @@ +//! A rectangle, circle, ellipse or curve dragged on the map is added as the drag previewed it +//! (#2032 C2f-6, `"frame": "view"`): built in the map's own coordinates as the view faces, on a +//! map in another projection and on one turned. A command that names no frame builds them as +//! every release did. + +use crate::{Project, Session}; +use rustgis_data::Geometry; +use rustgis_geom::Coord; +use serde_json::{Value, json}; + +/// A session on a map in Swiss LV95 (EPSG:2056), whose grid is turned from the meridians away +/// from its centre, looking at the corners used below. +fn on_lv95() -> Session { + let mut s = Session::new(Project::default()); + s.run("map.projection", &json!({"type": "EPSG:2056"})).unwrap(); + s.run("map.goToXY", &json!({"lon": 9.0, "lat": 46.5, "scale": 2_000_000})).unwrap(); + s +} + +/// The outer ring of the graphic `r` added, in longitude/latitude. +fn ring_of(s: &Session, r: &Value) -> Vec { + let (id, row) = (r["layer"].as_u64().unwrap() as u32, r["row"].as_u64().unwrap() as usize); + match s.map().layer(id).unwrap().dataset.features[row].geometry.clone() { + Some(Geometry::Polygon(p)) => p[0][0].clone(), + other => panic!("{other:?}"), + } +} + +/// `c` as the camera places it, in map units from the view's centre: x right, y up on screen. +/// Read through the camera's own turn ([`rustgis_map::camera::Camera::ground_px`]), not the +/// graphics plane's, so a turn the wrong way in either shows. +fn in_view(s: &Session, c: Coord) -> Coord { + let cam = &s.map().camera; + let (u, v) = cam.ground_px(s.map().to_map(c).unwrap()); + Coord::new(u * cam.res, -v * cam.res) +} + +fn close(a: f64, b: f64, tol: f64) -> bool { + (a - b).abs() <= tol * b.abs().max(1.0) +} + +#[test] +fn a_dragged_rectangle_has_the_views_corners_on_any_map() { + for bearing in [0.0, 30.0] { + let mut s = on_lv95(); + s.run("map.setBearing", &json!({"bearing": bearing})).unwrap(); + let r = s.run("graphics.add", &json!({"shape": "rectangle", "points": [[8.0, 46.0], [10.0, 47.0]], "frame": "view"})).unwrap(); + let ring: Vec = ring_of(&s, &r).into_iter().map(|c| in_view(&s, c)).collect(); + assert_eq!(ring.len(), 5); + // Its sides run along the view's x and y. + for w in ring.windows(2) { + let (dx, dy) = (w[1].x - w[0].x, w[1].y - w[0].y); + assert!(dx.abs() < 1e-4 || dy.abs() < 1e-4, "bearing {bearing}: side {dx} {dy}"); + } + // And the corners dragged between are two of its corners. + for c in [Coord::new(8.0, 46.0), Coord::new(10.0, 47.0)] { + let v = in_view(&s, c); + assert!(ring.iter().any(|r| close(r.x, v.x, 1e-7) && close(r.y, v.y, 1e-7)), "bearing {bearing}: {c:?}"); + } + } + // Named by no frame, it is a box of longitudes and latitudes, as before: on LV95 its sides + // don't run along the map's grid. + let mut s = on_lv95(); + let r = s.run("graphics.add", &json!({"shape": "rectangle", "points": [[8.0, 46.0], [10.0, 47.0]]})).unwrap(); + let ring = ring_of(&s, &r); + assert_eq!(ring[..4], [Coord::new(8.0, 46.0), Coord::new(10.0, 46.0), Coord::new(10.0, 47.0), Coord::new(8.0, 47.0)]); + let (a, b) = (in_view(&s, ring[0]), in_view(&s, ring[1])); + assert!((b.y - a.y).abs() > 1_000.0, "a parallel isn't a grid line on LV95: {}", b.y - a.y); +} + +#[test] +fn a_dragged_circle_and_ellipse_are_round_in_the_view() { + let mut s = on_lv95(); + s.run("map.setBearing", &json!({"bearing": -20.0})).unwrap(); + let r = s.run("graphics.add", &json!({"shape": "circle", "points": [[9.0, 46.5], [9.5, 46.5]], "frame": "view"})).unwrap(); + let (c, e) = (in_view(&s, Coord::new(9.0, 46.5)), in_view(&s, Coord::new(9.5, 46.5))); + let radius = ((e.x - c.x).powi(2) + (e.y - c.y).powi(2)).sqrt(); + for p in ring_of(&s, &r) { + let v = in_view(&s, p); + let d = ((v.x - c.x).powi(2) + (v.y - c.y).powi(2)).sqrt(); + // Within what LV95's round trip through longitude/latitude moves a place (a millimetre). + assert!(close(d, radius, 1e-7), "{d} vs {radius}"); + } + // An ellipse fills the view's box between its corners: its widest points touch the box. + let r = s.run("graphics.add", &json!({"shape": "ellipse", "points": [[8.0, 46.0], [10.0, 47.0]], "frame": "view"})).unwrap(); + let (a, b) = (in_view(&s, Coord::new(8.0, 46.0)), in_view(&s, Coord::new(10.0, 47.0))); + let ring: Vec = ring_of(&s, &r).into_iter().map(|p| in_view(&s, p)).collect(); + let max_x = ring.iter().map(|p| p.x).fold(f64::MIN, f64::max); + let min_y = ring.iter().map(|p| p.y).fold(f64::MAX, f64::min); + assert!(close(max_x, a.x.max(b.x), 1e-7) && close(min_y, a.y.min(b.y), 1e-7), "{max_x} {min_y}"); + // The preview is the outline added. + let preview = crate::cmd::graphics::dragged_outline(&s, "ellipse", &[Coord::new(8.0, 46.0), Coord::new(10.0, 47.0)]).unwrap(); + assert_eq!(preview, ring_of(&s, &r)); +} + +#[test] +fn a_frame_other_than_view_or_mercator_is_refused() { + let mut s = on_lv95(); + let e = s.run("graphics.add", &json!({"shape": "rectangle", "points": [[8.0, 46.0], [10.0, 47.0]], "frame": "map"})).unwrap_err(); + assert!(e.contains("frame \"map\""), "{e}"); + let e = s.run("graphics.add", &json!({"shape": "rectangle", "points": [[8.0, 46.0], [10.0, 47.0]], "frame": true})).unwrap_err(); + assert!(e.contains("frame true"), "{e}"); + // A shape that leaves the map's projection is refused, not drawn folded. + let e = s.run("graphics.add", &json!({"shape": "rectangle", "points": [[-170.0, -80.0], [170.0, 80.0]], "frame": "view"})).unwrap_err(); + assert!(e.contains("isn't on the map") || e.contains("past the map's projection"), "{e}"); +} + +/// On a map that shows a pole, a corner dragged past 85° is added where it was dragged, as the +/// preview shows it: only Web Mercator keeps points within 85° of the equator. +#[test] +fn a_dragged_corner_near_a_pole_stays_where_it_was_dragged() { + let mut s = Session::new(Project::default()); + s.run("map.projection", &json!({"type": "EPSG:3413"})).unwrap(); + s.run("map.goToXY", &json!({"lon": -45.0, "lat": 88.0, "scale": 20_000_000})).unwrap(); + let corners = [Coord::new(-60.0, 87.0), Coord::new(-30.0, 88.5)]; + let r = s.run("graphics.add", &json!({"shape": "rectangle", "points": [[-60.0, 87.0], [-30.0, 88.5]], "frame": "view"})).unwrap(); + let ring = ring_of(&s, &r); + for c in corners { + assert!(ring.iter().any(|p| (p.x - c.x).abs() < 1e-6 && (p.y - c.y).abs() < 1e-6), "{c:?} in {ring:?}"); + } + assert_eq!(crate::cmd::graphics::dragged_outline(&s, "rectangle", &corners).unwrap(), ring); +} + +/// The point a graphic `r` added is at, in longitude/latitude. +fn point_of(s: &Session, layer: u64, row: u64) -> Coord { + match s.map().layer(layer as u32).unwrap().dataset.features[row as usize].geometry.clone() { + Some(Geometry::Point(c)) => c, + other => panic!("{other:?}"), + } +} + +#[test] +fn a_point_keeps_within_85_degrees_on_a_web_mercator_map_and_not_on_a_polar_one() { + // Web Mercator, where a pole is infinitely far: clicked at 88°, placed at 85° as the map + // draws it, by `"frame": "view"` as by the default. + let mut s = Session::new(Project::default()); + for frame in [json!("view"), Value::Null] { + let r = s.run("graphics.add", &json!({"shape": "point", "points": [[10.0, 88.0]], "frame": frame})).unwrap(); + assert_eq!(point_of(&s, r["layer"].as_u64().unwrap(), r["row"].as_u64().unwrap()), Coord::new(10.0, 85.0), "{frame}"); + } + // A polar map shows the pole: a point at 88° stays there, added and placed again. + let mut s = Session::new(Project::default()); + s.run("map.projection", &json!({"type": "EPSG:3413"})).unwrap(); + let r = s.run("graphics.add", &json!({"shape": "point", "points": [[0.0, 88.0]], "frame": "view"})).unwrap(); + let (layer, row) = (r["layer"].as_u64().unwrap(), r["row"].as_u64().unwrap()); + assert_eq!(point_of(&s, layer, row), Coord::new(0.0, 88.0)); + s.run("graphics.edit", &json!({"layer": layer, "row": row, "points": [[5.0, 88.5]]})).unwrap(); + assert_eq!(point_of(&s, layer, row), Coord::new(5.0, 88.5)); + // Below 85° nothing is clamped on either map. + s.run("graphics.edit", &json!({"layer": layer, "row": row, "points": [[5.0, 60.0]]})).unwrap(); + assert_eq!(point_of(&s, layer, row), Coord::new(5.0, 60.0)); +} + +#[test] +fn the_view_turns_as_the_screen_does() { + // Turned 90°, east is up on screen: a rectangle dragged from west to east is tall on screen + // and its east side is at the top. + let mut s = on_lv95(); + s.run("map.setBearing", &json!({"bearing": 90.0})).unwrap(); + let (w, e) = (in_view(&s, Coord::new(8.0, 46.5)), in_view(&s, Coord::new(10.0, 46.5))); + assert!(e.y - w.y > 100_000.0 && (e.x - w.x).abs() < 20_000.0, "{w:?} {e:?}"); + let r = s.run("graphics.add", &json!({"shape": "rectangle", "points": [[8.0, 46.4], [10.0, 46.6]], "frame": "view"})).unwrap(); + let ring: Vec = ring_of(&s, &r).into_iter().map(|c| in_view(&s, c)).collect(); + for w in ring.windows(2) { + let (dx, dy) = (w[1].x - w[0].x, w[1].y - w[0].y); + assert!(dx.abs() < 1e-4 || dy.abs() < 1e-4, "side {dx} {dy}"); + } +} + +#[test] +fn a_ring_point_past_the_maps_projection_is_refused() { + // A plane point far past LV95's area reads back to no place the map shows there. + let s = on_lv95(); + let plane = crate::cmd::graphics::Plane::view(&s); + assert!(plane.back_for_tests(Coord::new(2_600_000.0, 1_200_000.0)).is_some()); + assert!(plane.back_for_tests(Coord::new(9e7, 9e7)).is_none()); +} + +#[test] +fn a_circle_near_85_degrees_on_a_web_mercator_map_is_drawn_and_one_round_the_pole_on_a_polar_map() { + // The default map: a circle near 85° is added whole, within the 85° its points are kept in. + let mut s = Session::new(Project::default()); + let r = s.run("graphics.add", &json!({"shape": "circle", "points": [[0.0, 84.0], [0.0, 84.9]], "frame": "view"})).unwrap(); + let ring = ring_of(&s, &r); + assert_eq!(ring.len(), 73, "{ring:?}"); + assert!(ring.iter().all(|c| c.is_finite() && c.y > 82.0 && c.y <= 85.0), "{ring:?}"); + // A polar map: a circle round the pole, its ring through 90° itself. + let mut s = Session::new(Project::default()); + s.run("map.projection", &json!({"type": "EPSG:3413"})).unwrap(); + let r = s.run("graphics.add", &json!({"shape": "circle", "points": [[-45.0, 89.0], [-45.0, 90.0]], "frame": "view"})).unwrap(); + assert!(ring_of(&s, &r).iter().all(|c| c.y >= 87.9), "{:?}", ring_of(&s, &r)); +} + +#[test] +fn a_drag_previews_and_adds_within_85_degrees_on_a_web_mercator_map_and_says_so() { + // A corner dragged to 85.04° previews, and is added, at 85°, and the command says so; one + // dragged below 85° moves nowhere and says nothing. + let mut s = Session::new(Project::default()); + let corners = [Coord::new(0.0, 84.9), Coord::new(1.0, 85.04)]; + let outline = crate::cmd::graphics::dragged_outline(&s, "rectangle", &corners).unwrap(); + let mark = s.notice_mark(); + let r = s.run("graphics.add", &json!({"shape": "rectangle", "points": [[0.0, 84.9], [1.0, 85.04]], "frame": "view"})).unwrap(); + assert_eq!(outline, ring_of(&s, &r)); + assert!(outline.iter().all(|c| c.y <= 85.0) && outline.iter().any(|c| c.y == 85.0), "{outline:?}"); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(said.iter().any(|t| t.contains("placed at 85°")), "{said:?}"); + let mark = s.notice_mark(); + let below = [Coord::new(0.0, 80.0), Coord::new(1.0, 84.5)]; + let outline = crate::cmd::graphics::dragged_outline(&s, "rectangle", &below).unwrap(); + let r = s.run("graphics.add", &json!({"shape": "rectangle", "points": [[0.0, 80.0], [1.0, 84.5]], "frame": "view"})).unwrap(); + assert_eq!(outline, ring_of(&s, &r)); + assert!(outline.iter().any(|c| (c.y - 84.5).abs() < 1e-9), "{outline:?}"); + assert!(s.notices_since(mark).iter().all(|n| !n.text.contains("85°"))); +} diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index 63da2526d5..f84f174dbb 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -3689,7 +3689,8 @@ pub fn finish_graphic(app: &mut RustGisApp, shape: &str, pts: Vec) { return; } let coords: Vec<[f64; 2]> = pts.iter().map(|c| [c.x, c.y]).collect(); - let ok = app.run("graphics.add", json!({"shape": shape, "points": coords})).is_ok(); + // Built as the view faces, as the drag previewed it. + let ok = app.run("graphics.add", json!({"shape": shape, "points": coords, "frame": "view"})).is_ok(); app.map.cancel_sketch(); // A failed graphic (a click without a drag) keeps the tool; the error is in the notices. if ok && !app.session.keep_tool { @@ -3867,31 +3868,40 @@ fn overlays(app: &mut RustGisApp, ui: &mut Ui, p: &egui::Painter, rect: Rect, t: if !app.map.sketch.is_empty() && let Some(shape) = drag_shape(tool).filter(|s| !matches!(*s, "freehand" | "lasso")) { - // Rectangles, circles and ellipses preview as their outline between the two points. - if let (Some(a), Some(b)) = ( + // Rectangles, circles, ellipses and pictures preview as the outline they are added with + // (`"frame": "view"`): on a map in another projection, or turned, that is what was dragged. + let green = Color32::from_rgb(0x16, 0x9A, 0x5A); + let stroke = Stroke::new(2.0, green); + let outline = rustgis_engine::cmd::graphics::dragged_outline(&app.session, shape, &app.map.sketch); + let pts: Vec = outline.iter().flatten().filter_map(|c| lonlat_to_screen(app, rect, *c)).collect(); + // A picture is drawn upright on screen between its box's north-west and south-east + // corners (render's picture graphics), so it previews as that, turned map or not. + let picture = outline + .as_deref() + .filter(|_| shape == "picture") + .map(|cs| { + cs.iter().fold(Extent::EMPTY, |mut e, c| { + e.expand(*c); + e + }) + }) + .filter(|e| !e.is_empty()) + .and_then(|e| { + Some(( + lonlat_to_screen(app, rect, Coord::new(e.min_x, e.max_y))?, + lonlat_to_screen(app, rect, Coord::new(e.max_x, e.min_y))?, + )) + }); + if let Some((a, b)) = picture { + p.rect_stroke(Rect::from_two_pos(a, b), 0.0, stroke, egui::StrokeKind::Middle); + } else if shape != "picture" && pts.len() == outline.as_ref().map_or(0, Vec::len) && pts.len() >= 3 { + p.add(egui::Shape::closed_line(pts, stroke)); + } else if let (Some(a), Some(b)) = ( app.map.sketch.first().and_then(|c| lonlat_to_screen(app, rect, *c)), app.map.sketch.last().and_then(|c| lonlat_to_screen(app, rect, *c)), ) { - let green = Color32::from_rgb(0x16, 0x9A, 0x5A); - let stroke = Stroke::new(2.0, green); - match shape { - "circle" => { - p.circle_stroke(a, (b - a).length(), stroke); - } - "ellipse" => { - let r = Rect::from_two_pos(a, b); - let pts: Vec = (0..72) - .map(|i| { - let t = i as f32 / 72.0 * std::f32::consts::TAU; - pos2(r.center().x + r.width() / 2.0 * t.cos(), r.center().y + r.height() / 2.0 * t.sin()) - }) - .collect(); - p.add(egui::Shape::closed_line(pts, stroke)); - } - _ => { - p.rect_stroke(Rect::from_two_pos(a, b), 0.0, stroke, egui::StrokeKind::Middle); - } - } + // Not a shape yet (a click without a drag), or partly off the map: the drag itself. + p.rect_stroke(Rect::from_two_pos(a, b), 0.0, stroke, egui::StrokeKind::Middle); } previewed = true; } diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index f269dc6a84..7bee22e373 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -942,7 +942,15 @@ compare it with what's beneath), **Masking** and **Rotation**. **Edit › Graphics** draws shapes in a graphics layer (**Home › Add › Add Data › Graphics Layer**, or one is made with the first graphic). Click once for a Point. Line, Curve and Polygon are clicked vertex by vertex (double-click to finish); Freehand, Lasso, Rectangle, Circle and Ellipse are -dragged. **Edit › Graphics and Text › Text** places a text where you click, as a layout's text +dragged. A dragged Rectangle, Circle or Ellipse is built in the map's own coordinates as the view +faces, so the graphic is the outline the drag previews on any map: on a map in UTM or Swiss LV95, +or turned, a rectangle keeps the view's square corners and a circle is round there; on a map that +shows a pole, a graphic clicked or dragged past 85° stays there (a Web Mercator map, which can't +show a pole, keeps it at 85° and says so). A shape reaching past what the map's projection shows is refused, +not drawn folded. A Curve is smoothed in the +same plane. A picture's rectangle stays a box of longitudes and latitudes, drawn upright. A +`graphics.add` command builds them in Web Mercator facing north, as before, unless it gives +`"frame": "view"`. **Edit › Graphics and Text › Text** places a text where you click, as a layout's text is placed: it says "Text", is selected, and opens in the **Format** pane (beside the other right-hand panes) with its text selected, so you type over it. Shift+Enter starts a new line, and Enter ends the text. Dynamic Text is a menu of values that