From bb53e4e77db19eeea887f8344041ef50df05b109 Mon Sep 17 00:00:00 2001 From: okereke-dev <293682657+okereke-dev@users.noreply.github.com> Date: Sun, 22 Nov 2026 09:24:28 -0500 Subject: [PATCH] TRIM/EXTEND: preview every piece a Fence or a Crossing window will change while it is drawn While a fence (Fence, or Quick mode's two-point fence) or a crossing window is drawn, every piece it will remove (EXTEND: every stretch it will add) is highlighted with the same band as a single pick. - trimextend.rs: fence() and crossing() are split into fence_work()/crossing_work(), which find what they cut, and run_picks(). picks_preview() works the same run out without changing the drawing: each object at its picks in turn, against edges that include what the run has already made of other objects (Overlay), so the preview follows a fence whose trims change each other's edges. - modify/trim.rs: trim_kind() and extend_kind() trim or extend a shape; edge_segments_over() gathers edges with an Overlay in place of the objects it names. - Interactive::highlight_all / Session::highlight_all; the canvas draws it in place of the object under the cursor. Tests: a fence highlighting both lines it crosses, the drawing untouched; a fence through a grid and a circle removing exactly the highlighted length; Quick mode's two-point fence and a crossing window; an EXTEND fence adding exactly what it highlighted. --- crates/engine/src/cmd/modify.rs | 4 +- crates/engine/src/cmd/modify/trim.rs | 62 ++++++++++--- crates/engine/src/cmd/trimextend.rs | 112 ++++++++++++++++++++++- crates/engine/src/guard.rs | 9 ++ crates/engine/src/prompt.rs | 7 ++ crates/engine/src/session/interactive.rs | 8 ++ crates/engine/tests/it/trim_highlight.rs | 101 ++++++++++++++++++++ crates/ui-egui/src/canvas/viewport.rs | 10 +- 8 files changed, 292 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/modify.rs b/crates/engine/src/cmd/modify.rs index dfc296728..ee800e92e 100644 --- a/crates/engine/src/cmd/modify.rs +++ b/crates/engine/src/cmd/modify.rs @@ -37,7 +37,9 @@ use select_then::{DisplaceM, Op, SelectThen}; use stretch::{StretchM, run_stretch}; pub(crate) use transform::{holds_ole_frame, ole_refusal, refuse_ole_frames, transform_entities}; use transform::{run_copy, run_erase, run_mirror, run_move, run_rotate, run_scale}; -pub(crate) use trim::{CUT_ONCE, Edges, edge_segments, extend, extended, json_pick_error, trim, trimmed}; +pub(crate) use trim::{ + CUT_ONCE, Edges, Overlay, edge_segments, edge_segments_over, extend, extend_kind, extended, json_pick_error, trim, trim_kind, trimmed, +}; pub fn specs() -> Vec { vec![ diff --git a/crates/engine/src/cmd/modify/trim.rs b/crates/engine/src/cmd/modify/trim.rs index 7127fa75e..7a8f7cbf3 100644 --- a/crates/engine/src/cmd/modify/trim.rs +++ b/crates/engine/src/cmd/modify/trim.rs @@ -19,27 +19,50 @@ pub(crate) struct Edges<'a> { /// All primitives of the cutting edges (excluding `exclude`). pub(crate) fn edge_segments(s: &Session, edges: Edges, exclude: Handle) -> Result> { + edge_segments_over(s, edges, exclude, &Overlay::new()) +} + +/// Objects as a run of trims would have left them, without changing the drawing: for each object +/// of the drawing it names, the pieces in its place, each with its handle (the first keeps the +/// object's, as [`replace_with_pieces`] does; none: the object is gone). TRIM's Fence and +/// Crossing preview works a whole run out this way. +pub(crate) type Overlay = std::collections::HashMap>; + +/// [`edge_segments`] with the objects `overlay` names in their pieces' place. +pub(crate) fn edge_segments_over(s: &Session, edges: Edges, exclude: Handle, overlay: &Overlay) -> Result> { let d = s.doc()?; let space = s.space(); let store = d.space(&space).ok_or(EngineError::NoDocument)?; let mut out = Vec::new(); - for e in store.iter() { - if e.handle == exclude || !d.is_visible(e) { - continue; - } - if let Some(es) = edges.only - && !es.contains(&e.handle) - { - continue; - } + let mut add = |kind: &EntityKind| { if edges.implied - && let Some(segs) = implied_edge(&e.kind) + && let Some(segs) = implied_edge(kind) { out.extend(segs); + return; + } + for p in kind.prims() { + out.extend(prim_to_segments(&p)); + } + }; + // An object is an edge when it is one of `edges.only` (all of them: `None`). A trim leaves + // its first piece under the object's handle and the others under new ones, so only the first + // stays one of the picked edges, as in a run of trims on the drawing itself. + let is_edge = |h: &Handle| edges.only.is_none_or(|es| es.contains(h)); + for e in store.iter() { + if !d.is_visible(e) { continue; } - for p in e.kind.prims() { - out.extend(prim_to_segments(&p)); + match overlay.get(&e.handle) { + Some(pieces) => { + for (h, k) in pieces { + if *h != exclude && is_edge(h) { + add(k); + } + } + } + None if e.handle != exclude && is_edge(&e.handle) => add(&e.kind), + None => {} } } Ok(out) @@ -160,7 +183,13 @@ pub(crate) fn trimmed(s: &Session, h: Handle, pick: Vec2, edges: Edges, cut: &[S // A polyline that is one of the edges (picked, or with every object in either mode) cuts // itself too. let itself = edges.only.is_none_or(|o| o.contains(&h)); - let pieces: Vec = match &e.kind { + trim_kind(&e.kind, pick, itself, cut) +} + +/// [`trimmed`] for an object of shape `kind` (not on a locked layer); `itself`: it is one of the +/// cutting edges, so a polyline cuts itself too. +pub(crate) fn trim_kind(kind: &EntityKind, pick: Vec2, itself: bool, cut: &[Segment]) -> Result>> { + let pieces: Vec = match kind { EntityKind::Line(l) => { let ln = Line::new(l.a.xy(), l.b.xy()); let mut ts: Vec = cut @@ -589,7 +618,12 @@ pub(crate) fn extended(s: &Session, h: Handle, pick: Vec2, cut: &[Segment]) -> R } let d = s.doc()?; let e = d.entity(h).ok_or_else(|| EngineError::Other("no such object".into()))?; - let new_kind = match &e.kind { + extend_kind(&e.kind, pick, cut) +} + +/// [`extended`] for an object of shape `kind` (not on a locked layer). +pub(crate) fn extend_kind(kind: &EntityKind, pick: Vec2, cut: &[Segment]) -> Result { + let new_kind = match kind { EntityKind::Line(l) => { let (a, b) = (l.a.xy(), l.b.xy()); let from_b = pick.dist(b) < pick.dist(a); diff --git a/crates/engine/src/cmd/trimextend.rs b/crates/engine/src/cmd/trimextend.rs index 43864c408..7c1dcfd20 100644 --- a/crates/engine/src/cmd/trimextend.rs +++ b/crates/engine/src/cmd/trimextend.rs @@ -11,7 +11,9 @@ use serde_json::{Value, json}; use super::curves::KW; use super::helpers::{line, lwpoly, rect_vertices}; -use super::modify::{CUT_ONCE, Edges, edge_segments, extend, extended, json_pick_error, trim, trimmed}; +use super::modify::{ + CUT_ONCE, Edges, Overlay, edge_segments, edge_segments_over, extend, extend_kind, extended, json_pick_error, trim, trim_kind, trimmed, +}; use super::{bad, point_param, points_param}; use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step}; @@ -58,6 +60,13 @@ fn apply(s: &mut Session, h: Handle, at: Vec2, extending: bool, edges: Edges, qu /// Trim (or extend) every object the fence `pts` crosses, at each crossing (extend: at the first). /// Returns how many trims or extends were made. fn fence(s: &mut Session, pts: &[Vec2], extending: bool, edges: Edges, quick: bool) -> Result { + let (work, tol) = fence_work(s, pts)?; + run_picks(s, work, extending, edges, quick, tol) +} + +/// What a fence through `pts` trims or extends: each object it crosses with its crossings, in +/// fence order, and the tolerance they were found to. +fn fence_work(s: &Session, pts: &[Vec2]) -> Result<(Vec<(Handle, Vec)>, f64)> { let space = s.space(); let d = s.doc()?; let fb = Bounds2::from_points(pts.iter().copied()); @@ -82,7 +91,7 @@ fn fence(s: &mut Session, pts: &[Vec2], extending: bool, edges: Edges, quick: bo } work.push((h, xs)); } - run_picks(s, work, extending, edges, quick, tol) + Ok((work, tol)) } /// How far along a segment from its end a crossing window's pick is kept: past the 5e-7 within @@ -93,6 +102,13 @@ const OFF_VERTEX: f64 = 1e-6; /// Trim (or extend) every object a crossing window from `a` to `b` touches, picked at its point /// in the window nearest the first corner `a`. fn crossing(s: &mut Session, a: Vec2, b: Vec2, extending: bool, edges: Edges, quick: bool) -> Result { + let (work, tol) = crossing_work(s, a, b)?; + run_picks(s, work, extending, edges, quick, tol) +} + +/// What a crossing window from `a` to `b` trims or extends: each object it touches with its pick +/// point, and the tolerance they were found to. +fn crossing_work(s: &Session, a: Vec2, b: Vec2) -> Result<(Vec<(Handle, Vec)>, f64)> { let space = s.space(); let d = s.doc()?; let bx = Bounds2::new(a, b); @@ -131,7 +147,82 @@ fn crossing(s: &mut Session, a: Vec2, b: Vec2, extending: bool, edges: Edges, qu work.push((h, vec![p])); } } - run_picks(s, work, extending, edges, quick, tol) + Ok((work, tol)) +} + +/// What [`run_picks`] would change, worked out without changing the drawing: for each trim, the +/// piece it removes (a whole object Quick mode erases), and for each extend the stretch it adds, +/// with the handle of the object it belongs to. Each object is trimmed at its picks in turn, as +/// `run_picks` does, against edges that include what the run has already made of other objects +/// ([`Overlay`]), so the preview of a fence or a crossing window is what it will do. `px`: the +/// tolerance the changes are drawn to. +fn picks_preview( + s: &Session, + work: &[(Handle, Vec)], + extending: bool, + edges: Edges, + quick: bool, + tol: f64, + px: f64, +) -> Vec<(Handle, EntityKind)> { + let Ok(d) = s.doc() else { return Vec::new() }; + let mut overlay = Overlay::new(); + let mut out = Vec::new(); + // Handles for the pieces a trim makes, apart from any in the drawing. + let mut next = u64::MAX; + let mut fresh = || { + next -= 1; + Handle(next) + }; + for (h, picks) in work { + let Some(orig) = d.entity(*h) else { continue }; + if crate::cmd::curves::is_locked(s, *h) { + continue; + } + let entity = |handle: Handle, kind: &EntityKind| Entity { handle, common: orig.common.clone(), kind: kind.clone() }; + let mut live: Vec<(Handle, EntityKind)> = vec![(*h, orig.kind.clone())]; + for x in picks { + let target = live + .iter() + .enumerate() + .map(|(i, (ph, k))| (i, crate::select::entity_distance(d, &entity(*ph, k), *x, tol))) + .filter(|(_, dist)| *dist <= 3.0 * tol) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(i, _)| i); + let Some(i) = target else { continue }; + let Some((ph, piece)) = live.get(i).cloned() else { continue }; + overlay.insert(*h, live.clone()); + let Ok(cut) = edge_segments_over(s, edges, ph, &overlay) else { continue }; + if extending { + if let Ok(grown) = extend_kind(&piece, *x, &cut) { + out.extend(uncovered(d, &entity(ph, &grown), std::slice::from_ref(&piece), px).into_iter().map(|k| (*h, k))); + if let Some(slot) = live.get_mut(i) { + slot.1 = grown; + } + } + break; + } + let itself = edges.only.is_none_or(|o| o.contains(&ph)); + match trim_kind(&piece, *x, itself, &cut) { + Ok(Some(kept)) => { + out.extend(uncovered(d, &entity(ph, &piece), &kept, px).into_iter().map(|k| (*h, k))); + live.remove(i); + let mut kept = kept.into_iter(); + if let Some(first) = kept.next() { + live.insert(i, (ph, first)); + } + live.extend(kept.map(|k| (fresh(), k))); + } + Err(err) if quick && misses_edges(&err) => { + out.push((*h, piece)); + live.remove(i); + } + Ok(None) | Err(_) => {} + } + } + overlay.insert(*h, live); + } + out } /// Trim (or extend) each object at its pick points. A trim leaves the object in pieces, so later @@ -607,6 +698,21 @@ impl Interactive for TrimM { } self.change(s, h, cursor) } + fn highlight_all(&self, s: &Session, cursor: Vec2) -> Option> { + let (quick, implied) = (quick_mode(s), edge_mode(s)); + let found = match &self.stage { + Stage::Fence(pts) if !pts.is_empty() => { + let pts: Vec = pts.iter().copied().chain(std::iter::once(cursor)).collect(); + fence_work(s, &pts) + } + Stage::QuickFence(a) => fence_work(s, &[*a, cursor]), + Stage::Crossing(Some(a)) => crossing_work(s, *a, cursor), + _ => return None, + }; + let (work, tol) = found.ok()?; + let px = (s.pixel_size() / 2.0).max(1e-9); + Some(picks_preview(s, &work, self.extend, self.edges(quick, implied), quick, tol, px)) + } fn preview(&self, _s: &Session, c: Vec2) -> Vec { match &self.stage { Stage::Fence(pts) if !pts.is_empty() => pts diff --git a/crates/engine/src/guard.rs b/crates/engine/src/guard.rs index 3d690d335..1b9f1c8d4 100644 --- a/crates/engine/src/guard.rs +++ b/crates/engine/src/guard.rs @@ -101,6 +101,15 @@ impl Interactive for Guarded { None }) } + fn highlight_all(&self, s: &Session, cursor: Vec2) -> Option> { + if self.broken.get().is_some() { + return None; + } + catch_unwind(AssertUnwindSafe(|| self.inner.highlight_all(s, cursor))).unwrap_or_else(|_| { + self.broken.set(Some("panic in preview")); + None + }) + } fn drag(&self, s: &Session, cursor: Vec2) -> Option { if self.broken.get().is_some() { return None; diff --git a/crates/engine/src/prompt.rs b/crates/engine/src/prompt.rs index b5a8a7ffb..c9dea6187 100644 --- a/crates/engine/src/prompt.rs +++ b/crates/engine/src/prompt.rs @@ -332,6 +332,13 @@ pub trait Interactive: Send { fn highlight(&self, _s: &Session, _h: cadcraft_doc::Handle, _cursor: Vec2) -> Option> { None } + /// What the running command will change wherever the cursor is, highlighted in place of the + /// object under it (TRIM's Fence and Crossing: every piece the fence or the window will + /// remove), each with the handle of the object it is part of. `None`: nothing of the kind, + /// and the object under the cursor is highlighted as [`Interactive::highlight`] says. + fn highlight_all(&self, _s: &Session, _cursor: Vec2) -> Option> { + None + } /// The preview as existing objects under one transform, when it is that (MOVE, COPY, /// ROTATE, SCALE). The UI then draws them from geometry uploaded once instead of rebuilding /// the transformed copies every frame; `None` falls back to [`Interactive::preview`]. diff --git a/crates/engine/src/session/interactive.rs b/crates/engine/src/session/interactive.rs index 360a247eb..3fac682cc 100644 --- a/crates/engine/src/session/interactive.rs +++ b/crates/engine/src/session/interactive.rs @@ -617,6 +617,14 @@ impl Session { Some(kinds.into_iter().map(|k| Entity { handle: h, common: common.clone(), kind: k }).collect()) } + /// What the running command will change wherever the cursor is, with each part's properties + /// ([`Interactive::highlight_all`]: TRIM's Fence and Crossing). `None`: nothing of the kind. + pub fn highlight_all(&self, cursor: Vec2) -> Option> { + let parts = self.running.as_ref()?.machine.highlight_all(self, cursor)?; + let d = self.doc().ok()?; + Some(parts.into_iter().filter_map(|(h, k)| Some(Entity { handle: h, common: d.entity(h)?.common.clone(), kind: k })).collect()) + } + /// What the drawing area shows in place of the drawing while a command runs (DVIEW's preview /// set, see [`Interactive::display_only`]), also while a transparent command interrupts it. /// `None`: the drawing. diff --git a/crates/engine/tests/it/trim_highlight.rs b/crates/engine/tests/it/trim_highlight.rs index 89266ddb0..cb1c49e80 100644 --- a/crates/engine/tests/it/trim_highlight.rs +++ b/crates/engine/tests/it/trim_highlight.rs @@ -174,3 +174,104 @@ fn the_edges_are_gathered_again_once_the_drawing_changes() { assert_eq!(ends(&s, l, [12.0, 0.0]), Some(vec![seg([10.0, 0.0], [15.0, 0.0])]), "it still meets the line at its end"); assert_eq!(ends(&s, l, [-3.0, 0.0]), Some(vec![seg([-5.0, 0.0], [0.0, 0.0])])); } + +/// The highlight while a fence or a crossing window is drawn, as outlines. +fn highlight_all(s: &Session, at: [f64; 2]) -> Option>> { + let ents = s.highlight_all(Vec2::new(at[0], at[1]))?; + Some(outline(s, &ents)) +} + +/// The total length of every object's outline. +fn drawn(s: &Session) -> f64 { + length(&outline(s, &s.doc().unwrap().model.iter().map(|e| (**e).clone()).collect::>())) +} + +#[test] +fn a_fence_highlights_every_piece_it_will_remove() { + let (mut s, _) = ladder(); + let upper = line(&mut s, [-5.0, 2.0], [15.0, 2.0]); + s.start("trim").unwrap(); + s.input(Input::Keyword("Fence".into())).unwrap(); + assert!(s.highlight_all(Vec2::new(5.0, 3.0)).is_none(), "nothing before the fence's first point"); + s.input(Input::Point(Vec2::new(5.0, -3.0))).unwrap(); + let before = s.state().unwrap().doc.clone(); + let shown = highlight_all(&s, [5.0, 3.0]).unwrap(); + let mut spans: Vec<[[i64; 2]; 2]> = shown + .iter() + .map(|pl| { + let r = |p: Vec2| [(p.x * 1e6).round() as i64, (p.y * 1e6).round() as i64]; + let (a, b) = (r(pl[0]), r(*pl.last().unwrap())); + if a <= b { [a, b] } else { [b, a] } + }) + .collect(); + spans.sort(); + assert_eq!(spans, vec![seg([0.0, 0.0], [10.0, 0.0]), seg([0.0, 2.0], [10.0, 2.0])], "both lines between the edges"); + assert!(std::sync::Arc::ptr_eq(&before, &s.state().unwrap().doc), "the drawing is left alone"); + // Short of the upper line, only the lower one. + assert_eq!(highlight_all(&s, [5.0, 1.0]).unwrap().len(), 1); + assert!(s.highlight(upper, Vec2::new(5.0, 2.0)).is_none(), "no single-object highlight while fencing"); +} + +#[test] +fn a_fence_removes_exactly_what_it_highlighted() { + // A grid of lines and a circle, with a fence through several of them: some of what it trims + // is an edge of what it trims next, so the preview must follow the run trim by trim. + let mut s = Session::new(); + for x in [0.0, 10.0, 20.0] { + line(&mut s, [x, -10.0], [x, 10.0]); + } + for y in [0.0, 5.0] { + line(&mut s, [-5.0, y], [25.0, y]); + } + s.execute("circle", &json!({ "center": [10, 2.5], "radius": 4 })).unwrap(); + s.zoom_extents().unwrap(); + let fence = [[3.0, -4.0], [12.0, 3.0], [17.0, 8.0]]; + s.start("trim").unwrap(); + s.input(Input::Keyword("Fence".into())).unwrap(); + for p in &fence[..2] { + s.input(Input::Point(Vec2::new(p[0], p[1]))).unwrap(); + } + let shown = length(&highlight_all(&s, fence[2]).unwrap()); + let before = drawn(&s); + s.input(Input::Point(Vec2::new(fence[2][0], fence[2][1]))).unwrap(); + s.input(Input::Enter).unwrap(); + let removed = before - drawn(&s); + assert!(removed > 1.0, "the fence trimmed something"); + assert!((shown - removed).abs() < 1e-3 * before, "highlighted {shown}, removed {removed}"); +} + +#[test] +fn a_quick_fence_and_a_crossing_window_are_previewed_too() { + // Quick mode: a pick in empty space starts a two-point fence. + let (mut s, _) = ladder(); + s.start("trim").unwrap(); + s.input(Input::Point(Vec2::new(5.0, -3.0))).unwrap(); + let shown = highlight_all(&s, [5.0, 3.0]).expect("the two-point fence is previewed"); + assert!((length(&shown) - 10.0).abs() < 1e-6, "{}", length(&shown)); + s.cancel(); + // A crossing window round the middle of the line. + s.start("trim").unwrap(); + s.input(Input::Keyword("Crossing".into())).unwrap(); + s.input(Input::Point(Vec2::new(4.0, -1.0))).unwrap(); + let shown = highlight_all(&s, [6.0, 1.0]).expect("the window is previewed"); + assert!((length(&shown) - 10.0).abs() < 1e-6, "{}", length(&shown)); +} + +#[test] +fn an_extend_fence_highlights_the_stretches_it_adds() { + let mut s = Session::new(); + line(&mut s, [10.0, -5.0], [10.0, 5.0]); + line(&mut s, [0.0, 0.0], [4.0, 0.0]); + line(&mut s, [0.0, 2.0], [6.0, 2.0]); + s.zoom_extents().unwrap(); + s.start("extend").unwrap(); + s.input(Input::Keyword("Fence".into())).unwrap(); + s.input(Input::Point(Vec2::new(4.0, -1.0))).unwrap(); + let shown = length(&highlight_all(&s, [4.0, 3.0]).unwrap()); + assert!((shown - (6.0 + 4.0)).abs() < 1e-6, "both lines run on to x = 10: {shown}"); + // And the fence extends them by just that. + let before = drawn(&s); + s.input(Input::Point(Vec2::new(4.0, 3.0))).unwrap(); + s.input(Input::Enter).unwrap(); + assert!((drawn(&s) - before - shown).abs() < 1e-6); +} diff --git a/crates/ui-egui/src/canvas/viewport.rs b/crates/ui-egui/src/canvas/viewport.rs index 353003e16..f9c805c65 100644 --- a/crates/ui-egui/src/canvas/viewport.rs +++ b/crates/ui-egui/src/canvas/viewport.rs @@ -317,8 +317,11 @@ pub(super) struct HoverPart { } impl HoverPart { + /// What a running command will change wherever the cursor is (TRIM's Fence and Crossing, + /// [`cadcraft_engine::Session::highlight_all`]) comes first; otherwise the part of the object + /// under the cursor ([`cadcraft_engine::Session::highlight`]). pub(super) fn update(&mut self, session: &cadcraft_engine::Session, hover: Option, cursor: Option, scale: f64) { - let (Some(h), Some(c), Ok(st)) = (hover, cursor, session.state()) else { + let (Some(c), Ok(st)) = (cursor, session.state()) else { self.key = None; self.list = None; return; @@ -327,14 +330,15 @@ impl HoverPart { use std::hash::{Hash, Hasher}; let mut hs = std::collections::hash_map::DefaultHasher::new(); let doc = (st.uid, st.revision, std::sync::Arc::as_ptr(&st.doc) as usize); - (h, c.x.to_bits(), c.y.to_bits(), scale.to_bits(), doc, session.prompt_text(), super::list::font_generation()).hash(&mut hs); + (hover, c.x.to_bits(), c.y.to_bits(), scale.to_bits(), doc, session.prompt_text(), super::list::font_generation()).hash(&mut hs); hs.finish() }; if self.key == Some(key) { return; } self.key = Some(key); - self.list = session.highlight(h, c).map(|ents| super::list::rebuilt_preview(&st.doc, ents.iter(), scale)); + let ents = session.highlight_all(c).or_else(|| hover.and_then(|h| session.highlight(h, c))); + self.list = ents.map(|ents| super::list::rebuilt_preview(&st.doc, ents.iter(), scale)); self.list_gen = self.list_gen.wrapping_add(1); } }