SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Sketch Trim: keep the stored offset distance after deleting its dimension (#12186)
cronos21a1269d5cbb
diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rsindex ac1b935876..cfa5d03834 100644--- a/crates/engine/src/cmd/sketch_modify.rs+++ b/crates/engine/src/cmd/sketch_modify.rs@@ -66,7 +66,7 @@ pub static COMMANDS: &[CommandSpec] = &[.icon("trim").enabled(in_sketch).params(concat!(- "points: [[x,y]…] (2…2000 positions: a path drawn across the sketch). Every piece the path crosses is removed as `sketch.trim` removes the piece at that crossing, in the order the path crosses them; a piece crossed again after it is gone is not trimmed twice; projected geometry, infinite lines, offset outputs and pieces trim refuses are passed over (why in `skipped`). dry_run?: bool (report without changing the design). One undo step → trimmed: [each trim's result], removed: [[[x,y]…]] (each removed piece as a polyline)",+ "points: [[x,y]…] (2…2000 positions: a path drawn across the sketch). Every piece the path crosses is removed as `sketch.trim` removes the piece at that crossing, in the order the path crosses them; a piece crossed again after it is gone is not trimmed twice; eligible single-line offset outputs are trimmed while preserving their distance; projected geometry, infinite lines, other offset outputs and pieces trim refuses are passed over (why in `skipped`). dry_run?: bool (report without changing the design). One undo step → trimmed: [each trim's result], removed: [[[x,y]…]] (each removed piece as a polyline)",created_doc!())),CommandSpec::new("sketch.extend", "Extend", extend)@@ -504,6 +504,7 @@ fn refuse_offset_ends(sk: &Sketch, ci: usize, what: &str, cmd: &str) -> Result<(}}+/// Trim the picked piece and release eligible offset extents in the same undo step.fn trim(s: &mut Session, p: &Value) -> Result<Value> {let cmd = "sketch.trim";let at = req_vec2(cmd, p, "at")?;@@ -522,7 +523,8 @@ fn trim(s: &mut Session, p: &Value) -> Result<Value> {/// Source lines and their single-line offsets can have independent endpoints. Materialize/// the affected line chains before Trim, retaining their original driving distance parameters-/// as point-line dimensions. Closed or mixed-curve output chains still need their association.+/// as point-line dimensions. Without a dimension, the stored distance stays a fixed distance.+/// Closed or mixed-curve output chains still need their association.fn release_line_offsets(sk: &mut Sketch, doc: &solidcraft_doc::Document, ci: usize, cmd: &str) -> Result<Vec<String>> {let Some(curve) = sk.curves.get(ci) else { return Ok(Vec::new()) };if curve.infinite || sk.is_linked_curve(ci) || !matches!(curve.kind, CurveKind::Line { .. }) {@@ -562,10 +564,9 @@ fn release_line_offsets(sk: &mut Sketch, doc: &solidcraft_doc::Document, ci: usimatches!(&c.kind,ConstraintKind::OffsetDistance { output, .. } if record.outputs.contains(output))})- .cloned()- .ok_or_else(|| bad(cmd, "missing offset distance dimension"))?;- let value = match dimension.kind {- ConstraintKind::OffsetDistance { value, .. } => value,+ .cloned();+ let value = match dimension.as_ref().map(|c| &c.kind) {+ Some(ConstraintKind::OffsetDistance { value, .. }) => *value,_ => record.distance.abs(),};sk.constraints.retain(|c| !matches!(&c.kind, ConstraintKind::OffsetDistance { output, .. } if record.outputs.contains(output)));@@ -592,8 +593,10 @@ fn release_line_offsets(sk: &mut Sketch, doc: &solidcraft_doc::Document, ci: usi}let p = sk.curves.get(target).and_then(|c| c.kind.ends()).map(|ends| ends.0).ok_or_else(|| bad(cmd, "missing offset line endpoint"))?;let kind = ConstraintKind::PointLineDistance { p, l: source, value };- let id = sk.add_constraint(kind.clone(), dimension.param.clone())?;- if let Some(added) = sk.constraints.iter_mut().find(|c| c.id == id) {+ let id = sk.add_constraint(kind.clone(), dimension.as_ref().and_then(|c| c.param.clone()))?;+ if let Some(dimension) = &dimension+ && let Some(added) = sk.constraints.iter_mut().find(|c| c.id == id)+ {let mut kept = dimension.clone();kept.id = if index == 0 { dimension.id.clone() } else { id };kept.kind = kind;@@ -824,6 +827,7 @@ fn seg_cross(a: Vec2, b: Vec2, c: Vec2, d: Vec2) -> Option<(f64, Vec2)> {((0.0..=1.0).contains(&t) && (0.0..=1.0).contains(&u)).then(|| (t, a + r * t))}+/// Preview or trim the pieces crossed by a path, skipping protected or unsupported geometry.fn trim_path(s: &mut Session, p: &Value) -> Result<Value> {let cmd = "sketch.trim.path";let path = vec2_list(cmd, p, "points", MAX_PATH_POINTS)?;diff --git a/crates/engine/src/cmd/sketch_modify_tests.rs b/crates/engine/src/cmd/sketch_modify_tests.rsindex 91797d98ba..e53735cad5 100644--- a/crates/engine/src/cmd/sketch_modify_tests.rs+++ b/crates/engine/src/cmd/sketch_modify_tests.rs@@ -5351,6 +5351,7 @@ fn trim_source_and_two_offsets_independently_in_any_order() {}}+/// Trimming one output preserves the source, sibling association and unrelated offsets; Undo restores the full design.#[test]fn trimming_one_offset_line_keeps_its_source_sibling_and_other_offsets() {let mut s = new_sketch();@@ -5378,6 +5379,79 @@ fn trimming_one_offset_line_keeps_its_source_sibling_and_other_offsets() {assert_eq!(s.doc.to_json(), document, "one Undo restores the offset association as well as the trimmed end");}+/// Deleting the driving dimension freezes its last distance; both Trim entry points must+/// still cut the output, or remove it entirely without a crossing, and undo in one step.+#[test]+fn trim_offset_after_deleting_its_dimension_keeps_the_stored_distance() {+ for distance in [2.0_f64, -3.0] {+ for path in [false, true] {+ for crossing in [false, true] {+ let mut s = new_sketch();+ run(&mut s, "sketch.line", json!({"points": [[0,0],[20,0]], "connect": false, "infer": false, "ids": ["source"]}));+ run(&mut s, "sketch.constraint.fix", json!({"entities": ["source"]}));+ let out = run(&mut s, "sketch.offset", json!({"curves": ["source"], "distance": distance, "chain": false}));+ let output = ids(&out["curves"])[0].clone();+ let parameter = out["param"].as_str().unwrap().to_string();+ run(&mut s, "parameters.change", json!({"name": parameter, "expression": "4 mm"}));+ let sk = sketch(&s);+ let dimension = sk.constraints.iter().find(|c| c.param.as_deref() == Some(¶meter)).unwrap().id.clone();+ run(&mut s, "sketch.delete", json!({"entities": [dimension]}));+ assert!(s.doc.param(¶meter).is_none());+ let before_sketch = sketch(&s);+ let stored_distance = before_sketch.offsets[0].distance;+ assert!((stored_distance.abs() - 4.0).abs() < 1e-6);+ if crossing {+ run(&mut s, "sketch.line", json!({"points": [[10,-10],[10,10]], "connect": false, "infer": false}));+ }+ let before = s.doc.to_json();+ let request = json!({"points": [[5,stored_distance-0.5],[5,stored_distance+0.5]]});+ if path {+ let mut preview = request.clone();+ preview["dry_run"] = json!(true);+ let preview = run(&mut s, "sketch.trim.path", preview);+ assert_eq!(preview["trimmed"].as_array().unwrap().len(), 1, "{preview}");+ assert_eq!(s.doc.to_json(), before, "preview must leave the stored association intact");+ let result = run(&mut s, "sketch.trim.path", request);+ assert_eq!(result["trimmed"], preview["trimmed"]);+ assert!(result["skipped"].as_array().unwrap().is_empty());+ } else {+ run(&mut s, "sketch.trim", json!({"curve": output, "at": [5,stored_distance]}));+ }+ let after_sketch = sketch(&s);+ assert!(after_sketch.offsets.is_empty());+ assert!(s.doc.param(¶meter).is_none(), "Trim must not resurrect the deleted parameter");+ assert_eq!(+ after_sketch.polyline(after_sketch.curve_index("source").unwrap()),+ before_sketch.polyline(before_sketch.curve_index("source").unwrap())+ );+ if crossing {+ let solidcraft_sketch::Shape::Line { a, b } = after_sketch.shape(after_sketch.curve_index(&output).unwrap()).unwrap() else {+ panic!("line")+ };+ assert!((a.x.min(b.x) - 10.0).abs() < 1e-6 && (a.x.max(b.x) - 20.0).abs() < 1e-6, "{a:?} {b:?}");+ assert!((a.y - stored_distance).abs() < 1e-6 && (b.y - stored_distance).abs() < 1e-6);+ } else {+ assert!(after_sketch.curve_index(&output).is_none(), "an uncut output must be removed completely");+ }+ let after = s.doc.to_json();+ run(&mut s, "edit.undo", json!({}));+ assert_eq!(s.doc.to_json(), before);+ run(&mut s, "edit.redo", json!({}));+ assert_eq!(s.doc.to_json(), after);+ if crossing {+ run(&mut s, "sketch.move_point", json!({"point": format!("{output}.end"), "to": [25,stored_distance+2.0]}));+ let reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap());+ let state = reopened.world_state().unwrap();+ let sk = &state.sketch(1).unwrap().sketch;+ let solidcraft_sketch::Shape::Line { a, b } = sk.shape(sk.curve_index(&output).unwrap()).unwrap() else { panic!("line") };+ assert!((a.y - stored_distance).abs() < 1e-6 && (b.y - stored_distance).abs() < 1e-6);+ }+ }+ }+ }+}++/// Path preview is inert; applying the same path trims all three lines at their own crossings in one undo step.#[test]fn trim_path_cuts_source_and_two_offsets_at_their_own_crossings() {let mut s = new_sketch();@@ -5429,6 +5503,7 @@ fn trim_whole_source_keeps_its_offsets_and_unrelated_associations() {assert_eq!(s.doc.to_json(), doc_before);}+/// All pick orders retain driving distances through repeated trims, dragging, parameter edits and native reload.#[test]fn trim_keeps_offset_distances_driving_after_trims_drag_and_reopen() {let verify = |s: &Session, distance: f64, parameter: &str| {diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rsindex 8628b0f521..bdce6c3b5a 100644--- a/crates/ui-egui/src/context_menu.rs+++ b/crates/ui-egui/src/context_menu.rs@@ -3095,6 +3095,7 @@ mod tests {assert!(h.app.viewport.context_menu.is_none());}+ /// Direct Trim undoes back to the association; the explicit Break menu still makes the offset editable.#[test]fn line_offset_context_menu_breaks_association_and_allows_trim() {use solidcore_record::Vec2;diff --git a/crates/ui-egui/src/sketch_trim_drag_ui_tests.rs b/crates/ui-egui/src/sketch_trim_drag_ui_tests.rsindex b1853a6d1d..eb4fec7723 100644--- a/crates/ui-egui/src/sketch_trim_drag_ui_tests.rs+++ b/crates/ui-egui/src/sketch_trim_drag_ui_tests.rs@@ -151,6 +151,7 @@ fn play(h: &mut Harness) {h.frames(2);}+/// Clicks and a drag that start on an offset trim independent ends and preserve the expected undo history.#[test]fn trimming_construction_source_and_offsets_by_click_or_drag_is_independent() {for drag in [false, true] {