Skip to content

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

Sketch: groundwork for pierce constraints, no UI yet (#3599) (#11388)

Homero Thompson99d96482af7c
diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs
index 9421121265..463f3c1e1d 100644
--- a/crates/engine/src/cmd/sketch.rs
+++ b/crates/engine/src/cmd/sketch.rs
@@ -3910,3 +3910,7 @@ mod redundant_tests;
#[cfg(test)]
#[path = "sketch_symmetry_point_tests.rs"]
mod symmetry_point_tests;
+
+#[cfg(test)]
+#[path = "sketch_pierce_tests.rs"]
+mod pierce_tests;
diff --git a/crates/engine/src/cmd/sketch_constraints.rs b/crates/engine/src/cmd/sketch_constraints.rs
index 287af484dc..ec6b0a5f4e 100644
--- a/crates/engine/src/cmd/sketch_constraints.rs
+++ b/crates/engine/src/cmd/sketch_constraints.rs
@@ -498,6 +498,8 @@ fn anchor(sk: &Sketch, k: &ConstraintKind) -> Option<Vec2> {
PatternPoint { q, center, .. } => pt(center.unwrap_or(q)),
PatternRadius { b, .. } => mid(b),
Coincident { p, .. } | Fix { p } | Midpoint { p, .. } => pt(p),
+ // A pierce is drawn at the point it holds.
+ Pierce { p, .. } => pt(p),
PointOnCurve { p, .. } => pt(p),
HorizontalPoints { p, q } | VerticalPoints { p, q } | Symmetric { p, q, .. } => Some((pt(p)? + pt(q)?) * 0.5),
Horizontal { l } | Vertical { l } => mid(l),
diff --git a/crates/engine/src/cmd/sketch_pierce_tests.rs b/crates/engine/src/cmd/sketch_pierce_tests.rs
new file mode 100644
index 0000000000..53574630e5
--- /dev/null
+++ b/crates/engine/src/cmd/sketch_pierce_tests.rs
@@ -0,0 +1,84 @@
+use serde_json::{Value, json};
+
+use crate::Session;
+
+fn run(s: &mut Session, id: &str, p: Value) -> Value {
+ match s.execute(id, &p) {
+ Ok(v) => v,
+ Err(e) => panic!("{id} {p}: {e}"),
+ }
+}
+
+/// The other sketch: a line on the XZ plane that crosses the XY plane at x = 5.
+fn other_sketch(s: &mut Session) -> u64 {
+ let id = run(s, "sketch.create", json!({"plane": "XZ"}))["sketch"].as_u64().unwrap();
+ run(s, "sketch.line", json!({"points": [[5, -5], [5, 5]], "ids": ["l1"]}));
+ run(s, "sketch.finish", json!({}));
+ id
+}
+
+/// The point of the sketch being edited, by id.
+fn point(si: &Value, id: &str) -> Value {
+ si["points"].as_array().unwrap().iter().find(|p| p["id"] == id).unwrap().clone()
+}
+
+/// A Pierce constraint holds a point of this sketch where a curve of another sketch crosses
+/// this sketch's plane (#3599): the point of the XY sketch sits on the XZ sketch's line.
+#[test]
+#[ignore = "the engine command sketch.constraint.pierce is not implemented yet"]
+fn a_pierce_constraint_holds_a_point_where_another_sketches_curve_crosses_this_plane() {
+ let mut s = Session::default();
+ let other = other_sketch(&mut s);
+ run(&mut s, "sketch.create", json!({"plane": "XY"}));
+ run(&mut s, "sketch.point", json!({"point": [20, 20], "id": "p1"}));
+
+ let r = run(&mut s, "sketch.constraint.pierce", json!({"point": "p1", "curve": {"sketch": other, "curve": "l1"}}));
+ assert!(r["constraint"].is_string(), "{r}");
+
+ // The point of this sketch now sits where the other sketch's line crosses this plane.
+ let si = run(&mut s, "sketch.inspect", json!({}));
+ let p = point(&si, "p1");
+ assert!((p["at"][0].as_f64().unwrap() - 5.0).abs() < 1e-9, "{p}");
+ assert!(p["at"][1].as_f64().unwrap().abs() < 1e-9, "{p}");
+ assert!((p["world"][2].as_f64().unwrap()).abs() < 1e-9, "{p}");
+
+ // The constraint is a Pierce one, named as such.
+ let c = si["constraints"].as_array().unwrap().iter().find(|c| c["name"] == "Pierce").unwrap().clone();
+ assert_eq!(c["type"], "pierce", "{c}");
+ assert_eq!(c["sketch"], other, "{c}");
+ assert_eq!(c["curve"], "l1", "{c}");
+
+ // The point is held there, not free to be dragged off the curve.
+ assert_eq!(p["fixed"], true, "{p}");
+}
+
+/// The point follows the other sketch: the curve moves, the pierced point moves with it.
+#[test]
+#[ignore = "the engine command sketch.constraint.pierce is not implemented yet"]
+fn a_pierced_point_follows_the_curve_of_the_other_sketch() {
+ let mut s = Session::default();
+ let other = other_sketch(&mut s);
+ run(&mut s, "sketch.create", json!({"plane": "XY"}));
+ run(&mut s, "sketch.point", json!({"point": [20, 20], "id": "p1"}));
+ run(&mut s, "sketch.constraint.pierce", json!({"point": "p1", "curve": {"sketch": other, "curve": "l1"}}));
+
+ // The other sketch's line moves across this plane: the pierced point follows it.
+ run(&mut s, "sketch.edit", json!({"sketch": other}));
+ run(&mut s, "sketch.line", json!({"points": [[7, -5], [7, 5]], "ids": ["l2"]}));
+ run(&mut s, "sketch.finish", json!({}));
+
+ let si = run(&mut s, "sketch.inspect", json!({"sketch": "XY"}));
+ let p = point(&si, "p1");
+ assert!((p["at"][0].as_f64().unwrap() - 7.0).abs() < 1e-9, "{p}");
+}
+
+/// A Pierce constraint needs a curve of another sketch: anything else is refused.
+#[test]
+#[ignore = "the engine command sketch.constraint.pierce is not implemented yet"]
+fn a_pierce_constraint_needs_a_curve_of_another_sketch() {
+ let mut s = Session::default();
+ run(&mut s, "sketch.create", json!({"plane": "XY"}));
+ run(&mut s, "sketch.point", json!({"point": [20, 20], "id": "p1"}));
+ let e = s.execute("sketch.constraint.pierce", &json!({"point": "p1", "curve": {"sketch": "p1"}})).unwrap_err().to_string();
+ assert!(e.contains("curve"), "{e}");
+}
diff --git a/crates/sketch/src/lib.rs b/crates/sketch/src/lib.rs
index 41ddaa1893..9912ca28d5 100644
--- a/crates/sketch/src/lib.rs
+++ b/crates/sketch/src/lib.rs
@@ -33,6 +33,7 @@ mod offset;
mod offset_topology;
mod pattern;
mod periodic;
+pub mod pierce;
mod profiles;
#[cfg(feature = "solver-profiling")]
pub mod profiling;
diff --git a/crates/sketch/src/model.rs b/crates/sketch/src/model.rs
index 91f7955549..2503482d77 100644
--- a/crates/sketch/src/model.rs
+++ b/crates/sketch/src/model.rs
@@ -1,5 +1,5 @@
use serde::{Deserialize, Serialize};
-use solidcore_record::{Seg2, Vec2, Vec3};
+use solidcore_record::{Plane, Seg2, Vec2, Vec3};
use solidcraft_geom::Aabb2;
use solidcraft_geom::prelude::*;
@@ -344,6 +344,21 @@ pub enum ConstraintKind {
Fix {
p: usize,
},
+ /// A pierce (#3599): the point `p` of this sketch is held where the curve `curve` of the
+ /// sketch `sketch` crosses the plane of this sketch.
+ Pierce {
+ /// The point of this sketch the pierce holds.
+ p: usize,
+ /// The sketch the pierced curve belongs to.
+ sketch: u64,
+ /// The id of the pierced curve in that sketch.
+ curve: String,
+ /// The plane of this sketch, in world coordinates: the curve is cut against it.
+ plane: Plane,
+ /// The pierced curve, in world coordinates: it crosses the plane where it changes
+ /// side.
+ world: Vec<Vec3>,
+ },
// Dimensions (driving).
Distance {
p: usize,
@@ -534,6 +549,7 @@ impl ConstraintKind {
Midpoint { .. } => "MidPoint",
Symmetric { .. } => "Symmetry",
Fix { .. } => "Fix",
+ Pierce { .. } => "Pierce",
Distance { .. }
| DistanceX { .. }
| DistanceY { .. }
@@ -579,6 +595,8 @@ impl ConstraintKind {
CircleCircleDistance { a, b, .. } => (vec![], vec![a, b]),
Symmetric { p, q, l } => (vec![p, q], vec![l]),
Fix { p } => (vec![p], vec![]),
+ // The pierced curve belongs to another sketch: it has no index here.
+ Pierce { p, .. } => (vec![p], vec![]),
Smooth { a, b } => (vec![], vec![a, b]),
ArcLength { c, .. } => (vec![], vec![c]),
LinearDiameter { p, l, .. } => (vec![p], vec![l]),
@@ -658,6 +676,9 @@ impl ConstraintKind {
fc(l);
}
Fix { p } => fp(p),
+ // Only the point of this sketch is renumbered; the pierced curve is another
+ // sketch's, named by id.
+ Pierce { p, .. } => fp(p),
Smooth { a, b } => {
fc(a);
fc(b);
@@ -1000,6 +1021,15 @@ impl Sketch {
/// same kind on the same entities, in either order where the order doesn't matter.
pub fn same_constraint(&self, kind: &ConstraintKind) -> Option<&str> {
use ConstraintKind::*;
+ // A pierce names a curve of another sketch by id, so its identity is not a pair of
+ // indices: the same point pierced by the same curve of the same sketch.
+ if let Pierce { p, sketch, curve, .. } = kind {
+ return self
+ .constraints
+ .iter()
+ .find(|c| matches!(&c.kind, Pierce { p: q, sketch: s, curve: k, .. } if q == p && s == sketch && k == curve))
+ .map(|c| c.id.as_str());
+ }
let pair = |x: usize, y: usize| if x <= y { (x, y) } else { (y, x) };
let key = |k: &ConstraintKind| -> Option<(u8, usize, usize, usize)> {
Some(match *k {
@@ -1172,6 +1202,11 @@ impl Sketch {
{
return Err(SketchError::Invalid("arc sweep must be nonzero and less than a full turn".into()));
}
+ if let Pierce { plane, world, .. } = k
+ && crate::pierce::pierce_point_world(plane, world).is_none()
+ {
+ return Err(SketchError::Invalid("the pierced curve does not cross this sketch's plane".into()));
+ }
Ok(())
}
@@ -1189,6 +1224,9 @@ impl Sketch {
}
let sizes = self.constraints.iter().any(|c| match c.kind {
ConstraintKind::Fix { .. } | ConstraintKind::PatternPoint { .. } | ConstraintKind::PatternRadius { .. } => true,
+ // A pierce holds its point where another sketch's curve crosses this plane:
+ // scaling the sketch would move it off the crossing.
+ ConstraintKind::Pierce { .. } => true,
ref k => k.is_dimension() && !k.is_angle() && !c.driven,
});
if sizes
@@ -1250,10 +1288,11 @@ impl Sketch {
}
/// Is point `i` held in place: fixed, projected (linked), fixed by a Fix constraint or a
- /// point of a fixed curve.
+ /// point of a fixed curve, or held there by a pierce.
pub fn point_locked(&self, i: usize) -> bool {
self.points.get(i).is_some_and(|p| p.fixed || p.link.is_some())
|| self.constraints.iter().any(|c| c.kind == ConstraintKind::Fix { p: i })
+ || self.constraints.iter().any(|c| matches!(&c.kind, ConstraintKind::Pierce { p, .. } if *p == i))
|| self.curves.iter().any(|c| c.fixed && c.kind.uses(i))
}
@@ -1269,6 +1308,9 @@ impl Sketch {
if let ConstraintKind::Fix { p } = c.kind {
set(p);
}
+ if let ConstraintKind::Pierce { p, .. } = c.kind {
+ set(p);
+ }
}
for c in self.curves.iter().filter(|c| c.fixed) {
for p in c.kind.point_ids() {
diff --git a/crates/sketch/src/pierce.rs b/crates/sketch/src/pierce.rs
new file mode 100644
index 0000000000..6a9eb9f637
--- /dev/null
+++ b/crates/sketch/src/pierce.rs
@@ -0,0 +1,213 @@
+//! The geometry of a pierce: where a curve of another sketch crosses the plane of this one.
+//!
+//! A Pierce constraint (#3599) puts a point of this sketch on a curve of another sketch, at
+//! the point where that curve crosses the plane of this sketch. Each sketch is flat on its
+//! own plane, so the crossing is a question about two planes: the curve of the other sketch
+//! is a polyline in that sketch's own coordinates, and the plane of this sketch cuts it.
+//!
+//! The cut is the one the Project + Coincident workaround already makes in the document
+//! crate (`section_of_polyline` in `crates/doc/src/project.rs`, reached through
+//! `LinkSource::SketchCurve` with `LinkKind::Intersect`): every segment of the world
+//! polyline against the plane. That function lives in the document crate, which is built
+//! above this one, so the cut is repeated here over the same `Plane` and `Vec3` types.
+//!
+//! Conventions:
+//!
+//! - The crossing comes back in the coordinates of *this* sketch: measured from this
+//! sketch's plane origin along this sketch's own axes.
+//! - A curve that crosses the plane more than once gives every crossing, in the order the
+//! curve meets the plane; [`pierce_point`] gives the first of them.
+//! - A curve that never reaches the plane gives no crossing, and so does a curve that lies
+//! in it: such a curve meets the plane everywhere and nowhere, so there is no single
+//! point to pierce (two sketches sharing a plane is a mistake in the relation, not a
+//! degenerate pierce).
+//! - A point of the curve close enough to the plane counts as lying on it, so a curve that
+//! touches the plane at its end pierces there.
+
+use solidcore_record::{Plane, Vec2, Vec3};
+use solidcraft_geom::prelude::*;
+
+/// A point counts as lying on the plane when it is this close to it, as a fraction of how
+/// far the curve reaches from the plane's origin: a curve far from the origin is not judged
+/// by a tolerance meant for a curve near it.
+const REL_TOL: f64 = 1e-9;
+
+/// The points where the curve of another sketch crosses the plane of this one.
+///
+/// `plane` is the plane of this sketch, `curve_plane` the plane of the sketch that owns the
+/// curve, and `curve_points` the points of that curve in the owning sketch's own
+/// coordinates. The crossings come back in the coordinates of this sketch, in the order the
+/// curve meets the plane.
+///
+/// A curve that never reaches the plane gives nothing, and so does a curve that lies in it:
+/// there is no single point where such a curve meets the plane. A curve that crosses the
+/// plane more than once gives every crossing.
+pub fn pierce_points(plane: &Plane, curve_plane: &Plane, curve_points: &[Vec2]) -> Vec<Vec2> {
+ let world: Vec<Vec3> = curve_points.iter().map(|p| curve_plane.to_world(*p)).collect();
+ pierce_points_world(plane, &world)
+}
+
+/// The point where the curve of another sketch crosses the plane of this one.
+///
+/// The first crossing, in the order the curve meets the plane; see [`pierce_points`] for
+/// every crossing, and for the curves that have none.
+pub fn pierce_point(plane: &Plane, curve_plane: &Plane, curve_points: &[Vec2]) -> Option<Vec2> {
+ pierce_points(plane, curve_plane, curve_points).into_iter().next()
+}
+
+/// The points where a curve already in world coordinates crosses the plane of this sketch.
+///
+/// The crossings come back in the coordinates of this sketch, in the order the curve meets
+/// the plane.
+pub fn pierce_points_world(plane: &Plane, curve: &[Vec3]) -> Vec<Vec2> {
+ let tol = tolerance(plane, curve);
+ let mut out: Vec<Vec2> = Vec::new();
+ for w in curve.windows(2) {
+ let (Some(a), Some(b)) = (w.first(), w.get(1)) else { continue };
+ let (ha, hb) = (plane.height(*a), plane.height(*b));
+ let (on_a, on_b) = (ha.abs() <= tol, hb.abs() <= tol);
+ // A segment lying in the plane meets it all along: no single point to give.
+ let p = if on_a && on_b {
+ continue;
+ } else if on_a {
+ *a
+ } else if on_b {
+ *b
+ } else if (ha > 0.0) == (hb > 0.0) {
+ // Both ends on the same side: the segment never meets the plane.
+ continue;
+ } else {
+ a.lerp(*b, ha / (ha - hb))
+ };
+ let local = plane.to_local(p);
+ // A vertex on the plane is the crossing of both of its segments: give it once.
+ if !out.iter().any(|q| q.dist(local) <= tol) {
+ out.push(local);
+ }
+ }
+ out
+}
+
+/// The point where a curve already in world coordinates crosses the plane of this sketch.
+///
+/// The first crossing, in the order the curve meets the plane; see [`pierce_points_world`]
+/// for every crossing, and for the curves that have none.
+pub fn pierce_point_world(plane: &Plane, curve: &[Vec3]) -> Option<Vec2> {
+ pierce_points_world(plane, curve).into_iter().next()
+}
+
+/// How close to the plane a point counts as lying on it.
+fn tolerance(plane: &Plane, curve: &[Vec3]) -> f64 {
+ let reach = curve.iter().fold(0.0_f64, |m, p| m.max((*p - plane.origin).len()));
+ reach.max(1.0) * REL_TOL
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{pierce_point, pierce_point_world, pierce_points, pierce_points_world};
+ use solidcore_record::{Plane, Vec2, Vec3};
+ use solidcraft_geom::prelude::*;
+
+ fn v(x: f64, y: f64) -> Vec2 {
+ Vec2::new(x, y)
+ }
+
+ fn near(a: Vec2, b: Vec2) -> bool {
+ a.dist(b) < 1e-9
+ }
+
+ /// A line of a sketch on the XZ plane, given in that sketch's own coordinates.
+ fn xz_line(a: (f64, f64), b: (f64, f64)) -> Vec<Vec2> {
+ vec![v(a.0, a.1), v(b.0, b.1)]
+ }
+
+ #[test]
+ fn a_line_of_another_sketch_pierces_this_plane() {
+ // A sketch on the XZ plane, a line at x = 5 running from (5, -5) to (5, 5): it
+ // crosses the XY plane (z = 0) at the world point (5, 0, 0), which is (5, 0) here.
+ let p = pierce_point(&Plane::XY, &Plane::XZ, &xz_line((5.0, -5.0), (5.0, 5.0)));
+ assert!(p.is_some_and(|q| near(q, v(5.0, 0.0))), "{p:?}");
+ }
+
+ #[test]
+ fn a_curve_that_already_touches_the_plane_pierces_there() {
+ // The same line, but ending on the plane: the crossing is that end point.
+ let p = pierce_point(&Plane::XY, &Plane::XZ, &xz_line((5.0, -5.0), (5.0, 0.0)));
+ assert!(p.is_some_and(|q| near(q, v(5.0, 0.0))), "{p:?}");
+ }
+
+ #[test]
+ fn a_curve_touching_the_plane_at_a_vertex_pierces_once() {
+ // The vertex on the plane is the crossing of both of its segments, and it is one
+ // point, not two.
+ let pts = pierce_points(&Plane::XY, &Plane::XZ, &xz_line((5.0, -5.0), (5.0, 5.0)));
+ assert_eq!(pts.len(), 1, "{pts:?}");
+ assert!(near(pts[0], v(5.0, 0.0)), "{pts:?}");
+ let p = pierce_point(&Plane::XY, &Plane::XZ, &[v(5.0, -5.0), v(5.0, 0.0), v(5.0, 5.0)]);
+ assert!(p.is_some_and(|q| near(q, v(5.0, 0.0))), "{p:?}");
+ }
+
+ #[test]
+ fn a_curve_that_never_reaches_the_plane_does_not_pierce() {
+ // The same line, but on the other side of the plane: it never crosses it.
+ assert!(pierce_point(&Plane::XY, &Plane::XZ, &xz_line((5.0, 1.0), (5.0, 5.0))).is_none());
+ // A sketch on a parallel plane, ten units above: it never reaches this one.
+ let above = Plane { origin: Vec3::new(0.0, 0.0, 10.0), x: Vec3::X, y: Vec3::Y };
+ assert!(pierce_point(&Plane::XY, &above, &xz_line((5.0, -5.0), (5.0, 5.0))).is_none());
+ }
+
+ #[test]
+ fn a_curve_in_the_same_plane_has_no_single_crossing() {
+ // The curve lies in the plane of this sketch: it meets it everywhere and nowhere,
+ // so there is no point to pierce.
+ assert!(pierce_point(&Plane::XY, &Plane::XY, &[v(0.0, 0.0), v(5.0, 5.0)]).is_none());
+ assert!(pierce_points(&Plane::XY, &Plane::XY, &[v(0.0, 0.0), v(5.0, 5.0)]).is_empty());
+ }
+
+ #[test]
+ fn a_curve_that_crosses_twice_gives_both_crossings() {
+ // A U on the XZ plane, dipping through the XY plane and coming back: two
+ // crossings, the first one is the pierce.
+ let u = [v(0.0, 1.0), v(0.0, -1.0), v(2.0, -1.0), v(2.0, 1.0)];
+ let pts = pierce_points(&Plane::XY, &Plane::XZ, &u);
+ assert_eq!(pts.len(), 2, "{pts:?}");
+ assert!(near(pts[0], v(0.0, 0.0)), "{pts:?}");
+ assert!(near(pts[1], v(2.0, 0.0)), "{pts:?}");
+ let p = pierce_point(&Plane::XY, &Plane::XZ, &u);
+ assert!(p.is_some_and(|q| near(q, v(0.0, 0.0))), "{p:?}");
+ }
+
+ #[test]
+ fn a_point_within_tolerance_of_the_plane_counts_as_on_it() {
+ // An end point a hundredth of a nanometre above the plane is on it: the curve
+ // pierces there.
+ let p = pierce_point(&Plane::XY, &Plane::XZ, &xz_line((5.0, -5.0), (5.0, -1e-10)));
+ assert!(p.is_some_and(|q| near(q, v(5.0, 0.0))), "{p:?}");
+ // A thousandth of a unit off the plane is not on it: the curve never reaches it.
+ assert!(pierce_point(&Plane::XY, &Plane::XZ, &xz_line((5.0, -5.0), (5.0, -1e-3))).is_none());
+ }
+
+ #[test]
+ fn the_crossing_is_in_this_sketches_coordinates() {
+ // The same world crossing, measured from another plane origin: (5, 0, 0) is
+ // (3, -3) in a plane whose origin is (2, 3, 0).
+ let shifted = Plane { origin: Vec3::new(2.0, 3.0, 0.0), x: Vec3::X, y: Vec3::Y };
+ let p = pierce_point(&shifted, &Plane::XZ, &xz_line((5.0, -5.0), (5.0, 5.0)));
+ assert!(p.is_some_and(|q| near(q, v(3.0, -3.0))), "{p:?}");
+ }
+
+ #[test]
+ fn a_curve_with_no_length_does_not_pierce() {
+ assert!(pierce_point(&Plane::XY, &Plane::XZ, &[]).is_none());
+ assert!(pierce_point(&Plane::XY, &Plane::XZ, &[v(5.0, 0.0)]).is_none());
+ }
+
+ #[test]
+ fn a_world_curve_pierces_the_plane() {
+ // The same geometry, given straight in world coordinates.
+ let world = [Vec3::new(5.0, 0.0, 5.0), Vec3::new(5.0, 0.0, -5.0)];
+ let p = pierce_point_world(&Plane::XY, &world);
+ assert!(p.is_some_and(|q| near(q, v(5.0, 0.0))), "{p:?}");
+ assert_eq!(pierce_points_world(&Plane::XY, &world).len(), 1);
+ }
+}
diff --git a/crates/sketch/src/solver.rs b/crates/sketch/src/solver.rs
index a6e2de8c2c..0ab8fda944 100644
--- a/crates/sketch/src/solver.rs
+++ b/crates/sketch/src/solver.rs
@@ -461,6 +461,25 @@ fn wrap_angle(a: f64) -> f64 {
a
}
+/// Put every pierced point where the curve of the other sketch crosses this sketch's plane
+/// (#3599). The point is held there (it is locked), so the solve keeps it: the crossing is a
+/// fact about the two sketches, not something the iteration works out.
+fn place_pierced_points(sk: &mut Sketch) {
+ let places: Vec<(usize, Vec2)> = sk
+ .constraints
+ .iter()
+ .filter_map(|c| match &c.kind {
+ ConstraintKind::Pierce { p, plane, world, .. } => crate::pierce::pierce_point_world(plane, world).map(|at| (*p, at)),
+ _ => None,
+ })
+ .collect();
+ for (p, at) in places {
+ if let Some(point) = sk.points.get_mut(p) {
+ point.pos = at;
+ }
+ }
+}
+
/// Distance from `p` to the infinite line through `a`, `b` (signed by side).
fn line_dist(p: Vec2, a: Vec2, b: Vec2) -> f64 {
let d = b - a;
@@ -595,6 +614,10 @@ fn residuals(s: &State, k: &ConstraintKind, out: &mut Vec<f64>) {
out.push((qq - pp).dot(dir) / len);
}
Fix { .. } => {}
+ // A pierce holds its point where the other sketch's curve crosses this sketch's
+ // plane: the point is placed there before the solve and kept there (it is
+ // locked), so the constraint adds no rows of its own.
+ Pierce { .. } => {}
// A distance within convergence tolerance of zero means coincidence: two
// component rows keep both directions constrained even when the points meet.
Distance { p, q, value } if value.abs() <= TOL => {
@@ -973,7 +996,7 @@ fn block_refs(sk: &Sketch, b: &Block) -> Vec<Ref> {
Tangent { a, b } => tangent(a, b).to_vec(),
Smooth { a, b } => vec![C(a), C(b)],
Symmetric { p, q, l } => vec![P(p), P(q), L(l)],
- Fix { .. } | OffsetDistance { .. } => vec![],
+ Fix { .. } | OffsetDistance { .. } | Pierce { .. } => vec![],
},
Block::TangentAt(_, k, p) => match **k {
ConstraintKind::Tangent { a, b } if freeform(a) || freeform(b) => vec![P(*p), C(a), C(b)],
@@ -2693,6 +2716,7 @@ fn solve_inner(
profiling::count(|c| c.solve_calls = c.solve_calls.saturating_add(1));
sk.prune_patterns();
sk.refresh_pattern_shapes();
+ place_pierced_points(sk);
let mut orientation_before = Vec::new();
for constraint in &sk.constraints {
if !constraint.driven
diff --git a/crates/sketch/src/tests.rs b/crates/sketch/src/tests.rs
index fbc85c223d..37661bd5c0 100644
--- a/crates/sketch/src/tests.rs
+++ b/crates/sketch/src/tests.rs
@@ -1,7 +1,7 @@
use solidcraft_geom::prelude::*;
use std::f64::consts::{FRAC_PI_2, PI};
-use solidcore_record::{Seg2, Vec2};
+use solidcore_record::{Plane, Seg2, Vec2, Vec3};
use crate::*;
@@ -1653,6 +1653,67 @@ fn rounded_rectangles_sharing_their_sides_leave_every_profile_closed() {
}
}
+/// A Pierce constraint holds a point of this sketch where a curve of another sketch crosses
+/// the plane of this one (#3599): the point of the XY sketch sits where the XZ sketch's line
+/// crosses it, and stays there.
+#[test]
+fn a_pierce_constraint_holds_its_point_where_the_other_sketches_curve_crosses_this_plane() {
+ let mut sk = Sketch::new();
+ let p = sk.add_point(v(20.0, 20.0), None).unwrap();
+ // The other sketch's line on the XZ plane: it crosses the XY plane at (5, 0, 0).
+ let world = vec![Vec3::new(5.0, 0.0, -5.0), Vec3::new(5.0, 0.0, 5.0)];
+ sk.add_constraint(ConstraintKind::Pierce { p, sketch: 7, curve: "l1".into(), plane: Plane::XY, world }, None).unwrap();
+ let report = solve(&mut sk);
+ assert!(report.ok(), "{report:?}");
+ let at = sk.points[p].pos;
+ assert!((at.x - 5.0).abs() < 1e-9 && at.y.abs() < 1e-9, "{at:?}");
+ // The point sits in the plane: nothing off it.
+ assert!(Plane::XY.height(Plane::XY.to_world(at)).abs() < 1e-9);
+}
+
+/// The point follows the curve of the other sketch: the curve moves across this plane, the
+/// pierced point moves with it.
+#[test]
+fn a_pierced_point_follows_the_curve_of_the_other_sketch() {
+ let mut sk = Sketch::new();
+ let p = sk.add_point(v(20.0, 20.0), None).unwrap();
+ let world = vec![Vec3::new(5.0, 0.0, -5.0), Vec3::new(5.0, 0.0, 5.0)];
+ sk.add_constraint(ConstraintKind::Pierce { p, sketch: 7, curve: "l1".into(), plane: Plane::XY, world }, None).unwrap();
+ solve(&mut sk);
+ assert!((sk.points[p].pos.x - 5.0).abs() < 1e-9, "{:?}", sk.points[p].pos);
+
+ // The other sketch's line moves across this plane.
+ if let ConstraintKind::Pierce { world, .. } = &mut sk.constraints[0].kind {
+ *world = vec![Vec3::new(7.0, 0.0, -5.0), Vec3::new(7.0, 0.0, 5.0)];
+ }
+ solve(&mut sk);
+ assert!((sk.points[p].pos.x - 7.0).abs() < 1e-9, "{:?}", sk.points[p].pos);
+}
+
+/// A pierce needs a curve that meets this sketch's plane: a curve that never crosses it has
+/// no point to pierce, and the constraint is refused.
+#[test]
+fn a_pierce_constraint_whose_curve_never_crosses_the_plane_is_refused() {
+ let mut sk = Sketch::new();
+ let p = sk.add_point(v(20.0, 20.0), None).unwrap();
+ // A line on the XZ plane that stays above the XY plane: it never reaches it.
+ let world = vec![Vec3::new(5.0, 0.0, 1.0), Vec3::new(5.0, 0.0, 5.0)];
+ let e = sk.add_constraint(ConstraintKind::Pierce { p, sketch: 7, curve: "l1".into(), plane: Plane::XY, world }, None).unwrap_err().to_string();
+ assert!(e.contains("cross"), "{e}");
+}
+
+/// A pierce renumbers with the sketch: its point is renumbered, the curve of the other
+/// sketch is not (it has no index here).
+#[test]
+fn a_pierce_constraint_remaps_its_point() {
+ let mut kind = ConstraintKind::Pierce { p: 3, sketch: 7, curve: "l1".into(), plane: Plane::XY, world: vec![] };
+ assert!(kind.remap(&|i| Some(i + 1), &|_| Some(0)));
+ assert!(matches!(kind, ConstraintKind::Pierce { p: 4, .. }), "{kind:?}");
+ // A point with no new number leaves the constraint partly renumbered: it must go.
+ let mut kind = ConstraintKind::Pierce { p: 3, sketch: 7, curve: "l1".into(), plane: Plane::XY, world: vec![] };
+ assert!(!kind.remap(&|_| None, &|_| Some(0)));
+}
+
/// A drag step that cannot succeed gives up once the iteration has stalled (#6606). Holding
/// the two right corners of a rectangle further apart than its dimensioned left side leaves the
/// left corners a least-squares valley (the perpendicular repeats what horizontal and vertical