Skip to content

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

Sketch: construction lines with a length (#10258) (#10427)

kaltenbrunnermarkus9d01f6e00509
diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs
index 0064bc9b55..46425de782 100644
--- a/crates/engine/src/cmd/mod.rs
+++ b/crates/engine/src/cmd/mod.rs
@@ -46,7 +46,10 @@ pub use file::open_steps::OpenSteps;
pub use join_pieces::{Addition, addition};
pub use sketch::dimension_roles;
pub(crate) use sketch::face::face_pick_form;
-pub use sketch_construction::{ConstructionLine, construction_line_choice, construction_line_mode, construction_line_solutions};
+pub use sketch_construction::{
+ ConstructionLine, construction_line_choice, construction_line_mode, construction_line_solutions, construction_line_takes_length,
+ construction_segment,
+};
pub use sketch_create::tangent_arc_preview;
pub use sketch_import::drawing_import_command;
pub use sketch_modify::{extend_arc_preview, extend_preview, trim_piece};
diff --git a/crates/engine/src/cmd/sketch_construction.rs b/crates/engine/src/cmd/sketch_construction.rs
index bac2317242..2d91ceec0f 100644
--- a/crates/engine/src/cmd/sketch_construction.rs
+++ b/crates/engine/src/cmd/sketch_construction.rs
@@ -1,4 +1,5 @@
-//! Fast infinite reference lines. Preview and creation use the same analytic solutions.
+//! Fast reference lines, infinite or with a length (#10258). Preview and creation use the same
+//! analytic solutions.
use serde_json::{Value, json};
use solidcraft_geom::{Seg2, Vec2};
@@ -23,7 +24,7 @@ macro_rules! variant {
.enabled(in_sketch)
.contract(&CONTRACT)
.output(output_schema_for::<ConstructionLineResult>)
- .params(concat!("Infinite construction line, ", $mode, ". at: point; through?: second point; curve?, curve2?: sketch references; angle?: degrees from sketch X; near?: solution selector; solution?: zero-based solution index. Tangents take circles/arcs, or an open spline/conic endpoint for tangent_at.", created_doc!()))
+ .params(concat!("Construction line, ", $mode, ". at: point; through?: second point; curve?, curve2?: sketch references; angle?: degrees from sketch X; near?: solution selector, and the side a line with a length runs towards; solution?: zero-based solution index; length?: a segment of this length from `at`, held by a length dimension, instead of an infinite line (horizontal, vertical, angle, parallel, perpendicular). Tangents take circles/arcs, or an open spline/conic endpoint for tangent_at.", created_doc!()))
};
}
@@ -54,6 +55,19 @@ impl ConstructionLine {
}
}
+/// The methods that take a `length`: the ones whose line starts at `at` with a known direction.
+pub fn construction_line_takes_length(mode: &str) -> bool {
+ matches!(mode, "horizontal" | "vertical" | "angle" | "parallel" | "perpendicular")
+}
+
+/// The two ends of a construction line cut to `length` from its start: along its direction, or
+/// the other way when `near` lies behind the start. The preview draws exactly what is created.
+pub fn construction_segment(line: ConstructionLine, length: f64, near: Option<Vec2>) -> (Vec2, Vec2) {
+ let behind = near.is_some_and(|q| (q - line.start).dot(line.direction) < 0.0);
+ let direction = if behind { -line.direction } else { line.direction };
+ (line.start, line.start + direction * length)
+}
+
/// The method belonging to an interactive command. The generic command defaults to two points.
pub fn construction_line_mode(id: &str) -> Option<&str> {
if id == CMD { Some("free") } else { id.strip_prefix("sketch.construction_line.") }
@@ -277,6 +291,21 @@ fn run(s: &mut Session, p: &Value, default_mode: &str) -> Result<Value> {
} else {
None
};
+ let length = match p.get("length") {
+ None | Some(Value::Null) => None,
+ Some(_) if !construction_line_takes_length(mode) => {
+ return Err(bad(CMD, "`length` is for the horizontal, vertical, angle, parallel and perpendicular methods"));
+ }
+ Some(_) => {
+ let e = expr(&p, "length").ok_or_else(|| bad(CMD, "`length` must be a length or expression"))?;
+ let e = doc.with_design_unit(e.as_str(), solidcraft_doc::expr::Kind::Length);
+ let value = doc.eval(&e, solidcraft_doc::expr::Kind::Length).map_err(|e| bad(CMD, format!("length: {e}")))?;
+ if !(value > 1e-9 && value < 1e8) {
+ return Err(bad(CMD, "length must be positive"));
+ }
+ Some((e, value))
+ }
+ };
let solutions = construction_line_solutions(sk, &params, mode)?;
let choice = construction_line_choice(&solutions, &params)?;
let chosen = solutions.get(choice).ok_or_else(|| bad(CMD, "no solution"))?;
@@ -294,10 +323,14 @@ fn run(s: &mut Session, p: &Value, default_mode: &str) -> Result<Value> {
} else {
at.idx()
};
- let end = through.as_ref().map_or(chosen.start + chosen.direction * 10.0, |q| q.pos());
- let l = sk.add_line(chosen.start, end, start_ref, through.as_ref().and_then(|q| q.idx()), None)?;
+ let near = p.get("near").and_then(vec2);
+ let (start, end) = match &length {
+ Some((_, value)) => construction_segment(*chosen, *value, near),
+ None => (chosen.start, through.as_ref().map_or(chosen.start + chosen.direction * 10.0, |q| q.pos())),
+ };
+ let l = sk.add_line(start, end, start_ref, through.as_ref().and_then(|q| q.idx()), None)?;
if let Some(c) = sk.curves.get_mut(l) {
- c.infinite = true;
+ c.infinite = length.is_none();
c.construction = true;
}
let mut cons = Vec::new();
@@ -314,6 +347,11 @@ fn run(s: &mut Session, p: &Value, default_mode: &str) -> Result<Value> {
let parameter = angle_expression.map(|e| doc.new_model_param(&e, "deg"));
cons.push(sk.add_constraint(k, parameter)?);
}
+ if let Some((e, value)) = &length {
+ let unit = solidcraft_doc::expr::length_unit_or_mm(&doc.units).to_string();
+ let parameter = doc.new_model_param(e, &unit);
+ cons.push(sk.add_constraint(ConstraintKind::Length { l, value: *value }, Some(parameter))?);
+ }
if let ("tangent_two", Some(b)) = (mode, second) {
cons.push(add_c(sk, ConstraintKind::Tangent { a: l, b })?);
}
diff --git a/crates/engine/src/cmd/sketch_infinite_tests.rs b/crates/engine/src/cmd/sketch_infinite_tests.rs
index 85f30fb002..a63bb413a2 100644
--- a/crates/engine/src/cmd/sketch_infinite_tests.rs
+++ b/crates/engine/src/cmd/sketch_infinite_tests.rs
@@ -57,6 +57,63 @@ fn construction_line_methods_make_infinite_lines_with_direction_constraints() {
assert!(s.execute("sketch.construction_line", &json!({"mode": "parallel", "at": [0, 0], "curve": "missing"})).is_err());
}
+#[test]
+fn construction_lines_with_a_length_are_segments_held_by_a_dimension() {
+ let mut s = new_sketch();
+ run(&mut s, "sketch.line", json!({"points": [[0, 0], [3, 4]], "ids": ["reference"], "infer": false}));
+ for (mode, near, expected) in [
+ ("horizontal", json!([20, 10]), Vec2::new(1.0, 0.0)),
+ ("horizontal", json!([0, 10]), Vec2::new(-1.0, 0.0)),
+ ("vertical", json!([10, 0]), Vec2::new(0.0, -1.0)),
+ ("angle", json!([20, 20]), Vec2::new(0.5, 3.0_f64.sqrt() / 2.0)),
+ ("parallel", json!([20, 20]), Vec2::new(0.6, 0.8)),
+ ("perpendicular", json!([0, 20]), Vec2::new(-0.8, 0.6)),
+ ] {
+ let p = json!({"mode": mode, "at": [10, 10], "curve": "reference", "angle": 60, "length": 25, "near": near});
+ let out = run(&mut s, "sketch.construction_line", p);
+ let sk = sketch(&s);
+ let c = curve(&sk, out["curves"][0].as_str().unwrap());
+ assert!(c.construction && !c.infinite, "{mode}: a construction segment");
+ let CurveKind::Line { a, b } = c.kind else { panic!("expected a line") };
+ let (a, b) = (sk.point(a).unwrap(), sk.point(b).unwrap());
+ assert!(a.dist(Vec2::new(10.0, 10.0)) < 1e-6, "{mode}: starts at `at`");
+ assert!(((b - a).len() - 25.0).abs() < 1e-6, "{mode}: {:?}", b - a);
+ assert!((b - a).normalized().unwrap().dist(expected) < 1e-6, "{mode} towards {near}: {:?}", b - a);
+ assert_eq!(out["constraints"].as_array().unwrap().len(), 2, "{mode}: direction and length");
+ assert!(
+ sk.constraints.iter().any(|k| matches!(k.kind, solidcraft_sketch::ConstraintKind::Length { value, .. } if (value - 25.0).abs() < 1e-9))
+ );
+ }
+ // The length is a dimension: it follows its parameter, and the line keeps its direction.
+ run(&mut s, "parameters.add", json!({"name": "rib", "expression": "40 mm"}));
+ let out = run(&mut s, "sketch.construction_line.parallel", json!({"at": [0, 10], "curve": "reference", "length": "rib"}));
+ let id = out["curves"][0].as_str().unwrap().to_string();
+ run(&mut s, "parameters.change", json!({"name": "rib", "expression": "15 mm"}));
+ let sk = sketch(&s);
+ let CurveKind::Line { a, b } = curve(&sk, &id).kind else { panic!("line") };
+ let v = sk.point(b).unwrap() - sk.point(a).unwrap();
+ assert!((v.len() - 15.0).abs() < 1e-6 && v.cross(Vec2::new(0.6, 0.8)).abs() < 1e-6, "{v:?}");
+ // It is saved as a finite construction line.
+ let back = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap();
+ let c = curve(back.sketch(s.active_sketch.unwrap()).unwrap(), &id);
+ assert!(c.construction && !c.infinite);
+ // Refused, leaving the design as it was: bad lengths, and the methods without a start and
+ // direction of their own.
+ run(&mut s, "sketch.circle.center", json!({"center": [50, 0], "radius": 5, "id": "c"}));
+ for p in [
+ json!({"mode": "horizontal", "at": [0, 0], "length": 0}),
+ json!({"mode": "horizontal", "at": [0, 0], "length": -3}),
+ json!({"mode": "horizontal", "at": [0, 0], "length": "nonsense +"}),
+ json!({"mode": "horizontal", "at": [0, 0], "length": true}),
+ json!({"at": [0, 0], "through": [5, 5], "length": 10}),
+ json!({"mode": "tangent_external", "at": [70, 0], "curve": "c", "length": 10}),
+ ] {
+ let before = s.doc.to_json();
+ assert!(s.execute("sketch.construction_line", &p).is_err(), "{p}");
+ assert_eq!(s.doc.to_json(), before, "{p}");
+ }
+}
+
#[test]
fn construction_angle_keeps_its_parameter_expression() {
let mut s = new_sketch();
diff --git a/crates/engine/src/schema/sketch_create.rs b/crates/engine/src/schema/sketch_create.rs
index 1430694808..f482d9adb2 100644
--- a/crates/engine/src/schema/sketch_create.rs
+++ b/crates/engine/src/schema/sketch_create.rs
@@ -4,9 +4,9 @@ use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
-use super::types::{AngleExpr, SketchRef, present};
+use super::types::{AngleExpr, LengthExpr, SketchRef, present};
-/// Create an infinite reference line in the active sketch.
+/// Create a reference line in the active sketch: infinite, or a segment of a given length.
#[derive(Debug, Deserialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct ConstructionLineParams {
@@ -16,7 +16,8 @@ pub struct ConstructionLineParams {
pub at: Value,
/// Second point of a two-point construction line.
pub through: Option<Value>,
- /// Point used to select the closest solution when several exist.
+ /// Point used to select the closest solution when several exist; for a line with a
+ /// `length`, the side of `at` it runs towards.
pub near: Option<[f64; 2]>,
/// Zero-based index in the deterministic list of solutions.
pub solution: Option<usize>,
@@ -28,6 +29,9 @@ pub struct ConstructionLineParams {
pub alternate: Option<bool>,
/// Direction measured counter-clockwise from sketch X, in degrees.
pub angle: Option<AngleExpr>,
+ /// A segment of this length from `at` instead of an infinite line, held by a length
+ /// dimension. For the horizontal, vertical, angle, parallel and perpendicular methods.
+ pub length: Option<LengthExpr>,
/// The sketch (default: the one being edited).
pub sketch: Option<SketchRef>,
}
diff --git a/crates/engine/src/schema/sketch_create_tests.rs b/crates/engine/src/schema/sketch_create_tests.rs
index e9c69cf505..4c4643fcdc 100644
--- a/crates/engine/src/schema/sketch_create_tests.rs
+++ b/crates/engine/src/schema/sketch_create_tests.rs
@@ -42,7 +42,7 @@ fn construction_line_contracts_and_replies_match() {
use super::{ConstructionLineParams, ConstructionLineResult};
assert_keys(
input_schema_for::<ConstructionLineParams>(),
- &["alternate", "angle", "at", "curve", "curve2", "mode", "near", "sketch", "solution", "through"],
+ &["alternate", "angle", "at", "curve", "curve2", "length", "mode", "near", "sketch", "solution", "through"],
);
let schema = output_schema_for::<ConstructionLineResult>();
let schema = schema.as_value();
@@ -52,6 +52,7 @@ fn construction_line_contracts_and_replies_match() {
("sketch.construction_line", json!({"at":[0,0],"through":[5,5]})),
("sketch.construction_line.horizontal", json!({"at":[0,10]})),
("sketch.construction_line.angle", json!({"at":[10,10],"angle":30})),
+ ("sketch.construction_line.vertical", json!({"at":[20,0],"length":"12 mm","near":[20,-5]})),
] {
let r = s.execute(id, &p).unwrap();
assert!(conforms(schema, schema, &r), "{r}");
diff --git a/docs/book/src/guide/sketching.md b/docs/book/src/guide/sketching.md
index d7bd14053d..98ee944de9 100644
--- a/docs/book/src/guide/sketching.md
+++ b/docs/book/src/guide/sketching.md
@@ -121,6 +121,10 @@ Parallel and perpendicular lines ask for a straight sketch line, then a point;
the reference stays picked so you can place several lines. Right-click clears the current
points and references; Escape ends the tool.
+A command call can cut a horizontal, vertical, angle, parallel or perpendicular construction
+line to a length instead: `length` makes a segment from the point `at`, running towards `near`,
+and adds a length dimension that follows its expression (#10258).
+
Tangents through an external point take a circle or circular arc, the external point, and a
click choosing the desired preview. A common tangent takes two circles/arcs and a click choosing
the solution. Contacts outside an arc's drawn sweep are excluded. A tangent at a curve point