Skip to content

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

Sketch: an option to make the part active when sketching on its face (#10215) (#10216)

raykholo2e3448f3489a
diff --git a/assets/locales/pending/sketch-face-activates-part.json b/assets/locales/pending/sketch-face-activates-part.json
new file mode 100644
index 0000000000..b4a8652ca4
--- /dev/null
+++ b/assets/locales/pending/sketch-face-activates-part.json
@@ -0,0 +1,26 @@
+{
+ "en": {
+ "prefs.sketch_face_activates_part": "Sketching on a part's face makes that part active",
+ "prefs.sketch_face_activates_part_note": "A sketch started on a face of another component's body activates that component first, so the sketch belongs to it and stays with that part in the browser. The part stays active afterwards. Off: the sketch belongs to the active component."
+ },
+ "ar": {
+ "prefs.sketch_face_activates_part": "الرسم على وجه جزء يجعل ذلك الجزء نشطًا",
+ "prefs.sketch_face_activates_part_note": "الرسم الذي يبدأ على وجه جسم في مكوّن آخر ينشّط ذلك المكوّن أولًا، فينتمي الرسم إليه ويبقى مع ذلك الجزء في المستعرض. ويبقى الجزء نشطًا بعد ذلك. عند الإيقاف: ينتمي الرسم إلى المكوّن النشط."
+ },
+ "he": {
+ "prefs.sketch_face_activates_part": "שרטוט על פאה של חלק הופך את החלק לפעיל",
+ "prefs.sketch_face_activates_part_note": "שרטוט שמתחיל על פאה של גוף ברכיב אחר מפעיל קודם את הרכיב הזה, כך שהשרטוט שייך לו ונשאר עם החלק בסייר. החלק נשאר פעיל אחר כך. כבוי: השרטוט שייך לרכיב הפעיל."
+ },
+ "ja": {
+ "prefs.sketch_face_activates_part": "部品の面にスケッチするとその部品をアクティブにする",
+ "prefs.sketch_face_activates_part_note": "別のコンポーネントのボディの面で始めたスケッチは、先にそのコンポーネントをアクティブにし、スケッチはそのコンポーネントに属してブラウザでその部品の下に表示されます。部品はその後もアクティブのままです。オフ:スケッチはアクティブなコンポーネントに属します。"
+ },
+ "vi": {
+ "prefs.sketch_face_activates_part": "Phác thảo trên mặt của một chi tiết sẽ kích hoạt chi tiết đó",
+ "prefs.sketch_face_activates_part_note": "Bản phác thảo bắt đầu trên mặt của một khối thuộc thành phần khác sẽ kích hoạt thành phần đó trước, nên bản phác thảo thuộc về nó và nằm cùng chi tiết đó trong trình duyệt. Chi tiết vẫn được kích hoạt sau đó. Tắt: bản phác thảo thuộc thành phần đang hoạt động."
+ },
+ "zh": {
+ "prefs.sketch_face_activates_part": "在零件的面上绘制草图时激活该零件",
+ "prefs.sketch_face_activates_part_note": "在另一个组件的实体面上开始的草图会先激活该组件,因此草图属于它,并在浏览器中留在该零件下。之后该零件保持激活。关闭时:草图属于当前激活的组件。"
+ }
+}
diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs
index 42203e85be..9d2c48f228 100644
--- a/crates/engine/src/cmd/sketch.rs
+++ b/crates/engine/src/cmd/sketch.rs
@@ -37,7 +37,7 @@ pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("sketch.create", "Create Sketch", create_sketch)
.at("SOLID", "CREATE")
.icon("sketch")
- .params("plane: XY|XZ|YZ | construction plane name or id | {origin?: [x,y,z] numbers in mm, default [0,0,0] (not an expression), x_dir, y_dir} (in world coordinates unless frame says otherwise; a named plane is the active component's own) | {face: [world x,y,z], body?: exact world body, index?: face index, path?: complete occurrence ids, fixed?: bool}; new face attachments require a unique certified source (a flat face of a sheet metal body attaches to its panel instead, in the flat pattern's coordinates), fixed:true explicitly freezes the selected plane; offset?: expr, flip?: bool | \"x\" | \"y\" (not on a face: sketch the plane from its other side, so the normal and the default extrude direction are reversed; a half turn about the plane's own x or y axis, true picks the one keeping the sketch's y axis upward; offset still moves along the unflipped normal), frame?: world (default) | component (which coordinates an explicit plane is in; the reply's `frame` says which, with a `note` when the active component is moved or turned), project_edges?: bool, name?"),
+ .params("plane: XY|XZ|YZ | construction plane name or id | {origin?: [x,y,z] numbers in mm, default [0,0,0] (not an expression), x_dir, y_dir} (in world coordinates unless frame says otherwise; a named plane is the active component's own) | {face: [world x,y,z], body?: exact world body, index?: face index, path?: complete occurrence ids, fixed?: bool}; new face attachments require a unique certified source (a flat face of a sheet metal body attaches to its panel instead, in the flat pattern's coordinates), fixed:true explicitly freezes the selected plane; offset?: expr, flip?: bool | \"x\" | \"y\" (not on a face: sketch the plane from its other side, so the normal and the default extrude direction are reversed; a half turn about the plane's own x or y axis, true picks the one keeping the sketch's y axis upward; offset still moves along the unflipped normal), frame?: world (default) | component (which coordinates an explicit plane is in; the reply's `frame` says which, with a `note` when the active component is moved or turned), project_edges?: bool, activate_part?: bool (default false; on a face of a body of another component than the active one: activate that component at the picked placement first, as component.activate would, and make the sketch there; it stays active afterwards and the reply's `activated` names it), name?"),
CommandSpec::new("sketch.edit", "Edit Sketch", edit_sketch).noundo().icon("sketch").params("sketch: id or name"),
CommandSpec::new("sketch.finish", "Finish Sketch", finish_sketch).at("SKETCH", "FINISH SKETCH").icon("finish").enabled(in_sketch).noundo(),
CommandSpec::new("sketch.cancel", "Cancel Sketch", cancel_sketch)
@@ -818,8 +818,43 @@ fn create_sketch(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, format!("`{key}` belongs inside `plane`: {example}")));
}
}
+ let activate = match p.get("activate_part") {
+ None | Some(Value::Null) => false,
+ Some(Value::Bool(on)) => *on,
+ Some(_) => return Err(bad(cmd, "`activate_part` must be true or false")),
+ };
let frame = plane_frame(p, cmd)?;
- let mut plane = plane_ref(s, p, cmd)?;
+ let plane = plane_ref(s, p, cmd)?;
+ // On a face of another component's body, `activate_part` activates that component at the
+ // picked placement first, as `component.activate` would, and the sketch is made there. It
+ // stays active, as after an explicit activate, so what is built from the sketch lands in the
+ // same part. On an error the active component goes back to what it was.
+ let owner = match p.get("plane") {
+ Some(value) if activate && face::is_face(p) => face::pick_owner(s, value, &plane, cmd)?,
+ _ => None,
+ };
+ let Some((component, path)) = owner.filter(|(component, _)| *component != s.active_component) else {
+ return create_sketch_on(s, p, plane, frame, cmd);
+ };
+ let before = (s.active_component, s.active_occurrence_path.clone());
+ s.active_component = component;
+ s.active_occurrence_path = (!path.is_empty()).then(|| path.clone());
+ s.revision += 1;
+ let made = plane_ref(s, p, cmd).and_then(|plane| create_sketch_on(s, p, plane, frame, cmd));
+ match made {
+ Ok(mut out) => {
+ out["activated"] = json!({"component": component, "path": path});
+ Ok(out)
+ }
+ Err(error) => {
+ (s.active_component, s.active_occurrence_path) = before;
+ Err(error)
+ }
+ }
+}
+
+/// The rest of `sketch.create` once the active component is settled: `flip`, the sketch, the reply's `frame`.
+fn create_sketch_on(s: &mut Session, p: &Value, mut plane: PlaneRef, frame: Option<&str>, cmd: &str) -> Result<Value> {
if let Some(about_y) = flip_param(s, p, &plane, cmd)? {
plane = PlaneRef::Flipped { base: Box::new(plane), about_y };
}
diff --git a/crates/engine/src/cmd/sketch_face.rs b/crates/engine/src/cmd/sketch_face.rs
index 2742b8ada6..3473854276 100644
--- a/crates/engine/src/cmd/sketch_face.rs
+++ b/crates/engine/src/cmd/sketch_face.rs
@@ -275,6 +275,27 @@ pub(in crate::cmd) fn capture_positions(s: &mut Session, plane: &PlaneRef) -> Re
Ok(())
}
+/// The component and placement (occurrence path, empty for the design) whose body a face pick
+/// `value` lies on: the pick's `path`, else its `body`'s first placement, else the exact
+/// attachment `captured` from it. `None` when none of them names one (a sheet metal panel
+/// face picked by its point alone, or a fixed plane picked by its point alone).
+pub(in crate::cmd) fn pick_owner(s: &Session, value: &Value, captured: &PlaneRef, cmd: &str) -> Result<Option<(u64, Vec<u64>)>> {
+ let form = face_pick_form(value).map_err(|why| bad(cmd, why))?;
+ if let Some(path) = form.path {
+ if path.is_empty() {
+ return Ok(Some((0, path)));
+ }
+ let component = s.occurrence_placement(&path)?.component;
+ return Ok(Some((component, path)));
+ }
+ if let Some(body) = form.body {
+ let state = s.model.state();
+ let doc = s.placed_document();
+ return Ok(state.body(body).map(|body| doc.model_body_component(body)).map(|component| (component, doc.first_path(component))));
+ }
+ Ok(anchor(captured).map(|anchor| (anchor.component, anchor.path.clone())))
+}
+
#[cfg(test)]
#[path = "sketch_face_tests.rs"]
mod tests;
diff --git a/crates/engine/src/cmd/sketch_face_tests.rs b/crates/engine/src/cmd/sketch_face_tests.rs
index 4b8b2795b7..ae9c880658 100644
--- a/crates/engine/src/cmd/sketch_face_tests.rs
+++ b/crates/engine/src/cmd/sketch_face_tests.rs
@@ -821,3 +821,38 @@ fn a_sketch_on_the_ring_of_a_lid_underside_parted_by_its_lip_keeps_the_cap() {
let plane = s.model.state().sketch(id).unwrap().plane;
assert!(plane.normal().dot(-Vec3::Z) > 0.999 && (plane.origin.z - 25.).abs() < 1e-6, "{plane:?}");
}
+
+/// `activate_part` (#10215): a sketch on a face of another component's body is made in that
+/// component, which stays active; without it the sketch belongs to the active component.
+#[test]
+fn activate_part_makes_the_sketch_in_the_faces_component() {
+ for activate in [true, false] {
+ let mut s = Session::default();
+ let part = run(&mut s, "component.create", json!({"name":"Part","parent":0,"grounded":false}));
+ let (component, occurrence) = (part["component"].as_u64().unwrap(), part["occurrence"].as_u64().unwrap());
+ run(&mut s, "solid.box", json!({"length":10,"width":10,"height":10,"body_name":"Base"}));
+ run(&mut s, "occurrence.move", json!({"occurrence":occurrence,"translate":[30,0,0]}));
+ run(&mut s, "component.activate", json!({"component":0}));
+ let mut pick = top_pick(&s, "Base");
+ pick["path"] = json!([occurrence]);
+ let out = run(&mut s, "sketch.create", json!({"name":"OnFace","plane":pick,"activate_part":activate,"project_edges":false}));
+ let id = out["sketch"].as_u64().unwrap();
+ let owner = s.doc.feature(id).unwrap().component;
+ if activate {
+ assert_eq!(owner, component);
+ assert_eq!((s.active_component, s.active_occurrence_path.clone()), (component, Some(vec![occurrence])));
+ assert_eq!(out["activated"], json!({"component": component, "path": [occurrence]}));
+ let solidcraft_doc::FeatureKind::Sketch { plane, .. } = &s.doc.feature(id).unwrap().kind else { panic!("not sketch") };
+ assert_eq!(super::anchor(plane).unwrap().author_path, vec![occurrence]);
+ } else {
+ assert_eq!(owner, 0);
+ assert_eq!(s.active_component, 0);
+ assert!(out.get("activated").is_none());
+ }
+ let world = s.world_state();
+ let plane = world.sketch(id).unwrap().plane;
+ assert!((plane.origin.z - 10.).abs() < 1e-6 && plane.normal().z > 1. - 1e-9, "{activate}: {plane:?}");
+ draw(&mut s);
+ assert!(s.model.result(id).unwrap().error.is_none());
+ }
+}
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index d42e614de5..d10b961b60 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -3479,7 +3479,11 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
{
plane["fixed"] = json!(true);
let before = app.settled_cam();
- match app.run("sketch.create", json!({"plane":plane})) {
+ let mut params = json!({"plane":plane});
+ if app.preferences.sketch_face_activates_part {
+ params["activate_part"] = json!(true);
+ }
+ match app.run("sketch.create", params) {
Ok(_) => {
app.look_at_opened_sketch(before);
cancel = true;
@@ -3890,7 +3894,10 @@ fn hole_defaults(s: &Session) -> Kind {
pub fn start_sketch(app: &mut SolveApp, sel: &Sel) -> Result<(), String> {
let mut params = match sel {
Sel::Plane { name } => json!({ "plane": shown_origin_plane(app, name).unwrap_or_else(|| json!(name)) }),
- Sel::Face { .. } => json!({ "plane": crate::sketch_attachment_ui::face_plane(app, sel).ok_or("Selected face placement no longer exists")? }),
+ Sel::Face { .. } => json!({
+ "plane": crate::sketch_attachment_ui::face_plane(app, sel).ok_or("Selected face placement no longer exists")?,
+ "activate_part": app.preferences.sketch_face_activates_part,
+ }),
_ => return Err("Select an origin plane, construction plane or planar body face".into()),
};
if let Sel::Plane { name } = sel
diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs
index 56e443f305..78db7c1256 100644
--- a/crates/ui-egui/src/prefs.rs
+++ b/crates/ui-egui/src/prefs.rs
@@ -1387,6 +1387,10 @@ preference_settings! {
/// Opening or editing a sketch turns the view to face it (the default). Off: the view stays as
/// it is, and Look At faces the sketch when asked.
sketch_open_look_at: bool = true, PAGE_SKETCH;
+ /// A sketch started on a face of a body in another component than the active one activates
+ /// that component first, so the sketch belongs to it (`sketch.create` `activate_part`,
+ /// #10215). Off (the default): the sketch belongs to the active component, as before.
+ sketch_face_activates_part: bool = false, PAGE_SKETCH => check_id("prefs.sketch_face_activates_part");
/// Where the view goes when a sketch ends (#7038). Keep (the default) leaves it as it is.
sketch_exit_view: SketchExitView = SketchExitView::default(), PAGE_SKETCH;
/// A shape drawn in a sketch gets all its dimensions at once: the typed values, and every
diff --git a/crates/ui-egui/src/prefs/sketch.rs b/crates/ui-egui/src/prefs/sketch.rs
index 34be255e15..3dceac3042 100644
--- a/crates/ui-egui/src/prefs/sketch.rs
+++ b/crates/ui-egui/src/prefs/sketch.rs
@@ -19,6 +19,8 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
if ui_kit::checkbox(ui, crate::i18n::tr_label("Project face edges into new sketches"), &mut auto).changed() {
let _ = app.run("sketch.auto_project", json!({"value": auto}));
}
+ let owner = setting::sketch_face_activates_part(app, ui).on_hover_text(app.tr("prefs.sketch_face_activates_part_note"));
+ crate::scenario::publish_target("prefs:sketch_face_activates_part", owner.rect);
ui_kit::checkbox(ui, app.tr("prefs.project_options_dialog"), &mut app.preferences.project_options_dialog)
.on_hover_text(app.tr("prefs.project_options_dialog_note"));
ui_kit::checkbox(ui, crate::i18n::tr_label("Pressing a tool's shortcut again switches its mode"), &mut app.preferences.shortcut_cycles_modes)
diff --git a/crates/ui-egui/src/sketch_attachment_ui_tests.rs b/crates/ui-egui/src/sketch_attachment_ui_tests.rs
index 46f4472eca..53f1274c70 100644
--- a/crates/ui-egui/src/sketch_attachment_ui_tests.rs
+++ b/crates/ui-egui/src/sketch_attachment_ui_tests.rs
@@ -421,3 +421,35 @@ fn redefine_panel_names_the_plane_a_sketch_is_on() {
assert_eq!(plane_description(&h.app.session.doc, &offset), "The XY plane, offset by 12 mm");
assert_eq!(plane_description(&h.app.session.doc, &PlaneRef::Flipped { base: xy, about_y: false }), "The XY plane, from its other side");
}
+
+/// Preferences › Sketch › "Sketching on a part's face makes that part active" (#10215): a face of
+/// a part's body picked for Create Sketch while the design is active puts the sketch in the part,
+/// which stays active; off, the sketch belongs to the design.
+#[test]
+fn face_pick_makes_its_part_active_only_with_the_preference() {
+ for on in [true, false] {
+ let mut h = Harness::new();
+ h.app.set_origin_shown(false);
+ h.app.session.auto_project = false;
+ h.app.preferences.sketch_face_activates_part = on;
+ let part = h.app.run("component.create", json!({"name":"Part"})).unwrap();
+ let (component, occurrence) = (part["component"].as_u64().unwrap(), part["occurrence"].as_u64().unwrap());
+ h.app.run("solid.box", json!({"length":10,"width":10,"height":10,"body_name":"PartBox"})).unwrap();
+ h.app.run("component.activate", json!({"component":0})).unwrap();
+ h.call("ui.view", json!({"view":"top"}));
+ h.call("ui.view", json!({"view":"fit"}));
+ h.settle();
+ h.step(&json!({"start":"sketch.create"})).unwrap();
+ h.step(&json!({"click":{"world":[3,4,10]}})).unwrap();
+ let sketch = h.app.session.active_sketch.expect("the picked face takes a sketch");
+ let owner = h.app.session.doc.feature(sketch).unwrap().component;
+ if on {
+ assert_eq!(owner, component);
+ assert_eq!((h.app.session.active_component, h.app.session.active_occurrence_path.clone()), (component, Some(vec![occurrence])));
+ } else {
+ assert_eq!((owner, h.app.session.active_component), (0, 0));
+ }
+ h.app.finish_sketch();
+ assert_eq!(h.app.session.active_component, if on { component } else { 0 }, "the part stays active as after Activate");
+ }
+}
diff --git a/docs/book/src/guide/sketching.md b/docs/book/src/guide/sketching.md
index 08e1e591c4..275fa56d62 100644
--- a/docs/book/src/guide/sketching.md
+++ b/docs/book/src/guide/sketching.md
@@ -12,6 +12,16 @@ an edited one goes back to how it was, as one step that Undo brings back.
Opening a sketch turns the view to face it; to keep the view as it is and face the sketch only with **Look At**, turn off Preferences › Sketch › **Turn to face a sketch when it opens**. When the sketch ends, the view stays where it is by default. Preferences › Sketch › **When a sketch ends** changes that: **Return to the previous view** goes back to the view from before the sketch, and **Return unless rotated** goes back only when you panned or zoomed the sketch view but didn't turn it.
+In an assembly a new sketch belongs to the active component and is listed in its Sketches
+folder. Turn on Preferences › Sketch › **Sketching on a part's face makes that part active** to
+keep sketches with the part they are drawn on: a sketch started on a face of another component's
+body first activates that component, at the placement you picked, and is made there, as if you had
+activated the part yourself. The part stays active afterwards, so an extrude or cut made from the
+sketch lands in the same part; activate the design or another part again as usual. Off (the
+default), the sketch belongs to the active component. In scripts the same is
+`sketch.create {"plane": {"face": …}, "activate_part": true}`; the reply's `activated` names the
+component and placement it activated.
+
In scripts, `XY`, `XZ`, `YZ` and their `Top`, `Front`, `Right` aliases name origin planes.
Preferences › Interface › **Origin plane names** shows them as Top, Front and Right in the
browser, dialogs and lists; scripts and saved designs keep XY, XZ and YZ.