diff --git a/crates/doc/src/perspective.rs b/crates/doc/src/perspective.rs index ab347529e6..d1322de74f 100644 --- a/crates/doc/src/perspective.rs +++ b/crates/doc/src/perspective.rs @@ -5,9 +5,10 @@ //! stay attached and deleted objects leave nothing stale behind. use serde::{Deserialize, Serialize}; -use vectorcraft_geom::{Homography, Rect}; +use vectorcraft_geom::{Homography, Point, Rect}; -use crate::{Node, NodeKind}; +use crate::symbols::SYMBOL_SQUARE; +use crate::{Node, NodeKind, SymbolBoxes}; /// The plane an object in perspective lies on. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] @@ -58,6 +59,33 @@ impl Node { } } + /// The corners of the box a symbol instance or type is drawn in, on the page (top left, top + /// right, bottom right, bottom left): an instance's art box (measured from `symbols`, or + /// `SYMBOL_SQUARE` when it has none) placed by its transform, and type's flat bounds, both + /// through the projection of type or an instance in perspective. Joined by straight lines, + /// they outline the box as drawn. When the projection sends a corner to infinity the corners + /// stay flat, as the flat box is kept for [`Node::geometric_bounds_with`]. `None` for other + /// objects and for type without bounds. + pub fn drawn_corners(&self, symbols: &SymbolBoxes) -> Option<[Point; 4]> { + let flat = match &self.kind { + NodeKind::SymbolInstance { symbol, xf } => { + let art = symbols.art(symbol).map_or(SYMBOL_SQUARE, |a| a.geometric); + [(art.x0, art.y0), (art.x1, art.y0), (art.x1, art.y1), (art.x0, art.y1)].map(|(x, y)| *xf * Point::new(x, y)) + } + NodeKind::Text(t) => { + let b = t.bounds()?; + [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)].map(|(x, y)| Point::new(x, y)) + } + _ => return None, + }; + let Some(h) = self.projection() else { return Some(flat) }; + let [a, b, c, d] = flat.map(|p| h.apply(p)); + Some(match (a, b, c, d) { + (Some(a), Some(b), Some(c), Some(d)) => [a, b, c, d], + _ => flat, + }) + } + /// Keep a projection drawing the same picture moved by `a` (the flat art moves by `a` too). An /// invertible `a` that the projection cannot follow removes it, and the art is drawn flat. pub(crate) fn transform_projection(&mut self, a: vectorcraft_geom::Affine) { diff --git a/crates/ui-egui/src/canvas/outline.rs b/crates/ui-egui/src/canvas/outline.rs index 7a80d814d6..50ab4ed40a 100644 --- a/crates/ui-egui/src/canvas/outline.rs +++ b/crates/ui-egui/src/canvas/outline.rs @@ -8,9 +8,9 @@ pub(super) fn c32(rgb: [u8; 3]) -> Color32 { Color32::from_rgb(rgb[0], rgb[1], rgb[2]) } -/// Outline of a node for highlighting (paths, compound children, area type frames, other -/// text/image bounds, symbol instances' bounds measured by their art from `symbols`; a clip -/// group's clipping path only, as [`walk_drawn`] visits it). +/// Outline of a node for highlighting (paths, compound children, area type frames, image bounds, +/// the box as drawn of type in perspective and of symbol instances, whose art `symbols` measures +/// ([`Node::drawn_corners`]); a clip group's clipping path only, as [`walk_drawn`] visits it). pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath { let mut bp = BezPath::new(); walk_drawn(n, &mut |c| match &c.kind { @@ -27,13 +27,19 @@ pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath { bp.line_to(t.xf * b); } } - } else if let Some(b) = c.geometric_bounds_with(symbols) { + } else if let Some(q) = c.drawn_corners(symbols) { + corners(&mut bp, q); + } + } + NodeKind::Image(_) => { + if let Some(b) = c.geometric_bounds_with(symbols) { bp.extend(vectorcraft_geom::shapes::rectangle(b).to_bezpath()); } } - NodeKind::Image(_) | NodeKind::SymbolInstance { .. } => { - if let Some(b) = c.geometric_bounds_with(symbols) { - bp.extend(vectorcraft_geom::shapes::rectangle(b).to_bezpath()); + // A symbol instance shows its art's box, turned, skewed or in perspective with it. + NodeKind::SymbolInstance { .. } => { + if let Some(q) = c.drawn_corners(symbols) { + corners(&mut bp, q); } } // A placed document shows its box, turned with it. @@ -56,6 +62,14 @@ pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath { bp } +/// Adds the closed outline through the four corners `q` to `bp`. +fn corners(bp: &mut BezPath, q: [Point; 4]) { + let [a, b, c, d] = q; + bp.move_to(a); + [b, c, d].into_iter().for_each(|p| bp.line_to(p)); + bp.close_path(); +} + /// The most points ([`overlay_points`]) the selection's outlines and anchors, and the hover /// highlight, are drawn for: an Image Trace of a photo selects hundreds of thousands of paths at /// once, and selecting all of an opened PDF can select as many type objects, images and gradient diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 4d11dc884d..24ec91b2ca 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -53,6 +53,94 @@ fn a_symbol_instance_is_outlined_around_its_art() { assert_eq!(node_outline(inst.unwrap(), &st.doc.symbol_boxes()).bounding_box(), Rect::new(20.0, 30.0, 40.0, 50.0)); } +/// The points of `bp`'s move and line elements, in order. +fn outline_points(bp: &vectorcraft_geom::BezPath) -> Vec { + use vectorcraft_geom::kurbo::PathEl; + bp.elements() + .iter() + .filter_map(|el| match el { + PathEl::MoveTo(p) | PathEl::LineTo(p) => Some(*p), + _ => None, + }) + .collect() +} + +/// Whether `got` are the points `want`, each within 1e-9, a last point of `got` that repeats its +/// first left out. +fn same_points(got: &[Point], want: &[Point]) -> bool { + let near = |a: &Point, b: &Point| a.distance(*b) < 1e-9; + let got = match got { + [first, rest @ .., last] if !rest.is_empty() && near(first, last) => &got[..got.len() - 1], + _ => got, + }; + got.len() == want.len() && got.iter().zip(want).all(|(a, b)| near(a, b)) +} + +/// Puts `n` in perspective, drawn through `h`. +fn in_perspective(n: &mut Node, h: vectorcraft_geom::Homography) { + let at = vectorcraft_doc::PerspectiveAttachment { projection: Some(h.to_array()), ..vectorcraft_doc::PerspectiveAttachment::new("left", 0.0) }; + n.extras_mut().perspective = Some(Box::new(at)); +} + +#[test] +fn a_turned_or_skewed_symbol_instance_is_outlined_along_its_frame() { + // The 20 × 20 square symbol of the test above, its instance at (20, 30). + let svg = r##""##; + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "star.svg", "dataBase64": vectorcraft_format::base64_encode(svg.as_bytes())})).unwrap(); + let st = s.active().unwrap(); + let mut inst = None; + st.doc.walk(|n| { + if matches!(n.kind, NodeKind::SymbolInstance { .. }) { + inst = Some(n.clone()); + } + }); + let inst = inst.unwrap(); + let symbols = st.doc.symbol_boxes(); + let square = [(0.0, 0.0), (20.0, 0.0), (20.0, 20.0), (0.0, 20.0)].map(|(x, y)| Point::new(x, y)); + let placed = |a: Affine| { + let mut n = inst.clone(); + let NodeKind::SymbolInstance { xf, .. } = &mut n.kind else { panic!("an instance") }; + *xf = a * *xf; + let xf = *xf; + (n, square.map(|p| xf * p)) + }; + for (case, a) in [ + ("unturned", Affine::IDENTITY), + ("turned 30 degrees", Affine::rotate_about(30f64.to_radians(), Point::new(30.0, 40.0))), + ("skewed", Affine::skew(0.5, 0.0)), + ] { + let (n, frame) = placed(a); + let got = outline_points(&node_outline(&n, &symbols)); + assert!(same_points(&got, &frame), "{case}: {got:?} is not the frame {frame:?}"); + } + // In perspective, the frame's corners go through the projection. + let h = vectorcraft_geom::Homography([[1.0, 0.0, 0.0], [0.1, 1.0, 0.0], [0.004, 0.0, 1.0]]); + let mut n = inst.clone(); + in_perspective(&mut n, h); + let (_, flat) = placed(Affine::IDENTITY); + let drawn = flat.map(|p| h.apply(p).unwrap()); + let got = outline_points(&node_outline(&n, &symbols)); + assert!(same_points(&got, &drawn), "in perspective: {got:?} is not the projected frame {drawn:?}"); +} + +#[test] +fn type_in_perspective_is_outlined_by_its_projected_box() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("text.create", &json!({"x": 100, "y": 150, "text": "Hello world", "size": 24})).unwrap(); + let id = vectorcraft_doc::NodeId(r["id"].as_u64().unwrap()); + let st = s.active().unwrap(); + let mut n = st.doc.node(id).unwrap().clone(); + let NodeKind::Text(t) = &n.kind else { panic!("type") }; + let b = t.bounds().unwrap(); + let h = vectorcraft_geom::Homography([[1.0, 0.0, 0.0], [0.1, 1.0, 0.0], [0.002, 0.0, 1.0]]); + in_perspective(&mut n, h); + let drawn = [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)].map(|(x, y)| h.apply(Point::new(x, y)).unwrap()); + let got = outline_points(&node_outline(&n, &st.doc.symbol_boxes())); + assert!(same_points(&got, &drawn), "{got:?} is not the projected box {drawn:?}"); +} + /// One headless canvas frame on an 800 × 600 window. fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) { let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() };