SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Top-level cut and join reach bodies in sub-components (#5679) (#6246)
HiroKenEz0d32821e9ec4
diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rsindex dd1ea52f9e..9f765eb230 100644--- a/crates/engine/src/cmd/features.rs+++ b/crates/engine/src/cmd/features.rs@@ -198,14 +198,21 @@ fn auto_operation_in(s: &Session, p: &Value, world_faces: bool) -> Option<&'stat// Probe in the same coordinate frame as the face picks.let grouped = p.get("faces").and_then(Value::as_array).and_then(|faces| faces.first()).and_then(vec3);let st = if grouped.is_some() && world_faces { s.world_state() } else { s.model.state() };+ // The body the extrude starts on, when it is in a component inside the active one: it takes+ // part as the active component's own bodies do (#5679).+ let mut started_on = None;let (base, n) = if let Some(point) = grouped {let (mesh, index, distance, name) = super::face::face_at_state(&st, point, str_(p, "face_body")).ok().flatten()?;if distance > (mesh.bounds().diagonal() * 1e-3).max(1e-3) * 10.0 {return None;}let normal = st.body(&name)?.body.planar_face(index as usize)?.normal();+ started_on = Some(name);(point, normal)} else {+ if p.get("face").is_none() {+ started_on = feature_sketch(s, p, "Extrude").ok().and_then(|sketch| face_body_reached(s, sketch).ok().flatten());+ }extrude_base(s, p)?};// The extrude starts at its From Object or start offset, not at the profile: probe from@@ -232,17 +239,27 @@ fn auto_operation_in(s: &Session, p: &Value, world_faces: bool) -> Option<&'stat// A component with no body of its own works on those of the components inside it (#3223).let parts = string_list(p, "participants");let implicit_all = grouped.is_some() && !st.bodies.iter().any(|body| s.doc.model_body_component(body) == s.active_component);- let bodies: Vec<_> = if !parts.is_empty() {+ let mut bodies: Vec<_> = if !parts.is_empty() {st.bodies.iter().filter(|b| parts.contains(&b.name)).collect()} else if implicit_all {st.bodies.iter().collect()} else {active_scope(s, &st)};+ if parts.is_empty()+ && let Some(body) = started_on.as_deref().and_then(|name| st.body(name))+ && !bodies.iter().any(|b| b.name == body.name)+ && s.doc.component_within(s.doc.model_body_component(body), s.active_component)+ {+ bodies.push(body);+ }if bodies.is_empty() {return Some("new");}- let inside = |q: Vec3| bodies.iter().any(|b| b.mesh().contains(q));+ // A profile's points are in the active component's frame; a body placed differently (in a+ // moved or turned component) is probed where it is shown. Face picks are in `st`'s frame.+ let frames: Vec<Option<solidcraft_doc::Mat>> = bodies.iter().map(|b| if grouped.is_some() { None } else { into_body_frame(s, b) }).collect();+ let inside = |q: Vec3| bodies.iter().zip(&frames).any(|(b, m)| b.mesh().contains(m.as_ref().map_or(q, |m| solidcraft_doc::apply_point(m, q))));// A step into whatever is right in front of the profile, short of the far end.let near = |d: f64| d.signum() * (d.abs() * 0.5).min(START_PROBE_MM);let into = |d: f64| inside(base + n * near(d)) || inside(base + n * (d * 0.5));@@ -780,14 +797,20 @@ fn extrude(s: &mut Session, p: &Value) -> Result<Value> {_ => operation(p, cmd)?,};let mut targets = string_list(p, "targets");- if operation == Operation::Join && targets.is_empty() && string_list(p, "participants").is_empty() {+ let mut p = std::borrow::Cow::Borrowed(p);+ if operation == Operation::Join && targets.is_empty() && string_list(&p, "participants").is_empty() {// A face's outward extension joins that body, and so does a profile sketched on a body's// face. Assembly neighbours can touch only an edge of the tool: trying to join them// first fails, or absorbs unrelated parts (#226). A profile drawn past the face can lie// on a neighbour's face too: a rib on a bracket's side welded in the motor the bracket// holds, a join that ran for minutes and failed (#1349).// Store the resolved target so recomputes and reopening keep the same scope.- targets.extend(face_body.or_else(|| sketch_face_body(s, sketch)));+ targets.extend(match face_body {+ Some(body) => Some(body),+ None => face_body_reached(s, sketch)?,+ });+ } else if let Some(parts) = cut_scope(s, &p, operation, sketch, face_body)? {+ p.to_mut()["participants"] = json!(parts);}let kind = FeatureKind::Extrude {sketch: SketchId(sketch),@@ -795,14 +818,39 @@ fn extrude(s: &mut Session, p: &Value) -> Result<Value> {Some(f) => f,None if thin.is_some() => ProfileSel::All,None if p.get("profiles").is_none() => default_extrude_profiles(s, sketch),- None => profiles(p, cmd)?,+ None => profiles(&p, cmd)?,},extent,operation,targets: targets.into_iter().map(BodyName).collect(),thin,};- add_feature(s, p, kind)+ add_feature(s, &p, kind)+}++/// The bodies a cut or intersect from a profile on a body's face takes part in when it names+/// none and that body is in a component inside the active one (#5679): the active component's+/// own bodies, as by default, and that body. `None` when the default already reaches it: it is+/// one of the active component's, or a component with no body of its own cuts every body.+fn cut_scope(s: &Session, p: &Value, operation: Operation, sketch: u64, face_body: Option<String>) -> Result<Option<Vec<String>>> {+ if !matches!(operation, Operation::Cut | Operation::Intersect)+ || !string_list(p, "targets").is_empty()+ || !string_list(p, "participants").is_empty()+ {+ return Ok(None);+ }+ let Some(body) = face_body_reached(s, sketch)?.or(face_body) else { return Ok(None) };+ let st = s.model.state();+ if s.cut_takes_every_body(&st) {+ return Ok(None);+ }+ let mut parts: Vec<String> = active_scope(s, &st).into_iter().map(|b| b.name.clone()).collect();+ let within = st.body(&body).is_some_and(|b| s.doc.component_within(s.doc.model_body_component(b), s.active_component));+ if parts.contains(&body) || !within {+ return Ok(None);+ }+ parts.push(body);+ Ok(Some(parts))}/// The profiles an extrude takes when `profiles` is omitted: even-odd nesting over what was drawn,@@ -846,6 +894,68 @@ fn default_extrude_profiles(s: &Session, sketch: u64) -> ProfileSel {}}+/// The matrix taking a point of the active component's frame into the frame `b`'s geometry is+/// kept in, as the evaluator moves a tool into it; `None` when the two are the same.+fn into_body_frame(s: &Session, b: &solidcraft_doc::ModelBody) -> Option<solidcraft_doc::Mat> {+ let frame = s.doc.component_transform(s.doc.model_body_component(b));+ let world = s.doc.model_body_offset(b).map_or(frame, |offset| solidcraft_doc::mat_mul(&frame, offset));+ let active = s.doc.component_transform(s.active_component);+ if world == active {+ return None;+ }+ solidcraft_doc::mat_inverse(&world).map(|into| solidcraft_doc::mat_mul(&into, &active))+}++/// The body whose face `sketch` is attached to, when a join or cut made in the active component+/// can change it: one of the active component's own ([`active_scope`]), or one in a component+/// inside it, moved or turned, which is changed in its own component, so every placement of that+/// component shows the change (#5679). `Ok(None)` when the sketch is not on a face, or the body is+/// outside the active component. Refused where the change can't be made in the body's component:+/// its bodies come from a linked design file, or the face was picked on a further placement of a+/// component placed more than once (the change is drawn at the first).+fn face_body_reached(s: &Session, sketch: u64) -> Result<Option<String>> {+ let Some(FeatureKind::Sketch { plane: solidcraft_doc::PlaneRef::Face { anchor: Some(anchor), .. }, .. }) = s.doc.feature(sketch).map(|f| &f.kind)+ else {+ return Ok(None);+ };+ let st = s.model.state();+ if let Some(own) = active_scope(s, &st).into_iter().find(|b| b.name == anchor.target.body) {+ return Ok(Some(own.name.clone()));+ }+ let Some(body) = st.body(&anchor.target.body) else { return Ok(None) };+ let component = s.doc.model_body_component(body);+ if !s.doc.component_within(component, s.active_component) {+ return Ok(None);+ }+ let name = |c: u64| s.doc.components.iter().find(|x| x.id == c).map_or_else(|| format!("component {c}"), |x| x.name.clone());+ let mut c = component;+ for _ in 0..1000 {+ if c == s.active_component || c == 0 {+ break;+ }+ if s.doc.links.contains_key(&c) {+ return Err(EngineError::Other(format!(+ "`{}` is in {}, which is linked to a design file: open that design to change it, or break the link first",+ body.name,+ name(c)+ )));+ }+ match s.doc.components.iter().find(|x| x.id == c) {+ Some(x) => c = x.parent,+ None => break,+ }+ }+ if !anchor.path.is_empty() && anchor.path != s.doc.first_path(component) {+ return Err(EngineError::Other(format!(+ "`{}` is in {}, which is placed more than once, and the sketch is on another placement than the first: activate that placement of {} to cut or join it there",+ body.name,+ name(component),+ name(component)+ )));+ }+ Ok(Some(body.name.clone()))+}+/// The body whose face `sketch` is attached to (on the face itself, not offset from it), when/// it is one the active component works on ([`active_scope`]).fn sketch_face_body(s: &Session, sketch: u64) -> Option<String> {@@ -857,13 +967,20 @@ fn sketch_face_body(s: &Session, sketch: u64) -> Option<String> {}/// The bodies a Join named none for: the body whose face a profile sketch is on (the first-/// sketch that is on one), as for an extrude. Explicit `targets` or `participants` keep theirs.-fn face_join_targets(s: &Session, p: &Value, operation: Operation, sketches: &[u64]) -> Vec<BodyName> {+/// sketch that is on one), as for an extrude, also in a component inside the active one, moved+/// or turned (#5679; refused as [`face_body_reached`] says). Explicit `targets` or+/// `participants` keep theirs.+fn face_join_targets(s: &Session, p: &Value, operation: Operation, sketches: &[u64]) -> Result<Vec<BodyName>> {let mut targets = string_list(p, "targets");if operation == Operation::Join && targets.is_empty() && string_list(p, "participants").is_empty() {- targets.extend(sketches.iter().find_map(|sk| sketch_face_body(s, *sk)));+ for sketch in sketches {+ if let Some(body) = face_body_reached(s, *sketch)? {+ targets.push(body);+ break;+ }+ }}- targets.into_iter().map(BodyName).collect()+ Ok(targets.into_iter().map(BodyName).collect())}/// The bodies a feature of the active component works on when it names none: the component's@@ -1031,19 +1148,26 @@ fn revolve(s: &mut Session, p: &Value) -> Result<Value> {Some(value) => serde_json::from_value(value.clone()).map_err(|_| bad(cmd, "`convention` must be sketch_normal or legacy_axis_start"))?,};let operation = operation(p, cmd)?;+ let targets = face_join_targets(s, p, operation, &[sketch])?;+ // From a profile on a body's face in a component inside the active one, a cut changes that+ // body too, as an extrude's does (#5679).+ let mut p = std::borrow::Cow::Borrowed(p);+ if let Some(parts) = cut_scope(s, &p, operation, sketch, None)? {+ p.to_mut()["participants"] = json!(parts);+ }let kind = FeatureKind::Revolve {sketch: SketchId(sketch),profiles,axis,angle,operation,- targets: face_join_targets(s, p, operation, &[sketch]),+ targets,angle2,symmetric,convention,to: to.map(FacePick),};- add_feature(s, p, kind)+ add_feature(s, &p, kind)}/// A revolve axis of `sketch` from its parameter: a sketch line id, the sketch's x or y axis, a@@ -2501,7 +2625,7 @@ fn sweep(s: &mut Session, p: &Value) -> Result<Value> {let (orientation, twist, scale) = sweep_options(s, p, cmd)?;let (rails, rail_fit) = sweep_rails(s, p, cmd, path_sketch)?;let operation = operation(p, cmd)?;- let targets = face_join_targets(s, p, operation, &[sketch]);+ let targets = face_join_targets(s, p, operation, &[sketch])?;add_feature(s,p,@@ -2639,7 +2763,7 @@ fn loft(s: &mut Session, p: &Value) -> Result<Value> {let (rails, rail_fit) = guide_rails(s, p, cmd, "loft", None)?;let operation = operation(p, cmd)?;let sketches: Vec<u64> = sections.iter().map(|sec| sec.sketch.0).collect();- let targets = face_join_targets(s, p, operation, &sketches);+ let targets = face_join_targets(s, p, operation, &sketches)?;add_feature(s, p, FeatureKind::Loft { sections, operation, targets, rails, rail_fit })}diff --git a/crates/engine/src/cmd/features_more_tests.rs b/crates/engine/src/cmd/features_more_tests.rsindex f29933b317..f174a0ae2b 100644--- a/crates/engine/src/cmd/features_more_tests.rs+++ b/crates/engine/src/cmd/features_more_tests.rs@@ -52,7 +52,22 @@ fn grouped_face_auto_operation_keeps_implicit_and_explicit_participants() {}run(&mut s, "solid.box", json!({"corner":[100,0,0],"length":10,"width":10,"height":10,"body_name":"Other"}));let mut params = json!({"faces":[[32,2,10],[38,8,10]],"face_body":"Stock","distance":-2});- assert_eq!(crate::auto_operation(&s, ¶ms), Some("join"), "an existing active-component body keeps its original participant scope");+ // The picked part takes part beside the active component's own body (#5679): going in cuts+ // it, and the top level's own body is left alone.+ assert_eq!(crate::auto_operation(&s, ¶ms), Some("cut"), "the picked body takes part beside the active component's own");+ for operation in ["auto", "cut"] {+ let mut t = s.scratch();+ let mut p = params.clone();+ p["operation"] = json!(operation);+ run(&mut t, "solid.extrude", p);+ let volume = |name: &str| solidcraft_kernel::measure(&t.model.state().body(name).unwrap().body).unwrap().volume;+ assert!(+ (volume("Stock") - 800.).abs() < 1e-6 && (volume("Other") - 1000.).abs() < 1e-6,+ "{operation}: {} {}",+ volume("Stock"),+ volume("Other")+ );+ }params["participants"] = json!(["Stock"]);assert_eq!(crate::auto_operation(&s, ¶ms), Some("cut"));params["participants"] = json!(["Other"]);@@ -160,6 +175,183 @@ fn every_inward_extrude_into_a_part_in_another_component_cuts_it() {assert!(wrong.is_empty(), "{} wrong:\n{}", wrong.len(), wrong.join("\n"));}+/// #5679's part: a 10 mm cube `Stock` in component Part, its placement moved to (30, 5, 2) and+/// turned 35 degrees about (1, 2, 0), with the top level active; with `base`, the top level has a+/// body of its own, a 20 x 20 x 5 `Base` at (-40, -40, 0). Returns Part's placement.+fn turned_part(base: bool) -> (Session, solidcraft_doc::Mat) {+ let mut s = Session::default();+ let part = run(&mut s, "component.create", json!({"name": "Part", "grounded": false}));+ run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Stock"}));+ run(&mut s, "component.activate", json!({"component": "root"}));+ run(&mut s, "occurrence.move", json!({"occurrence": part["occurrence"], "translate": [30, 5, 2], "axis": [1, 2, 0], "angle": "35 deg"}));+ run(&mut s, "component.capture_position", json!({}));+ if base {+ run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 5, "corner": [-40, -40, 0], "operation": "new", "body_name": "Base"}));+ }+ let placed = s.doc.component_transform(part["component"].as_u64().unwrap());+ (s, placed)+}++/// A sketch on the face at world point `at`, with `draw` given the point's place in the sketch.+fn sketch_on_face(s: &mut Session, at: solidcraft_geom::Vec3, draw: impl FnOnce(&mut Session, solidcraft_geom::Vec2, solidcraft_geom::Plane)) {+ run(s, "sketch.create", json!({"plane": {"face": [at.x, at.y, at.z]}, "project_edges": false}));+ let plane = s+ .doc+ .features+ .iter()+ .rev()+ .find_map(|f| match &f.kind {+ solidcraft_doc::FeatureKind::Sketch { plane: solidcraft_doc::PlaneRef::Face { plane, .. }, .. } => Some(*plane),+ _ => None,+ })+ .unwrap();+ draw(s, plane.to_local(at), plane);+ run(s, "sketch.finish", json!({}));+}++fn body_volume(s: &Session, name: &str) -> f64 {+ solidcraft_kernel::measure(&s.model.state().body(name).unwrap().body).unwrap().volume+}++/// #5679: with the top level active, a circle sketched on the top face of a part in a moved and+/// turned sub-component reads as a Cut going in and a Join going out, and either one, automatic+/// or chosen, changes that part's body in its own component: the hole is where the circle is+/// shown, not where the numbers would be in the part's frame. The top level's own body is left+/// alone, whether it has one or not.+#[test]+fn a_sketch_on_a_turned_sub_components_face_cuts_and_joins_it_from_the_top_level() {+ let hole = std::f64::consts::PI * 4.0 * 3.0;+ for base in [false, true] {+ let (mut s, placed) = turned_part(base);+ let top = solidcraft_doc::apply_point(&placed, solidcraft_geom::Vec3::new(5.0, 5.0, 10.0));+ sketch_on_face(&mut s, top, |s, c, _| {+ run(s, "sketch.circle.center", json!({"center": [c.x, c.y], "radius": 2}));+ });+ for (distance, expected) in [(-3.0, "cut"), (3.0, "join")] {+ assert_eq!(crate::auto_operation(&s, &json!({"distance": distance})), Some(expected), "base {base}, {distance}");+ for operation in ["auto", expected] {+ let mut t = s.scratch();+ run(&mut t, "solid.extrude", json!({"distance": distance, "operation": operation}));+ let case = format!("base {base}, {distance} {operation}");+ let names: Vec<String> = t.model.state().bodies.iter().map(|b| b.name.clone()).collect();+ assert_eq!(names, if base { vec!["Stock", "Base"] } else { vec!["Stock"] }, "{case}");+ let want = if expected == "cut" { 1000.0 - hole } else { 1000.0 + hole };+ assert!((body_volume(&t, "Stock") - want).abs() < 1e-3 * hole, "{case}: {}", body_volume(&t, "Stock"));+ // In the part's own frame: through the middle of its top, not beside it.+ let stock = t.model.state().body("Stock").unwrap().mesh();+ let at = |x: f64, y: f64, z: f64| stock.contains(solidcraft_geom::Vec3::new(x, y, z));+ if expected == "cut" {+ assert!(!at(5.0, 5.0, 8.0) && at(5.0, 5.0, 6.0) && at(1.0, 1.0, 9.0), "{case}");+ } else {+ assert!(at(5.0, 5.0, 12.0) && !at(1.0, 1.0, 12.0), "{case}");+ }+ if base {+ assert!((body_volume(&t, "Base") - 2000.0).abs() < 1e-6, "{case}");+ }+ }+ }+ }+}++/// #5679: a revolve from the top level, from a profile on the turned part's top face, joins or+/// cuts that part. A 6 x 1 rectangle turned about its long edge, which lies on the face, is a+/// cylinder of radius 1 half above the face and half in the part: a Join adds 3π, a Cut takes it.+#[test]+fn a_revolve_from_a_turned_sub_components_face_joins_and_cuts_it_from_the_top_level() {+ let half = std::f64::consts::PI * 3.0;+ for (operation, want) in [("join", 1000.0 + half), ("cut", 1000.0 - half)] {+ let (mut s, placed) = turned_part(true);+ let top = solidcraft_doc::apply_point(&placed, solidcraft_geom::Vec3::new(5.0, 5.0, 10.0));+ let mut axis = json!(null);+ sketch_on_face(&mut s, top, |s, c, plane| {+ run(s, "sketch.rectangle.two_point", json!({"p0": [c.x - 3.0, c.y], "p1": [c.x + 3.0, c.y + 1.0]}));+ axis = json!({"origin": [top.x, top.y, top.z], "dir": [plane.x.x, plane.x.y, plane.x.z]});+ });+ run(&mut s, "solid.revolve", json!({"axis": axis, "operation": operation}));+ let names: Vec<String> = s.model.state().bodies.iter().map(|b| b.name.clone()).collect();+ assert_eq!(names, ["Stock", "Base"], "{operation}");+ assert_eq!(s.model.state().body("Stock").map(|b| b.body.shell_count()), Some(1), "{operation}");+ assert!((body_volume(&s, "Stock") - want).abs() < 1e-3 * half, "{operation}: {}", body_volume(&s, "Stock"));+ assert!((body_volume(&s, "Base") - 2000.0).abs() < 1e-6, "{operation}");+ }+}++/// #5679 for Loft (and Sweep, through the same join target): with the top level active, a loft+/// from a circle on the turned part's top face to one 5 mm above joins the part, in one piece.+#[test]+fn a_loft_from_a_turned_sub_components_face_joins_it_from_the_top_level() {+ let (mut s, placed) = turned_part(true);+ let top = solidcraft_doc::apply_point(&placed, solidcraft_geom::Vec3::new(5.0, 5.0, 10.0));+ let mut centre = solidcraft_geom::Vec2::new(0.0, 0.0);+ sketch_on_face(&mut s, top, |s, c, _| {+ run(s, "sketch.circle.center", json!({"center": [c.x, c.y], "radius": 2}));+ centre = c;+ });+ let low = s.doc.features.iter().rev().find(|f| matches!(f.kind, solidcraft_doc::FeatureKind::Sketch { .. })).unwrap().id;+ let high = run(&mut s, "sketch.create", json!({"plane": {"face": [top.x, top.y, top.z]}, "offset": 5, "project_edges": false}))["sketch"].clone();+ run(&mut s, "sketch.circle.center", json!({"center": [centre.x, centre.y], "radius": 2}));+ run(&mut s, "sketch.finish", json!({}));+ run(&mut s, "solid.loft", json!({"sections": [{"sketch": low}, {"sketch": high}], "operation": "join"}));+ let names: Vec<String> = s.model.state().bodies.iter().map(|b| b.name.clone()).collect();+ assert_eq!(names, ["Stock", "Base"]);+ assert_eq!(s.model.state().body("Stock").map(|b| b.body.shell_count()), Some(1));+ let added = std::f64::consts::PI * 4.0 * 5.0;+ assert!((body_volume(&s, "Stock") - 1000.0 - added).abs() < 1e-3 * added, "{}", body_volume(&s, "Stock"));+ assert!((body_volume(&s, "Base") - 2000.0).abs() < 1e-6);+}++/// #5679: the part changes in its component, so a second placement of it shows the hole too. A+/// sketch on that second placement's face would draw the hole where the first one is: the cut+/// is refused with the reason, and the design stays as it was.+#[test]+fn a_cut_from_the_top_level_shows_in_every_placement_and_a_later_placement_is_refused() {+ let (mut s, placed) = turned_part(true);+ let second = run(&mut s, "occurrence.copy", json!({"component": "Part", "translate": [0, 40, 0]}))["occurrence"].as_u64().unwrap();+ let top = solidcraft_doc::apply_point(&placed, solidcraft_geom::Vec3::new(5.0, 5.0, 10.0));+ let mut first = s.scratch();+ sketch_on_face(&mut first, top, |s, c, _| {+ run(s, "sketch.circle.center", json!({"center": [c.x, c.y], "radius": 2}));+ });+ run(&mut first, "solid.extrude", json!({"distance": -3, "operation": "cut"}));+ let world = first.world_state();+ let placements: Vec<f64> =+ world.bodies.iter().filter(|b| b.definition_name() == "Stock").map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).collect();+ let want = 1000.0 - std::f64::consts::PI * 4.0 * 3.0;+ assert_eq!(placements.len(), 2, "{placements:?}");+ assert!(placements.iter().all(|v| (v - want).abs() < 1e-2), "{placements:?}");++ let (_, moved) = s.doc.path_placement(&[second]).unwrap();+ let top = solidcraft_doc::apply_point(&moved, solidcraft_geom::Vec3::new(5.0, 5.0, 10.0));+ sketch_on_face(&mut s, top, |s, c, _| {+ run(s, "sketch.circle.center", json!({"center": [c.x, c.y], "radius": 2}));+ });+ let features = s.doc.features.len();+ for operation in ["cut", "join"] {+ let refused = s.execute("solid.extrude", &json!({"distance": -3, "operation": operation})).unwrap_err().to_string();+ assert!(refused.contains("placed more than once") && refused.contains("activate"), "{refused}");+ }+ assert_eq!(s.doc.features.len(), features);+ assert!((body_volume(&s, "Stock") - 1000.0).abs() < 1e-6);+}++/// #5679: with the top level's own body as the target, nothing changes: a cut from a sketch on+/// its face keeps the default scope (no bodies stored), cuts it, and leaves the part alone.+#[test]+fn a_sketch_on_a_top_level_body_beside_a_turned_part_cuts_only_that_body() {+ let (mut s, _) = turned_part(true);+ sketch_on_face(&mut s, solidcraft_geom::Vec3::new(-30.0, -30.0, 5.0), |s, c, _| {+ run(s, "sketch.circle.center", json!({"center": [c.x, c.y], "radius": 2}));+ });+ assert_eq!(crate::auto_operation(&s, &json!({"distance": -2})), Some("cut"));+ assert_eq!(crate::auto_operation(&s, &json!({"distance": 2})), Some("join"));+ let made = run(&mut s, "solid.extrude", json!({"distance": -2, "operation": "auto"}));+ let feature = s.doc.feature(made["feature"].as_u64().unwrap()).unwrap();+ assert!(feature.participants.is_empty(), "{:?}", feature.participants);+ let hole = std::f64::consts::PI * 4.0 * 2.0;+ assert!((body_volume(&s, "Base") - (2000.0 - hole)).abs() < 1e-3 * hole, "{}", body_volume(&s, "Base"));+ assert!((body_volume(&s, "Stock") - 1000.0).abs() < 1e-6);+}+fn run(s: &mut Session, id: &str, p: Value) -> Value {match s.execute(id, &p) {Ok(v) => v,diff --git a/crates/engine/src/cmd/occurrence_tests.rs b/crates/engine/src/cmd/occurrence_tests.rsindex 24da8dd817..a5d57816b3 100644--- a/crates/engine/src/cmd/occurrence_tests.rs+++ b/crates/engine/src/cmd/occurrence_tests.rs@@ -595,6 +595,42 @@ fn a_linked_design_brings_its_bodies_in_and_follows_edits_to_the_part_file() {let _ = std::fs::remove_dir_all(&dir);}+/// #5679: a linked part's bodies come from its design file, so a cut or join from the top level+/// on a sketch on its face is refused with the reason, and the plate stays as the file has it.+#[test]+fn a_cut_or_join_from_the_top_level_into_a_linked_part_is_refused() {+ let dir = std::env::temp_dir().join(format!("solidcraft-linked-cut-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let part = dir.join("plate.solidcraft");+ saved_box_design(&part, 30.0);+ let mut s = Session::default();+ run(&mut s, INSERT_DESIGN, json!({"path": part, "translate": [50, 0, 0]}));+ let _ = std::fs::remove_dir_all(&dir);+ run(&mut s, "component.activate", json!({"component": "root"}));+ run(&mut s, "sketch.create", json!({"plane": {"face": [55, 10, 30]}, "project_edges": false}));+ let plane = s+ .doc+ .features+ .iter()+ .rev()+ .find_map(|f| match &f.kind {+ solidcraft_doc::FeatureKind::Sketch { plane: solidcraft_doc::PlaneRef::Face { plane, .. }, .. } => Some(*plane),+ _ => None,+ })+ .unwrap();+ let c = plane.to_local(solidcraft_geom::Vec3::new(55.0, 10.0, 30.0));+ run(&mut s, "sketch.circle.center", json!({"center": [c.x, c.y], "radius": 2}));+ run(&mut s, "sketch.finish", json!({}));+ let features = s.doc.features.len();+ for (operation, distance) in [("cut", -5), ("join", 5)] {+ let refused = s.execute("solid.extrude", &json!({"distance": distance, "operation": operation})).unwrap_err().to_string();+ assert!(refused.contains("`Plate`") && refused.contains("linked to a design file"), "{operation}: {refused}");+ }+ assert_eq!(s.doc.features.len(), features);+ let volume = run(&mut s, "inspect.measure", json!({"bodies": ["Plate"]}))["total"]["volume_mm3"].clone();+ near(&volume, 6000.0);+}+/// The compact list counts what a component holds and leaves out identity transforms; the full/// list stays as it was.#[test]@@ -687,9 +723,9 @@ fn matrix_move_turns_a_quarter_and_moves() {}/// #3223, #2872: a STEP assembly whose part sits two levels down, each level placed, opened and-/// stood up. With the imported root active, as Open leaves it, a circle sketched on the part's-/// top face cuts it through, reads as a Cut dragged in and a Join dragged out, and joins it in-/// one piece instead of starting a body of the root's own.+/// stood up. With the imported root active, as Open leaves it, or the top level, a circle sketched+/// on the part's top face cuts it through, reads as a Cut dragged in and a Join dragged out, and+/// joins it in one piece instead of starting a body of the active component's own.#[test]fn a_stood_up_nested_step_part_is_cut_and_joined_from_its_face() {let dir = std::env::temp_dir().join(format!("solidcraft-nested-stood-{}", std::process::id()));@@ -705,40 +741,52 @@ fn a_stood_up_nested_step_part_is_cut_and_joined_from_its_face() {let top = solidcraft_doc::apply_point(&src.doc.component_transform(part), solidcraft_geom::Vec3::new(20.0, 12.0, 10.0));run(&mut src, "file.export", json!({"path": path, "format": "step"}));- let mut s = Session::default();- run(&mut s, "doc.open", json!({"path": path, "up": "y"}));- let _ = std::fs::remove_dir_all(&dir);- let at = solidcraft_doc::apply_point(&s.doc.component_transform(s.active_component), top);- run(&mut s, "sketch.create", json!({"plane": {"face": [at.x, at.y, at.z]}, "project_edges": false}));- let centre = s- .doc- .features- .iter()- .rev()- .find_map(|f| match &f.kind {- solidcraft_doc::FeatureKind::Sketch { plane: solidcraft_doc::PlaneRef::Face { plane, .. }, .. } => Some(plane.to_local(top)),- _ => None,- })- .unwrap();- run(&mut s, "sketch.circle.center", json!({"center": [centre.x, centre.y], "radius": 3}));- run(&mut s, "sketch.finish", json!({}));- assert_eq!(crate::auto_operation(&s, &json!({"distance": -5})), Some("cut"));- assert_eq!(crate::auto_operation(&s, &json!({"distance": 5})), Some("join"));- let volume = |s: &mut Session| run(s, "inspect.measure", json!({"bodies": ["NestedBlock"]}))["total"]["volume_mm3"].as_f64().unwrap();- let block = 40.0 * 24.0 * 10.0;- let hole = std::f64::consts::PI * 3.0 * 3.0;-- // The circle is measured as faceted: within a thousandth of what it removes or adds.- for operation in ["cut", "auto"] {- run(&mut s, "solid.extrude", json!({"distance": -20, "operation": operation}));- assert!((block - volume(&mut s) - hole * 10.0).abs() < 1e-3 * hole * 10.0, "{operation}: {}", volume(&mut s));- run(&mut s, "edit.undo", json!({}));+ // #5679: the same from the top level, where the part is two moved and turned levels down+ // (#5678 was this cut silently doing nothing; `auto` read it as a new body).+ for top_level in [false, true] {+ let mut s = Session::default();+ run(&mut s, "doc.open", json!({"path": path, "up": "y"}));+ let at = solidcraft_doc::apply_point(&s.doc.component_transform(s.active_component), top);+ if top_level {+ run(&mut s, "component.activate", json!({"component": "root"}));+ }+ // The sketch is in the active component's frame: the imported root's, or the world's.+ let local = if top_level { at } else { top };+ run(&mut s, "sketch.create", json!({"plane": {"face": [at.x, at.y, at.z]}, "project_edges": false}));+ let centre = s+ .doc+ .features+ .iter()+ .rev()+ .find_map(|f| match &f.kind {+ solidcraft_doc::FeatureKind::Sketch { plane: solidcraft_doc::PlaneRef::Face { plane, .. }, .. } => Some(plane.to_local(local)),+ _ => None,+ })+ .unwrap();+ run(&mut s, "sketch.circle.center", json!({"center": [centre.x, centre.y], "radius": 3}));+ run(&mut s, "sketch.finish", json!({}));+ assert_eq!(crate::auto_operation(&s, &json!({"distance": -5})), Some("cut"), "top level {top_level}");+ assert_eq!(crate::auto_operation(&s, &json!({"distance": 5})), Some("join"), "top level {top_level}");+ let volume = |s: &mut Session| run(s, "inspect.measure", json!({"bodies": ["NestedBlock"]}))["total"]["volume_mm3"].as_f64().unwrap();+ let block = 40.0 * 24.0 * 10.0;+ let hole = std::f64::consts::PI * 3.0 * 3.0;++ // The circle is measured as faceted: within a thousandth of what it removes or adds.+ for operation in ["cut", "auto"] {+ run(&mut s, "solid.extrude", json!({"distance": -20, "operation": operation}));+ assert!((block - volume(&mut s) - hole * 10.0).abs() < 1e-3 * hole * 10.0, "{top_level} {operation}: {}", volume(&mut s));+ run(&mut s, "edit.undo", json!({}));+ }+ for operation in ["join", "auto"] {+ run(&mut s, "solid.extrude", json!({"distance": 5, "operation": operation}));+ let st = s.model.state();+ assert_eq!(st.bodies.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), ["NestedBlock"], "{top_level} {operation}");+ assert_eq!(st.body("NestedBlock").map(|b| b.body.shell_count()), Some(1), "{top_level} {operation}");+ assert!((volume(&mut s) - block - hole * 5.0).abs() < 1e-3 * hole * 5.0, "{top_level} {operation}: {}", volume(&mut s));+ run(&mut s, "edit.undo", json!({}));+ }}- run(&mut s, "solid.extrude", json!({"distance": 5, "operation": "join"}));- let st = s.model.state();- assert_eq!(st.bodies.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), ["NestedBlock"]);- assert_eq!(st.body("NestedBlock").map(|b| b.body.shell_count()), Some(1));- assert!((volume(&mut s) - block - hole * 5.0).abs() < 1e-3 * hole * 5.0, "join: {}", volume(&mut s));+ let _ = std::fs::remove_dir_all(&dir);}/// A rotation that is one only up to rounding is orthonormalised; a scale, a shear or a mirrordiff --git a/docs/step-import.md b/docs/step-import.mdindex 4a71b4d73b..54159e3d7e 100644--- a/docs/step-import.md+++ b/docs/step-import.md@@ -8,7 +8,7 @@ SolidCraft reads STEP (ISO 10303-21; AP203, AP214 and AP242 geometry) with its o## Imports are components-Every import (STEP, IGES, 3MF, STL, OBJ; inserted, dropped, opened as a new design, or run as `file.insert_step`, `file.insert_mesh` or `doc.open` from a script, the CLI or MCP) becomes a **new component named after the file** (`bracket.step` → component `bracket`), placed in the active component at the file's origin. The Import feature belongs to it, so the file's bodies never land loose next to your own. Opening a file as a design makes the component too, so the browser shows the file's name. The command's reply reports it: `component` (id), `component_name` and `occurrence`.+Every import (STEP, IGES, 3MF, STL, OBJ; inserted, dropped, opened as a new design, or run as `file.insert_step`, `file.insert_mesh` or `doc.open` from a script, the CLI or MCP) becomes a **new component named after the file** (`bracket.step` → component `bracket`), placed in the active component at the file's origin. The Import feature belongs to it, so the file's bodies never land loose next to your own. Opening a file as a design makes the component too, so the browser shows the file's name. The command's reply reports it: `component` (id), `component_name` and `occurrence`. With the top level (or any component above the part) active, an extrude, revolve or press-pull from a sketch on a part's face cuts or joins that part's body in its own component, wherever the part is placed, and every placement of the part shows the change. It is refused, with the reason, for a part linked to another design and for a face on a further placement of a part placed more than once (activate that placement to change it there).A STEP **assembly** keeps its structure: each product under the file's root becomes a component nested under the import's, named after the product, at the place the file gives it. IGES groups and subfigures become nested components the same way. A part (or sub-assembly) the file places more than once becomes **one component with an occurrence per placement**: the Import feature builds the part once and skips the file's later copies (`skip` in the feature, format 22), and the occurrences show it everywhere else. Placements that are scaled, mirrored or otherwise non-rigid keep their geometry in place in the parent component. The reply adds `subcomponents` (how many components were made below the import's) and `rigid_joints`.