Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Sketch Break and Extend: a cut or stop on a shape's centre ends there, with no second point (#12299) (#12301)

Daniel0c094142d3f8
diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rs
index cfa5d03834..f672b67080 100644
--- a/crates/engine/src/cmd/sketch_modify.rs
+++ b/crates/engine/src/cmd/sketch_modify.rs
@@ -617,6 +617,59 @@ fn middle_implied(sk: &Sketch, m: usize, l: usize) -> bool {
add_c(&mut with, ConstraintKind::Midpoint { p: m, l }).is_ok() && dof_now(&with) == dof_now(sk)
}
+/// Points held at the middle of line `ci`: `release_extent` drops that hold, so a cut there
+/// remembers them (a center rectangle's centre on its first diagonal).
+fn held_midpoints(sk: &Sketch, ci: usize) -> Vec<usize> {
+ sk.constraints
+ .iter()
+ .filter_map(|k| match k.kind {
+ ConstraintKind::Midpoint { p, l } if l == ci => Some(p),
+ _ => None,
+ })
+ .collect()
+}
+
+/// A point a Midpoint constraint holds at `at`, on a line `on` accepts.
+fn held_middle(sk: &Sketch, at: Vec2, on: impl Fn(usize) -> bool) -> Option<usize> {
+ sk.constraints.iter().find_map(|k| match k.kind {
+ ConstraintKind::Midpoint { p, l } if on(l) && sk.point(p).is_some_and(|q| q.dist(at) < TOL * 10.0) => Some(p),
+ _ => None,
+ })
+}
+
+/// Hold the new point `pi` that `cutter` cut a line at. A cut on a point already held there ends
+/// the pieces on that point instead, with no second point: the point to put in place of `pi` is
+/// returned. `midpoints` are the points held at the cut line's middle before `release_extent`
+/// (`held_midpoints`), and `before` the sketch as it was then.
+fn hold_cut(sk: &mut Sketch, before: Option<&Sketch>, midpoints: &[usize], pi: usize, cutter: usize) -> Result<Option<usize>> {
+ let Some(at) = sk.point(pi) else { return Ok(None) };
+ // The cutter's middle, held there, is taken as its ends are (`pin`).
+ if let Some(m) = held_middle(sk, at, |l| l == cutter) {
+ return Ok(Some(m));
+ }
+ let Some(m) = midpoints.iter().copied().find(|m| sk.point(*m).is_some_and(|q| q.dist(at) < TOL * 10.0)) else {
+ pin(sk, pi, cutter)?;
+ return Ok(None);
+ };
+ // The cut line's middle: it moves to the cutter's middle when the sketch makes it that too (a
+ // center rectangle's diagonals bisect each other), else it stays on the cutter. A cutter
+ // whose middle is there only by chance gets no hold it never had.
+ let middle = match sk.curves.get(cutter).map(|c| &c.kind) {
+ Some(CurveKind::Line { a, b }) => sk.point(*a).zip(sk.point(*b)).map(|(a, b)| (a + b) * 0.5),
+ _ => None,
+ };
+ let implied = match before {
+ Some(was) if middle.is_some_and(|q| q.dist(at) < TOL * 10.0) => middle_implied(was, m, cutter),
+ _ => false,
+ };
+ if implied {
+ add_c(sk, ConstraintKind::Midpoint { p: m, l: cutter })?;
+ } else {
+ pin(sk, m, cutter)?;
+ }
+ Ok(Some(m))
+}
+
/// Remove the piece of curve `ci` around `at`: between the nearest intersections on either
/// side, or the whole curve when nothing crosses it. Returns what `sketch.trim` reports and the
/// removed piece as a polyline.
@@ -661,14 +714,7 @@ fn remove_piece(sk: &mut Sketch, ci: usize, at: Vec2, cmd: &str) -> Result<(Valu
.collect();
// Points held at the middle of the trimmed line (a center rectangle's centre on its first
// diagonal): `release_extent` drops that hold, so remember them for the cuts below.
- let midpoints: Vec<usize> = sk
- .constraints
- .iter()
- .filter_map(|k| match k.kind {
- ConstraintKind::Midpoint { p, l } if l == ci => Some(p),
- _ => None,
- })
- .collect();
+ let midpoints = held_midpoints(sk, ci);
// The sketch as it was, for `middle_implied`: only needed when a midpoint can be cut.
let before = (!midpoints.is_empty()).then(|| sk.clone());
release_extent(sk, ci);
@@ -685,36 +731,8 @@ fn remove_piece(sk: &mut Sketch, ci: usize, at: Vec2, cmd: &str) -> Result<(Valu
// A cut on a point already held there ends the piece on that point: no second point.
let mut welds: Vec<(usize, usize)> = Vec::new();
for (pi, c) in pts.iter().zip(&cuts) {
- let cutter = c.2;
- let Some(at) = sk.point(*pi) else { continue };
- let near = |sk: &Sketch, p: usize| sk.point(p).is_some_and(|q| q.dist(at) < TOL * 10.0);
- // The cutter's middle, held there, is taken as its ends are (`pin`).
- let held = sk.constraints.iter().find_map(|k| match k.kind {
- ConstraintKind::Midpoint { p, l } if l == cutter && near(sk, p) => Some(p),
- _ => None,
- });
- if let Some(m) = held {
- welds.push((*pi, m));
- } else if let Some(m) = midpoints.iter().copied().find(|m| near(sk, *m)) {
- // The trimmed line's middle: it moves to the cutter's middle when the sketch makes it
- // that too (a center rectangle's diagonals bisect each other), else it stays on the
- // cutter. A cutter whose middle is there only by chance gets no hold it never had.
+ if let Some(m) = hold_cut(sk, before.as_ref(), &midpoints, *pi, c.2)? {
welds.push((*pi, m));
- let middle = match sk.curves.get(cutter).map(|c| &c.kind) {
- Some(CurveKind::Line { a, b }) => sk.point(*a).zip(sk.point(*b)).map(|(a, b)| (a + b) * 0.5),
- _ => None,
- };
- let implied = match &before {
- Some(was) if middle.is_some_and(|q| q.dist(at) < TOL * 10.0) => middle_implied(was, m, cutter),
- _ => false,
- };
- if implied {
- add_c(sk, ConstraintKind::Midpoint { p: m, l: cutter })?;
- } else {
- pin(sk, m, cutter)?;
- }
- } else {
- pin(sk, *pi, cutter)?;
}
}
let gone = pieces.get(k).copied().ok_or_else(|| bad(cmd, "piece"))?;
@@ -942,15 +960,27 @@ fn break_cmd(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, "the curve is already broken there"));
}
let (ts, cutters): (Vec<f64>, Vec<Option<usize>>) = kept.into_iter().unzip();
+ // A cut on a point held at the middle of either line joins the pieces at that point.
+ let midpoints = held_midpoints(sk, ci);
+ let before = (!midpoints.is_empty()).then(|| sk.clone());
// Its length (and its midpoint, an equal length) measured the whole curve: left on the
// first piece, it would stretch that piece back to the old size and skew the sketch.
release_extent(sk, ci);
let (pieces, pts) = split_at(sk, ci, &ts, cmd)?;
+ let mut welded = Vec::new();
for (pi, c) in pts.iter().zip(&cutters) {
- if let Some(c) = c {
- pin(sk, *pi, *c)?;
+ if let Some(c) = c
+ && let Some(m) = hold_cut(sk, before.as_ref(), &midpoints, *pi, *c)?
+ {
+ for piece in &pieces {
+ if let Some(curve) = sk.curves.get_mut(*piece) {
+ curve.kind.map_points(&|p| if p == *pi { m } else { p });
+ }
+ }
+ welded.push(*pi);
}
}
+ sk.remove_points(&welded);
tie(sk, &pieces)?;
Ok(ids_of(sk, &pieces))
})?;
@@ -1294,13 +1324,19 @@ fn add_arc_extension(sk: &mut Sketch, ci: usize, aim: &ArcAim, stop: Option<usiz
}
/// The point the extension stops at when the sketch already has one there: an end of another
-/// curve at the hit. Joining that point keeps the extension attached to the geometry that is
-/// there instead of laying a second point over it. `None` when the stop needs a new point.
+/// curve at the hit, or a point held at another line's middle there (a center rectangle's
+/// centre). Joining that point keeps the extension attached to the geometry that is there
+/// instead of laying a second point over it. `None` when the stop needs a new point.
fn stop_point(sk: &Sketch, ci: usize, q: Vec2) -> Option<usize> {
- sk.curves.iter().enumerate().filter(|(i, _)| *i != ci).find_map(|(_, c)| {
- let (a, b) = c.kind.ends()?;
- [a, b].into_iter().find(|p| sk.point(*p).is_some_and(|pt| pt.dist(q) <= TOL * 10.0))
- })
+ sk.curves
+ .iter()
+ .enumerate()
+ .filter(|(i, _)| *i != ci)
+ .find_map(|(_, c)| {
+ let (a, b) = c.kind.ends()?;
+ [a, b].into_iter().find(|p| sk.point(*p).is_some_and(|pt| pt.dist(q) <= TOL * 10.0))
+ })
+ .or_else(|| held_middle(sk, q, |l| l != ci))
}
/// Add the line an extension needs, from the growing end to the stop: the sketch's own point
diff --git a/crates/engine/src/cmd/sketch_modify_tests.rs b/crates/engine/src/cmd/sketch_modify_tests.rs
index e53735cad5..620aa6db38 100644
--- a/crates/engine/src/cmd/sketch_modify_tests.rs
+++ b/crates/engine/src/cmd/sketch_modify_tests.rs
@@ -687,6 +687,103 @@ fn trimming_at_a_held_midpoint_on_an_unrelated_line_adds_no_hold_to_that_line()
assert_eq!(sk.points.iter().filter(|p| p.pos.dist(Vec2::new(5.0, 0.0)) < 1e-7).count(), 1, "one point at the cut");
}
+/// Breaking a center rectangle's diagonal at the centre left two points there, one held by
+/// nothing: dragging a corner pulled them apart. Either diagonal, both pieces meet at the one
+/// centre point, which stays where the diagonals cross.
+#[test]
+fn breaking_a_center_rectangle_diagonal_at_its_centre_keeps_one_centre() {
+ for (diagonal, at) in [(0, [7.5, 4.25]), (1, [7.5, -0.25])] {
+ let mut s = new_sketch();
+ run(&mut s, "sketch.rectangle.center", json!({"center": [3, 2], "corner": [12, 6.5]}));
+ let sk = sketch(&s);
+ let diagonals: Vec<String> = sk.curves.iter().filter(|c| c.construction).map(|c| c.id.clone()).collect();
+ assert_eq!(diagonals.len(), 2, "{diagonals:?}");
+ let (cut, other) = (diagonals[diagonal].clone(), diagonals[1 - diagonal].clone());
+ run(&mut s, "sketch.break", json!({"curve": cut, "at": at}));
+ let sk = sketch(&s);
+ let at_centre = sk.points.iter().filter(|p| p.pos.dist(Vec2::new(3.0, 2.0)) < 1e-7).count();
+ assert_eq!(at_centre, 1, "diagonal {cut}: {} points at the centre", at_centre);
+ let si = run(&mut s, "sketch.inspect", json!({}));
+ assert_eq!(si["dof"], 4, "diagonal {cut}: {si}");
+ assert_ne!(si["status"], "conflict", "diagonal {cut}: {si}");
+ assert!(si["status"].as_str().is_none_or(|t| !t.contains("over")), "diagonal {cut}: {si}");
+ // Drag a corner: both pieces still end where the diagonals cross.
+ run(&mut s, "sketch.drag", json!({"entity": "l2.end", "from": [12, 6.5], "to": [16, 9]}));
+ let sk = sketch(&s);
+ let ends = |i: usize| {
+ let (a, b) = sk.curves[i].kind.ends().unwrap();
+ (sk.point(a).unwrap(), sk.point(b).unwrap())
+ };
+ let (o0, o1) = ends(sk.curve_index(&other).unwrap());
+ let centre = (o0 + o1) * 0.5;
+ let pieces: Vec<usize> = (0..sk.curves.len()).filter(|i| sk.curves[*i].construction && sk.curves[*i].id != other).collect();
+ assert_eq!(pieces.len(), 2, "diagonal {cut}: {pieces:?}");
+ for piece in pieces {
+ let (c0, c1) = ends(piece);
+ assert!(c0.dist(centre).min(c1.dist(centre)) < 1e-6, "diagonal {cut}: {c0:?} {c1:?}, centre {centre:?}");
+ }
+ }
+}
+
+/// A line's held midpoint broken at a crossing line that only happens to have its middle there
+/// joins the two pieces at that point and keeps it on the crossing line, without tying the
+/// crossing line's middle to it.
+#[test]
+fn breaking_at_a_held_midpoint_on_an_unrelated_line_adds_no_hold_to_that_line() {
+ let mut s = new_sketch();
+ let broken = ids(&run(&mut s, "sketch.line", json!({"points": [[0,0], [10,0]], "connect": false, "infer": false}))["curves"])[0].clone();
+ let crossing = ids(&run(&mut s, "sketch.line", json!({"points": [[5,-3], [5,3]], "connect": false, "infer": false}))["curves"])[0].clone();
+ run(&mut s, "sketch.point", json!({"point": format!("mid:{broken}")}));
+ let sk = sketch(&s);
+ let mid = sk.points.iter().find(|p| p.pos.dist(Vec2::new(5.0, 0.0)) < 1e-7).map(|p| p.id.clone()).unwrap();
+ run(&mut s, "sketch.break", json!({"curve": broken, "at": [8, 0]}));
+ let sk = sketch(&s);
+ let l = sk.curve_index(&crossing).unwrap();
+ let m = sk.resolve_point(&mid).unwrap();
+ assert!(
+ !sk.constraints.iter().any(|c| matches!(c.kind, ConstraintKind::Midpoint { l: cl, .. } if cl == l)),
+ "the crossing line gets no midpoint hold: {:?}",
+ sk.constraints
+ );
+ assert!(
+ sk.constraints.iter().any(|c| matches!(c.kind, ConstraintKind::PointOnCurve { p, c: cc } if p == m && cc == l)),
+ "the old midpoint stays on the crossing line: {:?}",
+ sk.constraints
+ );
+ assert_eq!(sk.points.iter().filter(|p| p.pos.dist(Vec2::new(5.0, 0.0)) < 1e-7).count(), 1, "one point at the cut");
+}
+
+/// Extending a line up to a center rectangle's centre ends it on the centre point, as an
+/// extension up to a curve's end joins that end. It used to end on one diagonal only, free to
+/// slide along it, so a corner drag took the line's end off the centre.
+#[test]
+fn extending_a_line_to_a_center_rectangle_centre_ends_it_on_the_centre() {
+ let mut s = new_sketch();
+ run(&mut s, "sketch.rectangle.center", json!({"center": [3, 2], "corner": [12, 6.5]}));
+ let line = ids(&run(&mut s, "sketch.line", json!({"points": [[3, -1], [3, 0]], "connect": false, "infer": false}))["curves"])[0].clone();
+ let dof = run(&mut s, "sketch.inspect", json!({}))["dof"].as_i64().unwrap();
+ run(&mut s, "sketch.extend", json!({"curve": line, "at": [3, -0.1]}));
+ let si = run(&mut s, "sketch.inspect", json!({}));
+ assert_eq!(si["dof"], dof - 2, "the extended end is held at the centre: {si}");
+ assert!(si["status"].as_str().is_none_or(|t| !t.contains("over")), "{si}");
+ run(&mut s, "sketch.drag", json!({"entity": "l2.end", "from": [12, 6.5], "to": [16, 9]}));
+ let sk = sketch(&s);
+ let diagonal = sk.curves.iter().find(|c| c.construction).unwrap();
+ let (a, b) = diagonal.kind.ends().unwrap();
+ let centre = (sk.point(a).unwrap() + sk.point(b).unwrap()) * 0.5;
+ let (e0, e1) = sk.curves[sk.curve_index(&line).unwrap()].kind.ends().unwrap();
+ let reach = sk.point(e0).unwrap().dist(centre).min(sk.point(e1).unwrap().dist(centre));
+ // The extension may be a new line from the old end: any line ending at the centre counts.
+ let joined = reach < 1e-6
+ || sk
+ .curves
+ .iter()
+ .filter(|c| !c.construction)
+ .filter_map(|c| c.kind.ends())
+ .any(|(p, q)| [p, q].iter().any(|e| sk.point(*e).is_some_and(|x| x.dist(centre) < 1e-6)));
+ assert!(joined, "no line ends at the centre {centre:?} after the drag");
+}
+
#[test]
fn exact_extend_ellipse_preserves_support_target_and_history() {
for (y, expected_x) in [(3.0, 12.0), (5.0, 20.0)] {