diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rs index 00c3189e4..b0c459b09 100644 --- a/crates/engine/src/cmd/sketch_modify.rs +++ b/crates/engine/src/cmd/sketch_modify.rs @@ -9,7 +9,7 @@ use solidcore_record::{Plane, Vec2}; use solidcraft_doc::ProfileSel; use solidcraft_sketch::{ConstraintKind, Curve, CurveKind, Shape, Sketch, Wire, WireSpace, intersections, intersections_within}; -use super::sketch::{add_c, coincident_points, edit, ids_of, line_or_axis_ref, solve_current}; +use super::sketch::{add_c, coincident_points, dof_now, edit, ids_of, line_or_axis_ref, solve_current}; use super::sketch_store; use super::{CommandSpec, in_sketch}; use crate::params::{bad, bool_, expr, num, req_expr, req_vec2, str_, string_list, vec2, vec2_list}; @@ -555,6 +555,14 @@ fn release_source_line_offsets(sk: &mut Sketch, doc: &solidcraft_doc::Document, Ok(released) } +/// Whether the sketch already holds point `m` at the middle of line `l`, though no constraint says +/// so: adding that Midpoint takes away no degree of freedom (a center rectangle's centre, held on +/// one diagonal, is the other's middle too because the diagonals bisect each other). +fn middle_implied(sk: &Sketch, m: usize, l: usize) -> bool { + let mut with = sk.clone(); + add_c(&mut with, ConstraintKind::Midpoint { p: m, l }).is_ok() && dof_now(&with) == dof_now(sk) +} + /// 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. @@ -597,6 +605,18 @@ fn remove_piece(sk: &mut Sketch, ci: usize, at: Vec2, cmd: &str) -> Result<(Valu .then(|| dimension.id.clone()) }) .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 = sk + .constraints + .iter() + .filter_map(|k| match k.kind { + ConstraintKind::Midpoint { p, l } if l == ci => Some(p), + _ => None, + }) + .collect(); + // 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); let tangencies = endpoint_tangencies(sk, ci); let ts: Vec = cuts.iter().map(|c| c.0).collect(); @@ -608,8 +628,40 @@ fn remove_piece(sk: &mut Sketch, ci: usize, at: Vec2, cmd: &str) -> Result<(Valu } else { ts.iter().filter(|t| **t < tq).count() }; + // 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) { - pin(sk, *pi, c.2)?; + 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. + 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"))?; let keep: Vec = pieces.iter().copied().filter(|x| *x != gone).collect(); @@ -632,6 +684,13 @@ fn remove_piece(sk: &mut Sketch, ci: usize, at: Vec2, cmd: &str) -> Result<(Valu }; rebind_endpoint_tangencies(sk, ci, &pieces, &tangencies); let keep: Vec = pieces.iter().copied().filter(|x| *x != gone).collect(); + for &(from, to) in &welds { + for piece in &keep { + if let Some(c) = sk.curves.get_mut(*piece) { + c.kind.map_points(&|p| if p == from { to } else { p }); + } + } + } tie(sk, &keep)?; if let Some((a, _)) = sk.curves.get(ci).and_then(|c| c.kind.ends()) { for dimension in &mut sk.constraints { diff --git a/crates/engine/src/cmd/sketch_modify_tests.rs b/crates/engine/src/cmd/sketch_modify_tests.rs index ecbc0de59..6cd1030e4 100644 --- a/crates/engine/src/cmd/sketch_modify_tests.rs +++ b/crates/engine/src/cmd/sketch_modify_tests.rs @@ -577,6 +577,116 @@ fn trim_circle_makes_an_arc_and_a_profile() { assert!(close(a[0], std::f64::consts::PI * 50.0), "{a:?}"); } +/// Trimming half of a center rectangle's diagonal left two points at the centre, one held by +/// nothing: dragging a corner pulled them apart. Either diagonal, the half that stays ends on the +/// one centre point, which stays where the diagonals cross. +#[test] +fn trimming_half_a_center_rectangle_diagonal_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 = 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.trim", 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: the trimmed half still ends 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 = |id: &str| { + let (a, b) = sk.curves[sk.curve_index(id).unwrap()].kind.ends().unwrap(); + (sk.point(a).unwrap(), sk.point(b).unwrap()) + }; + let (o0, o1) = ends(&other); + let centre = (o0 + o1) * 0.5; + let (c0, c1) = ends(&cut); + assert!(c0.dist(centre).min(c1.dist(centre)) < 1e-6, "diagonal {cut}: {c0:?} {c1:?}, centre {centre:?}"); + } +} + +#[test] +fn trimming_the_start_half_of_a_center_rectangle_diagonal_keeps_its_parallel_distance_on_the_centre() { + let mut s = new_sketch(); + run(&mut s, "sketch.rectangle.center", json!({"center": [3, 2], "corner": [12, 6.5]})); + let diagonal = sketch(&s).curves.iter().find(|c| c.construction).map(|c| c.id.clone()).unwrap(); + // A line parallel to the diagonal (-6,-2.5)-(12,6.5), 10 mm lower, dimensioned from the + // diagonal's start. + let line = ids(&run(&mut s, "sketch.line", json!({"points": [[-6, -12.5], [12, -3.5]], "connect": false, "infer": false}))["curves"])[0].clone(); + run(&mut s, "sketch.constraint.parallel", json!({"a": diagonal, "b": line})); + run(&mut s, "sketch.dimension", json!({"entities": [diagonal, line]})); + let value = |sk: &solidcraft_sketch::Sketch| { + sk.constraints.iter().find_map(|c| match c.kind { + ConstraintKind::PointLineDistance { p, value, .. } => Some((sk.point(p).unwrap(), value)), + _ => None, + }) + }; + let (from, d) = value(&sketch(&s)).expect("the distance between the parallel lines"); + assert!(from.dist(Vec2::new(-6.0, -2.5)) < 1e-7, "{from:?}"); + // Trim the half from the diagonal's start: the kept half starts at the centre, so the + // distance moves there, onto the one point the cut is welded to. + run(&mut s, "sketch.trim", json!({"curve": diagonal, "at": [-1.5, -0.25]})); + let sk = sketch(&s); + let (from, after) = value(&sk).expect("the distance survives the trim"); + assert!(from.dist(Vec2::new(3.0, 2.0)) < 1e-7, "{from:?}"); + assert!((after - d).abs() < 1e-9, "{after} != {d}"); +} + +/// A center rectangle whose bottom is held square to a side instead of horizontal keeps one +/// centre after a trim: what makes its diagonals bisect each other is the solver's to say, not +/// which constraints hold the sides. +#[test] +fn trimming_a_diagonal_of_a_center_rectangle_held_by_other_constraints_keeps_one_centre() { + let mut s = new_sketch(); + run(&mut s, "sketch.rectangle.center", json!({"center": [3, 2], "corner": [12, 6.5]})); + let sk = sketch(&s); + let bottom = sk.constraints.iter().find(|c| matches!(c.kind, ConstraintKind::Horizontal { l: 0 })).map(|c| c.id.clone()).unwrap(); + run(&mut s, "sketch.delete", json!({"entities": [bottom]})); + run(&mut s, "sketch.constraint.perpendicular", json!({"a": "l1", "b": "l2"})); + let dof = run(&mut s, "sketch.inspect", json!({}))["dof"].clone(); + let diagonal = sketch(&s).curves.iter().find(|c| c.construction).map(|c| c.id.clone()).unwrap(); + run(&mut s, "sketch.trim", json!({"curve": diagonal, "at": [7.5, 4.25]})); + 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, "{at_centre} points at the centre"); + let si = run(&mut s, "sketch.inspect", json!({})); + assert_eq!(si["dof"], dof, "the trim frees the centre: {si}"); +} + +/// A line's held midpoint trimmed at a crossing line that only happens to have its middle there +/// ends the kept half on that point and keeps it on the crossing line, without tying the crossing +/// line's middle to it: nothing held that middle before. +#[test] +fn trimming_at_a_held_midpoint_on_an_unrelated_line_adds_no_hold_to_that_line() { + let mut s = new_sketch(); + let trimmed = 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:{trimmed}")})); + 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.trim", json!({"curve": trimmed, "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"); +} + #[test] fn exact_extend_ellipse_preserves_support_target_and_history() { for (y, expected_x) in [(3.0, 12.0), (5.0, 20.0)] {