Skip to content

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

Wave 280/509: STEP import: spindle and horn tori, and a negative major radius (and 3 more)

jyviko57921d7fcd8b
diff --git a/crates/geom/src/brep/eval.rs b/crates/geom/src/brep/eval.rs
index 420579fac5..73b6260ccc 100644
--- a/crates/geom/src/brep/eval.rs
+++ b/crates/geom/src/brep/eval.rs
@@ -241,6 +241,26 @@ impl SurfaceEval {
let (a, b) = (su.len(), sv.len());
[a <= 1e-9 * b.max(1e-12), b <= 1e-9 * a.max(1e-12)]
}
+
+ /// [`Self::pole`], or within `reach` mm of one: moving along a direction across half its
+ /// period (or its whole range) moves the point no more than `reach` (a boundary point that
+ /// lies at a pole to within a tolerance, where its periodic parameter is free).
+ pub fn pole_within(&self, uv: [f64; 2], reach: f64) -> [bool; 2] {
+ let mut out = self.pole(uv);
+ let Some((_, su, sv)) = self.derivs(uv[0], uv[1]) else { return out };
+ let dom = self.domain();
+ for (d, speed) in [su.len(), sv.len()].into_iter().enumerate() {
+ let span = match (dom.period.get(d).copied().flatten(), dom.range.get(d).copied().flatten()) {
+ (Some(period), _) => 0.5 * period,
+ (None, Some((a, b))) => (b - a).abs(),
+ (None, None) => continue,
+ };
+ if let Some(flag) = out.get_mut(d) {
+ *flag |= speed * span <= reach;
+ }
+ }
+ out
+ }
}
/// A tensor spline's rows (`rows[i][j]`, i along u) as the evaluator's u-fastest array.
diff --git a/crates/geom/src/brep/geometry.rs b/crates/geom/src/brep/geometry.rs
index f349603070..6c0b92fc35 100644
--- a/crates/geom/src/brep/geometry.rs
+++ b/crates/geom/src/brep/geometry.rs
@@ -12,7 +12,7 @@
//! an edge's for its pcurves, an edge's and its vertex's together where they meet, a vertex's on
//! its surface. A point that cannot be evaluated is an error, never a panic.
use super::eval::{CurveEval, SurfaceEval};
-use super::{Brep, Loop};
+use super::{Brep, Curve2, Loop};
use crate::Vec3;
/// Where a record disagrees with itself.
@@ -84,6 +84,14 @@ fn v3(p: [f64; 3]) -> Vec3 {
fn unevaluable(record: Record, what: impl std::fmt::Display) -> Mismatch {
Mismatch { record, problem: Problem::Unevaluable(what.to_string()) }
}
+/// A use's pcurve at its edge's parameter `t`. The pcurve's interval is its edge's to within
+/// rounding ([`Brep::validate`], `PCURVE_INTERVAL`), so an edge parameter just past it is read at
+/// the pcurve's end.
+fn on_pcurve(pc: &Curve2, t: f64) -> Option<[f64; 2]> {
+ let [a, b] = pc.interval()?;
+ pc.eval(t.clamp(a.min(b), a.max(b)))
+}
+
/// `gap` within `tolerance` (a non-finite gap never is).
fn within(record: Record, what: &'static str, gap: f64, tolerance: f64) -> Result<()> {
if gap <= tolerance { Ok(()) } else { Err(Mismatch { record, problem: Problem::Off { what, gap, tolerance } }) }
@@ -147,7 +155,7 @@ impl Brep {
let [t0, t1] = e.interval;
let mut uv = [[0.0; 2]; 3];
for (k, t) in [t0, 0.5 * (t0 + t1), t1].into_iter().enumerate() {
- let q = u.pcurve.eval(t).ok_or_else(|| unevaluable(at, format!("the pcurve has no point at {t}")))?;
+ let q = on_pcurve(&u.pcurve, t).ok_or_else(|| unevaluable(at, format!("the pcurve has no point at {t}")))?;
let s = surface.point(q).ok_or_else(|| unevaluable(at, format!("the surface has no point at {q:?}")))?;
let (Some(c), Some(what), Some(slot)) = (p.get(k), PCURVE_POINTS.get(k), uv.get_mut(k)) else {
return Err(unevaluable(at, "pcurve sample"));
@@ -181,7 +189,7 @@ impl Brep {
for k in 0..AREA_SAMPLES {
let f = k as f64 / AREA_SAMPLES as f64;
let t = if u.forward { t0 + (t1 - t0) * f } else { t1 - (t1 - t0) * f };
- ring.push(u.pcurve.eval(t).ok_or_else(|| unevaluable(at, format!("the pcurve has no point at {t}")))?);
+ ring.push(on_pcurve(&u.pcurve, t).ok_or_else(|| unevaluable(at, format!("the pcurve has no point at {t}")))?);
}
}
let area = signed_area(&ring);
diff --git a/crates/geom/src/brep/pcurve.rs b/crates/geom/src/brep/pcurve.rs
index 8460e5dff3..5c31d60ae3 100644
--- a/crates/geom/src/brep/pcurve.rs
+++ b/crates/geom/src/brep/pcurve.rs
@@ -529,19 +529,7 @@ impl On {
/// parameter by half its period (or across its range) moves the point by no more than `reach`
/// at its speed there. There the parameter is as free as at the pole itself.
fn pole(&self, uv: [f64; 2], reach: f64) -> [bool; 2] {
- let mut out = self.surface.pole(uv);
- let Some((_, su, sv)) = self.surface.derivs(uv[0], uv[1]) else { return out };
- for (d, speed) in [su.len(), sv.len()].into_iter().enumerate() {
- let span = match (self.dom.period.get(d).copied().flatten(), self.dom.range.get(d).copied().flatten()) {
- (Some(period), _) => 0.5 * period,
- (None, Some((a, b))) => (b - a).abs(),
- (None, None) => continue,
- };
- if let Some(flag) = out.get_mut(d) {
- *flag |= speed * span <= reach;
- }
- }
- out
+ self.surface.pole_within(uv, reach)
}
/// The loop's uses moved by whole periods so each starts where the one before it ends (in
diff --git a/crates/geom/src/brep/tests.rs b/crates/geom/src/brep/tests.rs
index 02fd84fe1f..bd233a282f 100644
--- a/crates/geom/src/brep/tests.rs
+++ b/crates/geom/src/brep/tests.rs
@@ -530,6 +530,21 @@ fn shift(c: &mut Curve2, by: [f64; 2]) {
}
}
+/// A pcurve whose interval ends a rounding short of its edge's (as a kernel that snaps an edge's
+/// end to its knot hands it back) is read at its end: the record validates and checks.
+#[test]
+fn a_pcurve_a_rounding_short_of_its_edge_is_read_at_its_end() {
+ let mut b = sheet();
+ let Curve2::Spline { knots, .. } = pcurve_of(&mut b, 0, 0) else { panic!("a spline pcurve") };
+ let end = *knots.last().unwrap();
+ let short = end - 1e-11 * end.abs().max(1.0);
+ for k in knots.iter_mut().filter(|k| **k == end) {
+ *k = short;
+ }
+ b.validate().unwrap();
+ b.check_geometry().unwrap();
+}
+
/// One geometric defect each, structurally valid: every one is refused, naming the record.
#[test]
fn geometric_defects_are_refused_by_record() {
@@ -844,3 +859,16 @@ fn a_face_box_reaches_its_boundary_extremes() {
let [_, v] = form::extent(&cylinder, &[vec![(&cut, [0.1, 0.1 + TAU], true)]]).expect("an extent");
assert!((v[0] - 10.0).abs() < 1e-9 && (v[1] - 50.0).abs() < 1e-9, "{v:?}");
}
+
+/// A point next to a sphere's pole is a pole to within the reach it is given: crossing half a
+/// turn of longitude there moves it about π times its distance from the axis, and no further.
+#[test]
+fn a_point_beside_a_pole_is_one_within_its_reach() {
+ let sphere = eval::SurfaceEval::new(&Surface::Sphere { frame: a_frame(), radius: 2. }).unwrap();
+ let near = [0.3, FRAC_PI_2 - 1e-7];
+ // 2e-7 mm from the axis: half a turn moves it 2π·1e-7.
+ assert_eq!(sphere.pole(near), [false, false]);
+ assert_eq!(sphere.pole_within(near, 1e-6), [true, false]);
+ assert_eq!(sphere.pole_within(near, 1e-7), [false, false]);
+ assert_eq!(sphere.pole_within([0.3, 0.2], 1e-3), [false, false]);
+}
diff --git a/crates/kernel/src/step_in/tests.rs b/crates/kernel/src/step_in/tests.rs
index d0826a8c3c..7fdd21d72b 100644
--- a/crates/kernel/src/step_in/tests.rs
+++ b/crates/kernel/src/step_in/tests.rs
@@ -1061,6 +1061,216 @@ fn horn_torus_written_as_one_spline_face() {
assert!(rel(measure(&imp.bodies[0].body).unwrap().volume, v) < 1e-3);
}
+/// How a torus-capped cylinder ([`torus_capped_cylinder`]) ends.
+enum Tip {
+ /// The tube's quarter from its outside over to its top, at `z`, and a disc there of radius `r`.
+ Disc { z: f64, r: f64 },
+ /// The tube on to where it meets the axis: the pole, a vertex at height `apex` on the axis
+ /// reached by the tube's meridian as the torus face's seam, or (`seam` false) not, its one
+ /// bound the circle at z = 0.
+ Pole { apex: f64, seam: bool },
+}
+
+/// A cylinder about Z of radius `major + minor` from z = -2 to 0, its top a torus about Z with
+/// those radii (`torus`: the surface entity at #5 on placement #4) ending as `tip` says.
+fn torus_capped_cylinder(torus: &str, major: f64, minor: f64, tip: Tip) -> String {
+ let outer = major + minor;
+ let mut t = String::from(HEAD);
+ t += "#1=CARTESIAN_POINT('',(0.,0.,0.));\n#2=DIRECTION('',(0.,0.,1.));\n#3=DIRECTION('',(1.,0.,0.));\n#4=AXIS2_PLACEMENT_3D('',#1,#2,#3);\n";
+ t += &format!("{torus}\n#6=CYLINDRICAL_SURFACE('',#4,{outer:.16});\n");
+ t += "#7=CARTESIAN_POINT('',(0.,0.,-2.));\n#8=AXIS2_PLACEMENT_3D('',#7,#2,#3);\n#9=PLANE('',#8);\n";
+ t += &format!(
+ "#13=CARTESIAN_POINT('',({outer:.16},0.,-2.));\n#14=VERTEX_POINT('',#13);\n#15=CARTESIAN_POINT('',({outer:.16},0.,0.));\n#16=VERTEX_POINT('',#15);\n"
+ );
+ t += &format!(
+ "#19=CIRCLE('',#8,{outer:.16});\n#20=EDGE_CURVE('',#14,#14,#19,.T.);\n#21=CIRCLE('',#4,{outer:.16});\n#22=EDGE_CURVE('',#16,#16,#21,.T.);\n"
+ );
+ t += "#25=VECTOR('',#2,1.);\n#26=LINE('',#13,#25);\n#27=EDGE_CURVE('',#14,#16,#26,.T.);\n";
+ t += "#40=ORIENTED_EDGE('',*,*,#20,.F.);\n#41=EDGE_LOOP('',(#40));\n#42=FACE_OUTER_BOUND('',#41,.T.);\n#43=ADVANCED_FACE('',(#42),#9,.F.);\n";
+ t += "#44=ORIENTED_EDGE('',*,*,#20,.T.);\n#45=ORIENTED_EDGE('',*,*,#27,.T.);\n#46=ORIENTED_EDGE('',*,*,#22,.F.);\n#47=ORIENTED_EDGE('',*,*,#27,.F.);\n";
+ t += "#48=EDGE_LOOP('',(#44,#45,#46,#47));\n#49=FACE_OUTER_BOUND('',#48,.T.);\n#50=ADVANCED_FACE('',(#49),#6,.T.);\n#51=ORIENTED_EDGE('',*,*,#22,.T.);\n";
+ // The tube's meridian at u = 0 from (outer, 0, 0) to `end`, the torus face's seam: centre
+ // (major, 0, 0), angle from X towards Z (its axis -Y).
+ let meridian = |t: &mut String, end: [f64; 2]| {
+ *t += &format!("#17=CARTESIAN_POINT('',({:.16},0.,{:.16}));\n#18=VERTEX_POINT('',#17);\n", end[0], end[1]);
+ *t += &format!(
+ "#28=CARTESIAN_POINT('',({major:.16},0.,0.));\n#29=DIRECTION('',(0.,-1.,0.));\n#30=AXIS2_PLACEMENT_3D('',#28,#29,#3);\n#31=CIRCLE('',#30,{minor:.16});\n#32=EDGE_CURVE('',#16,#18,#31,.T.);\n"
+ );
+ *t += "#52=ORIENTED_EDGE('',*,*,#32,.T.);\n#54=ORIENTED_EDGE('',*,*,#32,.F.);\n";
+ };
+ let faces = match tip {
+ Tip::Disc { z, r } => {
+ meridian(&mut t, [r, z]);
+ t += &format!("#10=CARTESIAN_POINT('',(0.,0.,{z:.16}));\n#11=AXIS2_PLACEMENT_3D('',#10,#2,#3);\n#12=PLANE('',#11);\n");
+ t += &format!("#23=CIRCLE('',#11,{r:.16});\n#24=EDGE_CURVE('',#18,#18,#23,.T.);\n#53=ORIENTED_EDGE('',*,*,#24,.F.);\n");
+ t += "#55=EDGE_LOOP('',(#51,#52,#53,#54));\n#56=FACE_OUTER_BOUND('',#55,.T.);\n#57=ADVANCED_FACE('',(#56),#5,.T.);\n";
+ t += "#58=ORIENTED_EDGE('',*,*,#24,.T.);\n#59=EDGE_LOOP('',(#58));\n#60=FACE_OUTER_BOUND('',#59,.T.);\n#61=ADVANCED_FACE('',(#60),#12,.T.);\n";
+ "#43,#50,#57,#61"
+ }
+ Tip::Pole { apex, seam } => {
+ if seam {
+ meridian(&mut t, [0.0, apex]);
+ t += "#55=EDGE_LOOP('',(#51,#52,#54));\n";
+ } else {
+ t += "#55=EDGE_LOOP('',(#51));\n";
+ }
+ t += "#56=FACE_OUTER_BOUND('',#55,.T.);\n#57=ADVANCED_FACE('',(#56),#5,.T.);\n";
+ "#43,#50,#57"
+ }
+ };
+ t += &format!("#62=CLOSED_SHELL('',({faces}));\n#63=MANIFOLD_SOLID_BREP('Pin',#62);\n#64=ADVANCED_BREP_SHAPE_REPRESENTATION('',(#63),#70);\n");
+ t += &context(70, "(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))");
+ t += TAIL;
+ t
+}
+
+/// The one closed body of `text`, its volume and area against the closed forms; `warnings`
+/// the import's warnings.
+fn assert_closed_measures(text: &str, volume: f64, area: f64, warnings: &[&str]) {
+ let imp = step_import(text).unwrap();
+ assert_eq!(imp.bodies.len(), 1, "{:?}", imp.warnings);
+ assert_eq!(imp.warnings, warnings, "{:?}", imp.warnings);
+ assert!(imp.bodies[0].closed);
+ let m = measure(&imp.bodies[0].body).unwrap();
+ assert!(rel(m.volume, volume) < 1e-3, "volume {} vs {volume}", m.volume);
+ assert!(rel(m.area, area) < 1e-3, "area {} vs {area}", m.area);
+}
+
+/// A horn torus (major radius = minor, its tube touching its axis) as a round of radius 1 on a
+/// cylinder of radius 2, from the cylinder's top edge over to a disc of radius 1 at z = 1 (a
+/// round pin tip). Under the round, the solid's radius at height z is 1 + √(1 − z²):
+/// V = 8π + π∫₀¹(1 + √(1 − z²))² dz = 8π + π(5/3 + π/2); the round's area is
+/// 2π∫₀^{π/2}(1 + cos v) dv = π² + 2π, with the cylinder's 8π and the discs' 4π and π.
+#[test]
+fn horn_torus_round_on_a_pin_imports_whole() {
+ use std::f64::consts::PI;
+ let t = torus_capped_cylinder("#5=TOROIDAL_SURFACE('',#4,1.,1.);", 1.0, 1.0, Tip::Disc { z: 1.0, r: 1.0 });
+ assert_closed_measures(&t, 8.0 * PI + PI * (5.0 / 3.0 + PI / 2.0), 15.0 * PI + PI * PI, &[]);
+}
+
+/// The volume and area of a spindle torus's pin end ([`Tip::Pole`]): in the meridian plane the
+/// disc of radius `r` about (`major`, 0) above z = 0 and right of the axis, which the tube meets
+/// at z = c = √(r² − R²) (cos v = −R/r). With s = √(r² − z²) and S(a) = ∫₀^a s dz =
+/// (a√(r² − a²) + r² asin(a/r))/2: V = π∫₀^c (R + s)² dz + π∫_c^r 4Rs dz =
+/// π(R²c + r²c − c³/3 + 2R·S(c)) + 4πR(S(r) − S(c)); area 2πr(R·acos(−R/r) + c).
+fn pin_end(major: f64, r: f64) -> (f64, f64) {
+ use std::f64::consts::PI;
+ let c = (r * r - major * major).sqrt();
+ let s = |a: f64| 0.5 * (a * (r * r - a * a).max(0.0).sqrt() + r * r * (a / r).asin());
+ let volume = PI * (major * major * c + r * r * c - c.powi(3) / 3.0 + 2.0 * major * s(c)) + 4.0 * PI * major * (s(r) - s(c));
+ (volume, 2.0 * PI * r * (major * (-major / r).acos() + c))
+}
+
+/// A spindle torus (major radius below the minor, its tube across its axis) as a pin's end: the
+/// apple's part from the cylinder at z = 0 up over the tube's top and down to where the tube
+/// meets the axis, a pole in a dimple ([`pin_end`], with the cylinder's side and its disc).
+/// Major 1, minor 2 (the tube meets the axis at z = √3: V = 3√3π + 8π²/3, area
+/// 4π(2π/3 + √3)), written as a TOROIDAL_SURFACE (as SolidWorks writes it) and as the schema's
+/// DEGENERATE_TOROIDAL_SURFACE, its apple selected; with a seam to the pole, and with the
+/// circle at z = 0 its one bound (the reader adds the seam).
+#[test]
+fn spindle_torus_pin_tip_imports_whole() {
+ use std::f64::consts::PI;
+ let s3 = 3f64.sqrt();
+ let (volume, area) = pin_with_cylinder(1.0, 2.0);
+ assert!(rel(volume, 18.0 * PI + 3.0 * s3 * PI + 8.0 * PI * PI / 3.0) < 1e-12 && rel(area, 21.0 * PI + 4.0 * PI * (2.0 * PI / 3.0 + s3)) < 1e-12);
+ for torus in ["#5=TOROIDAL_SURFACE('',#4,1.,2.);", "#5=DEGENERATE_TOROIDAL_SURFACE('',#4,1.,2.,.T.);"] {
+ for (seam, warnings) in [(true, &[][..]), (false, &["solid 'Pin': 1 seam edges added to faces that wind around their surface"][..])] {
+ let t = torus_capped_cylinder(torus, 1.0, 2.0, Tip::Pole { apex: s3, seam });
+ assert_closed_measures(&t, volume, area, warnings);
+ }
+ }
+}
+
+/// [`pin_end`] on its cylinder from z = -2 ([`torus_capped_cylinder`]): its volume and area.
+fn pin_with_cylinder(major: f64, minor: f64) -> (f64, f64) {
+ use std::f64::consts::PI;
+ let (v, a) = pin_end(major, minor);
+ let outer = major + minor;
+ (v + 2.0 * PI * outer * outer, a + 4.0 * PI * outer + PI * outer * outer)
+}
+
+/// A nearly round pin end as SolidWorks writes it: a spindle torus of major radius 0.005 and
+/// minor 0.345 on a cylinder of radius 0.35, its apple's part in two halves (u in [0, π] and
+/// [π, 2π]) between the meridians at u = 0 and π, which meet at an apex vertex written at the
+/// tube's top, z = 0.345: 3.6e-5 mm above the pole (z = √(0.345² − 0.005²)), in a file of
+/// uncertainty 1e-5 mm. The meridians end 1.7e-6 rad short of the pole, where the tube's
+/// circle about the axis is 1.2e-6 mm across: a pole to within the uncertainty, so each half's
+/// loop jumps from one meridian to the other there. Volume and area as [`pin_end`].
+#[test]
+fn nearly_round_spindle_torus_pin_end_in_halves_imports_whole() {
+ let (major, minor) = (0.005, 0.345);
+ let outer = major + minor;
+ let mut t = String::from(HEAD);
+ t += "#1=CARTESIAN_POINT('',(0.,0.,0.));\n#2=DIRECTION('',(0.,0.,1.));\n#3=DIRECTION('',(1.,0.,0.));\n#4=AXIS2_PLACEMENT_3D('',#1,#2,#3);\n";
+ // The torus's angle from 45° below X: the halves are u in [π/4, 5π/4] and [5π/4, 9π/4] on
+ // it, three quarters of its NURBS form each, the meridians two apart.
+ t += "#88=DIRECTION('',(0.7071067811865476,-0.7071067811865476,0.));\n#89=AXIS2_PLACEMENT_3D('',#1,#2,#88);\n";
+ t += &format!("#5=TOROIDAL_SURFACE('',#89,{major:.16},{minor:.16});\n#6=CYLINDRICAL_SURFACE('',#4,{outer:.16});\n");
+ t += "#7=CARTESIAN_POINT('',(0.,0.,-2.));\n#8=AXIS2_PLACEMENT_3D('',#7,#2,#3);\n#9=PLANE('',#8);\n";
+ t += &format!(
+ "#13=CARTESIAN_POINT('',({outer:.16},0.,-2.));\n#14=VERTEX_POINT('',#13);\n#15=CARTESIAN_POINT('',({outer:.16},0.,0.));\n#16=VERTEX_POINT('',#15);\n"
+ );
+ t += &format!(
+ "#65=CARTESIAN_POINT('',({:.16},0.,0.));\n#66=VERTEX_POINT('',#65);\n#17=CARTESIAN_POINT('',(0.,0.,{minor:.16}));\n#18=VERTEX_POINT('',#17);\n",
+ -outer
+ );
+ t += &format!("#19=CIRCLE('',#8,{outer:.16});\n#20=EDGE_CURVE('',#14,#14,#19,.T.);\n#21=CIRCLE('',#4,{outer:.16});\n");
+ t += "#22=EDGE_CURVE('',#16,#66,#21,.T.);\n#67=EDGE_CURVE('',#66,#16,#21,.T.);\n#25=VECTOR('',#2,1.);\n#26=LINE('',#13,#25);\n#27=EDGE_CURVE('',#14,#16,#26,.T.);\n";
+ // The meridians, each angle from -Z: at u = 0 about (major, 0, 0) towards X (axis -Y); at
+ // u = π about (-major, 0, 0) towards -X (axis +Y).
+ t += "#82=DIRECTION('',(0.,0.,-1.));\n";
+ t += &format!(
+ "#28=CARTESIAN_POINT('',({major:.16},0.,0.));\n#29=DIRECTION('',(0.,-1.,0.));\n#30=AXIS2_PLACEMENT_3D('',#28,#29,#82);\n#31=CIRCLE('',#30,{minor:.16});\n#32=EDGE_CURVE('',#16,#18,#31,.T.);\n"
+ );
+ t += &format!(
+ "#80=CARTESIAN_POINT('',({:.16},0.,0.));\n#81=DIRECTION('',(0.,1.,0.));\n#83=AXIS2_PLACEMENT_3D('',#80,#81,#82);\n#84=CIRCLE('',#83,{minor:.16});\n#85=EDGE_CURVE('',#66,#18,#84,.T.);\n",
+ -major
+ );
+ t += "#40=ORIENTED_EDGE('',*,*,#20,.F.);\n#41=EDGE_LOOP('',(#40));\n#42=FACE_OUTER_BOUND('',#41,.T.);\n#43=ADVANCED_FACE('',(#42),#9,.F.);\n";
+ t += "#44=ORIENTED_EDGE('',*,*,#20,.T.);\n#45=ORIENTED_EDGE('',*,*,#27,.T.);\n#46=ORIENTED_EDGE('',*,*,#67,.F.);\n#47=ORIENTED_EDGE('',*,*,#22,.F.);\n#48=ORIENTED_EDGE('',*,*,#27,.F.);\n";
+ t += "#49=EDGE_LOOP('',(#44,#45,#46,#47,#48));\n#50=FACE_OUTER_BOUND('',#49,.T.);\n#51=ADVANCED_FACE('',(#50),#6,.T.);\n";
+ t += "#52=ORIENTED_EDGE('',*,*,#22,.T.);\n#53=ORIENTED_EDGE('',*,*,#85,.T.);\n#54=ORIENTED_EDGE('',*,*,#32,.F.);\n#55=EDGE_LOOP('',(#52,#53,#54));\n#56=FACE_OUTER_BOUND('',#55,.T.);\n#57=ADVANCED_FACE('',(#56),#5,.T.);\n";
+ t += "#58=ORIENTED_EDGE('',*,*,#67,.T.);\n#59=ORIENTED_EDGE('',*,*,#32,.T.);\n#60=ORIENTED_EDGE('',*,*,#85,.F.);\n#61=EDGE_LOOP('',(#58,#59,#60));\n#62=FACE_OUTER_BOUND('',#61,.T.);\n#63=ADVANCED_FACE('',(#62),#5,.T.);\n";
+ t += "#64=CLOSED_SHELL('',(#43,#51,#57,#63));\n#86=MANIFOLD_SOLID_BREP('Pin',#64);\n#87=ADVANCED_BREP_SHAPE_REPRESENTATION('',(#86),#70);\n";
+ t += &context(70, "(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))").replace("LENGTH_MEASURE(1.E-6)", "LENGTH_MEASURE(1.E-5)");
+ t += TAIL;
+ let (volume, area) = pin_with_cylinder(major, minor);
+ assert_closed_measures(&t, volume, area, &[]);
+}
+
+/// The lemon of a spindle torus (the tube's part across the axis: a closed surface with a pole
+/// at each end), one face bounded by its meridian used both ways, written with a negative major
+/// radius (-1, minor 2: the tube's centre on the other side of the axis, as some writers have
+/// it) and as the schema's DEGENERATE_TOROIDAL_SURFACE with its lemon selected (major radius 1,
+/// where the lemon is the tube's far side, R + r cos v < 0, and the surface's normal
+/// ∂S/∂u × ∂S/∂v points into it: `same_sense` .F.). Its radius at height z is √(4 − z²) − 1
+/// for |z| ≤ √3: V = π∫(5 − z² − 2√(4 − z²)) dz = π(6√3 − 8π/3); area
+/// 2π∫_{−π/3}^{π/3}(2 cos v − 1)·2 dv = 4π(2√3 − 2π/3).
+#[test]
+fn spindle_torus_lemon_with_a_negative_major_radius_imports_whole() {
+ use std::f64::consts::PI;
+ let s3 = 3f64.sqrt();
+ for (torus, sense) in [("#5=TOROIDAL_SURFACE('',#4,-1.,2.);", "T"), ("#5=DEGENERATE_TOROIDAL_SURFACE('',#4,1.,2.,.F.);", "F")] {
+ let mut t = String::from(HEAD);
+ t += "#1=CARTESIAN_POINT('',(0.,0.,0.));\n#2=DIRECTION('',(0.,0.,1.));\n#3=DIRECTION('',(1.,0.,0.));\n#4=AXIS2_PLACEMENT_3D('',#1,#2,#3);\n";
+ t += torus;
+ // The meridian at u = 0: the circle about (-1, 0, 0) from v = -π/3 to π/3, angle from X
+ // towards Z (its axis -Y).
+ t += &format!(
+ "\n#6=CARTESIAN_POINT('',(0.,0.,{:.16}));\n#7=VERTEX_POINT('',#6);\n#8=CARTESIAN_POINT('',(0.,0.,{s3:.16}));\n#9=VERTEX_POINT('',#8);\n",
+ -s3
+ );
+ t += "#10=CARTESIAN_POINT('',(-1.,0.,0.));\n#11=DIRECTION('',(0.,-1.,0.));\n#12=AXIS2_PLACEMENT_3D('',#10,#11,#3);\n#13=CIRCLE('',#12,2.);\n#14=EDGE_CURVE('',#7,#9,#13,.T.);\n";
+ t += "#15=ORIENTED_EDGE('',*,*,#14,.T.);\n#16=ORIENTED_EDGE('',*,*,#14,.F.);\n#17=EDGE_LOOP('',(#15,#16));\n#18=FACE_OUTER_BOUND('',#17,.T.);\n";
+ t += &format!("#19=ADVANCED_FACE('',(#18),#5,.{sense}.);\n");
+ t += "#20=CLOSED_SHELL('',(#19));\n#21=MANIFOLD_SOLID_BREP('Lemon',#20);\n#22=ADVANCED_BREP_SHAPE_REPRESENTATION('',(#21),#70);\n";
+ t += &context(70, "(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))");
+ t += TAIL;
+ assert_closed_measures(&t, PI * (6.0 * s3 - 8.0 * PI / 3.0), 4.0 * PI * (2.0 * s3 - 2.0 * PI / 3.0), &[]);
+ }
+}
+
/// Booleans and blends build the same body every time, so an export is byte-identical from
/// run to run (an export once listed a boolean's faces in hash order of their addresses). The
/// tee of oracle 35 with its rolling-ball fillet round the junction.
@@ -1744,7 +1954,13 @@ fn step_conformance_parts_read_into_smlib() {
/// looser than its context. The patch has no closed-form pcurves for them, so SMLib makes them,
/// on the surface, and they lie `dz` from their edges.
fn dome_with_edges_raised(dz: f64) -> String {
- let z = |i: usize, j: usize| if (1..=2).contains(&i) && (1..=2).contains(&j) { 6.0 } else { 0.0 };
+ patch_with_edges_raised(dz, false)
+}
+
+/// [`dome_with_edges_raised`], or with `flat` the plane z = 0 in its place: its edges' pcurves
+/// are then their control points' projections onto it, in closed form.
+fn patch_with_edges_raised(dz: f64, flat: bool) -> String {
+ let z = |i: usize, j: usize| if !flat && (1..=2).contains(&i) && (1..=2).contains(&j) { 6.0 } else { 0.0 };
let mut t = String::from(HEAD);
let mut rows = Vec::new();
for i in 0..4 {
@@ -1754,10 +1970,14 @@ fn dome_with_edges_raised(dz: f64) -> String {
}
rows.push(format!("({})", row.join(",")));
}
- t += &format!(
- "#10=B_SPLINE_SURFACE_WITH_KNOTS('',3,3,({}),.UNSPECIFIED.,.F.,.F.,.F.,(4,4),(4,4),(0.,1.),(0.,1.),.UNSPECIFIED.);\n",
- rows.join(",")
- );
+ if flat {
+ t += "#10=PLANE('',#13);\n#11=CARTESIAN_POINT('',(0.,0.,0.));\n#12=DIRECTION('',(0.,0.,1.));\n#14=DIRECTION('',(1.,0.,0.));\n#13=AXIS2_PLACEMENT_3D('',#11,#12,#14);\n";
+ } else {
+ t += &format!(
+ "#10=B_SPLINE_SURFACE_WITH_KNOTS('',3,3,({}),.UNSPECIFIED.,.F.,.F.,.F.,(4,4),(4,4),(0.,1.),(0.,1.),.UNSPECIFIED.);\n",
+ rows.join(",")
+ );
+ }
// The boundary, counter-clockwise from above: (i, j) runs i = 0 → 3 at j = 0, j = 0 → 3 at
// i = 3, then back; each side's control points are the patch's, raised.
let sides: [[(usize, usize); 4]; 4] =
@@ -1806,3 +2026,16 @@ fn edges_written_off_their_spline_face_carry_their_gap_as_their_tolerance() {
};
assert!(refused, "{far:?}");
}
+
+#[test]
+fn spline_edges_off_their_plane_by_less_than_the_file_states_get_their_closed_form() {
+ // 0.8e-6 mm off, inside the file's 1e-6 mm but past the half of it a closed-form pcurve is
+ // checked within: each edge's distance from the plane, measured first, is its tolerance
+ // (with margin), and the face reads with its pcurves the edges' projections. A plane has no
+ // parameter box for SMLib to make pcurves in, so without them the face is refused.
+ let imp = step_import(&patch_with_edges_raised(0.8e-6, true)).unwrap();
+ assert_eq!(imp.bodies.len(), 1, "{:?}", imp.warnings);
+ assert!(imp.warnings.iter().any(|w| w.contains("4 edges lie off their faces' surfaces")), "{:?}", imp.warnings);
+ let m = measure(&imp.bodies[0].body).unwrap();
+ assert!(rel(m.area, 900.0) < 1e-6, "{}", m.area);
+}
diff --git a/crates/step/src/read.rs b/crates/step/src/read.rs
index ecae51adc1..f9c9c11fa7 100644
--- a/crates/step/src/read.rs
+++ b/crates/step/src/read.rs
@@ -668,8 +668,10 @@ impl<'a> Reader<'a> {
"TOROIDAL_SURFACE" | "DEGENERATE_TOROIDAL_SURFACE" => {
let major_radius = self.length(p.get(2), "major radius")?;
let minor_radius = positive(self.length(p.get(3), "minor radius")?, "torus minor radius")?;
- if major_radius < 0.0 {
- return Err("torus major radius must not be negative".into());
+ // A negative major radius (outside the schema, which some writers use for a
+ // spindle torus) is the same formula: its tube on the other side of the axis.
+ if !major_radius.is_finite() {
+ return Err("torus major radius must be finite".into());
}
let position = position(self)?;
if e.name() == "DEGENERATE_TOROIDAL_SURFACE" {
diff --git a/crates/step/src/topology.rs b/crates/step/src/topology.rs
index 5ce1bd5668..07453e91cd 100644
--- a/crates/step/src/topology.rs
+++ b/crates/step/src/topology.rs
@@ -83,8 +83,13 @@ const MAX_VERTEX_GAP: f64 = 1.0;
const MAX_EDGE_GAP: f64 = 1.0;
/// Intervals an edge's curve is measured over against each face's surface it bounds.
const EDGE_GAP_SAMPLES: usize = 16;
-/// An edge's tolerance over the largest gap measured on its samples, as a vertex's is.
+/// An edge's tolerance over the largest gap measured between its pcurves and its curve, as the
+/// record check measures it: with margin, as a vertex's.
const EDGE_GAP_MARGIN: f64 = 1.5;
+/// An edge's tolerance over its largest distance from a face's surface, measured before its
+/// pcurve is made: a closed-form pcurve is accepted within half its edge's tolerance
+/// (`pcurve::pcurves_within`), so the tolerance goes past twice the distance.
+const EDGE_SURFACE_MARGIN: f64 = 3.0;
/// A solid (or sheet) read from the file.
#[derive(Clone, Debug)]
@@ -445,16 +450,58 @@ impl<'b, 'a> Builder<'b, 'a> {
Ok(())
}
- /// Edge `e`'s tolerance covers `gap` (with margin): refused if far off.
- fn cover_edge(&mut self, e: u32, gap: f64) -> R<()> {
+ /// An edge's curve as the file has it may lie off a face's surface by more than the file's
+ /// uncertainty states (a B-spline edge whose control points stand 9 µm off its plane, in a
+ /// file that states 10 µm, gets no closed-form pcurve, which is checked within half that).
+ /// On a surface whose nearest point is in closed form (a plane, cylinder, cone, sphere or
+ /// torus) the edge's distance from it is measured along the edge before its pcurve is made,
+ /// and the edge's tolerance covers it. A spline face's gaps are measured on the pcurves its
+ /// kernel makes (`raise_edges`): an iterative nearest point may settle elsewhere on it.
+ fn measure_edges(&mut self, surface: &BSurface, edge_loops: &[Vec<(u32, bool)>]) -> R<()> {
+ if !matches!(
+ surface,
+ BSurface::Plane { .. }
+ | BSurface::PlaneThrough { .. }
+ | BSurface::Cylinder { .. }
+ | BSurface::Cone { .. }
+ | BSurface::Sphere { .. }
+ | BSurface::Torus { .. }
+ ) {
+ return Ok(());
+ }
+ let on = SurfaceEval::new(surface).map_err(|m| m.to_string())?;
+ for l in edge_loops {
+ for &(e, _) in l {
+ let edge = self.edges.get(e as usize).ok_or("edge reference")?;
+ let (curve, [t0, t1]) = match &edge.form {
+ Some((c, i)) => (c, *i),
+ None => (&edge.curve, edge.interval),
+ };
+ let eval = CurveEval::new(curve).map_err(|m| m.to_string())?;
+ let mut gap = 0.0f64;
+ for k in 0..=EDGE_GAP_SAMPLES {
+ let t = t0 + (t1 - t0) * (k as f64 / EDGE_GAP_SAMPLES as f64);
+ let Some(p) = eval.point(t) else { continue };
+ // A point with no nearest point is the pcurves' to refuse, with why.
+ let Some(s) = on.project(p, None, f64::INFINITY).and_then(|q| on.point(q)) else { continue };
+ gap = gap.max(s.dist(p));
+ }
+ self.cover_edge(e, gap, EDGE_SURFACE_MARGIN)?;
+ }
+ }
+ Ok(())
+ }
+
+ /// Edge `e`'s tolerance covers `gap` with `margin`: refused if far off.
+ fn cover_edge(&mut self, e: u32, gap: f64, margin: f64) -> R<()> {
let Some(x) = self.edges.get_mut(e as usize) else { return Err("edge reference".into()) };
- if gap <= x.tolerance {
+ if margin * gap <= x.tolerance {
return Ok(());
}
if !(gap <= MAX_EDGE_GAP) {
return Err(format!("an edge lies {gap} mm off the face's surface"));
}
- x.tolerance = EDGE_GAP_MARGIN * gap;
+ x.tolerance = margin * gap;
self.raised_edges.insert(e);
Ok(())
}
@@ -483,7 +530,7 @@ impl<'b, 'a> Builder<'b, 'a> {
gap = gap.max(s.dist(p));
}
}
- self.cover_edge(e, gap)?;
+ self.cover_edge(e, gap, EDGE_GAP_MARGIN)?;
}
}
Ok(())
@@ -1082,6 +1129,8 @@ impl<'b, 'a> Builder<'b, 'a> {
None => (None, None),
};
let surface = form.clone().unwrap_or_else(|| label.clone());
+ // How far each edge lies off this surface, so its closed form is checked at that.
+ self.measure_edges(&label, &edge_loops)?;
// Closed forms where the geometry has them; the kernel makes the rest (`trims`).
let exact = pcurve::exact_pcurves(&surface, &uses_of(&self.edges, &edge_loops, None)?, tol, box_on_form).map_err(|e| e.to_string())?;
// Without a kernel, a use with neither is refused below with why.
@@ -1104,10 +1153,11 @@ impl<'b, 'a> Builder<'b, 'a> {
// does not wrap: a loop around a closed spline surface without a seam edge jumps across
// its domain.
let natural = surface.natural();
- // At a pole (where the surface collapses to a point across a direction) a loop may jump
- // in that direction: the seam's two uses meet there a period apart.
+ // At a pole (where the surface collapses to a point across a direction, to within the
+ // tolerance, as the pcurves closed the loop there) a loop may jump in that direction: the
+ // seam's two uses meet there a period apart.
let poles = SurfaceEval::new(&surface).ok();
- let at_pole = |uv: [f64; 2]| poles.as_ref().is_some_and(|e| e.pole(uv).iter().any(|p| *p));
+ let at_pole = |uv: [f64; 2]| poles.as_ref().is_some_and(|e| e.pole_within(uv, tol).iter().any(|p| *p));
for (l, pc) in edge_loops.iter().zip(&pcs) {
let mut ends = Vec::with_capacity(l.len());
for (&(_, forward), c) in l.iter().zip(pc) {
@@ -1230,7 +1280,7 @@ fn uses_of<'e>(edges: &'e [EdgeB], edge_loops: &[Vec<(u32, bool)>], given: Optio
Some(g) => Some(g.get(li).and_then(|l| l.get(p)).ok_or("a pcurve the kernel did not make")?),
None => None,
};
- u.push(EdgeUse { edge: e, curve, interval, forward, tolerance: 0.0, given });
+ u.push(EdgeUse { edge: e, curve, interval, forward, tolerance: edge.tolerance, given });
}
uses.push(u);
}
diff --git a/crates/step/src/topology/swept.rs b/crates/step/src/topology/swept.rs
index 2279026599..c26ddda14a 100644
--- a/crates/step/src/topology/swept.rs
+++ b/crates/step/src/topology/swept.rs
@@ -323,23 +323,101 @@ fn revolution(profile: &Curve, axis: &Axis1, ext: &Extent) -> R<BSurface> {
Some(r) => Span::Open { inner: r, outer: r },
None => span(&ts, &seam, is_closed(c))?,
};
- // Stop where the profile crosses the axis outside the face.
+ // Stop where the profile meets the axis outside the face: a circle or ellipse that
+ // meets it is its whole arc on the face's side, pole to pole (closed form), so a face
+ // with one bound around the axis reaches its pole and nothing folds over; another
+ // profile stops where it crosses.
+ let face_mid = match s {
+ Span::Open { inner, .. } => 0.5 * (inner.0 + inner.1),
+ Span::Turn { start } => start + (mid - start).rem_euclid(TAU),
+ };
+ let arc = conic_side_arc(c, o, e, face_mid);
let side = |t: f64| probe(t).map(|q| (q - o).dot(e));
- let s = match s {
- Span::Open { inner, outer } => {
+ let s = match (s, arc) {
+ (_, Some(arc)) => Span::Open { inner: arc, outer: arc },
+ (Span::Open { inner, outer }, None) => {
let lo = crossing(&side, inner.0, outer.0).unwrap_or(outer.0);
let hi = crossing(&side, inner.1, outer.1).unwrap_or(outer.1);
Span::Open { inner, outer: (lo, hi) }
}
- turn => turn,
+ (turn, None) => turn,
};
- bounded(c, s)?
+ let curve = bounded(c, s)?;
+ match arc {
+ Some(arc) => clip_form(curve, arc)?,
+ None => curve,
+ }
}
};
let identity = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]];
Ok(BSurface::PlacedRevolution { profile: Box::new(curve), origin: p3(o), axis: p3(k), matrix: identity, forward: false })
}
+/// A torus whose tube reaches its axis (a spindle or horn torus: major radius at most the
+/// minor, or written with a negative major radius, its tube on the other side of the axis) as
+/// what it is, its tube's meridian circle revolved about its axis: ISO 10303-42 gives the torus
+/// `C + (R + r cos v)(cos u X + sin u Y) + r sin v Z`, the revolution of the circle about `C`'s
+/// Z through `C + R X` with the same normal (∂S/∂u × ∂S/∂v). The revolution keeps the tube's
+/// arc on the face's side of the axis, pole to pole (`revolution`): the face's boundary, not a
+/// degenerate torus's `select_outer`, says which part (the apple or the lemon) it is on.
+fn torus_revolved(position: &Placement, major: f64, minor: f64, ext: &Extent) -> R<BSurface> {
+ // The circle in the X–Z half-plane: its parameter from X towards Z, as the torus's v.
+ let circle = Curve::Circle {
+ position: Placement {
+ origin: crate::geom::add(position.origin, crate::geom::scale(position.ref_direction, major)),
+ axis: crate::geom::scale(position.y(), -1.0),
+ ref_direction: position.ref_direction,
+ },
+ radius: minor,
+ };
+ revolution(&circle, &Axis1 { origin: position.origin, direction: position.axis }, ext)
+}
+
+/// The arc of a circle or ellipse profile on the positive side of the plane through the axis
+/// point `o` square to `e` (the face's side of its axis), as angles: the one round `near`, its
+/// ends where the profile meets that plane; `None` for another profile, or one that does not
+/// meet it. On the conic `O + a cos t X + b sin t Y` the side is `s₀ + A cos t + B sin t =
+/// s₀ + M cos(t − φ)`, zero at `φ ± acos(−s₀/M)`; a profile that only touches the axis (a horn
+/// torus's tube) has its arc a whole turn, both ends at the touching point.
+fn conic_side_arc(c: &Curve, o: Vec3, e: Vec3, near: f64) -> Option<(f64, f64)> {
+ let (position, a, b) = match c {
+ Curve::Circle { position, radius } => (position, *radius, *radius),
+ Curve::Ellipse { position, semi_axis_1, semi_axis_2 } => (position, *semi_axis_1, *semi_axis_2),
+ _ => return None,
+ };
+ let s0 = (v3(position.origin) - o).dot(e);
+ let (ca, cb) = (a * v3(position.ref_direction).dot(e), b * v3(position.y()).dot(e));
+ let m = ca.hypot(cb);
+ let ratio = -s0 / m;
+ if !(m > 0.0 && (-1.0..=1.0).contains(&ratio)) {
+ return None;
+ }
+ let half = ratio.acos();
+ let phi = cb.atan2(ca);
+ let centre = phi + ((near - phi) / TAU).round() * TAU;
+ (centre.is_finite() && half > 0.0).then_some((centre - half, centre + half))
+}
+
+/// A conic's NURBS form (on its quarter grid) cut to the angles `arc` where it reaches past
+/// them: the same curve at the same parameters (`bspline::segment`, exact knot insertion), so
+/// it keeps the grid its edges' forms share and stops where the profile meets the axis.
+fn clip_form(curve: BCurve, (a0, a1): (f64, f64)) -> R<BCurve> {
+ use solidcraft_geom::bspline::{HPoint, segment};
+ let BCurve::RationalSpline { knots, homogeneous } = curve else { return Ok(curve) };
+ let (Some(&k0), Some(&k1)) = (knots.first(), knots.last()) else { return Err("a profile without knots".into()) };
+ let (lo, hi) = (solidcraft_geom::brep::form::param(a0).max(k0), solidcraft_geom::brep::form::param(a1).min(k1));
+ if lo <= k0 && hi >= k1 {
+ return Ok(BCurve::RationalSpline { knots, homogeneous });
+ }
+ if !(lo < hi) {
+ return Err(unsupported("a revolved profile on its axis"));
+ }
+ let degree = knots.len().checked_sub(homogeneous.len() + 1).ok_or("a profile's knots")?;
+ let ctrl: Vec<HPoint> = homogeneous.iter().map(|h| HPoint { x: h[0], y: h[1], z: h[2], w: h[3] }).collect();
+ let (knots, ctrl) = segment(degree, &knots, &ctrl, lo, hi).map_err(|e| format!("a revolved profile cut at its axis: {e}"))?;
+ Ok(BCurve::RationalSpline { knots, homogeneous: ctrl.iter().map(|h| [h.x, h.y, h.z, h.w]).collect() })
+}
+
/// Going from `from` (where `side` is positive or zero) towards `to`, the first parameter
/// where `side` reaches zero, if it does.
fn crossing(side: &dyn Fn(f64) -> Option<f64>, from: f64, to: f64) -> Option<f64> {
@@ -561,11 +639,13 @@ fn map_surface_in(s: &Surface, ext: &Extent, tol: f64, depth: usize, reversed: &
Surface::Sphere { position, radius } => BSurface::Sphere { frame: frame(position), radius: *radius },
Surface::Torus { position, major_radius, minor_radius } => {
if !(major_radius > minor_radius) {
- return Err(unsupported("a spindle or horn torus"));
+ return torus_revolved(position, *major_radius, *minor_radius, ext);
}
BSurface::Torus { frame: frame(position), major_radius: *major_radius, minor_radius: *minor_radius }
}
- Surface::DegenerateTorus { .. } => return Err(unsupported("DEGENERATE_TOROIDAL_SURFACE")),
+ Surface::DegenerateTorus { position, major_radius, minor_radius, .. } => {
+ return torus_revolved(position, *major_radius, *minor_radius, ext);
+ }
Surface::BSpline(b) => super::map_bspline_surface(b)?,
Surface::RectangularTrimmed { basis, .. } => map_surface_in(basis, ext, tol, depth + 1, reversed)?,
Surface::Revolution { profile, axis } => revolution(profile, axis, ext)?,