SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
STEP import: an edge on a CURVE_REPLICA reads as its parent moved (#10755) (#12915)
dudedagger42ecbd05ef5ea3
diff --git a/crates/step/src/eval.rs b/crates/step/src/eval.rsindex b55eba4102..a32386da27 100644--- a/crates/step/src/eval.rs+++ b/crates/step/src/eval.rs@@ -135,6 +135,7 @@ impl Curve {Curve::SurfaceCurve { curve_3d, .. } => curve_3d.point_at(t, depth + 1)?,// Needs the basis curve's derivative; not evaluated yet.Curve::OffsetCurve3d { .. } => return None,+ Curve::Replica { parent, transform } => transform.point(parent.point_at(t, depth + 1)?),};p.iter().all(|x| x.is_finite()).then_some(p)}diff --git a/crates/step/src/geom.rs b/crates/step/src/geom.rsindex 25844f764c..86a2d69514 100644--- a/crates/step/src/geom.rs+++ b/crates/step/src/geom.rs@@ -169,6 +169,36 @@ pub enum Associated {Surface(Arc<Surface>),}+/// CARTESIAN_TRANSFORMATION_OPERATOR_3D: `origin + scale·(x·X + y·Y + z·Z)`, where `X`, `Y`+/// and `Z` are the operator's unit axes (orthogonal, `Y` = ±`Z` × `X`: a negative sign mirrors).+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Transform {+ pub origin: P3,+ pub x: P3,+ pub y: P3,+ pub z: P3,+ pub scale: f64,+}++impl Transform {+ /// The point `p` moved.+ pub fn point(&self, p: P3) -> P3 {+ add(self.origin, self.vector(p))+ }+ /// The vector `v` turned and scaled, not translated.+ pub fn vector(&self, v: P3) -> P3 {+ scale(add(scale(self.x, v[0]), add(scale(self.y, v[1]), scale(self.z, v[2]))), self.scale)+ }+ /// The direction `d` turned (its length kept).+ pub fn direction(&self, d: P3) -> P3 {+ add(scale(self.x, d[0]), add(scale(self.y, d[1]), scale(self.z, d[2])))+ }+ /// Whether the operator keeps handedness (no mirror).+ pub fn is_proper(&self) -> bool {+ dot(cross(self.x, self.y), self.z) > 0.0+ }+}+/// A STEP curve.#[derive(Clone, Debug, PartialEq)]pub enum Curve {@@ -221,6 +251,11 @@ pub enum Curve {self_intersect: Logical,ref_direction: P3,},+ /// CURVE_REPLICA: the parent curve moved by `transform`, with the parent's parameter.+ Replica {+ parent: Arc<Curve>,+ transform: Transform,+ },}/// A STEP surface.diff --git a/crates/step/src/geom_tests.rs b/crates/step/src/geom_tests.rsindex a1c9bf237d..0f51761668 100644--- a/crates/step/src/geom_tests.rs+++ b/crates/step/src/geom_tests.rs@@ -363,6 +363,38 @@ fn offset_curve_reads_and_round_trips() {round_trip_curve(&c, &[]);}+/// A CURVE_REPLICA's operator: x' = +Y, z' = +Z (so y' = z' x x' = -X), origin (5, 0, 0), scale 2.+const TURNED: &str = "#20=CARTESIAN_POINT('',(5.,0.,0.));#21=CARTESIAN_TRANSFORMATION_OPERATOR_3D('','',#5,$,#20,2.,#2);";++#[test]+fn curve_replica_is_its_parent_moved_and_scaled() {+ let c = curve(&format!("{TURNED}#10=CIRCLE('',#4,10.);#11=CURVE_REPLICA('',#10,#21);"), 11, MM);+ // The parent's point at t is origin + 2 (cos t · 10 · x' + sin t · 10 · y').+ at_curve(&c, 0.0, [5.0, 20.0, 0.0]);+ at_curve(&c, FRAC_PI_2, [-15.0, 0.0, 0.0]);+ at_curve(&c, PI, [5.0, -20.0, 0.0]);+ // A line keeps its parameter: its point at t is the parent's, moved.+ let l = curve(&format!("{TURNED}#10=LINE('',#1,#12);#12=VECTOR('',#3,3.);#11=CURVE_REPLICA('',#10,#21);"), 11, MM);+ at_curve(&l, 1.0, [5.0, 6.0, 0.0]);+}++#[test]+fn curve_replica_scales_its_placement_with_the_file_units() {+ let inches = Units { len: 25.4, ang: 1.0 };+ let c = curve(+ "#20=CARTESIAN_POINT('',(1.,0.,0.));#21=CARTESIAN_TRANSFORMATION_OPERATOR_3D('','',$,$,#20,$,$);#10=LINE('',#1,#12);#12=VECTOR('',#3,1.);#11=CURVE_REPLICA('',#10,#21);",+ 11,+ inches,+ );+ at_curve(&c, 1.0, [50.8, 0.0, 0.0]);+}++#[test]+fn curve_replica_round_trips() {+ let c = curve(&format!("{TURNED}#10=CIRCLE('',#4,10.);#11=CURVE_REPLICA('',#10,#21);"), 11, MM);+ round_trip_curve(&c, &[0.0, 1.0, FRAC_PI_2, PI]);+}+#[test]fn shared_entities_are_written_once() {let c = Arc::new(Curve::Circle {diff --git a/crates/step/src/read.rs b/crates/step/src/read.rsindex 36b2ba40ce..457ae9907e 100644--- a/crates/step/src/read.rs+++ b/crates/step/src/read.rs@@ -7,7 +7,7 @@ use std::sync::Arc;use crate::geom::{Associated, Axis1, BSplineCurve, BSplineSurface, Curve, CurveForm, KnotSpec, Logical, P3, Pcurve, Placement, PreferredRep, Surface,- SurfaceCurveKind, SurfaceForm, Trim, TrimPreference, dot, norm, scale, sub,+ SurfaceCurveKind, SurfaceForm, Transform, Trim, TrimPreference, cross, dot, norm, scale, sub,};use crate::p21::{Entity, Exchange, Param};@@ -358,6 +358,43 @@ impl<'a> Reader<'a> {Ok(Axis1 { origin, direction })}+ /// CARTESIAN_TRANSFORMATION_OPERATOR_3D, its axes made orthonormal as STEP derives them:+ /// `Z` from `axis3` (default +Z), `X` from `axis1` made orthogonal to `Z`, `Y` = `Z` × `X`,+ /// or its opposite (a mirror) when `axis2` points that way.+ pub fn transform(&self, id: u64) -> R<Transform> {+ let e = entity(self.ex, id)?;+ if e.name() != "CARTESIAN_TRANSFORMATION_OPERATOR_3D" {+ return Err(format!("not supported yet: transformation {}", e.name()));+ }+ // (name, description, axis1, axis2, local_origin, scale, axis3): the entity inherits a name+ // from representation_item and a name and description from the functionally defined+ // transformation.+ let p = e.params();+ let axis = |i: usize| p.get(i).and_then(Param::as_ref_id).map(|d| self.direction(d)).transpose();+ let z = axis(6)?.unwrap_or([0.0, 0.0, 1.0]);+ let x = match axis(2)? {+ Some(a) => sub(a, scale(z, dot(a, z))),+ None => {+ let a = if z == [0.0, 0.0, 1.0] { [1.0, 0.0, 0.0] } else { [0.0, 0.0, 1.0] };+ sub(a, scale(z, dot(a, z)))+ }+ };+ let x = unit(x, &format!("#{id} axes"))?;+ let mut y = cross(z, x);+ if axis(3)?.is_some_and(|a| dot(a, y) < 0.0) {+ y = scale(y, -1.0);+ }+ let origin = self.point(reference(p.get(4), "transformation origin")?)?;+ let k = match p.get(5) {+ Some(v) if v.as_f64().is_some() => num(Some(v), "transformation scale")?,+ _ => 1.0,+ };+ if !(k > 0.0 && k.is_finite()) {+ return Err(format!("#{id}: scale must be positive"));+ }+ Ok(Transform { origin, x, y, z, scale: k })+ }+/// A VECTOR: unit direction and magnitude (scaled as a length by `len`).fn vector_scaled(&self, id: u64, s: [f64; 3], dim: usize) -> R<(P3, f64)> {let e = entity(self.ex, id)?;@@ -529,6 +566,11 @@ impl<'a> Reader<'a> {let ref_direction = self.direction(reference(p.get(4), "offset curve direction")?)?;Ok(Curve::OffsetCurve3d { basis, distance, self_intersect, ref_direction })}+ "CURVE_REPLICA" if dim == 3 => {+ let parent = self.curve_in(reference(p.get(1), "curve replica parent")?, depth + 1)?;+ let transform = self.transform(reference(p.get(2), "curve replica transformation")?)?;+ Ok(Curve::Replica { parent, transform })+ }n => Err(format!("not supported yet: curve {n}{}", if dim == 2 { " in parameter space" } else { "" })),}}@@ -585,6 +627,7 @@ impl<'a> Reader<'a> {match c {Curve::Circle { .. } | Curve::Ellipse { .. } => ParamKind::Angle,Curve::Trimmed { basis, .. } | Curve::OffsetCurve3d { basis, .. } => Self::curve_param_kind(basis),+ Curve::Replica { parent, .. } => Self::curve_param_kind(parent),Curve::SurfaceCurve { curve_3d, .. } => Self::curve_param_kind(curve_3d),_ => ParamKind::Plain,}diff --git a/crates/step/src/topology.rs b/crates/step/src/topology.rsindex fa693f7bc7..dfee558bc9 100644--- a/crates/step/src/topology.rs+++ b/crates/step/src/topology.rs@@ -46,7 +46,7 @@ use solidcore_record::brep::{use solidcraft_geom::brep::eval::{CurveEval, SurfaceEval, face_flux};use solidcraft_geom::brep::pcurve::{self, EdgeUse, TrimEdge, TrimFace, TrimUse, Trims};-use crate::geom::{BSplineCurve, BSplineSurface, Curve, P3, Placement, dot, scale, sub};+use crate::geom::{BSplineCurve, BSplineSurface, Curve, P3, Placement, Transform, dot, scale, sub};use crate::p21::{Entity, Exchange, Param};use crate::read::{R, Reader};use crate::units;@@ -745,6 +745,7 @@ impl<'b, 'a> Builder<'b, 'a> {match c {Curve::SurfaceCurve { curve_3d, .. } => c = curve_3d,Curve::Trimmed { basis, .. } => c = basis,+ Curve::Replica { parent, transform } => return replicate(parent, transform, 0),_ => return Ok(c.clone()),}}@@ -1704,6 +1705,42 @@ fn map_bspline_surface(b: &BSplineSurface) -> R<BSurface> {})}+/// A CURVE_REPLICA's curve: the parent (under its SURFACE_CURVE and TRIMMED_CURVE wrappers)+/// moved by `t`, as the same kind of curve, with the parent's parameter. A mirroring operator+/// would turn a conic over, so it is not supported.+fn replicate(parent: &Curve, t: &Transform, depth: usize) -> R<Curve> {+ if depth > MAX_NESTING {+ return Err("curve replicas nested too deeply".into());+ }+ if !t.is_proper() {+ return Err(unsupported("a CURVE_REPLICA that mirrors"));+ }+ let place = |p: &Placement| Placement { origin: t.point(p.origin), axis: t.direction(p.axis), ref_direction: t.direction(p.ref_direction) };+ let k = t.scale;+ Ok(match parent {+ Curve::Line { origin, direction, magnitude } => {+ Curve::Line { origin: t.point(*origin), direction: t.direction(*direction), magnitude: magnitude * k }+ }+ Curve::Circle { position, radius } => Curve::Circle { position: place(position), radius: radius * k },+ Curve::Ellipse { position, semi_axis_1, semi_axis_2 } => {+ Curve::Ellipse { position: place(position), semi_axis_1: semi_axis_1 * k, semi_axis_2: semi_axis_2 * k }+ }+ Curve::Hyperbola { position, semi_axis, semi_imag_axis } => {+ Curve::Hyperbola { position: place(position), semi_axis: semi_axis * k, semi_imag_axis: semi_imag_axis * k }+ }+ Curve::Parabola { position, focal_dist } => Curve::Parabola { position: place(position), focal_dist: focal_dist * k },+ Curve::BSpline(b) => {+ let mut moved = (**b).clone();+ moved.points = b.points.iter().map(|p| t.point(*p)).collect();+ Curve::BSpline(Box::new(moved))+ }+ Curve::Polyline(points) => Curve::Polyline(points.iter().map(|p| t.point(*p)).collect()),+ Curve::SurfaceCurve { curve_3d: inner, .. } | Curve::Trimmed { basis: inner, .. } => replicate(inner, t, depth + 1)?,+ Curve::Replica { parent, transform } => replicate(&replicate(parent, transform, depth + 1)?, t, depth + 1)?,+ Curve::OffsetCurve3d { .. } => return Err(unsupported("a CURVE_REPLICA of an OFFSET_CURVE_3D")),+ })+}+/// An edge on its schema curve.#[derive(Debug)]struct Mapped {@@ -1771,6 +1808,7 @@ fn map_edge(curve: &Curve, ps: P3, pe: P3, same_sense: bool, closed: bool, full:open_conic(curve, ps, pe, same_sense, closed, |lo, hi| swept::parabola_spline(position, *focal_dist, lo, hi))}Curve::OffsetCurve3d { .. } => Err(unsupported("OFFSET_CURVE_3D")),+ Curve::Replica { parent, transform } => map_edge(&replicate(parent, transform, 0)?, ps, pe, same_sense, closed, full, tol),Curve::Trimmed { .. } | Curve::SurfaceCurve { .. } => Err(unsupported("nested trimmed or surface curves")),}}diff --git a/crates/step/src/topology/swept.rs b/crates/step/src/topology/swept.rsindex c9e447f4a9..e9a89835c0 100644--- a/crates/step/src/topology/swept.rs+++ b/crates/step/src/topology/swept.rs@@ -231,6 +231,7 @@ fn whole(c: &Curve) -> R<Option<BCurve>> {}Curve::Line { .. } | Curve::Circle { .. } | Curve::Ellipse { .. } | Curve::Hyperbola { .. } | Curve::Parabola { .. } => None,Curve::OffsetCurve3d { .. } => return Err(unsupported("an OFFSET_CURVE_3D profile")),+ Curve::Replica { .. } => return Err(unsupported("a CURVE_REPLICA profile")),Curve::Trimmed { .. } | Curve::SurfaceCurve { .. } => return Err(unsupported("nested profile curves")),})}diff --git a/crates/step/src/topology_tests.rs b/crates/step/src/topology_tests.rsindex 6f810e883b..652a7db1d3 100644--- a/crates/step/src/topology_tests.rs+++ b/crates/step/src/topology_tests.rs@@ -775,6 +775,43 @@ fn edited(edit: impl Fn(&str) -> String) -> Solids {read_solids(&parse(&text))}+/// The cube with its first edge's LINE replaced by a CURVE_REPLICA of a line 7 mm lower, moved up+/// by a transformation operator (what FreeCAD writes for a repeated edge).+fn replica_edge(t: &str) -> String {+ let at = t.find("=LINE('',#").expect("a line");+ let (_, line_id) = t[..at].rsplit_once('#').expect("an id");+ let tail = &t[at + "=LINE('',#".len()..];+ let (point, tail) = tail.split_once(",#").expect("a vector");+ let (vector, _) = tail.split_once(')').expect("the end");+ let pt = t.split_once(&format!("#{point}=CARTESIAN_POINT('',(")).expect("the point").1;+ let xyz: Vec<f64> = pt.split_once(')').unwrap().0.split(',').map(|v| v.parse().unwrap()).collect();+ let replaced = t.replacen(&format!("#{line_id}=LINE('',#{point},#{vector})"), &format!("#{line_id}=CURVE_REPLICA('',#9003,#9004)"), 1);+ format!(+ "{replaced}#9001=CARTESIAN_POINT('',({},{},{}));#9002=CARTESIAN_POINT('',(0.,0.,7.));#9003=LINE('',#9001,#{vector});#9004=CARTESIAN_TRANSFORMATION_OPERATOR_3D('','',$,$,#9002,$,$);",+ real(xyz[0]),+ real(xyz[1]),+ real(xyz[2] - 7.0)+ )+}++#[test]+fn an_edge_on_a_curve_replica_is_the_moved_curve() {+ let plain = edited(str::to_string);+ let moved = edited(|t| {+ let edited = replica_edge(t);+ assert!(edited.contains("CURVE_REPLICA"), "the edit did not apply");+ edited+ });+ assert!(moved.failures.is_empty(), "{:?}", moved.failures);+ assert_eq!(moved.solids.len(), 1);+ let (a, b) = (&plain.solids[0].brep, &moved.solids[0].brep);+ solidcraft_geom::brep::check::validate(b).unwrap();+ assert_eq!(counts(a), counts(b));+ // The replica's edge is the plain cube's edge: same curve, same interval.+ assert_eq!(a.edges[0].curve, b.edges[0].curve);+ assert_eq!(a.edges[0].interval, b.edges[0].interval);+}+#[test]fn hostile_topology_is_an_error_never_a_panic() {// Sanity: unedited, the cube reads.diff --git a/crates/step/src/write.rs b/crates/step/src/write.rsindex 44c1235450..524c26a384 100644--- a/crates/step/src/write.rs+++ b/crates/step/src/write.rs@@ -384,6 +384,13 @@ impl<'w> GeomWriter<'w> {});self.w.add(name, &[s(), r(c3), list(items), m])}+ Curve::Replica { parent, transform } => {+ let c = self.curve_in(parent, 3);+ let (x, y, z) = (self.direction(transform.x), self.direction(transform.y), self.direction(transform.z));+ let o = self.point(transform.origin);+ let t = self.w.add("CARTESIAN_TRANSFORMATION_OPERATOR_3D", &[s(), s(), r(x), r(y), r(o), f(transform.scale), r(z)]);+ self.w.add("CURVE_REPLICA", &[s(), r(c), r(t)])+ }Curve::OffsetCurve3d { basis, distance, self_intersect, ref_direction } => {let b = self.curve_in(basis, 3);let d = self.direction(*ref_direction);