Skip to content

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

Sketch: a dimension can measure a model edge (#7912) (#8010)

Homero Thompson184d4720be62
diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs
index 4f924f33c3..2be3a477e3 100644
--- a/crates/engine/src/cmd/sketch.rs
+++ b/crates/engine/src/cmd/sketch.rs
@@ -128,7 +128,7 @@ pub static COMMANDS: &[CommandSpec] = &[
.params(concat!("p0, p1: overall ends, width", connect_doc!(), created_doc!())),
CommandSpec::new("sketch.point", "Point", draw_point).at("SKETCH", "CREATE").icon("point").enabled(in_sketch).params(concat!("point: [x,y] (each a number or an expression over the design's parameters: the point is then fixed where it comes to and follows them) or a snap: \"mid:<line>\" (held at the line's midpoint), \"on:<curve>:x,y\" (on the curve near x,y), {vertex: [x,y,z]} or {on_edge: [x,y,z]} of the model; id?", connect_doc!(), created_doc!())),
CommandSpec::new("sketch.dimension", "Sketch Dimension", dimension).at("SKETCH", "CREATE").icon("dimension").key("D").enabled(in_sketch).params(
- "entities: [refs] (a line midpoint is \"mid:line_id\"), type?: auto|distance|horizontal|distance_x|vertical|distance_y|length|radius|diameter|angle, value?: number or expression (default: current; a bare number is in the design's units, e.g. 2 means 2 in in an inch design; give a unit such as \"50 mm\" to override), or `name = expression` (e.g. \"width = 40\"; also `#name = expression`), which adds the user parameter `name` with that expression and dimensions with `name` (refused when the name is taken or reserved; the reply's `defined` names it); text_at?: [x, y]. Two points, two midpoints or a line off the axes: with auto, text_at inside the box they span (as opposite corners) or in its outer corners is the distance between them, above or below the box horizontal, beside it vertical. Two lines: the angle between them (acute, or 180° − it when the value is nearer that) unless text_at picks a sector. A line and a circle or arc: the distance from the line to its edge (the gap, or how far the edge reaches past a line that cuts it; 0 is tangent); dimension the centre point for the distance to the centre. A point and a circle or arc: the distance from the point to its edge (or how far within it a point inside lies). Two circles or arcs: the gap between their edges (or how far they overlap when they cross, or the narrowest gap between them when one lies inside the other), or the centre-to-centre distance when they are the two caps of a slot. An arc and one of its end points: the arc's length (type arc_length does it from the arc alone). A dimension the sketch already determines is refused (naming what determines it); if_redundant?: \"driven\" places it as a driven (reference) dimension instead. scale_sketch?: bool (the dimension tool sends true): when this is the sketch's first length dimension and nothing in the sketch fixes a size (no other driving length dimension, nothing fixed or projected), the whole sketch scales about its origin to the value instead of distorting. Returns measured in unit (mm or deg), and scaled: the factor when the sketch was scaled",
+ "entities: [refs] (a line midpoint is \"mid:line_id\"; a model edge or vertex, {edge: [x,y,z], body?} or {vertex: [x,y,z], body?}, is projected into the sketch first and measured there: a point against the projected edge measures the distance to it), type?: auto|distance|horizontal|distance_x|vertical|distance_y|length|radius|diameter|angle, value?: number or expression (default: current; a bare number is in the design's units, e.g. 2 means 2 in in an inch design; give a unit such as \"50 mm\" to override), or `name = expression` (e.g. \"width = 40\"; also `#name = expression`), which adds the user parameter `name` with that expression and dimensions with `name` (refused when the name is taken or reserved; the reply's `defined` names it); text_at?: [x, y]. Two points, two midpoints or a line off the axes: with auto, text_at inside the box they span (as opposite corners) or in its outer corners is the distance between them, above or below the box horizontal, beside it vertical. Two lines: the angle between them (acute, or 180° − it when the value is nearer that) unless text_at picks a sector. A line and a circle or arc: the distance from the line to its edge (the gap, or how far the edge reaches past a line that cuts it; 0 is tangent); dimension the centre point for the distance to the centre. A point and a circle or arc: the distance from the point to its edge (or how far within it a point inside lies). Two circles or arcs: the gap between their edges (or how far they overlap when they cross, or the narrowest gap between them when one lies inside the other), or the centre-to-centre distance when they are the two caps of a slot. An arc and one of its end points: the arc's length (type arc_length does it from the arc alone). A dimension the sketch already determines is refused (naming what determines it); if_redundant?: \"driven\" places it as a driven (reference) dimension instead. scale_sketch?: bool (the dimension tool sends true): when this is the sketch's first length dimension and nothing in the sketch fixes a size (no other driving length dimension, nothing fixed or projected), the whole sketch scales about its origin to the value instead of distorting. Returns measured in unit (mm or deg), and scaled: the factor when the sketch was scaled",
),
CommandSpec::new("sketch.constraint.horizontal_vertical", "Horizontal/Vertical", c_horizontal_vertical)
.at("SKETCH", "CONSTRAINTS")
@@ -2468,6 +2468,10 @@ pub(super) fn line_pts(sk: &Sketch, l: usize) -> Option<(Vec2, Vec2)> {
fn dimension(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sketch.dimension";
+ // A dimension may measure model geometry (#7912): an `{edge: [x,y,z], body?}` or a
+ // `{vertex: [x,y,z], body?}` among its entities is projected into the sketch first, as
+ // `sketch.project` does, and stands for the projected curve (or point) there.
+ let p = &super::sketch_project::project_entities(s, p, cmd)?;
let ents = string_list(cmd, p, "entities")?;
if ents.is_empty() || ents.len() > 2 {
return Err(bad(cmd, "`entities` must list one or two sketch entities"));
diff --git a/crates/engine/src/cmd/sketch_project.rs b/crates/engine/src/cmd/sketch_project.rs
index e7b830e961..6bbdbad5e7 100644
--- a/crates/engine/src/cmd/sketch_project.rs
+++ b/crates/engine/src/cmd/sketch_project.rs
@@ -382,8 +382,7 @@ fn include_cmd(s: &mut Session, p: &Value) -> Result<Value> {
/// Any body's edges work, a mirrored or patterned copy's too; the link keeps the edge's
/// persistent name, so the constraint follows the edge through rebuilds.
pub(super) fn project_operands(s: &mut Session, p: &Value, cmd: &str, keys: &[&str]) -> Result<Value> {
- let model = |v: &Value| v.get("edge").is_some() || v.get("vertex").is_some();
- if !keys.iter().any(|k| p.get(*k).is_some_and(model)) {
+ if !keys.iter().any(|k| p.get(*k).is_some_and(model_ref)) {
return Ok(p.clone());
}
let id = sketch_store::target(s, p, cmd)?;
@@ -392,22 +391,69 @@ pub(super) fn project_operands(s: &mut Session, p: &Value, cmd: &str, keys: &[&s
refresh(s, &doc, id, &mut sk);
let mut out = p.clone();
for key in keys {
- let Some(v) = p.get(*key).filter(|v| model(v)) else { continue };
- let src = source(s, v, cmd)?;
- let what = src.describe();
- let link = add_link(s, &doc, id, &mut sk, LinkKind::Project, src).map_err(|e| bad(cmd, format!("{what}: {e}")))?;
- // An edge stands for its curve (a point when it is seen end on), a vertex for its point.
- let curve = if v.get("edge").is_some() { sk.link_curves(&link).first().and_then(|c| sk.curves.get(*c)).map(|c| c.id.clone()) } else { None };
- let entity = curve
- .or_else(|| sk.link_points(&link).first().and_then(|q| sk.points.get(*q)).map(|q| q.id.clone()))
- .ok_or_else(|| bad(cmd, format!("{what} projects to nothing on this sketch")))?;
- out[*key] = json!(entity);
+ let Some(v) = p.get(*key).filter(|v| model_ref(v)) else { continue };
+ out[*key] = json!(project_ref(s, &doc, id, &mut sk, v, cmd)?);
}
sketch_store::write(&mut doc, id, sk)?;
*s.doc_mut() = doc;
Ok(out)
}
+/// A model's reference among a command's operands (#6348): an `{edge: [x,y,z], body?}` or a
+/// `{vertex: [x,y,z], body?}`.
+fn model_ref(v: &Value) -> bool {
+ v.get("edge").is_some() || v.get("vertex").is_some()
+}
+
+/// Project one model reference into the sketch and report the entity it stands for: an edge's
+/// projected curve (a point when it is seen end on) or a vertex's projected point.
+fn project_ref(s: &mut Session, doc: &Document, id: u64, sk: &mut Sketch, v: &Value, cmd: &str) -> Result<String> {
+ let src = source(s, v, cmd)?;
+ let what = src.describe();
+ let link = add_link(s, doc, id, sk, LinkKind::Project, src).map_err(|e| bad(cmd, format!("{what}: {e}")))?;
+ // An edge stands for its curve (a point when it is seen end on), a vertex for its point.
+ let curve = if v.get("edge").is_some() { sk.link_curves(&link).first().and_then(|c| sk.curves.get(*c)).map(|c| c.id.clone()) } else { None };
+ curve
+ .or_else(|| sk.link_points(&link).first().and_then(|q| sk.points.get(*q)).map(|q| q.id.clone()))
+ .ok_or_else(|| bad(cmd, format!("{what} projects to nothing on this sketch")))
+}
+
+/// Most model references one call may project into a sketch: each one is a link and a resolve,
+/// so the count is capped before any of them is projected.
+const MAX_PROJECTED_ENTITIES: usize = 1_000;
+
+/// A dimension's entities may be model geometry (#7912): an `{edge: [x,y,z], body?}` or
+/// `{vertex: [x,y,z], body?}` among them is projected into the sketch first, as Project does,
+/// and stands for the projected curve (or point) in the entities returned.
+pub(super) fn project_entities(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
+ let Some(Value::Array(entities)) = p.get("entities") else { return Ok(p.clone()) };
+ // A long list is refused before anything is projected, so it costs nothing.
+ if entities.len() > MAX_PROJECTED_ENTITIES {
+ return Err(bad(cmd, format!("`entities` may list at most {MAX_PROJECTED_ENTITIES} entities")));
+ }
+ if !entities.iter().any(model_ref) {
+ return Ok(p.clone());
+ }
+ let id = sketch_store::target(s, p, cmd)?;
+ let mut doc = (*s.doc).clone();
+ let mut sk = sketch_store::read(&doc, id)?.clone();
+ refresh(s, &doc, id, &mut sk);
+ let mut out = entities.clone();
+ for entity in out.iter_mut().take(MAX_PROJECTED_ENTITIES) {
+ if !model_ref(entity) {
+ continue;
+ }
+ *entity = json!(project_ref(s, &doc, id, &mut sk, entity, cmd)?);
+ }
+ let mut params = p.clone();
+ if let Some(o) = params.as_object_mut() {
+ o.insert("entities".into(), Value::Array(out));
+ }
+ sketch_store::write(&mut doc, id, sk)?;
+ *s.doc_mut() = doc;
+ Ok(params)
+}
+
/// Add one link from `src` to the active sketch and report it.
fn one_link(s: &mut Session, cmd: &str, kind: LinkKind, src: LinkSource) -> Result<Value> {
let id = sketch_store::active(s).ok_or_else(|| EngineError::Other("no sketch is being edited".into()))?;
diff --git a/crates/engine/src/cmd/sketch_ux_tests.rs b/crates/engine/src/cmd/sketch_ux_tests.rs
index 589dd348f3..691dd6a374 100644
--- a/crates/engine/src/cmd/sketch_ux_tests.rs
+++ b/crates/engine/src/cmd/sketch_ux_tests.rs
@@ -1983,3 +1983,50 @@ fn a_changed_length_dimension_keeps_its_first_point() {
run(&mut s, "parameters.change", json!({"name": width, "expression": "60 mm"}));
assert!((at(&s, "p1").x + 30.0).abs() < 1e-6 && (at(&s, "p2").x - 30.0).abs() < 1e-6, "{:?} {:?}", at(&s, "p1"), at(&s, "p2"));
}
+
+/// #7912: a dimension can measure a model edge: the edge is projected into the sketch and the
+/// dimension measures the distance from the sketch's point to it.
+#[test]
+fn a_dimension_measures_a_model_edge() {
+ let mut s = Session::default();
+ // A sheet-metal base flange: a 100 x 50 plate whose front edge runs along y = 0.
+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Base"}));
+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [100, 50]}));
+ run(&mut s, "sketch.finish", json!({}));
+ run(&mut s, "sheet.flange", json!({"sketch": "Base", "body_name": "Flange"}));
+ // A sketch with a point 25 above the flange's front edge.
+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Near"}));
+ let point = run(&mut s, "sketch.point", json!({"point": [50, 25]}))["point"].as_str().unwrap().to_string();
+ let out = run(&mut s, "sketch.dimension", json!({"entities": [point, {"edge": [50, 0, 0], "body": "Flange"}]}));
+ assert!((out["measured"].as_f64().unwrap() - 25.0).abs() < 1e-6, "the distance to the edge: {out}");
+ // The edge is projected into the sketch, and the dimension measures that projection.
+ let sk = sketch(&s);
+ assert_eq!(sk.links.len(), 1, "{:?}", sk.links);
+}
+
+/// #7912: a dimension refuses a long list of entities before projecting any of them, so one
+/// request cannot make the engine resolve thousands of model edges.
+#[test]
+fn a_dimension_refuses_a_long_list_of_entities() {
+ // The most entities one call may project (the engine's `MAX_PROJECTED_ENTITIES`).
+ const MAX_PROJECTED: usize = 1_000;
+ let mut s = Session::default();
+ // A sheet-metal base flange: a 100 x 50 plate whose front edge runs along y = 0.
+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Base"}));
+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [100, 50]}));
+ run(&mut s, "sketch.finish", json!({}));
+ run(&mut s, "sheet.flange", json!({"sketch": "Base", "body_name": "Flange"}));
+ // A sketch with a point 25 above the flange's front edge.
+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Near"}));
+ let point = run(&mut s, "sketch.point", json!({"point": [50, 25]}))["point"].as_str().unwrap().to_string();
+ // More entities than a call may project, every one of them a model edge to project.
+ let mut entities = vec![json!(point)];
+ for _ in 0..MAX_PROJECTED {
+ entities.push(json!({"edge": [50, 0, 0], "body": "Flange"}));
+ }
+ let before = serde_json::to_value(&s.doc).unwrap();
+ let error = s.execute("sketch.dimension", &json!({"entities": entities})).unwrap_err();
+ assert!(error.to_string().contains("at most"), "{error}");
+ // The refused request leaves the design as it was.
+ assert_eq!(serde_json::to_value(&s.doc).unwrap(), before);
+}
diff --git a/crates/ui-egui/src/dim_view.rs b/crates/ui-egui/src/dim_view.rs
index 383d6e1591..e53ae0d680 100644
--- a/crates/ui-egui/src/dim_view.rs
+++ b/crates/ui-egui/src/dim_view.rs
@@ -104,7 +104,7 @@ impl DimensionDraft {
}
fn params(&self, expr: &str) -> serde_json::Value {
// The first dimension of a sketch scales it rather than distorting it (#1365).
- let mut params = json!({"entities": self.entities, "value": expr, "scale_sketch": true});
+ let mut params = json!({"entities": entities_value(&self.entities), "value": expr, "scale_sketch": true});
if let Some(at) = self.at {
params["text_at"] = json!([at.x, at.y]);
}
@@ -149,7 +149,7 @@ pub fn begin_dimension(app: &mut SolveApp, entities: Vec<String>, at: Vec2) -> R
let (param, expr, draft) = dimension_draft(app, entities, Some(at))?;
if draft.driven {
PLACEMENT.with(|preview| *preview.borrow_mut() = None);
- app.run("sketch.dimension", json!({"entities": draft.entities, "text_at": [at.x, at.y], "driven": true}))?;
+ app.run("sketch.dimension", json!({"entities": entities_value(&draft.entities), "text_at": [at.x, at.y], "driven": true}))?;
app.set_status(crate::i18n::tr("sketch.dimension_added_driven"), false);
return Ok(());
}
@@ -237,6 +237,18 @@ fn reevaluate(app: &SolveApp, draft: &mut DimensionDraft, expr: &str) {
}
}
+/// The entities a dimension measures, as the command takes them: a sketch entity by its id, a
+/// model edge or vertex by its reference (#7912), read back from the pick's text as the
+/// constraint tools do (#6348).
+fn entities_value(entities: &[String]) -> serde_json::Value {
+ serde_json::Value::Array(
+ entities
+ .iter()
+ .map(|entity| serde_json::from_str(entity).ok().filter(serde_json::Value::is_object).unwrap_or_else(|| json!(entity)))
+ .collect(),
+ )
+}
+
fn dimension_draft(app: &SolveApp, entities: Vec<String>, at: Option<Vec2>) -> Result<(String, String, DimensionDraft), String> {
let sketch = app.session.active_sketch.ok_or("Edit a sketch to add a dimension")?;
if entities.is_empty() || entities.len() > 2 || at.is_some_and(|at| !at.x.is_finite() || !at.y.is_finite()) {
@@ -251,7 +263,7 @@ fn dimension_draft(app: &SolveApp, entities: Vec<String>, at: Option<Vec2>) -> R
/// has no parameter), the parameter's expression, and the scratch session it was added in.
fn draft_of(app: &SolveApp, sketch: u64, entities: &[String], at: Option<Vec2>, driven: bool) -> Result<(String, String, DimensionDraft), String> {
let mut scratch = app.session.scratch();
- let mut params = json!({"entities": entities, "driven": driven});
+ let mut params = json!({"entities": entities_value(entities), "driven": driven});
if let Some(at) = at {
params["text_at"] = json!([at.x, at.y]);
}
diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs
index 4eca51a7b2..24cd85a7e9 100644
--- a/crates/ui-egui/src/tools.rs
+++ b/crates/ui-egui/src/tools.rs
@@ -388,15 +388,29 @@ pub fn on_click(app: &mut SolveApp, proj: &Proj, pos: Pos2, shift: bool) {
})
})
});
- let hit = midpoint.as_deref().and_then(|id| id.strip_prefix("mid:")).map(|id| (id.to_string(), true, true)).or_else(|| {
- hits.iter().find_map(|h| match h {
- Hit::SketchPoint { sketch, id, .. } if Some(*sketch) == app.session.active_sketch => Some((id.clone(), false, true)),
- Hit::SketchCurve { sketch, id, straight, .. } if Some(*sketch) == app.session.active_sketch => {
- Some((id.clone(), true, *straight))
- }
- _ => None,
+ let hit = midpoint
+ .as_deref()
+ .and_then(|id| id.strip_prefix("mid:"))
+ .map(|id| (id.to_string(), true, true))
+ .or_else(|| {
+ hits.iter().find_map(|h| match h {
+ Hit::SketchPoint { sketch, id, .. } if Some(*sketch) == app.session.active_sketch => Some((id.clone(), false, true)),
+ Hit::SketchCurve { sketch, id, straight, .. } if Some(*sketch) == app.session.active_sketch => {
+ Some((id.clone(), true, *straight))
+ }
+ _ => None,
+ })
})
- });
+ .or_else(|| {
+ // With nothing of the sketch under the cursor, a body's edge or vertex may be
+ // measured too (#7912): the command projects it into the sketch. An edge is a
+ // length of its own; a vertex waits for the entity it is measured against.
+ hits.iter().find_map(|h| match h {
+ Hit::Edge { .. } => crate::sketch_tools::model_ref(app, h).map(|r| (r.to_string(), true, false)),
+ Hit::Vertex { .. } => crate::sketch_tools::model_ref(app, h).map(|r| (r.to_string(), false, false)),
+ _ => None,
+ })
+ });
let fresh = |tool: &Tool, id: &String| !tool.picks.contains(id) && tool.picks.len() < 2;
// Before a new dimension is under way, a click on an existing one edits its value;
// the tool stays on for the next dimension.