SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Sketch Project: faces and edges of a part's second copy now project (#9957) (#10721)
semmelrinde32dc8750df8d
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rsindex c6fc6bdd78..6f85867da2 100644--- a/crates/doc/src/eval.rs+++ b/crates/doc/src/eval.rs@@ -1570,6 +1570,9 @@ fn cache_key(f: &Feature, chain_fp: u64, local: u64, ctx: u64, state: &ModelStat#[derive(Default)]struct PlacementReads {all: bool,+ /// A body named that `st` lacks: a further placement's (`Block (Part:2)`), found through+ /// its occurrence (#9957), or gone.+ unlisted: bool,components: std::collections::BTreeSet<u64>,paths: Vec<Vec<u64>>,bodies: std::collections::BTreeSet<String>,@@ -1608,14 +1611,17 @@ impl PlacementReads {}}- /// The component of body `name` in `st`; every component when the body is not there (a- /// projection then takes the body nearest its point, wherever that is).+ /// The component of body `name` in `st`; every component and every placement when the body+ /// is not there (a further placement's body, or the body nearest its point, wherever that is).fn body(&mut self, doc: &Document, st: Option<&ModelState>, name: &str) {match st.and_then(|st| st.body(name)) {Some(b) => {self.components.insert(doc.model_body_component(b));}- None => self.all = true,+ None => {+ self.all = true;+ self.unlisted = true;+ }}}@@ -1851,6 +1857,9 @@ fn placement_digest(doc: &Document, f: &Feature, st: Option<&ModelState>) -> u64}}hash_placed_bodies(doc, st, &reads.bodies, &inverse, &mut h);+ if reads.unlisted {+ placements_hash(doc).hash(&mut h);+ }// Legacy and component-wide reads still need the conservative offset dependency. Body// reads above already include just their own offsets, in the frame that evaluates them.if reads.all || !reads.components.is_empty() || !reads.paths.is_empty() {@@ -7243,6 +7252,14 @@ fn eval_feature(None if !plane_reads_geometry(plane) && sketch.links.is_empty() => std::borrow::Cow::Borrowed(st),None => state_in_frame(doc, st, f.component)?,};+ // A further placement a link reads is placed in its frame too (#9957).+ let named: Vec<&str> = sketch.links.iter().flat_map(|l| l.source.bodies()).collect();+ let fst = match anchor.map(|anchor| anchor.author_frame(doc, f.component)) {+ _ if named.is_empty() => fst,+ Some(Ok(frame)) => with_placed_copies(doc, st, fst, &frame, &named),+ Some(Err(_)) => fst,+ None => with_placed_copies(doc, st, fst, &doc.component_transform(f.component), &named),+ };let (plane, face_warning) = match (anchor, plane) {(Some(_), plane) => doc.resolve_attached_plane_noted(vals, plane, f.component, st, &fst)?,// A flat face of a sheet: the panel's exact plane, from its flat region and fold.@@ -8480,6 +8497,51 @@ pub fn state_in_frame_at<'a>(doc: &Document, st: &'a ModelState, comp: u64, framOk(Cow::Owned(out))}+/// `framed` (the model `st` in the frame that `frame` places in the world) with the further+/// placements `names` names (`Block (Part:2)`), where they are in the world. A component's model+/// holds its first placement only, so a sketch projecting a copy's face found no body of that+/// name and took the first placement's (#9957). Only the named ones are placed: placing every+/// body of an assembly for each sketch made sketch edits as slow as the design is big.+pub fn with_placed_copies<'a>(+ doc: &Document,+ st: &ModelState,+ framed: std::borrow::Cow<'a, ModelState>,+ frame: &Mat,+ names: &[&str],+) -> std::borrow::Cow<'a, ModelState> {+ let missing: Vec<&str> = names.iter().copied().filter(|n| !n.is_empty() && framed.body(n).is_none()).collect();+ if missing.is_empty() || doc.occurrences.is_empty() {+ return framed;+ }+ let Some(inv) = crate::mat_inverse(frame) else { return framed };+ let mut by_component: std::collections::HashMap<u64, Vec<&ModelBody>> = std::collections::HashMap::new();+ for (b, owner) in st.bodies.iter().zip(doc.model_body_components(st)) {+ by_component.entry(owner).or_default().push(b);+ }+ let world = crate::WorldNames::new(doc, st);+ let mut placed: Vec<ModelBody> = Vec::new();+ for (comp, path, m) in doc.placements() {+ for b in by_component.get(&comp).into_iter().flatten() {+ let name = world.name(&b.name, comp, &path);+ if !missing.contains(&name.as_str()) || placed.iter().any(|p| p.name == name) {+ continue;+ }+ let bm = doc.model_body_offset(b).map(|o| crate::mat_mul(&m, o)).unwrap_or(m);+ if let Ok(mut copy) = st.body_in_frame(b, &crate::mat_mul(&inv, &bm)) {+ copy.name = name;+ copy.source_name = Some(b.definition_name().to_string());+ placed.push(copy);+ }+ }+ }+ if placed.is_empty() {+ return framed;+ }+ let mut out = framed.into_owned();+ out.bodies.extend(placed);+ std::borrow::Cow::Owned(out)+}+/// The model placed in the world: each component's bodies, sketches, threads and construction/// geometry through every occurrence of it (bodies of the first placement keep their names;/// further instances get the occurrence path in brackets). Without components this is the modeldiff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rsindex 87c1bcb3f8..1815e4f7d1 100644--- a/crates/doc/src/lib.rs+++ b/crates/doc/src/lib.rs@@ -92,8 +92,8 @@ pub use eval::{blend_target, curve_pick_error, draft_corner_options, edge_names_for, edge_refs, face_point_names, face_point_state, hole_direction_at,hole_on_surface, import_body_names, join_pieces_added, map_wire, metric_thread_sizes, object_height, parse_metric_thread, pattern_matrices,revolve_extent, revolve_extent_for_handle, revolve_extent_with_convention, select_profiles, sketch_hole_direction, sketch_line_plane,- state_in_frame, state_in_frame_at, suggested_thread, suggested_thread_in, tangent_face_chain, through_all_distance, world_state,- world_state_reusing,+ state_in_frame, state_in_frame_at, suggested_thread, suggested_thread_in, tangent_face_chain, through_all_distance, with_placed_copies,+ world_state, world_state_reusing,};pub use eval::{EvalCache, KeptResults};pub use expr::Expr;diff --git a/crates/engine/src/cmd/browser.rs b/crates/engine/src/cmd/browser.rsindex c75286f6ec..fec2ab08bf 100644--- a/crates/engine/src/cmd/browser.rs+++ b/crates/engine/src/cmd/browser.rs@@ -1202,6 +1202,7 @@ fn rename_body(s: &mut Session, p: &Value) -> Result<Value> {}let previous = s.doc.clone();let st = s.model.state();+ let placed = s.doc.body_frames_with_source(&st);let b = st.body(&old).ok_or_else(|| bad(cmd, format!("no body `{old}`")))?;if st.body(name).is_some() {return Err(bad(cmd, format!("another body is called `{name}`")));@@ -1319,6 +1320,8 @@ fn rename_body(s: &mut Session, p: &Value) -> Result<Value> {return Err(bad(cmd, e));}d.rename_body_keys(&old, name);+ // A sketch projecting the body in another placement of its component keeps it.+ super::sketch_project::follow_placed_renames(d, &st, &placed, Some((&old, name)));s.remember_body_rename(&previous, &old, name);Ok(json!({"body": old, "name": name}))}diff --git a/crates/engine/src/cmd/component.rs b/crates/engine/src/cmd/component.rsindex 97f6a47fb8..3225f6a458 100644--- a/crates/engine/src/cmd/component.rs+++ b/crates/engine/src/cmd/component.rs@@ -394,6 +394,8 @@ fn rename(s: &mut Session, p: &Value) -> Result<Value> {let id = component(s, p, "component", cmd)?;let name =str_(p, "name").map(str::trim).filter(|n| !n.is_empty() && n.len() <= 128).ok_or_else(|| bad(cmd, "`name` must be 1…128 characters"))?;+ let st = s.model.state();+ let placed = s.doc.body_frames_with_source(&st);let d = s.doc_mut();if id == 0 {d.name = name.to_string();@@ -406,6 +408,8 @@ fn rename(s: &mut Session, p: &Value) -> Result<Value> {o.name = format!("{name}:{k}");}}+ // A sketch projecting a body of one of those placements keeps it.+ super::sketch_project::follow_placed_renames(d, &st, &placed, None);}Ok(json!({"component": id, "name": name}))}diff --git a/crates/engine/src/cmd/sketch_project.rs b/crates/engine/src/cmd/sketch_project.rsindex 25949c0934..f00fb86814 100644--- a/crates/engine/src/cmd/sketch_project.rs+++ b/crates/engine/src/cmd/sketch_project.rs@@ -145,21 +145,84 @@ fn sketch_plane(doc: &Document, id: u64, st: &solidcraft_doc::ModelState) -> Res}/// The model before sketch `id` in the frame its links and its plane are resolved in: the-/// attached face's frame for a sketch on a face, else its component's.+/// attached face's frame for a sketch on a face, else its component's. The further placements+/// `named` names (`Block (Part:2)`) are in it too, where they are (#9957).fn state_for_sketch<'a>(s: &Session,doc: &Document,id: u64,st: &'a solidcraft_doc::ModelState,+ named: &[&str],) -> std::result::Result<std::borrow::Cow<'a, solidcraft_doc::ModelState>, solidcraft_doc::DocError> {let comp = doc.feature(id).map(|f| f.component).unwrap_or(0);let attachment = doc.feature(id).and_then(|feature| match &feature.kind {solidcraft_doc::FeatureKind::Sketch { plane, .. } => super::sketch::face::anchor(plane),_ => None,});- match attachment {- Some(anchor) => solidcraft_doc::state_in_face_anchor_frame(doc, st, anchor, comp),- None => solidcraft_doc::state_in_frame_at(doc, st, comp, owner_frame(s, doc, comp)),+ let (framed, frame) = match attachment {+ Some(anchor) => (solidcraft_doc::state_in_face_anchor_frame(doc, st, anchor, comp)?, anchor.author_frame(doc, comp)?),+ None => {+ let frame = owner_frame(s, doc, comp);+ (solidcraft_doc::state_in_frame_at(doc, st, comp, frame)?, frame)+ }+ };+ Ok(solidcraft_doc::with_placed_copies(doc, st, framed, &frame, named))+}++/// The placed bodies of a design (`Document::body_frames_with_source`): world name, definition+/// name, component, occurrence path and frame.+pub(super) type PlacedBodies = Vec<(String, String, u64, Vec<u64>, solidcraft_doc::Mat)>;++/// Sketch links keep a further placement's body by the name the world gives it (`Block (Part:2)`,+/// #9957), which a rename of the body or of its component changes: each link naming one of+/// `before` (the placed bodies before the rename) now names what that body is called in `doc`.+/// `renamed` is the body renamed (old name, new name), if one was.+pub(super) fn follow_placed_renames(doc: &mut Document, st: &solidcraft_doc::ModelState, before: &PlacedBodies, renamed: Option<(&str, &str)>) {+ let renames: std::collections::HashMap<String, String> = {+ let names = solidcraft_doc::WorldNames::new(doc, st);+ before+ .iter()+ .filter(|(world, own, ..)| world != own)+ .filter_map(|(world, own, component, path, _)| {+ let source = match renamed {+ Some((old, new)) if own == old => new,+ _ => own.as_str(),+ };+ let now = names.name(source, *component, path);+ (now != *world).then(|| (world.clone(), now))+ })+ .collect()+ };+ if renames.is_empty() {+ return;+ }+ for f in &mut doc.features {+ if let FeatureKind::Sketch { sketch, .. } = &mut f.kind {+ for link in &mut sketch.links {+ rename_link_body(&mut link.source, &renames);+ }+ }+ }+}++fn rename_link_body(source: &mut LinkSource, renames: &std::collections::HashMap<String, String>) {+ match source {+ LinkSource::Edge { body, .. }+ | LinkSource::Face { body, .. }+ | LinkSource::Body { body }+ | LinkSource::Vertex { body, .. }+ | LinkSource::OnSurface { body, .. }+ | LinkSource::Iso { body, .. }+ | LinkSource::Spun { body, .. } => {+ if let Some(new) = renames.get(body.as_str()) {+ body.clone_from(new);+ }+ }+ LinkSource::Intersection { a, b } => {+ rename_link_body(a, renames);+ rename_link_body(b, renames);+ }+ _ => {}}}@@ -205,7 +268,8 @@ pub(super) fn refresh(s: &Session, doc: &Document, id: u64, sk: &mut Sketch) ->solidcraft_doc::FeatureKind::Sketch { plane, .. } => super::sketch::face::anchor(plane),_ => None,});- let Ok(st) = state_for_sketch(s, &doc, id, &st) else {+ let named: Vec<&str> = sk.links.iter().flat_map(|l| l.source.bodies()).collect();+ let Ok(st) = state_for_sketch(s, &doc, id, &st, &named) else {return vec!["lost face attachment; reattach explicitly".into()];};let Ok(plane) = sketch_plane(&doc, id, &st) else { return Vec::new() };@@ -257,7 +321,7 @@ pub(super) fn origin_axis_line(s: &Session, p: &Value, line: &Value, cmd: &str)let id = sketch_store::target(s, p, cmd)?;let doc = placed_candidate(s, &s.doc);let st = s.model.state_before(id);- let st = state_for_sketch(s, &doc, id, &st)?;+ let st = state_for_sketch(s, &doc, id, &st, &[])?;let plane = sketch_plane(&doc, id, &st)?;let src = source(s, line, cmd)?;let LinkSource::Axis { name } = &src else { return Err(bad(cmd, "the mirror line must be a straight sketch curve or an origin axis")) };@@ -297,7 +361,7 @@ fn add_link_unless_present(let (vals, _) = doc.param_values();let st = s.model.state_before(id);// The model as the sketch's component sees it.- let st = state_for_sketch(s, &doc, id, &st)?;+ let st = state_for_sketch(s, &doc, id, &st, &src.bodies())?;let plane = sketch_plane(&doc, id, &st)?;let r = resolve(&doc, &vals, &st, &plane, kind, &src)?;if skip_present && r.wires.is_empty() && sk.link_geometry_present(&r.geom) {@@ -719,7 +783,7 @@ pub(super) fn snap_points(s: &mut Session, p: &Value, cmd: &str) -> Result<Value} else if let Some(at) = edge {let l = add_link(s, d, id, sk, LinkKind::Project, LinkSource::Edge { body, at }).map_err(|e| bad(cmd, format!("edge: {e}")))?;let before = s.model.state_before(id);- let plane = sketch_plane(d, id, &*state_for_sketch(s, d, id, &before)?)?;+ let plane = sketch_plane(d, id, &*state_for_sketch(s, d, id, &before, &[])?)?;let q = plane.to_local(at);let ci = sk.link_curves(&l).first().copied().ok_or_else(|| bad(cmd, "the edge projects to a point"))?;let pi = sk.add_point(q, None)?;diff --git a/crates/engine/src/cmd/sketch_project_tests.rs b/crates/engine/src/cmd/sketch_project_tests.rsindex b5bbcfa189..9b46708d8d 100644--- a/crates/engine/src/cmd/sketch_project_tests.rs+++ b/crates/engine/src/cmd/sketch_project_tests.rs@@ -1578,3 +1578,56 @@ fn the_silhouette_of_conic_rounds_closes() {let area = profiles[0]["area_mm2"].as_f64().unwrap();assert!((area - exact).abs() < exact * 2e-4, "area {area}, exact {exact}");}++/// A second placement's body is projected where that placement puts it (#9957): a sketch sees+/// "Block (Part:2)" as the browser shows it, not only the first placement's "Block", on a plane+/// and on a face alike.+#[test]+fn a_second_placements_face_and_edge_project_where_it_is_placed() {+ let mut s = Session::default();+ run(&mut s, "solid.box", json!({"length":100,"width":40,"height":5,"body_name":"Plate"}));+ let part = run(&mut s, "component.create", json!({"name":"Part"}));+ run(&mut s, "solid.box", json!({"length":20,"width":20,"height":10,"body_name":"Block"}));+ run(&mut s, "component.activate", json!({"component":0}));+ run(&mut s, "occurrence.copy", json!({"component":part["component"],"translate":[50,0,5]}));+ let mut sketches = Vec::new();+ let picks = [+ (json!({"plane":"XY","offset":15}), json!({"body":"Block (Part:2)","face":[60,10,15]})),+ (json!({"plane":"XY","offset":15}), json!({"body":"Block (Part:2)","edge":[60,20,15]})),+ (json!({"plane":{"face":[90,35,5]},"project_edges":false}), json!({"body":"Block (Part:2)","face":[60,10,15]})),+ ];+ for (plane, pick) in picks {+ let id = run(&mut s, "sketch.create", plane)["sketch"].as_u64().unwrap();+ let projected = run(&mut s, "sketch.project", json!({"refs":[pick]}));+ assert_eq!(projected["links"].as_array().map(Vec::len), Some(1), "{projected}");+ run(&mut s, "sketch.finish", json!({}));+ sketches.push(id);+ }+ // Every projected point is on the copy (x 50..70, y from `y`), none on the original.+ let check = |s: &Session, y: f64| {+ let state = s.model.state();+ for id in &sketches {+ let ss = state.sketch(*id).unwrap();+ let sk = &ss.sketch;+ assert!(sk.links.iter().all(|l| !l.lost), "{:?}", sk.links);+ let points: Vec<_> =+ sk.links.iter().flat_map(|l| sk.link_points(&l.id)).filter_map(|p| sk.points.get(p)).map(|p| ss.plane.to_world(p.pos)).collect();+ assert!(!points.is_empty());+ assert!(points.iter().all(|p| p.x > 49.9 && p.x < 70.1 && p.y > y - 0.1 && p.y < y + 20.1), "sketch {id}, y {y}: {points:?}");+ }+ };+ check(&s, 0.0);+ // A design opened again, so rebuilt from its features, finds the copy as well.+ check(&Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()), 0.0);+ // Moving the copy moves what was projected from it.+ let first = s.doc.occurrences[0].id;+ let copy = s.doc.occurrences.iter().map(|o| o.id).find(|id| *id != first).unwrap();+ run(&mut s, "occurrence.move", json!({"occurrence":copy,"translate":[0,15,0],"capture":true}));+ check(&s, 15.0);+ // Renaming the part or the body renames the copy ("Base (Housing:2)"): the links follow it.+ run(&mut s, "component.rename", json!({"component":part["component"],"name":"Housing"}));+ run(&mut s, "body.rename", json!({"body":"Block","name":"Base"}));+ assert!(s.model.state().sketch(sketches[0]).unwrap().sketch.links.iter().all(|l| l.source.bodies() == ["Base (Housing:2)"]));+ check(&s, 15.0);+ check(&Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()), 15.0);+}diff --git a/crates/engine/src/frames.rs b/crates/engine/src/frames.rsindex 150a5d64f1..6bb8c4ee6b 100644--- a/crates/engine/src/frames.rs+++ b/crates/engine/src/frames.rs@@ -291,7 +291,10 @@ impl Mapper<'_> {m.insert(k.into(), y);}}+ // A sketch's view of the model holds a further placement by the name the world+ // gives it (`with_placed_copies`), so that name stays (#9957).if let Some(bn) = &b+ && !self.here&& let Some(own) = self.own_name(bn){m.insert("body".into(), Value::String(own));