SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Shell: show the tangent-chain face selection and explain full-body removal (#209) (#3809)
Colin Faulkingham36c732ddb76a
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rsindex f70531ac27..7b6ca2e32a 100644--- a/crates/doc/src/eval.rs+++ b/crates/doc/src/eval.rs@@ -4986,8 +4986,10 @@ fn face_samples(b: &ModelBody) -> Vec<Vec3> {out.into_iter().flatten().collect()}-/// The picked faces and every face joined to them smoothly (across tangent edges), as points.-fn smooth_chain(b: &ModelBody, picks: &[Vec3]) -> Vec<Vec3> {+/// The picked faces and every face joined to them smoothly (across tangent edges).+/// Each face appears once, with a point on it. Shell evaluation and selection feedback use+/// the same expansion; callers keep the original picks when saving the feature.+pub fn tangent_face_chain(b: &ModelBody, picks: &[Vec3]) -> Vec<(usize, Vec3)> {let m = b.mesh();let samples = face_samples(b);let face_of = |p: Vec3| crate::appearance::face_index_at(b, p);@@ -5004,6 +5006,8 @@ fn smooth_chain(b: &ModelBody, picks: &[Vec3]) -> Vec<Vec3> {.and_then(|(_, n)| n.normalized())};let mut chosen: Vec<u32> = picks.iter().filter_map(|p| face_of(*p).map(|f| f as u32)).collect();+ chosen.sort_unstable();+ chosen.dedup();let mut k = 0;while k < chosen.len() && chosen.len() < 10_000 {let f = chosen[k];@@ -5028,15 +5032,21 @@ fn smooth_chain(b: &ModelBody, picks: &[Vec3]) -> Vec<Vec3> {}}}- let mut out = picks.to_vec();+ let mut out = Vec::new();for f in chosen {- if let Some(p) = samples.iter().find(|p| face_of(**p) == Some(f as usize)) {- out.push(*p);+ if let Some(p) = picks.iter().chain(&samples).find(|p| face_of(**p) == Some(f as usize)) {+ out.push((f as usize, *p));}}out}+fn smooth_chain(b: &ModelBody, picks: &[Vec3]) -> Vec<Vec3> {+ let mut out = picks.to_vec();+ out.extend(tangent_face_chain(b, picks).into_iter().map(|(_, point)| point));+ out+}+/// `plane` with the sheet face it names (see `sheet::plane_sheet_face`) replaced by that face's current/// plane in the frame of component `comp`, or an error when the face is gone: a lost/// attachment is reported, never moved to the nearest face.@@ -5334,7 +5344,23 @@ fn eval_feature(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature, st:let t = val(vals, thickness, Kind::Length)?;let i = body_at(st, body, &crate::plain(faces))?;let Some(mb) = st.bodies.get(i).cloned() else { return Err(DocError::Invalid("body".into())) };- let open = if *tangent_chain { smooth_chain(&mb, &crate::plain(faces)) } else { crate::plain(faces) };+ let picks = crate::plain(faces);+ let open = if *tangent_chain {+ let chain = tangent_face_chain(&mb, &picks);+ if !chain.is_empty() && chain.len() == mb.body.face_count() {+ return Err(DocError::Invalid(+ "Tangent Chain opens every face of this body, leaving no walls; turn off Tangent Chain to remove only the picked faces"+ .into(),+ ));+ }+ // Keep every authored pick, including any the kernel must reject, as before+ // chain expansion. The derived samples must not silently drop a bad input.+ let mut open = picks;+ open.extend(chain.into_iter().map(|(_, point)| point));+ open+ } else {+ picks+ };let input = mb.traced();// The shell, and the operands of the operation that made it.let (nb, operands) = match direction.as_str() {@@ -6576,9 +6602,14 @@ mod chain_tests {m.evaluate(&doc);let st = m.state();let b = &st.bodies[0];- let pts = smooth_chain(b, &[Vec3::new(20.0, 15.0, 20.0)]);- let faces: std::collections::BTreeSet<usize> = pts.iter().filter_map(|p| crate::appearance::face_index_at(b, *p)).collect();+ let pts = tangent_face_chain(b, &[Vec3::new(20.0, 15.0, 20.0)]);+ let faces: std::collections::BTreeSet<usize> = pts.iter().map(|(index, _)| *index).collect();assert_eq!(faces.len(), 3, "{faces:?}");+ assert_eq!(pts.len(), faces.len());+ for (index, point) in &pts {+ assert_eq!(crate::appearance::face_index_at(b, *point), Some(*index));+ }+ assert_eq!(tangent_face_chain(b, &[Vec3::new(20.0, 15.0, 20.0); 2]), pts);}}diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rsindex 38bbb4505e..1118764638 100644--- a/crates/doc/src/lib.rs+++ b/crates/doc/src/lib.rs@@ -61,7 +61,7 @@ pub use eval::{EdgeRef, FeatureResult, Model, ModelBody, ModelState, PlacedBodies, RevolveExtent, SavedModel, SolvedSketch, ThreadInfo, curve_pick_error,edge_names_for, edge_refs, face_point_names, face_point_state, hole_direction_at, import_body_names, metric_thread_sizes, object_height,parse_metric_thread, pattern_matrices, revolve_extent, revolve_extent_with_convention, select_profiles, sketch_hole_direction, sketch_line_plane,- state_in_frame, state_in_frame_at, suggested_thread, through_all_distance, world_state, world_state_reusing,+ state_in_frame, state_in_frame_at, suggested_thread, tangent_face_chain, through_all_distance, world_state, world_state_reusing,};pub use expr::Expr;pub use names::{BodyName, FeatureName, SketchId};diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rsindex 5a3380b6e1..e9a6685d43 100644--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@ -3032,6 +3032,40 @@ fn shell_directions_and_tangent_chain() {assert!(s.execute("solid.shell", &json!({"faces": [[20, 15, 20]], "thickness": 2, "direction": "sideways"})).is_err());}+/// #209: selecting a tangent chain must explain why no shell can remain.+#[test]+fn shell_tangent_chain_that_opens_every_face_explains_how_to_keep_walls() {+ let mut s = Session::default();+ run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 60}));+ run(+ &mut s,+ "solid.fillet",+ json!({+ "edges": [[0,0,30], [40,0,30], [40,30,30], [0,30,30],+ [20,0,60], [20,30,60], [0,15,60], [40,15,60],+ [20,0,0], [20,30,0], [0,15,0], [40,15,0]],+ "radius": 1.5+ }),+ );+ let before = s.doc.to_json();+ for direction in ["inside", "outside", "both"] {+ let error = s+ .execute(+ "solid.shell",+ &json!({+ "faces": [[20,0,30]], "thickness": 2, "tangent_chain": true, "direction": direction+ }),+ )+ .unwrap_err()+ .to_string();+ assert!(error.contains("Tangent Chain") && error.contains("every face") && error.contains("turn off"), "{direction}: {error}");+ assert_eq!(s.doc.to_json(), before, "a refused shell must preserve the design");+ }+ run(&mut s, "solid.shell", json!({"faces": [[20,0,30]], "thickness": 2, "tangent_chain": false}));+ assert!((volume(&mut s) - 15_305.28).abs() < 0.1);+ assert_eq!(s.model.state().bodies.len(), 1);+}+/// Hole To Object (a face it meets, or a point) and holes at every point of a sketch.#[test]fn hole_to_object_and_at_sketch_points() {diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rsindex e763a97493..ed003ee0a3 100644--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@ -424,6 +424,15 @@ pub struct Dialog {pub(crate) picked_edges: Vec<Sel>,/// Whether `inputs[0]` currently includes the tangent chains of `picked_edges`.pub(crate) chain_applied: bool,+ /// Shell feedback is derived from the picks, never saved as additional face references.+ shell_chain: std::cell::RefCell<Option<ShellChain>>,+}++#[derive(Clone, Debug)]+struct ShellChain {+ revision: u64,+ picks: Vec<Sel>,+ faces: Vec<Sel>,}/// OK computing off the window thread: the dialog's commands evaluated on a scratch copy of the@@ -557,6 +566,7 @@ impl Dialog {then_start: None,picked_edges: Vec::new(),chain_applied,+ shell_chain: Default::default(),}}@@ -987,6 +997,47 @@ impl Dialog {self.inputs.iter().flat_map(|i| i.items.iter().cloned()).collect()}+ /// Faces Shell will open, including the tangent chain. Keep the input itself as the+ /// user's picks so switching the option off, clearing, and editing all remain reversible.+ fn shell_faces(&self, s: &Session) -> Option<Vec<Sel>> {+ if !matches!(self.kind, Kind::Shell { .. }) || self.extra.get("tangent_chain").and_then(Value::as_bool) != Some(true) {+ return None;+ }+ let picks = sels(self, 0);+ if let Ok(cache) = self.shell_chain.try_borrow()+ && let Some(chain) = cache.as_ref()+ && chain.revision == s.revision+ && chain.picks == picks+ {+ return Some(chain.faces.clone());+ }+ let state = s.world_state();+ let mut by_body = std::collections::BTreeMap::<&str, Vec<Vec3>>::new();+ for pick in picks {+ if let Sel::Face { body, point, .. } = pick {+ by_body.entry(body).or_default().push(*point);+ }+ }+ let mut faces = Vec::new();+ for (name, points) in by_body {+ if let Some(body) = state.body(name) {+ faces.extend(solidcraft_engine::doc::tangent_face_chain(body, &points).into_iter().map(|(index, point)| Sel::Face {+ body: name.to_string(),+ index,+ point,+ }));+ }+ }+ if let Ok(mut cache) = self.shell_chain.try_borrow_mut() {+ *cache = Some(ShellChain { revision: s.revision, picks: picks.to_vec(), faces: faces.clone() });+ }+ Some(faces)+ }++ pub(crate) fn highlighted(&self, s: &Session) -> Vec<Sel> {+ self.shell_faces(s).unwrap_or_else(|| self.items())+ }+pub fn highlight_key(&self) -> u64 {let mut h = std::collections::hash_map::DefaultHasher::new();serde_json::to_string(&self.items()).unwrap_or_default().hash(&mut h);@@ -1841,6 +1892,7 @@ fn input_rows_range(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, range: std::let mut clear: Option<usize> = None;let mut activate: Option<usize> = None;let mut remove = None;+ let shell_count = d.shell_faces(s).map(|faces| faces.len());for (i, inp) in d.inputs.iter().enumerate().skip(range.start).take(range.end.saturating_sub(range.start)) {let stored_reference = feature_pattern_reference_key(d, i).and_then(|key| d.extra.get(key)).filter(|_| inp.items.is_empty());form_row(ui, inp.label, |ui| {@@ -1855,7 +1907,8 @@ fn input_rows_range(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, range: std::} else if !inp.multi {inp.items.first().map(|item| selection_label(s, item)).unwrap_or_default()} else {- crate::i18n::format("dialog.selected_count", &[("count", &inp.items.len().to_string())])+ let count = if i == 0 { shell_count.unwrap_or(inp.items.len()) } else { inp.items.len() };+ crate::i18n::format("dialog.selected_count", &[("count", &count.to_string())])}).color(t.on_accent)} else {@@ -1864,6 +1917,13 @@ fn input_rows_range(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, range: std::let selected_text = text.text().strip_prefix("↖ ").unwrap_or_else(|| text.text());let prompt = if !filled && inp.label == "Edges" { tr("Select edges") } else { selected_text };let chip = crate::ui_kit::selection_field(ui, prompt, crate::ui_kit::Selection { active, filled });+ if matches!(d.kind, Kind::Shell { .. }) && i == 0 {+ chip.widget_info(|| {+ let mut info = egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), tr(inp.label));+ info.current_text_value = Some(prompt.to_string());+ info+ });+ }let chip_rect = chip.rect;let tooltip = if let Some(reference) = stored_reference {reference.to_string()diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 67b437b2bb..dc5a9417f7 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -1117,7 +1117,7 @@ impl SolveApp {pub fn highlighted(&self) -> Vec<solidcraft_engine::Sel> {let mut v = self.session.selection.clone();if let Some(d) = &self.dialog {- v.extend(d.items());+ v.extend(d.highlighted(&self.session));}v.extend(sketch_text::highlighted(self));v.extend(sketch_text_move::highlighted(self));diff --git a/crates/ui-egui/src/preselect_tests.rs b/crates/ui-egui/src/preselect_tests.rsindex c2af87bf0b..58f29300f5 100644--- a/crates/ui-egui/src/preselect_tests.rs+++ b/crates/ui-egui/src/preselect_tests.rs@@ -963,6 +963,43 @@ fn shell_direction_and_tangent_chain_round_trip() {assert_eq!(e.extra.get("tangent_chain"), Some(&json!(true)));}+#[test]+fn shell_tangent_chain_highlights_and_counts_faces_without_saving_extra_picks() {+ let mut h = crate::scenario::Harness::new();+ h.app.run("solid.box", json!({"length":40,"width":30,"height":20})).unwrap();+ h.app.run("solid.fillet", json!({"edges":[[20,0,20]],"radius":4})).unwrap();+ let top = face(&h.app, Vec3::new(20.0, 17.0, 20.0));+ start(&mut h.app, vec![top.clone()], "solid.shell");+ h.frames(3);+ let shown = |app: &SolveApp| -> std::collections::BTreeSet<usize> {+ app.highlighted()+ .into_iter()+ .filter_map(|sel| match sel {+ Sel::Face { index, .. } => Some(index),+ _ => None,+ })+ .collect()+ };+ assert_eq!(shown(&h.app).len(), 3, "the top, round and front are one tangent chain");+ assert!(h.widget("3 selected").is_some());+ let d = h.app.dialog.as_ref().unwrap();+ assert_eq!(d.inputs[0].items, vec![top.clone()]);+ assert_eq!(apply_commands(&h.app, d).unwrap()[0].1["faces"].as_array().unwrap().len(), 1);++ h.step(&json!({"click":{"handle":"dialog:Tangent Chain"}})).unwrap();+ h.frames(3);+ assert_eq!(shown(&h.app).len(), 1);+ assert!(h.widget("1 selected").is_some());+ assert_eq!(h.app.dialog.as_ref().unwrap().inputs[0].items, vec![top]);++ h.step(&json!({"click":{"handle":"dialog:Tangent Chain"}})).unwrap();+ h.frames(3);+ assert_eq!(shown(&h.app).len(), 3);+ h.step(&json!({"click":{"handle":"dialog:clear:Faces/Body"}})).unwrap();+ h.frames(3);+ assert!(h.app.dialog.as_ref().unwrap().highlighted(&h.app.session).is_empty(), "clear must also clear the expanded highlight");+}+#[test]fn variable_fillet_round_trip() {let mut app = boxed();