Skip to content

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

Wave 229/509: doc: a join keeps solids that only touch as separate bodies (and 3 more)

jyviko8554b2a0e4ff
diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs
index 46c70f3b50..ca797a11c7 100644
--- a/crates/doc/src/document.rs
+++ b/crates/doc/src/document.rs
@@ -196,6 +196,32 @@ impl Operation {
}
}
+/// What a join makes of solids that only touch, along an edge or at a point, or don't touch at
+/// all: they share no volume and no area, so nothing fuses them.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Touching {
+ /// Each becomes a body of its own.
+ #[default]
+ Separate,
+ /// They stay one body of several pieces.
+ OneBody,
+}
+
+impl Touching {
+ pub fn parse(s: &str) -> Option<Touching> {
+ Some(match s.to_ascii_lowercase().replace([' ', '-'], "_").as_str() {
+ "separate" => Touching::Separate,
+ "one_body" => Touching::OneBody,
+ _ => return None,
+ })
+ }
+
+ fn is_separate(&self) -> bool {
+ *self == Touching::Separate
+ }
+}
+
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Direction {
@@ -2559,6 +2585,10 @@ pub struct Feature {
/// its faces are named after them and references follow them through Update Links (#3330).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub link_faces: Vec<Vec<String>>,
+ /// What a join of this feature makes of solids that only touch or don't touch: separate
+ /// bodies (the default) or one body of several pieces.
+ #[serde(default, skip_serializing_if = "Touching::is_separate")]
+ pub touching: Touching,
#[serde(flatten)]
pub kind: FeatureKind,
}
@@ -3447,6 +3477,7 @@ impl Document {
kernel_piece_order: false,
inserted: false,
link_faces: Vec::new(),
+ touching: Touching::Separate,
kind,
};
self.place_feature(f);
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs
index 844096e3a2..d6eb4d3904 100644
--- a/crates/doc/src/eval.rs
+++ b/crates/doc/src/eval.rs
@@ -8,6 +8,7 @@ use std::hash::{Hash, Hasher};
use std::sync::{Arc, OnceLock};
use serde::{Deserialize, Serialize};
+use solidcraft_geom::brep::part::Contact;
use solidcraft_geom::tess::TessPlan;
use solidcraft_geom::{Mesh, Plane, Region2, UnitVec3, Vec2, Vec3, regions_apart};
use solidcraft_kernel::{self as kernel, Body, BoolOp};
@@ -776,6 +777,11 @@ impl ModelState {
self.fitted.get(&feature)?.iter().fold(None, |acc, r| Some(acc.map_or((*r, *r), |(lo, hi): (f64, f64)| (lo.min(*r), hi.max(*r)))))
}
+ /// How the solids join `feature` kept as separate bodies met, when it kept any apart.
+ pub fn kept_separate(&self, feature: u64) -> Option<KeptSeparate> {
+ self.kept_separate.get(&feature).copied()
+ }
+
/// Each edge fillet `feature` tapered (a point on it) with the radius spline it was given.
pub fn tapered(&self, feature: u64) -> Option<&[(Vec3, kernel::Taper)]> {
self.tapered.get(&feature).map(Vec::as_slice)
@@ -824,6 +830,40 @@ pub struct ModelState {
/// The radius spline of each edge a fillet tapered (a point on the edge with it, by feature
/// id, see `FilletFit::Taper`).
tapered: BTreeMap<u64, Vec<(Vec3, kernel::Taper)>>,
+ /// How the solids a join kept as separate bodies met (by feature id), for its notice.
+ kept_separate: BTreeMap<u64, KeptSeparate>,
+}
+
+/// How the solids a join kept as separate bodies (`Touching::Separate`) met: the most any two
+/// of them shared, least first.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
+pub enum KeptSeparate {
+ /// Nothing: they don't touch.
+ Apart,
+ /// A point.
+ AtPoint,
+ /// A curve: an edge of both.
+ AlongEdge,
+}
+
+impl KeptSeparate {
+ /// Its id in a feature's result: `apart`, `at_point` or `along_edge`.
+ pub fn id(self) -> &'static str {
+ match self {
+ KeptSeparate::Apart => "apart",
+ KeptSeparate::AtPoint => "at_point",
+ KeptSeparate::AlongEdge => "along_edge",
+ }
+ }
+
+ /// What a feature's result says about it.
+ pub fn notice(self) -> &'static str {
+ match self {
+ KeptSeparate::Apart => "These bodies don't touch, so they were kept as separate bodies.",
+ KeptSeparate::AtPoint => "These bodies only touch at a point, so they were kept as separate bodies.",
+ KeptSeparate::AlongEdge => "These bodies only touch along an edge, so they were kept as separate bodies.",
+ }
+ }
}
impl ModelState {
@@ -2935,66 +2975,16 @@ fn apply_traced_with(
}
match op {
Operation::Join => {
- // Each tool joins every target it meets into one body, kept under the first one's
- // name; a tool that meets none joins the first target as a separate lump. A sheet
- // metal body keeps its own identity: only the first body met may be one.
- let mut live: Vec<String> = target_idx.iter().filter_map(|i| state.bodies.get(*i).map(|b| b.name.clone())).collect();
- // Each union keeps the lineage of what it joins, so the joined body's faces keep
- // their names (the tool's new faces are named by their roles).
- let union = |a: &Traced, b: &Traced| -> Result<Traced> {
- let u = kernel::boolean(&a.body, &b.body, BoolOp::Union)?.ok_or_else(|| DocError::Invalid("join produced nothing".into()))?;
- Ok(Traced::step(u, &[a, b]))
- };
- // One target takes every tool, whichever it meets: the result is the union of all of
- // them in one kernel call, checked once.
- if let [keep] = live.as_slice()
- && tools.len() > 1
- {
- let Some(base) = state.body(keep).map(ModelBody::traced) else { return Ok(()) };
- let operands: Vec<&Traced> = std::iter::once(&base).chain(&tools).collect();
- let acc = union_all(&operands)?;
- if let Some(mb) = state.bodies.iter_mut().find(|b| b.name == *keep) {
- *mb = ModelBody::traced_new(mb.name.clone(), acc, mb.feature);
- }
- return Ok(());
- }
- for tool in &tools {
- let mut met: Vec<String> = Vec::new();
- for name in &live {
- let Some(mb) = state.body(name) else { continue };
- let sheet = state.sheets.iter().any(|s| &s.body == name);
- if mb.body.is_mesh() || (!met.is_empty() && sheet) {
- continue;
- }
- // Each body is met where it is shown: the tool goes into its frame (#3383).
- if mb.body.meets(&tool_in(tool, tool_frame(name))?.body)? {
- met.push(name.clone());
- }
- }
- let Some(keep) = met.first().or(live.first()).cloned() else { return Ok(()) };
- let Some(base) = state.body(&keep).map(ModelBody::traced) else { continue };
- let into_keep = tool_frame(&keep);
- let mut acc = union(&base, &tool_in(tool, into_keep)?)?;
- for name in met.iter().skip(1) {
- if let Some(b) = state.body(name) {
- // A body placed differently from the one kept joins it where it is shown.
- let from = match tool_frame(name) {
- Some(m) => crate::mat_inverse(&m),
- None => Some(crate::IDENTITY),
- };
- let m = from.map(|from| crate::mat_mul(&into_keep.unwrap_or(crate::IDENTITY), &from)).filter(|m| !crate::is_identity(m));
- acc = union(&acc, &tool_in(&b.traced(), m)?)?;
- }
- }
- let absorbed: std::collections::BTreeSet<String> = met.into_iter().skip(1).collect();
- if let Some(mb) = state.bodies.iter_mut().find(|b| b.name == keep) {
- *mb = ModelBody::traced_new(mb.name.clone(), acc, mb.feature);
+ let joined = join(state, tools, &target_idx)?;
+ if f.touching == crate::Touching::Separate {
+ let mut kept = None;
+ for name in joined {
+ kept = kept.max(separate_touching(state, &name)?);
}
- state.bodies.retain(|b| !absorbed.contains(&b.name));
- for t in state.threads.iter_mut().filter(|t| absorbed.contains(&t.body)) {
- t.body = keep.clone();
+ if let Some(k) = kept {
+ let most = state.kept_separate.entry(f.id).or_insert(k);
+ *most = (*most).max(k);
}
- live.retain(|n| !absorbed.contains(n));
}
}
Operation::Cut | Operation::Intersect => {
@@ -3071,18 +3061,7 @@ fn apply_traced_with(
split.push(mb);
continue;
}
- // Each piece's faces are named after the whole's, worked out once for the whole
- // (so pieces of one face in different bodies are told apart).
- let lineages = crate::lineage::Lineage::lumps(&mb.body, mb.lineage().as_deref(), &pieces);
- for (k, (p, lineage)) in pieces.into_iter().zip(lineages).enumerate() {
- let name = if k == 0 {
- mb.name.clone()
- } else {
- (k..=k + taken.len()).map(|j| format!("{} ({j})", mb.name)).find(|n| !taken.contains(n)).unwrap_or_default()
- };
- taken.insert(name.clone());
- split.push(ModelBody::new(name, p, mb.feature).with_lineage(lineage));
- }
+ split.extend(named_pieces(&mb, pieces, &mut taken));
}
state.bodies = split;
}
@@ -3091,6 +3070,152 @@ fn apply_traced_with(
Ok(())
}
+/// Join `tools` into the bodies at `target_idx`: each tool joins every target it meets into one
+/// body, kept under the first one's name; a tool that meets none joins the first target as a
+/// separate piece. A sheet metal body keeps its own identity: only the first body met may be
+/// one. The names of the bodies the tools went into.
+fn join(state: &mut ModelState, tools: Vec<Traced>, target_idx: &[usize]) -> Result<Vec<String>> {
+ let mut live: Vec<String> = target_idx.iter().filter_map(|i| state.bodies.get(*i).map(|b| b.name.clone())).collect();
+ // Each union keeps the lineage of what it joins, so the joined body's faces keep
+ // their names (the tool's new faces are named by their roles).
+ let union = |a: &Traced, b: &Traced| -> Result<Traced> {
+ let u = kernel::boolean(&a.body, &b.body, BoolOp::Union)?.ok_or_else(|| DocError::Invalid("join produced nothing".into()))?;
+ Ok(Traced::step(u, &[a, b]))
+ };
+ // One target takes every tool, whichever it meets: the result is the union of all of
+ // them in one kernel call, checked once.
+ if let [keep] = live.as_slice()
+ && tools.len() > 1
+ {
+ let Some(base) = state.body(keep).map(ModelBody::traced) else { return Ok(Vec::new()) };
+ // The tools go into the kept body's frame, where it is shown (#3383).
+ let into_keep = tool_frame(keep);
+ let tools = tools.iter().map(|tool| tool_in(tool, into_keep)).collect::<Result<Vec<_>>>()?;
+ let operands: Vec<&Traced> = std::iter::once(&base).chain(&tools).collect();
+ let acc = union_all(&operands)?;
+ if let Some(mb) = state.bodies.iter_mut().find(|b| b.name == *keep) {
+ *mb = ModelBody::traced_new(mb.name.clone(), acc, mb.feature);
+ }
+ return Ok(vec![keep.clone()]);
+ }
+ let mut joined = Vec::new();
+ for tool in &tools {
+ let mut met: Vec<String> = Vec::new();
+ for name in &live {
+ let Some(mb) = state.body(name) else { continue };
+ let sheet = state.sheets.iter().any(|s| &s.body == name);
+ if mb.body.is_mesh() || (!met.is_empty() && sheet) {
+ continue;
+ }
+ // Each body is met where it is shown: the tool goes into its frame (#3383).
+ if mb.body.meets(&tool_in(tool, tool_frame(name))?.body)? {
+ met.push(name.clone());
+ }
+ }
+ let Some(keep) = met.first().or(live.first()).cloned() else { return Ok(joined) };
+ let Some(base) = state.body(&keep).map(ModelBody::traced) else { continue };
+ let into_keep = tool_frame(&keep);
+ let mut acc = union(&base, &tool_in(tool, into_keep)?)?;
+ for name in met.iter().skip(1) {
+ if let Some(b) = state.body(name) {
+ // A body placed differently from the one kept joins it where it is shown.
+ let from = match tool_frame(name) {
+ Some(m) => crate::mat_inverse(&m),
+ None => Some(crate::IDENTITY),
+ };
+ let m = from.map(|from| crate::mat_mul(&into_keep.unwrap_or(crate::IDENTITY), &from)).filter(|m| !crate::is_identity(m));
+ acc = union(&acc, &tool_in(&b.traced(), m)?)?;
+ }
+ }
+ let absorbed: std::collections::BTreeSet<String> = met.into_iter().skip(1).collect();
+ if let Some(mb) = state.bodies.iter_mut().find(|b| b.name == keep) {
+ *mb = ModelBody::traced_new(mb.name.clone(), acc, mb.feature);
+ }
+ state.bodies.retain(|b| !absorbed.contains(&b.name));
+ for t in state.threads.iter_mut().filter(|t| absorbed.contains(&t.body)) {
+ t.body = keep.clone();
+ }
+ live.retain(|n| !absorbed.contains(n));
+ if !joined.contains(&keep) {
+ joined.push(keep);
+ }
+ }
+ Ok(joined)
+}
+
+/// With `Touching::Separate`: the pieces of the joined body `name` that share no area with each
+/// other become bodies of their own, named as a cut's pieces are; pieces that share a face stay
+/// one body. How the pieces kept apart met, when it has any (a sheet metal or mesh body keeps
+/// its pieces).
+fn separate_touching(state: &mut ModelState, name: &str) -> Result<Option<KeptSeparate>> {
+ let Some(i) = state.bodies.iter().position(|b| b.name == name) else { return Ok(None) };
+ let Some(mb) = state.bodies.get(i).filter(|b| !b.body.is_mesh() && !state.sheets.iter().any(|s| s.body == name)) else { return Ok(None) };
+ let n = mb.body.record().material_regions().len();
+ if n < 2 {
+ return Ok(None);
+ }
+ // Pieces sharing a face are one solid: each group is listed under its least piece.
+ let contacts = mb.body.region_contacts()?;
+ let mut root: Vec<usize> = (0..n).collect();
+ let find = |root: &[usize], mut k: usize| {
+ while let Some(&r) = root.get(k).filter(|&&r| r != k) {
+ k = r;
+ }
+ k
+ };
+ for c in contacts.iter().filter(|c| c.contact == Contact::Face) {
+ let [a, b] = c.regions.map(|k| find(&root, k));
+ if let Some(slot) = root.get_mut(a.max(b)) {
+ *slot = a.min(b);
+ }
+ }
+ let mut groups: Vec<Vec<usize>> = Vec::new();
+ let mut group_of: BTreeMap<usize, usize> = BTreeMap::new();
+ for k in 0..n {
+ let g = *group_of.entry(find(&root, k)).or_insert_with(|| {
+ groups.push(Vec::new());
+ groups.len() - 1
+ });
+ if let Some(list) = groups.get_mut(g) {
+ list.push(k);
+ }
+ }
+ if groups.len() < 2 {
+ return Ok(None);
+ }
+ // The most any two of the separate pieces share (never a face).
+ let kept = contacts
+ .iter()
+ .filter(|c| find(&root, c.regions[0]) != find(&root, c.regions[1]))
+ .map(|c| if c.contact == Contact::Vertex { KeptSeparate::AtPoint } else { KeptSeparate::AlongEdge })
+ .max()
+ .unwrap_or(KeptSeparate::Apart);
+ let pieces = mb.body.parts(&groups)?;
+ let mut taken: std::collections::BTreeSet<String> = state.bodies.iter().map(|b| b.name.clone()).collect();
+ let named = named_pieces(mb, pieces, &mut taken);
+ state.bodies.splice(i..=i, named);
+ Ok(Some(kept))
+}
+
+/// The bodies the pieces of `mb` become: the first keeps its name, the others are numbered after
+/// it ("Bar (1)") on past the names already `taken`. Each piece's faces are named after the
+/// whole's, worked out once for the whole (so pieces of one face in different bodies are told
+/// apart).
+fn named_pieces(mb: &ModelBody, pieces: Vec<Body>, taken: &mut std::collections::BTreeSet<String>) -> Vec<ModelBody> {
+ let lineages = crate::lineage::Lineage::lumps(&mb.body, mb.lineage().as_deref(), &pieces);
+ let mut out = Vec::with_capacity(pieces.len());
+ for (k, (p, lineage)) in pieces.into_iter().zip(lineages).enumerate() {
+ let name = if k == 0 {
+ mb.name.clone()
+ } else {
+ (k..=k + taken.len()).map(|j| format!("{} ({j})", mb.name)).find(|n| !taken.contains(n)).unwrap_or_default()
+ };
+ taken.insert(name.clone());
+ out.push(ModelBody::new(name, p, mb.feature).with_lineage(lineage));
+ }
+ out
+}
+
/// Distance that reaches through every target body from the sketch plane (either side).
pub fn through_all_distance(st: &ModelState, plane: &Plane, targets: &[String]) -> Result<f64> {
let mut far: f64 = 0.0;
diff --git a/crates/doc/src/format/pending/join-touching-bodies.rs b/crates/doc/src/format/pending/join-touching-bodies.rs
new file mode 100644
index 0000000000..6a3c465b84
--- /dev/null
+++ b/crates/doc/src/format/pending/join-touching-bodies.rs
@@ -0,0 +1,25 @@
+//! A feature that joins saves what it makes of solids that only touch, along an edge or at a
+//! point, or don't touch at all: `touching`, `separate` (each becomes a body of its own, the
+//! default, not saved) or `one_body` (one body of several pieces). Older builds kept every join's
+//! pieces in one body, so this step gives each feature of an older design that can join
+//! `one_body`, which keeps its bodies as they were. The last release refuses a design with this
+//! change (the newer format number).
+use serde_json::Value;
+
+/// Feature types that join without an `operation` saying so: a combine (whose `new` joins too),
+/// patterns and mirrors (which repeat a join), and the features that add material to a body.
+const JOINING: [&str; 8] = ["combine", "pattern", "mirror", "emboss", "rib", "boss", "snap_fit", "rest"];
+
+pub fn step(v: &mut Value) -> crate::Result<()> {
+ let Some(Value::Array(features)) = v.get_mut("features") else {
+ return Ok(());
+ };
+ for feature in features {
+ let joins = feature.get("type").and_then(Value::as_str).is_some_and(|t| JOINING.contains(&t))
+ || feature.get("operation").and_then(Value::as_str) == Some("join");
+ if joins && let Some(f) = feature.as_object_mut() {
+ f.insert("touching".into(), Value::from("one_body"));
+ }
+ }
+ Ok(())
+}
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index 491986451d..27383300fb 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -75,11 +75,11 @@ pub use assembly::{
pub use document::*;
pub use eval::KeptResults;
pub use eval::{
- EdgeRef, FeatureResult, Model, ModelBody, ModelState, PlacedBodies, RevolveExtent, SavedModel, SolvedSketch, ThreadInfo, blend_target,
- curve_pick_error, draft_corner_options, edge_names_for, edge_refs, face_point_names, face_point_state, hole_direction_at, import_body_names,
- map_wire, 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, tangent_face_chain,
- through_all_distance, world_state, world_state_reusing,
+ EdgeRef, FeatureResult, KeptSeparate, Model, ModelBody, ModelState, PlacedBodies, RevolveExtent, SavedModel, SolvedSketch, ThreadInfo,
+ blend_target, curve_pick_error, draft_corner_options, edge_names_for, edge_refs, face_point_names, face_point_state, hole_direction_at,
+ import_body_names, map_wire, 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,
+ tangent_face_chain, through_all_distance, world_state, world_state_reusing,
};
pub use expr::Expr;
pub use names::{BodyName, FeatureId, FeatureName, SketchId, copy_name};
diff --git a/crates/doc/src/model_cache.rs b/crates/doc/src/model_cache.rs
index 517cd6e628..5acf0539b1 100644
--- a/crates/doc/src/model_cache.rs
+++ b/crates/doc/src/model_cache.rs
@@ -370,6 +370,8 @@ impl SavedModel {
blend_edges: serde_json::from_value(field("blend_edges")?).map_err(invalid)?,
fitted: serde_json::from_value(field("fitted")?).map_err(invalid)?,
tapered: serde_json::from_value(field("tapered")?).map_err(invalid)?,
+ // A join's notice is for the evaluation that made it, not kept with the cache.
+ kept_separate: BTreeMap::new(),
};
held = held.saturating_add(st.bodies.len()).saturating_add(st.sketches.len()).saturating_add(st.sheets.len());
if held > MAX_HELD {
diff --git a/crates/engine/src/boolean_regression_tests.rs b/crates/engine/src/boolean_regression_tests.rs
index 961e074cb9..3f4e1fe490 100644
--- a/crates/engine/src/boolean_regression_tests.rs
+++ b/crates/engine/src/boolean_regression_tests.rs
@@ -284,7 +284,8 @@ fn buried_join_end_ignores_bodies_in_other_components() {
run(&mut s, "sketch.create", json!({"plane": "XY"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [2, 2], "p1": [4, 4]}));
run(&mut s, "sketch.finish", json!({}));
- run(&mut s, "solid.extrude", json!({"distance": 16, "operation": "join", "body_name": "Tab"}));
+ // Child's box is apart from the tab: `touching: one_body` keeps them one body to measure.
+ run(&mut s, "solid.extrude", json!({"distance": 16, "operation": "join", "body_name": "Tab", "touching": "one_body"}));
let got = volume(&s, if own_body { "Child" } else { "Tab" });
let expected = 64.0 + if own_body { 800.0 } else { 0.0 };
assert!((got - expected).abs() < 1e-6, "{got}");
@@ -1010,11 +1011,11 @@ fn multi_target_join_keeps_nearby_bodies_and_original_absorption_order() {
}
}
-/// Two posts joined into one body while apart, trimmed by a cut that splits neither, then joined
-/// to a case they stand on. The cut split the joined posts into "Posts" and "Posts (1)" without
-/// saying so (`created_bodies` was empty), and the join then took only "Posts", leaving the other
-/// post behind as a body of its own. A cut that does cut a body in two still makes two bodies,
-/// and its reply names the new one.
+/// Two posts joined into one body while apart (`touching: one_body`), trimmed by a cut that
+/// splits neither, then joined to a case they stand on. The cut split the joined posts into
+/// "Posts" and "Posts (1)" without saying so (`created_bodies` was empty), and the join then took
+/// only "Posts", leaving the other post behind as a body of its own. A cut that does cut a body in
+/// two still makes two bodies, and its reply names the new one.
#[test]
fn cut_keeps_posts_joined_while_apart_in_one_body() {
let mut s = Session::default();
@@ -1022,7 +1023,7 @@ fn cut_keeps_posts_joined_while_apart_in_one_body() {
s.execute("solid.box", &json!({"length": 60, "width": 40, "height": 10, "center": [0, 0, 5], "operation": "new", "body_name": "Case"})).unwrap();
s.execute("solid.box", &post("Posts", -20.0)).unwrap();
s.execute("solid.box", &post("Post2", 20.0)).unwrap();
- s.execute("solid.combine", &json!({"target": "Posts", "tools": ["Post2"], "operation": "join"})).unwrap();
+ s.execute("solid.combine", &json!({"target": "Posts", "tools": ["Post2"], "operation": "join", "touching": "one_body"})).unwrap();
s.execute("solid.box", &json!({"length": 80, "width": 20, "height": 10, "center": [0, 0, 40], "operation": "new", "body_name": "Trim"})).unwrap();
let cut = s.execute("solid.combine", &json!({"target": "Posts", "tools": ["Trim"], "operation": "cut"})).unwrap();
// Each post loses its top 5 mm: 10 x 10 x 25 left of each.
@@ -1063,7 +1064,7 @@ fn combine_of_a_piece_a_cut_used_to_split_off_takes_the_body_it_is_part_of() {
.unwrap();
s.execute("solid.box", &post("Posts", -20.0)).unwrap();
s.execute("solid.box", &post("Post2", 20.0)).unwrap();
- s.execute("solid.combine", &json!({"target": "Posts", "tools": ["Post2"], "operation": "join"})).unwrap();
+ s.execute("solid.combine", &json!({"target": "Posts", "tools": ["Post2"], "operation": "join", "touching": "one_body"})).unwrap();
s.execute("solid.box", &json!({"length": 80, "width": 20, "height": 10, "center": [0, 0, 40], "operation": "new", "body_name": "Trim"}))
.unwrap();
s.execute("solid.combine", &json!({"target": "Posts", "tools": ["Trim"], "operation": "cut"})).unwrap();
diff --git a/crates/engine/src/cmd/config_certificate_tests.rs b/crates/engine/src/cmd/config_certificate_tests.rs
index ffd0fd20e9..64fa932d5f 100644
--- a/crates/engine/src/cmd/config_certificate_tests.rs
+++ b/crates/engine/src/cmd/config_certificate_tests.rs
@@ -112,8 +112,9 @@ fn legacy_v9_imported_emboss_anchor_and_ordinary_face_paint_replay_without_renam
legacy["format"] = json!("solidcraft/9");
let reopened = Session::new(solidcraft_doc::Document::from_json(&legacy.to_string()).unwrap());
// Saved before format 14, it keeps naming the pieces it makes in the kernel's shell order,
- // and numbering the pieces of its faces as that build did (#3902).
- let anchored = solidcraft_doc::Feature { shell_piece_order: true, kernel_piece_order: true, ..anchored };
+ // and numbering the pieces of its faces as that build did (#3902); saved before joins kept
+ // solids that only touch apart, it keeps them one body.
+ let anchored = solidcraft_doc::Feature { shell_piece_order: true, kernel_piece_order: true, touching: solidcraft_doc::Touching::OneBody, ..anchored };
assert_eq!(reopened.doc.feature(anchored.id).unwrap(), &anchored);
// Names saved before format 14 keep naming the face they named, marked so they are found as
// the build that saved them found them.
diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs
index 15616d4675..b50fe881ce 100644
--- a/crates/engine/src/cmd/features.rs
+++ b/crates/engine/src/cmd/features.rs
@@ -3,7 +3,7 @@
use serde_json::{Value, json};
use solidcraft_doc::{
AxisRef, Direction, Expr, Extent, FeatureKind, Operation, PointExpr, ProfileSel, RailFit, SweepOrientation, SweepRail, ThinSide, ThinWall,
- expr::Kind, point_expr,
+ Touching, expr::Kind, point_expr,
};
use solidcraft_doc::{BodyName, FeatureName, SketchId};
use solidcraft_doc::{Dir, FacePick, Position};
@@ -11,7 +11,7 @@ use solidcraft_geom::Vec3;
use super::{CommandSpec, not_in_sketch};
use crate::params::{bad, bool_, expr, expr_problem, req_expr, str_, string_list, vec2, vec3};
-use crate::schema::features::{BoxParams, ExtrudeParams, FeatureResult};
+use crate::schema::features::{BoxParams, ExtrudeParams, FeatureNotice, FeatureResult, NoticeAction};
use crate::schema::{TypedContract, output_schema_for};
use crate::{EngineError, Result, Session};
@@ -25,33 +25,33 @@ pub static COMMANDS: &[CommandSpec] = &[
.key("E")
.contract(&EXTRUDE_CONTRACT)
.output(output_schema_for::<FeatureResult>)
- .params("distance: expr (or through_all: true); taper?: angle expr (positive: outward, so the far end is larger along the extrusion direction; negative: inward, so the far end is smaller); corner?: preserve_curvature|tangent|round (how a taper closes a sharp corner its offset opens: each wall continues as itself, a line's plane or an arc's cone, until it meets its neighbour; each continues straight along its end tangent; or an arc about the corner. Without it, each profile preserves curvature where every curve is a line or an arc and takes tangent where another curve has a corner, and the feature's warning says so; a corner rule given is kept, and refused where the kernel cannot build it); sketch?: id|name (default: active or last sketch); profiles?: all | [index] | [{curves: [ids]}] (the profile whose outer loop is made of exactly these curves, or pieces of them; found again on every recompute, so it follows parameter changes; islands inside are its holes; an error when no profile or several match) | [{point:[x,y]}] (index and point picks are stored by their curves when that finds the same profile; a pick on a drawn profile that reference geometry, such as the projected outline of the face the sketch is on, cuts into regions takes the whole drawn profile); exact_regions?: bool (each index or point pick is exactly the region it names, as the dialogs send); default: every drawn profile, except that a loop inside another is its hole and a loop inside that hole is material again; face?: [x,y,z] (extrude a planar body face instead of a sketch profile); faces?: [[x,y,z],…] (coplanar faces of one body); face_body?: name (whose face, where faces of several bodies meet at the point); direction?: positive|negative|symmetric (distance is total thickness, split evenly around the start plane); convention?: total_distance|legacy_per_side (default total_distance; legacy preserves older symmetric extents); distance2?: expr (Two Sides: a second distance the other way from the first side, which may be through_all or to; with direction: negative the first side goes against the normal and distance2 along it); start_offset?: expr (along the sketch normal, also with direction: negative); to?: [x,y,z] (To Object: a face, vertex or point; to_offset?: expr past it); from?: [x,y,z] (From Object: start at that face or point); operation?: new|join|cut|intersect|auto (cut into a body, otherwise join existing solids; new in an empty component); targets?: [body] (Join from a face, or from a sketch on a body's face, defaults to that face's body; explicit targets or participants override); name?; body_name?; thin?: true (Thin: a wall along sketch curves instead of the profiles) with curves?: [curve ids] (open chains and closed loops, joined where they meet end to end; default: every drawn curve of the sketch), thickness: expr, side?: center|inside|outside|two_sides (a closed loop's inside is the area it encloses, an open chain's the side it bends toward, a straight line's the left of its first curve as drawn; default center), thickness2?: expr (two_sides: the thickness outside); corners are mitred, crossing walls are one"),
+ .params("distance: expr (or through_all: true); taper?: angle expr (positive: outward, so the far end is larger along the extrusion direction; negative: inward, so the far end is smaller); corner?: preserve_curvature|tangent|round (how a taper closes a sharp corner its offset opens: each wall continues as itself, a line's plane or an arc's cone, until it meets its neighbour; each continues straight along its end tangent; or an arc about the corner. Without it, each profile preserves curvature where every curve is a line or an arc and takes tangent where another curve has a corner, and the feature's warning says so; a corner rule given is kept, and refused where the kernel cannot build it); sketch?: id|name (default: active or last sketch); profiles?: all | [index] | [{curves: [ids]}] (the profile whose outer loop is made of exactly these curves, or pieces of them; found again on every recompute, so it follows parameter changes; islands inside are its holes; an error when no profile or several match) | [{point:[x,y]}] (index and point picks are stored by their curves when that finds the same profile; a pick on a drawn profile that reference geometry, such as the projected outline of the face the sketch is on, cuts into regions takes the whole drawn profile); exact_regions?: bool (each index or point pick is exactly the region it names, as the dialogs send); default: every drawn profile, except that a loop inside another is its hole and a loop inside that hole is material again; face?: [x,y,z] (extrude a planar body face instead of a sketch profile); faces?: [[x,y,z],…] (coplanar faces of one body); face_body?: name (whose face, where faces of several bodies meet at the point); direction?: positive|negative|symmetric (distance is total thickness, split evenly around the start plane); convention?: total_distance|legacy_per_side (default total_distance; legacy preserves older symmetric extents); distance2?: expr (Two Sides: a second distance the other way from the first side, which may be through_all or to; with direction: negative the first side goes against the normal and distance2 along it); start_offset?: expr (along the sketch normal, also with direction: negative); to?: [x,y,z] (To Object: a face, vertex or point; to_offset?: expr past it); from?: [x,y,z] (From Object: start at that face or point); operation?: new|join|cut|intersect|auto (cut into a body, otherwise join existing solids; new in an empty component); touching?: separate|one_body (a join's solids that only touch, along an edge or at a point, or don't touch: separate bodies, the default, or one body); targets?: [body] (Join from a face, or from a sketch on a body's face, defaults to that face's body; explicit targets or participants override); name?; body_name?; thin?: true (Thin: a wall along sketch curves instead of the profiles) with curves?: [curve ids] (open chains and closed loops, joined where they meet end to end; default: every drawn curve of the sketch), thickness: expr, side?: center|inside|outside|two_sides (a closed loop's inside is the area it encloses, an open chain's the side it bends toward, a straight line's the left of its first curve as drawn; default center), thickness2?: expr (two_sides: the thickness outside); corners are mitred, crossing walls are one"),
CommandSpec::new("solid.revolve", "Revolve", revolve)
.at("SOLID", "CREATE")
.icon("revolve")
- .params("axis: sketch line id | x | y (sketch axes) | X|Y|Z (world) | construction axis name (followed when edited) | {origin, dir} | {edge|face: [x,y,z]} (a straight or circular edge, or a cylinder, cone or torus face: about its axis, followed as the model changes); angle?: expr (default 360 deg); angle2?: expr (Two Sides: the other side's angle); direction?: symmetric (angle split either side, independent of axis direction); convention?: sketch_normal|legacy_axis_start (default sketch_normal; legacy retains older angular starts); to?: [x,y,z] (To Object: turn until that face, vertex or point); sketch?, profiles? | face: [x,y,z] (a planar body face as the profile) and face_body?: name (whose face, where faces of several bodies meet), operation?, targets?, name?, body_name?"),
+ .params("axis: sketch line id | x | y (sketch axes) | X|Y|Z (world) | construction axis name (followed when edited) | {origin, dir} | {edge|face: [x,y,z]} (a straight or circular edge, or a cylinder, cone or torus face: about its axis, followed as the model changes); angle?: expr (default 360 deg); angle2?: expr (Two Sides: the other side's angle); direction?: symmetric (angle split either side, independent of axis direction); convention?: sketch_normal|legacy_axis_start (default sketch_normal; legacy retains older angular starts); to?: [x,y,z] (To Object: turn until that face, vertex or point); sketch?, profiles? | face: [x,y,z] (a planar body face as the profile) and face_body?: name (whose face, where faces of several bodies meet), operation?, touching?, targets?, name?, body_name?"),
CommandSpec::new("solid.sweep", "Sweep", sweep)
.at("SOLID", "CREATE")
.icon("sweep")
- .params("sketch: profile sketch; profiles?; path_sketch: sketch; path: [curve ids in order]; orientation?: perpendicular (default: square to the path, turning with it) | parallel (as drawn: the profile moves without turning; the path must keep crossing its plane) | [x,y,z] (square to the path, its turn about the path fixed by this direction); twist?: angle expr (the profile turns this much about the path over its length; within 4 turns); scale?: expr (the profile's scale at the end, linear along the path; 0.01…100); rails?: [{sketch?: sketch (default path_sketch), curves: [curve ids in order]}] (guide rails, one or two, each meeting every plane square to the path once along it, from the end nearest the path's start: one rail turns the profile so its point where the rail starts stays on the rail and scales it with the rail's distance from the path; two rails carry it between them, its points where they start staying on both; rails take the default orientation, no twist and no scale, and a path without sharp corners); rail_fit?: scale (default: the profile grows and shrinks evenly) | stretch (only across to the rail, between the rails); operation?, targets?, name?, body_name?"),
- CommandSpec::new("solid.loft", "Loft", loft).at("SOLID", "CREATE").icon("loft").params("sections: [{sketch, profiles?} | {sketch, point: id} (an apex)] (2…50, in order; matching hole counts, no holes at an apex); rails?: [{sketch, curves: [ids in order]}] (one or two guide rails from the first section to the last, through every section's outline: the loft follows them between the sections; not with sections that have holes); rail_fit?: scale|stretch (default scale: with one rail the sections grow evenly with the rail's distance from their middle, with two with the distance between the rails; stretch: only that way); operation?, targets? (Join excludes hidden bodies from automatic targets; explicit targets or participants may include them), name?, body_name?"),
+ .params("sketch: profile sketch; profiles?; path_sketch: sketch; path: [curve ids in order]; orientation?: perpendicular (default: square to the path, turning with it) | parallel (as drawn: the profile moves without turning; the path must keep crossing its plane) | [x,y,z] (square to the path, its turn about the path fixed by this direction); twist?: angle expr (the profile turns this much about the path over its length; within 4 turns); scale?: expr (the profile's scale at the end, linear along the path; 0.01…100); rails?: [{sketch?: sketch (default path_sketch), curves: [curve ids in order]}] (guide rails, one or two, each meeting every plane square to the path once along it, from the end nearest the path's start: one rail turns the profile so its point where the rail starts stays on the rail and scales it with the rail's distance from the path; two rails carry it between them, its points where they start staying on both; rails take the default orientation, no twist and no scale, and a path without sharp corners); rail_fit?: scale (default: the profile grows and shrinks evenly) | stretch (only across to the rail, between the rails); operation?, touching?, targets?, name?, body_name?"),
+ CommandSpec::new("solid.loft", "Loft", loft).at("SOLID", "CREATE").icon("loft").params("sections: [{sketch, profiles?} | {sketch, point: id} (an apex)] (2…50, in order; matching hole counts, no holes at an apex); rails?: [{sketch, curves: [ids in order]}] (one or two guide rails from the first section to the last, through every section's outline: the loft follows them between the sections; not with sections that have holes); rail_fit?: scale|stretch (default scale: with one rail the sections grow evenly with the rail's distance from their middle, with two with the distance between the rails; stretch: only that way); operation?, touching?, targets? (Join excludes hidden bodies from automatic targets; explicit targets or participants may include them), name?, body_name?"),
CommandSpec::new("solid.box", "Box", crate::checked!("solid.box", prim_box))
.at("SOLID", "CREATE")
.icon("box")
.contract(&BOX_CONTRACT)
.output(output_schema_for::<FeatureResult>)
- .params("length, width, height: expr; corner?: [x,y,z] | center?: [x,y,z] (numbers in mm or length expressions; default: the origin); operation?, targets?: [body], name?, body_name?"),
- CommandSpec::new("solid.cylinder", "Cylinder", prim_cylinder).at("SOLID", "CREATE").icon("cylinder").params("radius | diameter, height: expr; base?: [x,y,z] (centre of the bottom: numbers in mm or length expressions; default: the origin); axis?: X|Y|Z|[x,y,z] (default Z); operation?, targets?: [body], name?, body_name?"),
- CommandSpec::new("solid.sphere", "Sphere", prim_sphere).at("SOLID", "CREATE").icon("sphere").params("radius | diameter: expr; center?: [x,y,z] (numbers in mm or length expressions; default: the origin); operation?, targets?: [body], name?, body_name?"),
- CommandSpec::new("solid.torus", "Torus", prim_torus).at("SOLID", "CREATE").icon("torus").params("major, minor: expr (radii); center?: [x,y,z] (numbers in mm or length expressions; default: the origin); operation?, targets?: [body], name?, body_name?"),
- CommandSpec::new("solid.cone", "Cone", prim_cone).at("SOLID", "CREATE").icon("cone").params("radius | diameter, height: expr (the base circle, and the top's distance along the axis; a negative height goes the other way); top_radius? | top_diameter?: expr (the top circle; default 0: a full cone ending in an apex); base?: [x,y,z] (centre of the base circle: numbers in mm or length expressions; default: the origin); axis?: X|Y|Z|[x,y,z] (default Z); operation?, targets?: [body], name?, body_name?"),
+ .params("length, width, height: expr; corner?: [x,y,z] | center?: [x,y,z] (numbers in mm or length expressions; default: the origin); operation?, touching?, targets?: [body], name?, body_name?"),
+ CommandSpec::new("solid.cylinder", "Cylinder", prim_cylinder).at("SOLID", "CREATE").icon("cylinder").params("radius | diameter, height: expr; base?: [x,y,z] (centre of the bottom: numbers in mm or length expressions; default: the origin); axis?: X|Y|Z|[x,y,z] (default Z); operation?, touching?, targets?: [body], name?, body_name?"),
+ CommandSpec::new("solid.sphere", "Sphere", prim_sphere).at("SOLID", "CREATE").icon("sphere").params("radius | diameter: expr; center?: [x,y,z] (numbers in mm or length expressions; default: the origin); operation?, touching?, targets?: [body], name?, body_name?"),
+ CommandSpec::new("solid.torus", "Torus", prim_torus).at("SOLID", "CREATE").icon("torus").params("major, minor: expr (radii); center?: [x,y,z] (numbers in mm or length expressions; default: the origin); operation?, touching?, targets?: [body], name?, body_name?"),
+ CommandSpec::new("solid.cone", "Cone", prim_cone).at("SOLID", "CREATE").icon("cone").params("radius | diameter, height: expr (the base circle, and the top's distance along the axis; a negative height goes the other way); top_radius? | top_diameter?: expr (the top circle; default 0: a full cone ending in an apex); base?: [x,y,z] (centre of the base circle: numbers in mm or length expressions; default: the origin); axis?: X|Y|Z|[x,y,z] (default Z); operation?, touching?, targets?: [body], name?, body_name?"),
CommandSpec::new("solid.fillet", "Fillet", fillet)
.at("SOLID", "MODIFY")
.icon("fillet")
.key("F")
.params("edges: [[x,y,z] point on edge | {body, index}] ; radius: expr; tangent_chain?: bool (default true: each picked edge's tangent chain is rounded with it; false: exactly the picked edges); body?; type?: constant|curvature (alias g2: curvature-continuous quintic between planar faces along straight edges, one planar end face at each end (including sloped ends); radius sets the equivalent circular setback, not constant curvature; exact fit only)|chord (radius is the width across)|variable (radius at the end nearest start, radius2 at the other; one end may be 0, where the round closes to the corner)|spline (the radius along the edge is a clamped B-spline from the end nearest start: radius is its first control radius, radii the rest, knots its knot vector from 0 to 1; one end may be 0); radius2?; start?: [x,y,z]; radii?: [expr, …]; knots?: [number, …]; mid?: [[position 0…1 from start, radius expr], …] (variable radii between the ends); smooth?: bool (smooth instead of straight between the radii); corner?: rolling|g2 (rolling, the default: the corners where three blended edges meet are pieces of the rolling ball's sphere, tangent to each blend; g2: a patch repeating each blend's surface up to the second order, constant-radius exact fillets only, refused where it cannot be built); fit?: exact|reduce|taper (exact, the default: a radius too large for the geometry around the edges is refused; reduce: where it doesn't fit it is reduced to the largest that does, one radius for edges sharing a face; the smallest used is returned as `radius_applied`, each edge's as `radii_applied: [{edge: [x,y,z], radius}]`, and noted in the feature's warning; taper: along each straight edge between planar faces where it doesn't fit, the radius follows the room there as a smooth spline, down to 0 where a face closes to a point, noted in the feature's warning)"),
CommandSpec::new("solid.chamfer", "Chamfer", chamfer).at("SOLID", "MODIFY").icon("chamfer").params("edges: [[x,y,z] | {body, index}] ; distance: expr; tangent_chain?: bool (default true: each picked edge's tangent chain is cut with it; false: exactly the picked edges); distance2?: expr (along the second face) | angle?: expr (from the first face); flip?: bool (which face is first: by default the one facing up most); body?"),
- CommandSpec::new("solid.combine", "Combine", combine).at("SOLID", "MODIFY").icon("combine").params("target: body; tools: [body]; operation?: join|cut|intersect; keep_tools?: bool; new_component?: bool (the result goes into a new component; component_name?)"),
+ CommandSpec::new("solid.combine", "Combine", combine).at("SOLID", "MODIFY").icon("combine").params("target: body; tools: [body]; operation?: join|cut|intersect; touching?: separate|one_body (a join's solids that only touch, along an edge or at a point, or don't touch: separate bodies, the default, or one body); keep_tools?: bool; new_component?: bool (the result goes into a new component; component_name?)"),
CommandSpec::new("solid.pattern.rectangular", "Rectangular Pattern", pattern_rect)
.at("SOLID", "CREATE")
.icon("pattern_rect")
@@ -611,6 +611,11 @@ pub(super) fn add_feature(s: &mut Session, p: &Value, kind: FeatureKind) -> Resu
/// `add_feature`; `world` is false when `kind` is already in the active component's frame.
fn add_feature_in(s: &mut Session, p: &Value, kind: FeatureKind, world: bool) -> Result<Value> {
let name = str_(p, "name");
+ // What a join makes of solids that only touch or don't touch: separate bodies unless asked.
+ let touching = match p.get("touching") {
+ None | Some(Value::Null) => Touching::Separate,
+ Some(v) => v.as_str().and_then(Touching::parse).ok_or_else(|| EngineError::Other("`touching` must be separate or one_body".into()))?,
+ };
// The bodies before the feature, to say which ones it changed or removed.
let before = s.model.state();
// Commands speak world coordinates; the feature is authored in the active component.
@@ -721,6 +726,7 @@ fn add_feature_in(s: &mut Session, p: &Value, kind: FeatureKind, world: bool) ->
let id = s.doc_mut().add_feature(kind, name)?;
if let Some(f) = s.doc_mut().feature_mut(id) {
f.participants = participants;
+ f.touching = touching;
f.edge_refs = refs;
f.edge_names = names;
f.face_names = face_names;
@@ -774,6 +780,16 @@ fn add_feature_in(s: &mut Session, p: &Value, kind: FeatureKind, world: bool) ->
// A warning (a reference found again elsewhere, a reduced radius) is part of
// the reply: a script or an agent sees it without asking the timeline (#616).
let warning = r.as_ref().and_then(|r| r.warning.clone());
+ // A join that kept solids apart says so, with the edit that makes them one body instead.
+ let notice = r.as_ref().and_then(|r| r.state.kept_separate(id)).map(|kept| FeatureNotice {
+ message: kept.notice().to_string(),
+ contact: kept.id().to_string(),
+ action: NoticeAction {
+ label: "Make one body".into(),
+ command: "timeline.edit".into(),
+ params: json!({"feature": id, "set": {"touching": "one_body"}}),
+ },
+ });
let owned = |names: Vec<&str>| names.into_iter().map(str::to_string).collect();
let reply = FeatureResult {
feature: id,
@@ -783,6 +799,7 @@ fn add_feature_in(s: &mut Session, p: &Value, kind: FeatureKind, world: bool) ->
changed_bodies: owned(changed),
removed_bodies: owned(removed),
warning,
+ notice,
ms: r.map(|r| r.ms),
param_warnings: Vec::new(),
};
diff --git a/crates/engine/src/cmd/interference_tests.rs b/crates/engine/src/cmd/interference_tests.rs
index 09feb1c933..3a29a0fc5a 100644
--- a/crates/engine/src/cmd/interference_tests.rs
+++ b/crates/engine/src/cmd/interference_tests.rs
@@ -69,7 +69,11 @@ fn a_piece_of_a_body_inside_another_is_still_found() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 20, "corner": [0, 0, 0], "body_name": "Block"}));
run(&mut s, "solid.box", json!({"length": 2, "width": 2, "height": 2, "corner": [5, 5, 5], "operation": "new", "body_name": "Pieces"}));
- run(&mut s, "solid.box", json!({"length": 2, "width": 2, "height": 2, "corner": [30, 5, 5], "operation": "join", "targets": ["Pieces"]}));
+ run(
+ &mut s,
+ "solid.box",
+ json!({"length": 2, "width": 2, "height": 2, "corner": [30, 5, 5], "operation": "join", "targets": ["Pieces"], "touching": "one_body"}),
+ );
let st = s.world_state().unwrap();
let pieces = st.bodies.iter().find(|b| b.name == "Pieces").map(|b| b.body.shell_count());
assert_eq!(pieces, Some(2), "the two cubes are one body in two pieces");
diff --git a/crates/engine/src/cmd/patterns_tests.rs b/crates/engine/src/cmd/patterns_tests.rs
index 1740a09f71..08e096e515 100644
--- a/crates/engine/src/cmd/patterns_tests.rs
+++ b/crates/engine/src/cmd/patterns_tests.rs
@@ -705,7 +705,9 @@ fn copies_of_a_primitive_cut_only_its_targets() {
}
/// #3378: a pattern or mirror of a join whose targets the join merged into one body copies onto
-/// that body, as before #2755, instead of looking for the target the join used up.
+/// that body, as before #2755, instead of looking for the target the join used up. The spoke
+/// starts 1 mm inside the hub, so it shares volume with both (one tangent to the hub would only
+/// touch it along a line, and the join would keep the hub a body of its own).
#[test]
fn copies_of_a_join_that_merged_its_targets_join_the_merged_body() {
for (copy, n) in [
@@ -717,7 +719,7 @@ fn copies_of_a_join_that_merged_its_targets_join_the_merged_body() {
run(&mut s, "solid.cylinder", json!({"radius": 63, "height": 3, "base": [0, 0, 0], "axis": "Y", "operation": "cut", "targets": ["rim"]}));
run(&mut s, "solid.cylinder", json!({"radius": 12, "height": 3, "base": [0, 0, 0], "axis": "Y", "body_name": "hub"}));
let v0 = volume(&mut s);
- let spoke = json!({"length": 52, "width": 3, "height": 2.5, "corner": [12, 0, -1.25], "operation": "join", "targets": ["rim", "hub"], "name": "spoke"});
+ let spoke = json!({"length": 53, "width": 3, "height": 2.5, "corner": [11, 0, -1.25], "operation": "join", "targets": ["rim", "hub"], "name": "spoke"});
run(&mut s, "solid.box", spoke);
let v1 = volume(&mut s);
let (id, p) = (copy[0].as_str().unwrap_or_default(), copy[1].clone());
diff --git a/crates/engine/src/exact_tool_tests.rs b/crates/engine/src/exact_tool_tests.rs
index dc29b3c4c1..ee34231ccc 100644
--- a/crates/engine/src/exact_tool_tests.rs
+++ b/crates/engine/src/exact_tool_tests.rs
@@ -103,8 +103,9 @@ fn a_cut_leaves_what_stands_beside_it() {
}
/// A join adds only its sketch: a block against a wall narrower than the block adds nothing
-/// beside the wall, a block 0.1 mm from a wall leaves the gap, and a pad flush with a block's
-/// side does not reach a neighbour 0.8 mm from that side.
+/// beside the wall, a block 0.1 mm from a wall leaves the gap (and, meeting nothing, stays a body
+/// of its own), and a pad flush with a block's side does not reach a neighbour 0.8 mm from that
+/// side.
#[test]
fn a_join_adds_only_its_sketch() {
let wall = || {
@@ -119,8 +120,11 @@ fn a_join_adds_only_its_sketch() {
let mut s = wall();
rectangle(&mut s, at_height(0.0), [2.1, 10.0], [20.0, 50.0], 30.0, "join", Value::Null);
- assert!(same(volume(&s, "Wall"), 2.0 * 40.0 * 30.0 + 17.9 * 40.0 * 30.0), "{}", volume(&s, "Wall"));
- assert!(!has(&s, "Wall", [2.05, 30.0, 15.0]), "the 0.1 mm gap is filled");
+ let names = bodies(&s);
+ assert_eq!(names.len(), 2, "{names:?}");
+ let total: f64 = names.iter().map(|b| volume(&s, b)).sum();
+ assert!(same(total, 2.0 * 40.0 * 30.0 + 17.9 * 40.0 * 30.0), "{total}");
+ assert!(names.iter().all(|b| !has(&s, b, [2.05, 30.0, 15.0])), "the 0.1 mm gap is filled");
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 300, "width": 200, "height": 100, "body_name": "A"}));
diff --git a/crates/engine/src/schema/features.rs b/crates/engine/src/schema/features.rs
index 81286aa334..25fe04a38e 100644
--- a/crates/engine/src/schema/features.rs
+++ b/crates/engine/src/schema/features.rs
@@ -10,7 +10,7 @@ use serde::{Deserialize, Serialize};
use super::types::{
AngleExpr, ConventionParam, DirectionParam, ExtentKeyword, ExtrudeOperation, FacesParam, FromPoint, IdOrName, LengthExpr, OperationParam, Point3,
- PointExpr3, ProfilesParam, StringList, ThinSideParam, ToPoint, present,
+ PointExpr3, ProfilesParam, StringList, ThinSideParam, ToPoint, TouchingParam, present,
};
/// Add a box primitive.
@@ -38,6 +38,9 @@ pub struct BoxParams {
/// The bodies a join, cut or intersect works on. Default: the bodies the box meets.
#[serde(default)]
pub targets: Option<StringList>,
+ /// What a join makes of solids that only touch or don't touch. Default: separate.
+ #[serde(default)]
+ pub touching: Option<TouchingParam>,
/// The bodies taking part (the same as `targets` for a primitive).
#[serde(default)]
pub participants: Option<StringList>,
@@ -135,6 +138,9 @@ pub struct ExtrudeParams {
/// that body.
#[serde(default)]
pub targets: Option<StringList>,
+ /// What a join makes of solids that only touch or don't touch. Default: separate.
+ #[serde(default)]
+ pub touching: Option<TouchingParam>,
/// The bodies taking part; overrides the default scope.
#[serde(default)]
pub participants: Option<StringList>,
@@ -166,6 +172,28 @@ pub struct ExtrudeParams {
pub thickness2: Option<LengthExpr>,
}
+/// Something a feature's result tells the user without stopping them, with an action to take.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct FeatureNotice {
+ /// The text to show.
+ pub message: String,
+ /// How the solids kept apart met: `along_edge`, `at_point` or `apart`.
+ pub contact: String,
+ /// The command that changes the feature as the notice offers.
+ pub action: NoticeAction,
+}
+
+/// A command a notice offers to run.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct NoticeAction {
+ /// The action's label.
+ pub label: String,
+ /// The command's id.
+ pub command: String,
+ /// Its parameters.
+ pub params: Value,
+}
+
/// What a feature command returns.
#[derive(Debug, Serialize, JsonSchema)]
pub struct FeatureResult {
@@ -184,6 +212,11 @@ pub struct FeatureResult {
/// A warning from the evaluation (a Boolean that needed a retry, a reference found again
/// elsewhere), or `null`.
pub warning: Option<String>,
+ /// A join that kept solids as separate bodies because they only touch along an edge or at a
+ /// point, or don't touch (its `touching: separate`): what to tell the user, and the edit that
+ /// makes them one body instead. Left out otherwise.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub notice: Option<FeatureNotice>,
/// How long the feature took to evaluate, in milliseconds.
pub ms: Option<f64>,
/// In the warn parameter-check mode: what the call's parameters got wrong.
diff --git a/crates/engine/src/schema/features_tests.rs b/crates/engine/src/schema/features_tests.rs
index 4ed208cded..394e7ca445 100644
--- a/crates/engine/src/schema/features_tests.rs
+++ b/crates/engine/src/schema/features_tests.rs
@@ -9,7 +9,7 @@ use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
fn schemas_and_the_key_check_agree() {
assert_keys(
input_schema_for::<BoxParams>(),
- &["body_name", "body_names", "center", "corner", "height", "length", "name", "operation", "participants", "targets", "width"],
+ &["body_name", "body_names", "center", "corner", "height", "length", "name", "operation", "participants", "targets", "touching", "width"],
);
assert_keys(
input_schema_for::<ExtrudeParams>(),
@@ -43,6 +43,7 @@ fn schemas_and_the_key_check_agree() {
"through_all",
"to",
"to_offset",
+ "touching",
],
);
}
@@ -90,6 +91,7 @@ fn feature_result_serializes_like_the_old_reply() {
warning: warning.clone(),
ms,
param_warnings: vec![],
+ notice: None,
};
assert_eq!(serde_json::to_value(&new).ok(), Some(old));
}
diff --git a/crates/engine/src/schema/types.rs b/crates/engine/src/schema/types.rs
index 1aa122ac00..5b1a47a9c8 100644
--- a/crates/engine/src/schema/types.rs
+++ b/crates/engine/src/schema/types.rs
@@ -8,7 +8,7 @@ use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
use serde::de::Error as _;
use serde::{Deserialize, Deserializer};
use serde_json::{Value, json};
-use solidcraft_doc::{Expr, Operation, ThinSide};
+use solidcraft_doc::{Expr, Operation, ThinSide, Touching};
use solidcraft_geom::{Vec2, Vec3};
use super::check::whole;
@@ -379,6 +379,34 @@ impl JsonSchema for OperationParam {
}
}
+/// What a join makes of solids that only touch or don't touch, as `Touching::parse` reads it.
+#[derive(Clone, Debug, PartialEq)]
+pub struct TouchingParam(pub Touching);
+
+/// The feature commands' message for a `touching` they don't know.
+const TOUCHING_MESSAGE: &str = "`touching` must be separate or one_body";
+
+impl<'de> Deserialize<'de> for TouchingParam {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ match Value::deserialize(d)? {
+ Value::String(s) => Touching::parse(&s).map(TouchingParam).ok_or_else(|| D::Error::custom(whole(TOUCHING_MESSAGE))),
+ _ => Err(D::Error::custom(whole(TOUCHING_MESSAGE))),
+ }
+ }
+}
+
+impl JsonSchema for TouchingParam {
+ fn schema_name() -> Cow<'static, str> {
+ "Touching".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ enum_schema(
+ &["separate", "one_body"],
+ "What a join makes of solids that only touch, along an edge or at a point, or don't touch: separate bodies (separate, the default) or one body of several pieces (one_body).",
+ )
+ }
+}
+
/// Extrude's operation: the above or `auto` (matched with `eq_ignore_ascii_case`, as the
/// handler does).
#[derive(Clone, Debug, PartialEq)]
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index e3eb5a41e3..5ebb8decf9 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -203,12 +203,22 @@ fn join_merges_into_the_body_it_meets() {
assert!(rel(volume(&mut s), 2064.0) < 1e-6);
}
-/// A join that meets no body still joins the first body, as a separate lump.
+/// A join that meets no body keeps what it made as a body of its own beside the first body
+/// (`touching: separate`, the default), and says so with the edit that makes them one; with
+/// `touching: one_body` it joins the first body as a separate lump.
#[test]
fn join_meeting_nothing_keeps_the_first_body() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10}));
- run(&mut s, "solid.box", json!({"length": 4, "width": 4, "height": 4, "corner": [40, 0, 0], "operation": "join"}));
+ let r = run(&mut s, "solid.box", json!({"length": 4, "width": 4, "height": 4, "corner": [40, 0, 0], "operation": "join"}));
+ assert_eq!(r["notice"]["contact"], "apart", "{r}");
+ assert_eq!(r["notice"]["action"]["params"]["set"], json!({"touching": "one_body"}), "{r}");
+ assert_eq!(s.model.state().bodies.len(), 2);
+ assert!(rel(volume(&mut s), 1064.0) < 1e-6);
+ run(&mut s, "edit.undo", json!({}));
+ let r =
+ run(&mut s, "solid.box", json!({"length": 4, "width": 4, "height": 4, "corner": [40, 0, 0], "operation": "join", "touching": "one_body"}));
+ assert!(r.get("notice").is_none(), "{r}");
let st = s.model.state();
assert_eq!(st.bodies.len(), 1);
assert_eq!(st.bodies[0].body.lumps().unwrap().len(), 2);
diff --git a/crates/engine/src/tests/robustness.rs b/crates/engine/src/tests/robustness.rs
index df49cb5a21..355edd6b73 100644
--- a/crates/engine/src/tests/robustness.rs
+++ b/crates/engine/src/tests/robustness.rs
@@ -141,7 +141,8 @@ fn fillet_that_would_open_the_surface_is_refused() {
}
}
-/// Shell of a body in two pieces (a cylinder joined clear of a ring): each piece is shelled.
+/// Shell of a body in two pieces (a cylinder joined clear of a ring, kept one body with
+/// `touching: one_body`): each piece is shelled.
#[test]
fn shell_of_a_body_in_two_pieces() {
script(json!([
@@ -149,7 +150,7 @@ fn shell_of_a_body_in_two_pieces() {
{"command": "sketch.rectangle.two_point", "params": {"p0": [2.5, 0], "p1": [22.5, 17.5]}},
{"command": "sketch.finish", "params": {}},
{"command": "solid.revolve", "params": {"angle": "360 deg", "axis": "Z"}},
- {"command": "solid.cylinder", "params": {"axis": [0.0, 1.0, 0.0], "base": [-22.5, 22.5, 0.0], "height": 30.0, "operation": "join", "radius": 10.0}},
+ {"command": "solid.cylinder", "params": {"axis": [0.0, 1.0, 0.0], "base": [-22.5, 22.5, 0.0], "height": 30.0, "operation": "join", "radius": 10.0, "touching": "one_body"}},
{"command": "solid.shell", "params": {"faces": [[-22.5, 22.5, 0.0]], "thickness": 2.0}}
]));
}
diff --git a/crates/kernel/src/blend.rs b/crates/kernel/src/blend.rs
index 245480a74b..28047c9094 100644
--- a/crates/kernel/src/blend.rs
+++ b/crates/kernel/src/blend.rs
@@ -310,20 +310,15 @@ pub fn fillet_each(body: &Body, edges: &[Vec3], radii: &[f64]) -> Result<Body> {
crate::blend_smlib::fillet_each(body, edges, radii).and_then(|b| closed(body, b))
}
-/// The points' edges (the nearest edge of the body to each) grouped where they share a face or
-/// a vertex, directly or through other points' edges: indices into `pts`. `None` when a point
+/// The points' edges (each the edge a blend's pick there takes) grouped where they share a face
+/// or a vertex, directly or through other points' edges: indices into `pts`. `None` when a point
/// has no edge near it.
fn interacting_groups(body: &Body, pts: &[Vec3]) -> Option<Vec<Vec<usize>>> {
let rec = Faces::of(body).ok()?;
- let size = body.size();
- let tol = (size * 2e-3).max(1e-3);
+ let (picked, _) = crate::blend_smlib::picked_edges(body, pts).ok()?;
// What each point's edge touches: its faces and its ends.
let mut groups: Vec<(BTreeSet<u32>, BTreeSet<u32>, Vec<usize>)> = Vec::new();
- for (i, p) in pts.iter().enumerate() {
- let (idx, dist) = body.nearest_edge(*p, tol).ok()??;
- if dist > size * 0.05 + 1e-3 {
- return None;
- }
+ for (i, idx) in picked.into_iter().enumerate() {
let mut faces = rec.faces_of(idx);
let mut ends: BTreeSet<u32> = rec.rec.edges.get(idx)?.vertices.into_iter().collect();
let mut members = vec![i];
@@ -390,9 +385,10 @@ pub fn chamfer_sides(body: &Body, edges: &[Vec3], d1: f64, side: ChamferSide, fl
/// The picked edges' tangent chains, for a blend that is to run along them: `picks` (each the
/// nearest edge of `body` to it), then a point on every other edge that continues one of them
-/// tangentially (within 0.5° at a shared vertex), until no more do. An edge only one face uses
-/// ends a chain, and so does a smooth edge (its two faces meet tangentially, within 0.5°): it has
-/// no corner to round. Picks that find no edge are refused.
+/// tangentially (within 0.5° at a shared vertex), until no more do. Each pick takes its edge as a
+/// blend does (a pick at a vertex where a seam meets a rim takes the rim). An edge only one face
+/// uses ends a chain, and so do a seam and a smooth edge (its two faces meet tangentially, within
+/// 0.5°): they have no corner to round. Picks that find no edge are refused.
pub fn tangent_chain(body: &Body, picks: &[Vec3]) -> Result<Vec<Vec3>> {
/// Edges meeting at an angle below this continue one another.
const TANGENT_DEGREES: f64 = 0.5;
@@ -400,13 +396,9 @@ pub fn tangent_chain(body: &Body, picks: &[Vec3]) -> Result<Vec<Vec3>> {
return Err(KernelError::Invalid("select 1…1000 edges by finite points".into()));
}
let rec = Faces::of(body)?;
- let size = body.size();
+ let (seeds, hidden) = crate::blend_smlib::picked_edges(body, picks)?;
let mut chain: Vec<usize> = Vec::new();
- for p in picks {
- let (e, dist) = body.nearest_edge(*p, (size * 2e-3).max(1e-3))?.ok_or_else(|| KernelError::Invalid("the body has no edges".into()))?;
- if dist > size * 0.05 + 1e-3 {
- return Err(KernelError::Invalid(format!("no edge near the pick at ({:.3}, {:.3}, {:.3})", p.x, p.y, p.z)));
- }
+ for e in seeds {
if !chain.contains(&e) {
chain.push(e);
}
@@ -439,7 +431,8 @@ pub fn tangent_chain(body: &Body, picks: &[Vec3]) -> Result<Vec<Vec3>> {
for v in edge.vertices {
let Some(d) = leaving(e, v) else { continue };
for (f, other) in rec.rec.edges.iter().enumerate() {
- if chain.contains(&f) || other.uses.len() < 2 || !other.vertices.contains(&v) || smooth(f) {
+ let passed_over = hidden.get(f).copied().unwrap_or(false);
+ if passed_over || chain.contains(&f) || other.uses.len() < 2 || !other.vertices.contains(&v) || smooth(f) {
continue;
}
if leaving(f, v).is_some_and(|g| d.dot(g) < -cos) {
@@ -480,6 +473,29 @@ mod tests {
crate::native::brep_record(b).unwrap().vertices.iter().any(|v| v3(v.point).dist(p) < tol)
}
+ /// The ladder's 08-chamfers/008: a boss on a block, rounded where it meets the block, picked
+ /// at the top of its seam. The pick takes the top rim, and the chain keeps to it: it never
+ /// runs down the seam into the round's own seam, which continues it tangentially.
+ #[test]
+ fn a_chain_picked_where_a_seam_meets_a_rim_keeps_to_the_rim() {
+ let block = crate::build::box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 20.0)).unwrap();
+ let boss = crate::build::cylinder(Vec3::new(15.0, 15.0, 20.0), Vec3::Z, 8.0, 10.0).unwrap();
+ let joined = crate::boolean(&block, &boss, crate::BoolOp::Union).unwrap().unwrap();
+ let rec = joined.record();
+ // The seam: the edge both of whose uses lie on the boss's side.
+ let seam = rec.edges.iter().find(|e| e.uses.len() == 2 && e.uses[0].face == e.uses[1].face).unwrap();
+ let ends = seam.vertices.map(|v| v3(rec.vertices[v as usize].point));
+ let (foot, top) = if ends[0].z < ends[1].z { (ends[0], ends[1]) } else { (ends[1], ends[0]) };
+ let rounded = fillet(&joined, &[foot], 1.0).unwrap();
+ let chain = tangent_chain(&rounded, &[top]).unwrap();
+ assert_eq!(chain, vec![top], "the chain left the top rim");
+ assert!(chamfer(&rounded, &chain, 1.0).is_ok());
+ // Even from a pick on the seam itself, the chain takes no seam: the round's continues
+ // the boss's tangentially but has no corner to blend.
+ let side = (top + Vec3::new(top.x, top.y, 21.0)) * 0.5;
+ assert_eq!(tangent_chain(&rounded, &[side]).unwrap(), vec![side], "the chain ran into the round's seam");
+ }
+
#[test]
fn g2_fillet_has_the_quintics_area() {
let body = crate::build::box_solid(Vec3::ZERO, Vec3::new(20.0, 20.0, 20.0)).unwrap();
diff --git a/crates/kernel/src/blend_smlib.rs b/crates/kernel/src/blend_smlib.rs
index 86c060948c..aac1c49784 100644
--- a/crates/kernel/src/blend_smlib.rs
+++ b/crates/kernel/src/blend_smlib.rs
@@ -64,6 +64,14 @@ pub(crate) fn fillet_variable(body: &Body, edge_at: Vec3, start: Vec3, spline: &
imp::variable(body, edge_at, start, spline)
}
+/// The edges `picks` select, in the body's edge order, as a blend resolves them, and per edge
+/// whether a pick passes it over (a seam or a smooth join: never a blend's edge), for a caller
+/// that selects edges to blend ([`crate::tangent_chain`]).
+pub(crate) fn picked_edges(body: &Body, picks: &[Vec3]) -> Result<(Vec<usize>, Vec<bool>)> {
+ let picked = imp::resolve(body, picks)?;
+ Ok((picked.edges, picked.hidden))
+}
+
#[derive(Clone, Copy)]
enum Kind {
Round,
@@ -105,16 +113,18 @@ mod imp {
let mesh = body.mesh(&crate::MeshTolerance::chord((body.size() * 2e-3).max(1e-3)))?;
let seams = crate::topo::seam_flags(body, &mesh);
let (smooth, _) = crate::smooth_edges::flags(body, &mesh);
+ let hidden: Vec<bool> =
+ (0..mesh.edges.len()).map(|i| seams.get(i).copied().unwrap_or(false) || smooth.get(i).copied().unwrap_or(false)).collect();
let reach = pick_tolerance(body);
let tie = (body.size() * 1e-6).max(1e-6);
- let mut out = Picked { edges: Vec::with_capacity(picks.len()), points: Vec::with_capacity(picks.len()) };
+ let mut out = Picked { edges: Vec::with_capacity(picks.len()), points: Vec::with_capacity(picks.len()), hidden: Vec::new() };
for p in picks {
// The nearest edge, and the nearest that is no seam.
let (mut any, mut edge): (Option<(f64, usize)>, Option<(f64, usize)>) = (None, None);
for (i, line) in mesh.edges.iter().enumerate() {
let d =
line.windows(2).filter_map(|w| if let [a, b] = w { Some(p.dist_to_segment(*a, *b)) } else { None }).fold(f64::INFINITY, f64::min);
- let seam = seams.get(i).copied().unwrap_or(false) || smooth.get(i).copied().unwrap_or(false);
+ let seam = hidden.get(i).copied().unwrap_or(false);
for (slot, take) in [(&mut any, true), (&mut edge, !seam)] {
if take && slot.is_none_or(|(bd, _)| d < bd) {
*slot = Some((d, i));
@@ -132,6 +142,7 @@ mod imp {
out.edges.push(i);
out.points.push([mid.x, mid.y, mid.z]);
}
+ out.hidden = hidden;
Ok(out)
}
@@ -140,6 +151,8 @@ mod imp {
pub(super) edges: Vec<usize>,
/// A point halfway along each.
pub(super) points: Vec<[f64; 3]>,
+ /// Per edge of the body: does a pick pass it over (a seam or a smooth join)?
+ pub(super) hidden: Vec<bool>,
}
fn sizes_ok(what: &str, sizes: &[f64]) -> Result<()> {
@@ -350,6 +363,36 @@ mod tests {
}
}
+ #[test]
+ fn a_pick_where_a_bosss_seam_meets_its_base_takes_the_base_circle() {
+ // A boss joined onto a block, as the ladder's running part has (07-fillets/017 picks
+ // its base circle where the seam starts): its side lies on both sides of its seam.
+ let block = box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(40.0, 30.0, 20.0)).unwrap();
+ let boss = crate::cylinder(Vec3::new(15.0, 15.0, 20.0), Vec3::new(0.0, 0.0, 1.0), 8.0, 10.0).unwrap();
+ let b = crate::boolean(&block, &boss, crate::BoolOp::Union).unwrap().unwrap();
+ let mesh = b.mesh(&crate::MeshTolerance::chord(0.01)).unwrap();
+ let seams = crate::topo::seam_flags(&b, &mesh);
+ let record = b.record();
+ let one_face: Vec<usize> = crate::history::edge_faces(record)
+ .iter()
+ .zip(&record.edges)
+ .enumerate()
+ .filter(|(_, (faces, e))| faces.len() == 1 && e.uses.len() == 2)
+ .map(|(i, _)| i)
+ .collect();
+ assert_eq!(one_face.len(), 1, "the boss's side meets itself along its seam");
+ for &i in &one_face {
+ assert!(seams[i], "edge {i}, the boss's side on both of its sides, is a seam");
+ assert!(!mesh.edge_pickable(i), "edge {i} is drawn and picked as a seam");
+ // Its end on the base circle, where a pick takes the circle.
+ let line = &mesh.edges[i];
+ let foot = [line[0], line[line.len() - 1]].into_iter().find(|p| (p.z - 20.0).abs() < 1e-6).unwrap();
+ let picked = imp::resolve(&b, &[foot]).unwrap();
+ let [_, _, z] = picked.points[0];
+ assert!((z - 20.0).abs() < 1e-9, "the pick at {foot:?} took an edge through z = {z}");
+ }
+ }
+
#[test]
fn each_edge_takes_its_own_size() {
let b = cube();
diff --git a/crates/kernel/src/blend_variable.rs b/crates/kernel/src/blend_variable.rs
index 2ca0a0ca67..1d253077ca 100644
--- a/crates/kernel/src/blend_variable.rs
+++ b/crates/kernel/src/blend_variable.rs
@@ -224,13 +224,10 @@ struct EdgeSetup {
}
impl EdgeSetup {
- /// The edge of `body` nearest `at`.
+ /// The edge of `body` a pick at `at` takes, as the blend takes it.
fn new(body: &Body, at: Vec3) -> Result<EdgeSetup> {
- let size = body.size();
- let (edge, dist) = body.nearest_edge(at, (size * 2e-3).max(1e-3))?.ok_or_else(|| KernelError::Invalid(format!("no edge at {at:?}")))?;
- if dist > size * 0.05 + 1e-3 {
- return Err(KernelError::Invalid(format!("no edge at {at:?}")));
- }
+ let (picked, _) = crate::blend_smlib::picked_edges(body, &[at])?;
+ let edge = *picked.first().ok_or_else(|| KernelError::Invalid(format!("no edge at {at:?}")))?;
let rec = Faces::of(body)?;
if !rec.straight(edge) {
return Err(unsupported("only straight edges take a variable radius"));
@@ -239,7 +236,7 @@ impl EdgeSetup {
let [v0, v1] = rec.rec.edges.get(edge).ok_or_else(|| KernelError::Failed("edge not found".into()))?.vertices;
let (p0, p1) = rec.ends(edge).ok_or_else(|| KernelError::Failed("edge not found".into()))?;
let d = (p1 - p0).normalized().ok_or_else(|| KernelError::Failed("zero-length edge".into()))?;
- Ok(EdgeSetup { rec, fr, edge, v0, v1, p0, p1, d, tol: (size * 1e-7).max(1e-9) })
+ Ok(EdgeSetup { rec, fr, edge, v0, v1, p0, p1, d, tol: (body.size() * 1e-7).max(1e-9) })
}
/// How far a blend of radius `r` reaches into each face from the edge.
diff --git a/crates/kernel/src/topo.rs b/crates/kernel/src/topo.rs
index a9967a1502..b1bcd3b964 100644
--- a/crates/kernel/src/topo.rs
+++ b/crates/kernel/src/topo.rs
@@ -84,11 +84,22 @@ impl<'a> Faces<'a> {
}
}
-/// Per edge (in `Body::edges` order): is it a seam between two pieces of one curved surface?
+/// Per edge (in `Body::edges` order): is it a seam of a curved surface, between two pieces of it
+/// or where one face of it meets itself (a whole turn of a cylinder, its seam used twice)?
/// `mesh` is the body's tessellation, whose edges are the record's.
pub fn seam_flags(b: &Body, _mesh: &Mesh) -> Vec<bool> {
- let faces = Faces::new(b.record(), (b.size() * 1e-4).max(1e-6) * 10.0);
- edge_faces(b.record()).iter().map(|fs| matches!(fs[..], [x, y] if !faces.planar(x) && faces.same(x, y))).collect()
+ let record = b.record();
+ let faces = Faces::new(record, (b.size() * 1e-4).max(1e-6) * 10.0);
+ record
+ .edges
+ .iter()
+ .zip(edge_faces(record))
+ .map(|(e, fs)| match fs[..] {
+ [x, y] => !faces.planar(x) && faces.same(x, y),
+ [x] => e.uses.len() == 2 && !faces.planar(x),
+ _ => false,
+ })
+ .collect()
}
/// Merged face/edge/vertex counts (see module docs). `mesh` must be `b.mesh(..)`: faces of no
diff --git a/tests/kernel-cases/booleans/2896-join-arm-end-near-ring-wall-gap/expected.json b/tests/kernel-cases/booleans/2896-join-arm-end-near-ring-wall-gap/expected.json
index f7277377b1..3d9822f26e 100644
--- a/tests/kernel-cases/booleans/2896-join-arm-end-near-ring-wall-gap/expected.json
+++ b/tests/kernel-cases/booleans/2896-join-arm-end-near-ring-wall-gap/expected.json
@@ -4,8 +4,7 @@
],
"what": "a join of a ring and an arm whose R5 convex tip stops 0.01 mm short of the ring's outer wall: nothing overlaps, so nothing fuses",
"source": "analytic",
- "method": "ring pi*(30^2-24^2)*6 and arm 6*(350+12.5*pi) are 0.01 mm apart (arm tip at x=30.01): the join has nothing to fuse, so V is the sum of the two and the arm stays a separate shell. A combine's join of a tool that meets no target keeps it in the target as a separate lump (crates/doc eval.rs, Operation::Join; engine test join_meeting_nothing_keeps_the_first_body), and the tool body is consumed: one body (Ring) of two shells",
- "body_count": 1,
- "volume_mm3": 8442.875567597792,
- "shells": 2
+ "method": "ring pi*(30^2-24^2)*6 and arm 6*(350+12.5*pi) are 0.01 mm apart (arm tip at x=30.01): the join has nothing to fuse, so V is the sum of the two. Solids a join leaves apart (or touching only along an edge or at a point) stay separate bodies (owner decision 2026-10-22: a join's `touching` is `separate` by default; crates/doc eval.rs, separate_touching): the arm comes out of the combine as a body of its own beside Ring, the tool body consumed as before: two bodies of one shell each",
+ "body_count": 2,
+ "volume_mm3": 8442.875567597792
}
diff --git a/tests/kernel-cases/booleans/3379-circular-pattern-of-thin-spoke-on-ring/expected.json b/tests/kernel-cases/booleans/3379-circular-pattern-of-thin-spoke-on-ring/expected.json
index f8ca6d5642..d4aa56df0b 100644
--- a/tests/kernel-cases/booleans/3379-circular-pattern-of-thin-spoke-on-ring/expected.json
+++ b/tests/kernel-cases/booleans/3379-circular-pattern-of-thin-spoke-on-ring/expected.json
@@ -4,7 +4,7 @@
],
"what": "a circular pattern (count 5) of a spoke thinner than the ring it joins (faces 0.5 mm inside the rim and hub faces)",
"source": "analytic",
- "method": "ring pi*(66^2-63^2)*3 + hub pi*12^2*3 + 5 spokes. A spoke is the box 53x2x2.5 (x 11..64, z +-1.25, y 0.5..2.5; the issue starts it at x=12, tangent to the hub, which joins the hub by a line only, so it starts at 11 here to overlap it). It overlaps the ring by 5.021 and the hub by 4.891 (width * Int over z in -1.25..1.25 of 64 - sqrt(63^2-z^2) and of sqrt(12^2-z^2) - 11). V = ring + hub + 5*(265 - overlaps), one body",
+ "method": "ring pi*(66^2-63^2)*3 + hub pi*12^2*3 + 5 spokes. A spoke is the box 53x2x2.5 (x 11..64, z +-1.25, y 0.5..2.5; the issue starts it at x=12, tangent to the hub, which joins the hub by a line only, so it starts at 11 here to overlap it). It overlaps the ring by 5.021 and the hub by 4.891 (width * Int over z in -1.25..1.25 of 64 - sqrt(63^2-z^2) and of sqrt(12^2-z^2) - 11). V = ring + hub + 5*(265 - overlaps), one body. The hub, apart from the ring when it is joined, is joined with touching: one_body, so the ring and hub stay one body for the spokes to join (a join keeps solids that share no volume as separate bodies by default, owner decision 2026-10-22).",
"body_count": 1,
"volume_mm3": 6279.997172312351
}
diff --git a/tests/kernel-cases/booleans/3379-circular-pattern-of-thin-spoke-on-ring/recipe.json b/tests/kernel-cases/booleans/3379-circular-pattern-of-thin-spoke-on-ring/recipe.json
index 6e61872f99..b4a1542a88 100644
--- a/tests/kernel-cases/booleans/3379-circular-pattern-of-thin-spoke-on-ring/recipe.json
+++ b/tests/kernel-cases/booleans/3379-circular-pattern-of-thin-spoke-on-ring/recipe.json
@@ -45,7 +45,8 @@
"operation": "join",
"targets": [
"rim"
- ]
+ ],
+ "touching": "one_body"
}
},
{
diff --git a/tests/kernel-cases/booleans/3455-join-of-64-separate-pegs/expected.json b/tests/kernel-cases/booleans/3455-join-of-64-separate-pegs/expected.json
index aec452bd9c..22d70b04b1 100644
--- a/tests/kernel-cases/booleans/3455-join-of-64-separate-pegs/expected.json
+++ b/tests/kernel-cases/booleans/3455-join-of-64-separate-pegs/expected.json
@@ -4,7 +4,7 @@
],
"what": "one combine of 64 separate pegs that do not touch: 36 s on truck, growing 4-9x per doubling; must finish in seconds",
"source": "analytic",
- "method": "64 non-touching 48-gon pegs of circumradius 2, 1 mm tall, 6 mm apart: each area 0.5*48*2^2*sin(2pi/48) = 12.5305, V = 64 * 12.5305 * 1. The join keeps them in one body (several lumps). A hang is a failure: time should grow with the number of bodies. One body with 64 shells",
+ "method": "64 non-touching 48-gon pegs of circumradius 2, 1 mm tall, 6 mm apart: each area 0.5*48*2^2*sin(2pi/48) = 12.5305, V = 64 * 12.5305 * 1. The join keeps them in one body (several lumps). A hang is a failure: time should grow with the number of bodies. One body with 64 shells. The combine joins with touching: one_body, which keeps the pegs one body (by default a join keeps solids that share no volume as separate bodies, owner decision 2026-10-22).",
"body_count": 1,
"shells": 64,
"volume_mm3": 801.9529
diff --git a/tests/kernel-cases/booleans/3455-join-of-64-separate-pegs/recipe.json b/tests/kernel-cases/booleans/3455-join-of-64-separate-pegs/recipe.json
index 530e728156..d78d697606 100644
--- a/tests/kernel-cases/booleans/3455-join-of-64-separate-pegs/recipe.json
+++ b/tests/kernel-cases/booleans/3455-join-of-64-separate-pegs/recipe.json
@@ -12889,7 +12889,8 @@
"Peg (63)",
"Peg (64)"
],
- "operation": "join"
+ "operation": "join",
+ "touching": "one_body"
}
}
]
diff --git a/tests/kernel-cases/booleans/3526-intersect-keeps-every-lump/expected.json b/tests/kernel-cases/booleans/3526-intersect-keeps-every-lump/expected.json
index 2db4443d19..b2c6aa39e6 100644
--- a/tests/kernel-cases/booleans/3526-intersect-keeps-every-lump/expected.json
+++ b/tests/kernel-cases/booleans/3526-intersect-keeps-every-lump/expected.json
@@ -5,7 +5,7 @@
],
"what": "intersect of a two-lump target (two spheres joined while apart) with a box holding the bottom half of each",
"source": "analytic",
- "method": "box x -10..40, y -10..10, z -10..0 holds the z<=0 half of each r=4 sphere (centres (0,0,0), (30,0,0)): V = 2 * (2/3) pi 4^3 = 268.083. The body must not be removed. One body with two shells",
+ "method": "box x -10..40, y -10..10, z -10..0 holds the z<=0 half of each r=4 sphere (centres (0,0,0), (30,0,0)): V = 2 * (2/3) pi 4^3 = 268.083. The body must not be removed. One body with two shells. The second sphere is joined with touching: one_body, which makes the two-lump target (a join keeps solids that share no volume as separate bodies by default, owner decision 2026-10-22).",
"body_count": 1,
"shells": 2,
"volume_mm3": 268.0826
diff --git a/tests/kernel-cases/booleans/3526-intersect-keeps-every-lump/recipe.json b/tests/kernel-cases/booleans/3526-intersect-keeps-every-lump/recipe.json
index cd071542d9..bbc7a5242c 100644
--- a/tests/kernel-cases/booleans/3526-intersect-keeps-every-lump/recipe.json
+++ b/tests/kernel-cases/booleans/3526-intersect-keeps-every-lump/recipe.json
@@ -25,7 +25,8 @@
"operation": "join",
"targets": [
"Balls"
- ]
+ ],
+ "touching": "one_body"
}
},
{
diff --git a/tests/kernel-cases/ladder/07-fillets/016-corner-three-sequential-r5-r3-r7/recipe.json b/tests/kernel-cases/ladder/07-fillets/016-corner-three-sequential-r5-r3-r7/recipe.json
index 7b04d0d113..ab2c565c0d 100644
--- a/tests/kernel-cases/ladder/07-fillets/016-corner-three-sequential-r5-r3-r7/recipe.json
+++ b/tests/kernel-cases/ladder/07-fillets/016-corner-three-sequential-r5-r3-r7/recipe.json
@@ -24,7 +24,8 @@
20
]
],
- "radius": 3
+ "radius": 3,
+ "tangent_chain": false
}
},
{