Wave 224/509: STEP and IGES import: SMLib makes the pcurves that have no closed form (and 3 more)
4 commits, squashed; the originals stay reachable from tag archive/merge-main-develop. -306c7b75bjyviko: pcurve: a rim at a steady pace on a spline face, read from the edge itself -28e0eea80jyviko: pcurve: each use's closed form or none, and a kernel's trims for the rest -1bf206259jyviko: STEP and IGES import: SMLib makes the pcurves that have no closed form -879958721jyviko: pcurves: a flat patch's are a plane's; SMLib's sheet loops read either way round Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ
This commit is contained in:
1 parent
9767f95c31
commit
06c2c6087b
8 files changed
+411
-77
No files matched your search
+148
-37
@@ -84,6 +84,36 @@ pub fn pcurves_within(
|
||||
tolerance: f64,
|
||||
domain: Option<[[f64; 2]; 2]>,
|
||||
) -> Result<Vec<Vec<Curve2>>> {
|
||||
check_size(loops, tolerance)?;
|
||||
let on = On::new(surface_record)?.within(domain);
|
||||
let each = each_pcurve(surface_record, &on, loops, tolerance)?;
|
||||
let mut out = Vec::with_capacity(loops.len());
|
||||
for (l, pcs) in loops.iter().zip(each) {
|
||||
let mut fitted = Vec::with_capacity(l.len());
|
||||
for (u, pc) in l.iter().zip(pcs) {
|
||||
fitted.push((pc?, u.forward));
|
||||
}
|
||||
on.close(&mut fitted, tolerance)?;
|
||||
out.push(fitted.into_iter().map(|(c, _)| c).collect());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// For each loop of a face on `surface`, each use's pcurve where it has a closed form (or is
|
||||
/// given), else `None`: the uses whose pcurves the face's kernel makes ([`Trims`]). Not closed
|
||||
/// into loops; [`pcurves_within`] does that once every use has its pcurve.
|
||||
pub fn exact_pcurves(
|
||||
surface_record: &Surface,
|
||||
loops: &[Vec<EdgeUse<'_>>],
|
||||
tolerance: f64,
|
||||
domain: Option<[[f64; 2]; 2]>,
|
||||
) -> Result<Vec<Vec<Option<Curve2>>>> {
|
||||
check_size(loops, tolerance)?;
|
||||
let on = On::new(surface_record)?.within(domain);
|
||||
Ok(each_pcurve(surface_record, &on, loops, tolerance)?.into_iter().map(|l| l.into_iter().map(|pc| pc.ok()).collect()).collect())
|
||||
}
|
||||
|
||||
fn check_size(loops: &[Vec<EdgeUse<'_>>], tolerance: f64) -> Result<()> {
|
||||
if !(tolerance.is_finite() && tolerance > 0.0 && tolerance <= 1e3) {
|
||||
return Err(Error::Invalid(format!("pcurve tolerance {tolerance}")));
|
||||
}
|
||||
@@ -91,49 +121,96 @@ pub fn pcurves_within(
|
||||
if uses > MAX_USES {
|
||||
return Err(Error::TooLarge(format!("a face with {uses} edge uses")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Each use's pcurve: the given one, or its closed form; a use with neither is its `Failed`
|
||||
/// error, any other error fails the face.
|
||||
fn each_pcurve(surface_record: &Surface, on: &On, loops: &[Vec<EdgeUse<'_>>], tolerance: f64) -> Result<Vec<Vec<Result<Curve2>>>> {
|
||||
let mut budget = Budget(0);
|
||||
surface(surface_record, 0, &mut budget).map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
let on = On::new(surface_record)?.within(domain);
|
||||
// A seam edge used twice is fitted once.
|
||||
let mut done: Vec<(u32, Curve2)> = Vec::new();
|
||||
// A seam edge used twice is worked out once.
|
||||
let mut done: Vec<(u32, Result<Curve2>)> = Vec::new();
|
||||
let mut out = Vec::with_capacity(loops.len());
|
||||
for (w, l) in loops.iter().enumerate() {
|
||||
let mut fitted = Vec::with_capacity(l.len());
|
||||
let mut pcs = Vec::with_capacity(l.len());
|
||||
for (i, u) in l.iter().enumerate() {
|
||||
if let Some(given) = u.given {
|
||||
fitted.push((own_pcurve(given, u.interval, &mut budget).map_err(|e| Error::Invalid(format!("loop {w} use {i}: {e}")))?, u.forward));
|
||||
pcs.push(Ok(own_pcurve(given, u.interval, &mut budget).map_err(|e| Error::Invalid(format!("loop {w} use {i}: {e}")))?));
|
||||
continue;
|
||||
}
|
||||
let pc = match done.iter().find(|(e, _)| *e == u.edge) {
|
||||
Some((_, pc)) => pc.clone(),
|
||||
None => {
|
||||
curve(u.curve, 0, &mut budget).map_err(|e| Error::Invalid(format!("loop {w} use {i}: {e}")))?;
|
||||
interval(&u.interval, curve_natural(u.curve)).map_err(|e| Error::Invalid(format!("loop {w} use {i}: {e}")))?;
|
||||
let c = CurveEval::new(u.curve)?;
|
||||
// An edge record that holds a looser tolerance than the face's (another
|
||||
// kernel's approximated edge) is fitted to its own, up to the same cap.
|
||||
let own = if u.tolerance.is_finite() && u.tolerance <= 1e3 { tolerance.max(u.tolerance) } else { tolerance };
|
||||
let pc = on.pcurve(u.curve, &c, u.interval, own).map_err(|e| {
|
||||
let at = |t: f64| c.point(t).map(|p| [p.x, p.y, p.z]);
|
||||
let message = format!("pcurve of loop {w} use {i} ({:?} to {:?}): {e}", at(u.interval[0]), at(u.interval[1]));
|
||||
match e {
|
||||
Error::Invalid(_) => Error::Invalid(message),
|
||||
Error::Failed(_) => Error::Failed(message),
|
||||
Error::TooLarge(_) => Error::TooLarge(message),
|
||||
}
|
||||
})?;
|
||||
done.push((u.edge, pc.clone()));
|
||||
pc
|
||||
if let Some((_, pc)) = done.iter().find(|(e, _)| *e == u.edge) {
|
||||
pcs.push(pc.clone());
|
||||
continue;
|
||||
}
|
||||
curve(u.curve, 0, &mut budget).map_err(|e| Error::Invalid(format!("loop {w} use {i}: {e}")))?;
|
||||
interval(&u.interval, curve_natural(u.curve)).map_err(|e| Error::Invalid(format!("loop {w} use {i}: {e}")))?;
|
||||
let c = CurveEval::new(u.curve)?;
|
||||
// An edge record that holds a looser tolerance than the face's (another kernel's
|
||||
// approximated edge) is checked against its own, up to the same cap.
|
||||
let own = if u.tolerance.is_finite() && u.tolerance <= 1e3 { tolerance.max(u.tolerance) } else { tolerance };
|
||||
let pc = on.pcurve(u.curve, &c, u.interval, own).map_err(|e| {
|
||||
let at = |t: f64| c.point(t).map(|p| [p.x, p.y, p.z]);
|
||||
let message = format!("pcurve of loop {w} use {i} ({:?} to {:?}): {e}", at(u.interval[0]), at(u.interval[1]));
|
||||
match e {
|
||||
Error::Invalid(_) => Error::Invalid(message),
|
||||
Error::Failed(_) => Error::Failed(message),
|
||||
Error::TooLarge(_) => Error::TooLarge(message),
|
||||
}
|
||||
};
|
||||
fitted.push((pc, u.forward));
|
||||
});
|
||||
if let Err(e @ (Error::Invalid(_) | Error::TooLarge(_))) = pc {
|
||||
return Err(e);
|
||||
}
|
||||
done.push((u.edge, pc.clone()));
|
||||
pcs.push(pc);
|
||||
}
|
||||
on.close(&mut fitted, tolerance)?;
|
||||
out.push(fitted.into_iter().map(|(c, _)| c).collect());
|
||||
out.push(pcs);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// One edge of a face handed to a kernel for its pcurves ([`TrimFace`]).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct TrimEdge<'a> {
|
||||
/// What the edge is, and the NURBS form it is parameterised on when it has one (as
|
||||
/// [`super::Edge`]).
|
||||
pub curve: &'a Curve,
|
||||
pub nurbs: Option<&'a Curve>,
|
||||
pub interval: [f64; 2],
|
||||
/// Into [`TrimFace::vertices`].
|
||||
pub vertices: [u32; 2],
|
||||
pub tolerance: f64,
|
||||
}
|
||||
|
||||
/// One edge use of a [`TrimFace`]'s loop: its edge (into [`TrimFace::edges`]), whether the loop
|
||||
/// runs along it, and its exact pcurve where it has one.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct TrimUse {
|
||||
pub edge: u32,
|
||||
pub forward: bool,
|
||||
pub pcurve: Option<Curve2>,
|
||||
}
|
||||
|
||||
/// A face whose pcurves are partly unknown, as a kernel takes it to make them: its surface as
|
||||
/// [`super::Face`] holds it (what it is, the NURBS form it is parameterised on, the parameter
|
||||
/// box), its edges and their vertices, and its loops (relative to the surface's natural normal).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct TrimFace<'a> {
|
||||
pub surface: &'a Surface,
|
||||
pub nurbs: Option<&'a Surface>,
|
||||
pub domain: [[f64; 2]; 2],
|
||||
pub edges: Vec<TrimEdge<'a>>,
|
||||
pub vertices: Vec<[f64; 3]>,
|
||||
pub loops: Vec<Vec<TrimUse>>,
|
||||
pub tolerance: f64,
|
||||
}
|
||||
|
||||
/// A kernel that makes the pcurves of a face's uses that have no closed form, keeping the given
|
||||
/// ones: for each loop, every use's pcurve on its edge's interval in its curve's direction.
|
||||
pub trait Trims {
|
||||
fn trims(&self, face: &TrimFace<'_>) -> std::result::Result<Vec<Vec<Curve2>>, String>;
|
||||
}
|
||||
|
||||
/// A producer's own pcurve, checked as a record: a valid 2D B-spline on the use's interval
|
||||
/// (within 10⁻⁹ of its magnitude, the schema's slack for a linear remap's rounding).
|
||||
fn own_pcurve(c: &Curve2, [t0, t1]: [f64; 2], budget: &mut Budget) -> Result<Curve2> {
|
||||
@@ -164,6 +241,30 @@ fn cut(c: Curve2, [t0, t1]: [f64; 2]) -> Result<Curve2> {
|
||||
})
|
||||
}
|
||||
|
||||
/// A degree-1 patch of four control points on a parallelogram (a plane as a file's B-spline
|
||||
/// writes it) as that plane: the patch is affine in (u, v), so it is the plane at every
|
||||
/// parameter, and its pcurves have the plane's closed forms.
|
||||
fn flat_patch(s: &Surface) -> Option<Surface> {
|
||||
let Surface::Spline { u_knots, v_knots, points } = s else { return None };
|
||||
let (&[a, a1, b, b1], &[c, c1, d, d1]) = (u_knots.as_slice(), v_knots.as_slice()) else { return None };
|
||||
let [row0, row1] = points.as_slice() else { return None };
|
||||
let (&[p00, p01], &[p10, p11]) = (row0.as_slice(), row1.as_slice()) else { return None };
|
||||
let [p00, p01, p10, p11] = [p00, p01, p10, p11].map(Vec3::from);
|
||||
if a != a1 || b != b1 || c != c1 || d != d1 || !(a < b && c < d) {
|
||||
return None;
|
||||
}
|
||||
let size = [p00, p01, p10, p11].iter().flat_map(|p| [p.x.abs(), p.y.abs(), p.z.abs()]).fold(1.0, f64::max);
|
||||
if (p00 + p11 - p10 - p01).len() > EXACT * size {
|
||||
return None;
|
||||
}
|
||||
let (du, dv) = ((p10 - p00) * (1.0 / (b - a)), (p01 - p00) * (1.0 / (d - c)));
|
||||
if !(du.cross(dv).len() > EXACT * size * size) {
|
||||
return None;
|
||||
}
|
||||
let origin = p00 - du * a - dv * c;
|
||||
Some(Surface::Plane { origin: [origin.x, origin.y, origin.z], u_axis: [du.x, du.y, du.z], v_axis: [dv.x, dv.y, dv.z] })
|
||||
}
|
||||
|
||||
/// What a curve record is, for a message.
|
||||
fn curve_kind(c: &Curve) -> &'static str {
|
||||
match c {
|
||||
@@ -189,7 +290,8 @@ struct On {
|
||||
|
||||
impl On {
|
||||
fn new(s: &Surface) -> Result<Self> {
|
||||
let surface = SurfaceEval::new(s)?;
|
||||
let flat = flat_patch(s);
|
||||
let surface = SurfaceEval::new(flat.as_ref().unwrap_or(s))?;
|
||||
let dom = surface.domain();
|
||||
Ok(On { surface, starts: uv::Starts::default(), dom, face: None })
|
||||
}
|
||||
@@ -365,14 +467,23 @@ impl On {
|
||||
candidates.push(line([m[0], a[1]], [m[0], b[1]]));
|
||||
candidates.push(line([a[0], m[1]], [b[0], m[1]]));
|
||||
}
|
||||
// u or v the edge's own parameter, either way along and offset (forms on one frame's
|
||||
// quarter grid, or on the same grid turned over), the other fixed.
|
||||
if let Some([u, v]) = self.project_in(pm, exact) {
|
||||
// u or v moving at a steady pace in the edge's own parameter, the other fixed (or both
|
||||
// moving): a rim on the face's quarter grid, its knots scaled or turned over (a closed
|
||||
// rim's two ends are one point on the seam, so its pace is read inside it, from a quarter
|
||||
// to three quarters along, unwrapped from the middle).
|
||||
if let Some(m) = self.project_in(pm, exact) {
|
||||
let tm = 0.5 * (t0 + t1);
|
||||
for sign in [1.0, -1.0] {
|
||||
let (cu, cv) = (u - sign * tm, v - sign * tm);
|
||||
candidates.push(line([cu + sign * t0, v], [cu + sign * t1, v]));
|
||||
candidates.push(line([u, cv + sign * t0], [u, cv + sign * t1]));
|
||||
let (ta, tb) = (t0 + 0.25 * (t1 - t0), t0 + 0.75 * (t1 - t0));
|
||||
let near = |t: f64| curve.point(t).and_then(|p| self.project(p, Some(m), exact));
|
||||
if let (Some(a), Some(b)) = (near(ta), near(tb)) {
|
||||
let pace = [(b[0] - a[0]) / (tb - ta), (b[1] - a[1]) / (tb - ta)];
|
||||
let at = |t: f64, moving: [bool; 2]| {
|
||||
let d = t - tm;
|
||||
[m[0] + if moving[0] { pace[0] * d } else { 0.0 }, m[1] + if moving[1] { pace[1] * d } else { 0.0 }]
|
||||
};
|
||||
for moving in [[true, false], [false, true], [true, true]] {
|
||||
candidates.push(line(at(t0, moving), at(t1, moving)));
|
||||
}
|
||||
}
|
||||
}
|
||||
candidates.into_iter().find(|pc| self.lifts(pc, curve, [t0, t1], exact))
|
||||
|
||||
@@ -866,7 +866,7 @@ impl Reader {
|
||||
/// the file does not parse or has no solid the reader can read.
|
||||
pub fn step_orientation_errors(text: &str) -> std::result::Result<Vec<String>, String> {
|
||||
let ex = p21::parse(text)?;
|
||||
let read = solidcraft_step::topology::read_solids(&ex);
|
||||
let read = solidcraft_step::topology::read_solids_with(&ex, &solidcraft_smlib::pcurves::SmlibTrims);
|
||||
if read.solids.is_empty() {
|
||||
return Err(read.failures.first().map_or_else(|| "the file has no solids".into(), |f| format!("solid #{}: {}", f.item, f.message)));
|
||||
}
|
||||
|
||||
@@ -85,7 +85,7 @@ fn placed(body: &Body, m: &M4) -> crate::Result<Body> {
|
||||
/// and brought back as a body: the part SMLib made of the file. A solid the reader or SMLib
|
||||
/// refuses is not imported, with the reason.
|
||||
pub(super) fn smlib_part(ex: &Exchange, item: u64, units: Units) -> std::result::Result<(Part, Vec<String>), Failure> {
|
||||
let solid = solidcraft_step::topology::read_solid(ex, item, units).map_err(|msg| Failure { read: true, msg })?;
|
||||
let solid = solidcraft_step::topology::read_solid_with(ex, item, units, &solidcraft_smlib::pcurves::SmlibTrims).map_err(|msg| Failure { read: true, msg })?;
|
||||
let failed = |e: KernelError| Failure { read: false, msg: e.to_string().trim_start_matches("the operation failed: ").to_string() };
|
||||
let (brep, smlib_order) = crate::native::smlib_record_ordered(&solid.brep).map_err(failed)?;
|
||||
let (body, body_order) = crate::native::body_from_smlib_ordered(&brep).map_err(failed)?;
|
||||
|
||||
@@ -1682,7 +1682,7 @@ fn step_conformance_parts_read_back_their_exact_shape() {
|
||||
/// measured as the body of that record.
|
||||
pub(super) fn schema_4_volume(text: &str) -> f64 {
|
||||
let ex = solidcraft_step::p21::parse(text).unwrap();
|
||||
let r = solidcraft_step::topology::read_solids(&ex);
|
||||
let r = solidcraft_step::topology::read_solids_with(&ex, &solidcraft_smlib::pcurves::SmlibTrims);
|
||||
assert!(r.failures.is_empty() && r.solids.len() == 1, "{:?}", r.failures);
|
||||
measure(&Body::from_record(r.solids[0].brep.clone()).unwrap()).unwrap().volume
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
//! - Every end value (edge intervals, face domains) is already in the flat arrays' units, radians
|
||||
//! for angles; the C side converts them to SMLib's own pointwise.
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
|
||||
use solidcraft_geom::brep as b;
|
||||
|
||||
@@ -85,7 +85,7 @@ fn z_axis(f: &b::Frame) -> [f64; 3] {
|
||||
pub fn arrays(brep: &b::Brep, trusted: bool) -> R<Arrays> {
|
||||
brep.validate().map_err(|e| Unsupported::Invalid(e.0))?;
|
||||
let brep = analytic::analytic(brep)?;
|
||||
laid_out(brep.as_ref(), trusted, true)
|
||||
laid_out(brep.as_ref(), trusted, true, &HashSet::new())
|
||||
}
|
||||
|
||||
/// [`arrays`] with every surface as the record holds it: a round face truck holds as a rational
|
||||
@@ -94,12 +94,19 @@ pub fn arrays(brep: &b::Brep, trusted: bool) -> R<Arrays> {
|
||||
/// surfaces. A revolution is still refused (SMLib has no such surface).
|
||||
pub fn arrays_keeping_splines(brep: &b::Brep, trusted: bool) -> R<Arrays> {
|
||||
brep.validate().map_err(|e| Unsupported::Invalid(e.0))?;
|
||||
laid_out(brep, trusted, false)
|
||||
laid_out(brep, trusted, false, &HashSet::new())
|
||||
}
|
||||
|
||||
/// The flat arrays of a record whose uses in `bare` (face, loop, position) go without their
|
||||
/// UV trims, for SMLib to make (their pcurves in the record are not read): what
|
||||
/// [`crate::pcurves`] hands SMLib. Not validated, as its bare uses have no pcurves.
|
||||
pub(crate) fn arrays_with_bare_uses(brep: &b::Brep, bare: &HashSet<(u32, u32, u32)>) -> R<Arrays> {
|
||||
laid_out(brep, true, true, bare)
|
||||
}
|
||||
|
||||
/// The flat arrays; `analytic`: a plane on any axes goes as SMLib's plane (else, off unit
|
||||
/// orthogonal axes, as the bilinear patch it is).
|
||||
fn laid_out(brep: &b::Brep, trusted: bool, analytic: bool) -> R<Arrays> {
|
||||
/// orthogonal axes, as the bilinear patch it is). The uses in `bare` go without UV trims.
|
||||
fn laid_out(brep: &b::Brep, trusted: bool, analytic: bool, bare: &HashSet<(u32, u32, u32)>) -> R<Arrays> {
|
||||
let mut a = Arrays::default();
|
||||
|
||||
// Regions and shells. Each region gets its own copy of each shell it lists.
|
||||
@@ -174,7 +181,7 @@ fn laid_out(brep: &b::Brep, trusted: bool, analytic: bool) -> R<Arrays> {
|
||||
let any_spline_face =
|
||||
brep.faces.iter().any(|f| f.nurbs.is_some() || matches!(f.surface, b::Surface::Spline { .. } | b::Surface::RationalSpline { .. }));
|
||||
let any_form = brep.faces.iter().any(|f| f.nurbs.is_some());
|
||||
for f in &brep.faces {
|
||||
for (fi, f) in brep.faces.iter().enumerate() {
|
||||
a.i(flat::FACE_LOOP_COUNT).push(int(f.loops.len())?);
|
||||
a.i(flat::FACE_TRIM_TYPE).push(0);
|
||||
// A face with a NURBS form: what it is (its analytic entry), then the NURBS it is
|
||||
@@ -190,7 +197,7 @@ fn laid_out(brep: &b::Brep, trusted: bool, analytic: bool) -> R<Arrays> {
|
||||
if any_form {
|
||||
a.i(flat::FACE_NURBS_FORM).push(i64::from(f.nurbs.is_some()));
|
||||
}
|
||||
for l in &f.loops {
|
||||
for (li, l) in f.loops.iter().enumerate() {
|
||||
match l {
|
||||
b::Loop::Vertex { vertex } => {
|
||||
a.i(flat::LOOP_EDGEUSE_COUNT).push(0);
|
||||
@@ -199,11 +206,11 @@ fn laid_out(brep: &b::Brep, trusted: bool, analytic: bool) -> R<Arrays> {
|
||||
b::Loop::Edges { edges } => {
|
||||
a.i(flat::LOOP_EDGEUSE_COUNT).push(int(edges.len())?);
|
||||
a.i(flat::LOOP_VERTEX).push(-1);
|
||||
for u in edges {
|
||||
for (p, u) in edges.iter().enumerate() {
|
||||
a.i(flat::EDGEUSE_EDGE).push(i64::from(u.edge));
|
||||
a.i(flat::EDGEUSE_ORIENTATION).push(i64::from(u.forward));
|
||||
if any_spline_face {
|
||||
if spline {
|
||||
if spline && !bare.contains(&(idx(fi)?, idx(li)?, idx(p)?)) {
|
||||
let shift = intervals.get(u.edge as usize).map_or(0.0, |i| i.1);
|
||||
trim(&mut a, &u.pcurve, u.forward, shift)?;
|
||||
} else {
|
||||
|
||||
@@ -23,6 +23,7 @@ pub mod history;
|
||||
pub mod import;
|
||||
mod measure;
|
||||
mod ops;
|
||||
pub mod pcurves;
|
||||
mod sheets;
|
||||
mod split;
|
||||
pub mod ssi;
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
//! SMLib's own pcurves for a face's uses that have no closed form (an approximated intersection
|
||||
//! curve on a cone, a file's spline edge on a spline surface): the face goes to SMLib alone, an
|
||||
//! open sheet, with the trims it has and without the others, and SMLib makes those as it makes
|
||||
//! every trim it needs (`SmEdgeuse::GetOrCreateUVTrimCurve`, when the body is exported). They are
|
||||
//! SMLib's, relayed as it holds them on the record's parameters; nothing here fits a curve.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use solidcraft_geom::brep::pcurve::{TrimFace, Trims};
|
||||
use solidcraft_geom::brep::{self as b, Curve2, EdgeUseRef, Loop, OrientedEdge, OrientedFace, Region, Shell, Vertex};
|
||||
|
||||
/// [`Trims`] by SMLib.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct SmlibTrims;
|
||||
|
||||
impl Trims for SmlibTrims {
|
||||
fn trims(&self, face: &TrimFace<'_>) -> Result<Vec<Vec<Curve2>>, String> {
|
||||
trims(face).map_err(|e| format!("SMLib pcurves: {e}"))
|
||||
}
|
||||
}
|
||||
|
||||
fn trims(face: &TrimFace<'_>) -> Result<Vec<Vec<Curve2>>, String> {
|
||||
let (record, bare) = sheet(face)?;
|
||||
let arrays = crate::import::arrays_with_bare_uses(&record, &bare).map_err(|e| e.to_string())?;
|
||||
let body = crate::flat::Flat::from_arrays(&arrays).and_then(|f| f.import()).map_err(|e| e.to_string())?;
|
||||
let (out, order) = body.to_native_ordered().map_err(|e| e.to_string())?;
|
||||
let [made] = out.faces.as_slice() else { return Err(format!("SMLib made {} faces of one", out.faces.len())) };
|
||||
let made_uses: Vec<&OrientedEdge> = made
|
||||
.loops
|
||||
.iter()
|
||||
.flat_map(|l| match l {
|
||||
Loop::Edges { edges } => edges.as_slice(),
|
||||
Loop::Vertex { .. } => &[],
|
||||
})
|
||||
.collect();
|
||||
// SMLib keeps the edges in the order they came; the record renumbers them.
|
||||
let edge_of = |u: u32| order.edges.get(u as usize).copied().ok_or("an edge SMLib lost");
|
||||
// A sheet's loops come back the way SMLib runs them, which may be against ours: a use is the
|
||||
// same pcurve either way (on its edge's interval in its curve's direction), and the loop's
|
||||
// way round is read from an edge the face uses once.
|
||||
let ours = face.loops.iter().flatten();
|
||||
let once = ours.clone().find(|u| ours.clone().filter(|v| v.edge == u.edge).count() == 1).ok_or("a face of seam edges only")?;
|
||||
let at = edge_of(once.edge)?;
|
||||
let reversed = made_uses.iter().find(|m| m.edge as usize == at).ok_or("a use SMLib did not keep")?.forward != once.forward;
|
||||
let mut result = Vec::with_capacity(face.loops.len());
|
||||
for l in &face.loops {
|
||||
let mut pcs = Vec::with_capacity(l.len());
|
||||
for u in l {
|
||||
let e = edge_of(u.edge)?;
|
||||
let edge = out.edges.get(e).ok_or("an edge SMLib lost")?;
|
||||
let ours = face.edges.get(u.edge as usize).ok_or("edge reference")?;
|
||||
let slack = 1e-9 * ours.interval.iter().fold(1.0f64, |m, t| m.max(t.abs()));
|
||||
if (0..2).any(|k| (edge.interval[k] - ours.interval[k]).abs() > slack) {
|
||||
return Err(format!("SMLib moved an edge's interval from {:?} to {:?}", ours.interval, edge.interval));
|
||||
}
|
||||
let found = made_uses.iter().find(|m| m.edge as usize == e && m.forward == (u.forward != reversed));
|
||||
pcs.push(found.ok_or("a use SMLib did not keep")?.pcurve.clone());
|
||||
}
|
||||
result.push(pcs);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// The face as a one-face open sheet, and its uses that go without trims.
|
||||
fn sheet(face: &TrimFace<'_>) -> Result<(b::Brep, HashSet<(u32, u32, u32)>), String> {
|
||||
let mut edges: Vec<b::Edge> = face
|
||||
.edges
|
||||
.iter()
|
||||
.map(|e| b::Edge {
|
||||
curve: e.curve.clone(),
|
||||
nurbs: e.nurbs.cloned(),
|
||||
interval: e.interval,
|
||||
vertices: e.vertices,
|
||||
tolerance: e.tolerance,
|
||||
uses: Vec::new(),
|
||||
})
|
||||
.collect();
|
||||
let mut bare = HashSet::new();
|
||||
let mut loops = Vec::with_capacity(face.loops.len());
|
||||
for (li, l) in face.loops.iter().enumerate() {
|
||||
let li = u32::try_from(li).map_err(|_| "too many loops")?;
|
||||
let mut uses = Vec::with_capacity(l.len());
|
||||
for (p, u) in l.iter().enumerate() {
|
||||
let p = u32::try_from(p).map_err(|_| "too many uses")?;
|
||||
let edge = edges.get_mut(u.edge as usize).ok_or("edge reference")?;
|
||||
edge.uses.push(EdgeUseRef { face: 0, r#loop: li, position: p, upper: !u.forward });
|
||||
let pcurve = match &u.pcurve {
|
||||
Some(pc) => pc.clone(),
|
||||
None => {
|
||||
bare.insert((0, li, p));
|
||||
// Not read: the use goes without a trim (`arrays_with_bare_uses`).
|
||||
Curve2::Spline { knots: vec![edge.interval[0], edge.interval[0], edge.interval[1], edge.interval[1]], points: vec![[0.0; 2]; 2] }
|
||||
}
|
||||
};
|
||||
uses.push(OrientedEdge { edge: u.edge, forward: u.forward, pcurve });
|
||||
}
|
||||
loops.push(Loop::Edges { edges: uses });
|
||||
}
|
||||
let vertices = face.vertices.iter().map(|&point| Vertex { point, tolerance: face.tolerance }).collect();
|
||||
let record = b::Brep {
|
||||
version: b::VERSION,
|
||||
tolerance: face.tolerance,
|
||||
regions: vec![Region { shells: vec![0], void: false }],
|
||||
shells: vec![Shell::Faces { faces: vec![OrientedFace { face: 0, forward: true }], wires: Vec::new() }],
|
||||
faces: vec![b::Face { surface: face.surface.clone(), nurbs: face.nurbs.cloned(), domain: face.domain, loops }],
|
||||
edges,
|
||||
vertices,
|
||||
};
|
||||
Ok((record, bare))
|
||||
}
|
||||
+133
-28
@@ -27,8 +27,9 @@
|
||||
//! distance (with margin) as its tolerance; a face whose edges lie off its surface gets its
|
||||
//! pcurves fitted at a looser tolerance, which its edges then carry.
|
||||
//!
|
||||
//! Pcurves are computed from the 3D edges and our surfaces ([`pcurve::pcurves`]); the file's
|
||||
//! own PCURVE entities are not used.
|
||||
//! Pcurves are the closed forms the 3D edges have on our surfaces ([`pcurve::exact_pcurves`]); a
|
||||
//! use with none gets its pcurve from the kernel ([`read_solids_with`], SMLib's own trims). The
|
||||
//! file's own PCURVE entities are not used.
|
||||
//!
|
||||
//! Input is hostile: every reference is checked, nesting and counts are capped, and the work of
|
||||
//! a whole file is bounded (shared shells count each time a solid uses them).
|
||||
@@ -38,7 +39,7 @@ use std::f64::consts::TAU;
|
||||
|
||||
use solidcraft_geom::Vec3;
|
||||
use solidcraft_geom::brep::eval::{CurveEval, SurfaceEval};
|
||||
use solidcraft_geom::brep::pcurve::{self, EdgeUse};
|
||||
use solidcraft_geom::brep::pcurve::{self, EdgeUse, TrimEdge, TrimFace, TrimUse, Trims};
|
||||
use solidcraft_geom::brep::{
|
||||
self, Brep, Curve as BCurve, Curve2, Edge, EdgeUseRef, Face, Frame, Loop, Natural, OrientedEdge, OrientedFace, Region, Shell,
|
||||
Surface as BSurface, Vertex,
|
||||
@@ -227,8 +228,18 @@ impl Index {
|
||||
}
|
||||
|
||||
/// Read every solid of the file. A solid that cannot be read is listed in
|
||||
/// [`Solids::failures`] with its reason; the others are still read.
|
||||
/// [`Solids::failures`] with its reason; the others are still read. A face's use with no
|
||||
/// closed-form pcurve refuses its solid: [`read_solids_with`] has a kernel make those.
|
||||
pub fn read_solids(ex: &Exchange) -> Solids {
|
||||
read_solids_in(ex, None)
|
||||
}
|
||||
|
||||
/// [`read_solids`], with `trims` making the pcurves of uses that have no closed form.
|
||||
pub fn read_solids_with(ex: &Exchange, trims: &dyn Trims) -> Solids {
|
||||
read_solids_in(ex, Some(trims))
|
||||
}
|
||||
|
||||
fn read_solids_in(ex: &Exchange, trims: Option<&dyn Trims>) -> Solids {
|
||||
let mut items: Vec<u64> = ex.entities.iter().filter(|(_, e)| SOLID_ITEMS.contains(&e.name())).map(|(id, _)| *id).collect();
|
||||
items.sort_unstable();
|
||||
let index = Index::new(ex);
|
||||
@@ -247,7 +258,7 @@ pub fn read_solids(ex: &Exchange) -> Solids {
|
||||
(Reader::new(ex, c.units), c)
|
||||
});
|
||||
let context = *context;
|
||||
match read_with(ex, reader, item, context, &mut budget) {
|
||||
match read_with(ex, reader, item, context, &mut budget, trims) {
|
||||
Ok(mut s) => {
|
||||
s.product = index.product.get(&item).cloned();
|
||||
if s.name.is_empty()
|
||||
@@ -267,7 +278,14 @@ pub fn read_solids(ex: &Exchange) -> Solids {
|
||||
pub fn read_solid(ex: &Exchange, item: u64, context: units::Context) -> R<Solid> {
|
||||
let mut reader = Reader::new(ex, context.units);
|
||||
let mut budget = MAX_FILE_FACES;
|
||||
read_with(ex, &mut reader, item, context, &mut budget)
|
||||
read_with(ex, &mut reader, item, context, &mut budget, None)
|
||||
}
|
||||
|
||||
/// [`read_solid`], with `trims` making the pcurves of uses that have no closed form.
|
||||
pub fn read_solid_with(ex: &Exchange, item: u64, context: units::Context, trims: &dyn Trims) -> R<Solid> {
|
||||
let mut reader = Reader::new(ex, context.units);
|
||||
let mut budget = MAX_FILE_FACES;
|
||||
read_with(ex, &mut reader, item, context, &mut budget, Some(trims))
|
||||
}
|
||||
|
||||
/// The base tolerance of a context.
|
||||
@@ -275,11 +293,18 @@ pub fn tolerance(context: &units::Context) -> f64 {
|
||||
context.uncertainty.unwrap_or(DEFAULT_TOLERANCE).clamp(MIN_TOLERANCE, MAX_FIT_TOLERANCE)
|
||||
}
|
||||
|
||||
fn read_with<'a>(ex: &'a Exchange, reader: &mut Reader<'a>, item: u64, context: units::Context, budget: &mut usize) -> R<Solid> {
|
||||
fn read_with<'a>(
|
||||
ex: &'a Exchange,
|
||||
reader: &mut Reader<'a>,
|
||||
item: u64,
|
||||
context: units::Context,
|
||||
budget: &mut usize,
|
||||
trims: Option<&dyn Trims>,
|
||||
) -> R<Solid> {
|
||||
let e = entity(ex, item)?;
|
||||
let p = e.params();
|
||||
let name = p.first().and_then(Param::as_str).unwrap_or("").to_string();
|
||||
let mut b = Builder::new(ex, reader, tolerance(&context), budget);
|
||||
let mut b = Builder::new(ex, reader, tolerance(&context), budget, trims);
|
||||
let (shells, kind) = match e.name() {
|
||||
"MANIFOLD_SOLID_BREP" => (vec![b.shell(rid(p.get(1), "outer shell")?)?], Kind::Solid),
|
||||
"BREP_WITH_VOIDS" => {
|
||||
@@ -347,6 +372,8 @@ struct Builder<'b, 'a> {
|
||||
reader: &'b mut Reader<'a>,
|
||||
tol: f64,
|
||||
budget: &'b mut usize,
|
||||
/// Makes the pcurves of uses that have no closed form; without it such a face is refused.
|
||||
trims: Option<&'b dyn Trims>,
|
||||
vertex_ids: HashMap<u64, u32>,
|
||||
vertices: Vec<Vertex>,
|
||||
/// STEP edge → schema edge, and whether the schema edge runs with the STEP edge.
|
||||
@@ -358,12 +385,13 @@ struct Builder<'b, 'a> {
|
||||
}
|
||||
|
||||
impl<'b, 'a> Builder<'b, 'a> {
|
||||
fn new(ex: &'a Exchange, reader: &'b mut Reader<'a>, tol: f64, budget: &'b mut usize) -> Self {
|
||||
fn new(ex: &'a Exchange, reader: &'b mut Reader<'a>, tol: f64, budget: &'b mut usize, trims: Option<&'b dyn Trims>) -> Self {
|
||||
Builder {
|
||||
ex,
|
||||
reader,
|
||||
tol,
|
||||
budget,
|
||||
trims,
|
||||
vertex_ids: HashMap::new(),
|
||||
vertices: Vec::new(),
|
||||
edge_ids: HashMap::new(),
|
||||
@@ -965,23 +993,6 @@ impl<'b, 'a> Builder<'b, 'a> {
|
||||
// Which loop index in `face.loops` each edge loop is.
|
||||
let positions: Vec<usize> = face.loops.iter().enumerate().filter(|(_, l)| matches!(l, LoopB::Edges(_))).map(|(i, _)| i).collect();
|
||||
let tol = self.tol;
|
||||
// The face's pcurves on `on`, each edge on its NURBS form.
|
||||
let pcurves_on = |on: &BSurface, domain: Option<[[f64; 2]; 2]>| -> R<Vec<Vec<Curve2>>> {
|
||||
let mut uses = Vec::with_capacity(edge_loops.len());
|
||||
for l in &edge_loops {
|
||||
let mut u = Vec::with_capacity(l.len());
|
||||
for &(e, forward) in l {
|
||||
let edge = self.edges.get(e as usize).ok_or("edge reference")?;
|
||||
let (curve, interval) = match &edge.form {
|
||||
Some((c, i)) => (c, *i),
|
||||
_ => (&edge.curve, edge.interval),
|
||||
};
|
||||
u.push(EdgeUse { edge: e, curve, interval, forward, tolerance: 0.0, given: None });
|
||||
}
|
||||
uses.push(u);
|
||||
}
|
||||
pcurve::pcurves_within(on, &uses, tol, domain).map_err(|e| e.to_string())
|
||||
};
|
||||
// A cylinder, cone, sphere, torus or revolution on its NURBS form, over the extent of its
|
||||
// boundary on its label; then every pcurve on the forms.
|
||||
let form = match brep::form::frame_of(&label) {
|
||||
@@ -1004,8 +1015,21 @@ impl<'b, 'a> Builder<'b, 'a> {
|
||||
Some((f, d)) => (Some(f), Some(d)),
|
||||
None => (None, None),
|
||||
};
|
||||
let surface = form.clone().unwrap_or(label);
|
||||
let pcs = pcurves_on(&surface, box_on_form)?;
|
||||
let surface = form.clone().unwrap_or_else(|| label.clone());
|
||||
// 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.
|
||||
let made = match self.trims {
|
||||
Some(trims) if exact.iter().flatten().any(Option::is_none) => {
|
||||
let domain = match box_on_form {
|
||||
Some(d) => d,
|
||||
None => natural_box(&surface).ok_or_else(|| unsupported("a face on an unbounded surface without closed-form pcurves"))?,
|
||||
};
|
||||
Some(trims.trims(&self.trim_face(&label, form.as_ref(), domain, &edge_loops, exact)?)?)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let pcs = pcurve::pcurves_within(&surface, &uses_of(&self.edges, &edge_loops, made.as_ref())?, tol, box_on_form).map_err(|e| e.to_string())?;
|
||||
// Signed areas of the loops that close in (u, v).
|
||||
let periods = natural_periods(&surface);
|
||||
// Each use starts near where the one before it ends, along a bounded direction that
|
||||
@@ -1071,6 +1095,87 @@ impl<'b, 'a> Builder<'b, 'a> {
|
||||
}
|
||||
}
|
||||
|
||||
impl Builder<'_, '_> {
|
||||
/// The face as a kernel takes it to make its missing pcurves: its edges and vertices
|
||||
/// numbered within it, each use with its closed-form pcurve where `exact` has one.
|
||||
fn trim_face<'s>(
|
||||
&'s self,
|
||||
surface: &'s BSurface,
|
||||
nurbs: Option<&'s BSurface>,
|
||||
domain: [[f64; 2]; 2],
|
||||
edge_loops: &[Vec<(u32, bool)>],
|
||||
exact: Vec<Vec<Option<Curve2>>>,
|
||||
) -> R<TrimFace<'s>> {
|
||||
let (mut edge_at, mut vertex_at) = (HashMap::new(), HashMap::new());
|
||||
let (mut edges, mut vertices) = (Vec::new(), Vec::new());
|
||||
let mut loops = Vec::with_capacity(edge_loops.len());
|
||||
for (l, pcs) in edge_loops.iter().zip(exact) {
|
||||
let mut uses = Vec::with_capacity(l.len());
|
||||
for (&(e, forward), pcurve) in l.iter().zip(pcs) {
|
||||
let local = match edge_at.get(&e) {
|
||||
Some(i) => *i,
|
||||
None => {
|
||||
let edge = self.edges.get(e as usize).ok_or("edge reference")?;
|
||||
let mut ends = [0u32; 2];
|
||||
for (end, v) in ends.iter_mut().zip(edge.vertices) {
|
||||
*end = match vertex_at.get(&v) {
|
||||
Some(i) => *i,
|
||||
None => {
|
||||
let i = index(vertices.len())?;
|
||||
vertices.push(self.point(v)?);
|
||||
vertex_at.insert(v, i);
|
||||
i
|
||||
}
|
||||
};
|
||||
}
|
||||
let (curve, nurbs, interval) = match &edge.form {
|
||||
Some((n, i)) => (&edge.curve, Some(n), *i),
|
||||
None => (&edge.curve, None, edge.interval),
|
||||
};
|
||||
let i = index(edges.len())?;
|
||||
edges.push(TrimEdge { curve, nurbs, interval, vertices: ends, tolerance: edge.tolerance });
|
||||
edge_at.insert(e, i);
|
||||
i
|
||||
}
|
||||
};
|
||||
uses.push(TrimUse { edge: local, forward, pcurve });
|
||||
}
|
||||
loops.push(uses);
|
||||
}
|
||||
Ok(TrimFace { surface, nurbs, domain, edges, vertices, loops, tolerance: self.tol })
|
||||
}
|
||||
}
|
||||
|
||||
/// A face's uses on their edges' NURBS forms, with `given` pcurves where a kernel made them.
|
||||
fn uses_of<'e>(edges: &'e [EdgeB], edge_loops: &[Vec<(u32, bool)>], given: Option<&'e Vec<Vec<Curve2>>>) -> R<Vec<Vec<EdgeUse<'e>>>> {
|
||||
let mut uses = Vec::with_capacity(edge_loops.len());
|
||||
for (li, l) in edge_loops.iter().enumerate() {
|
||||
let mut u = Vec::with_capacity(l.len());
|
||||
for (p, &(e, forward)) in l.iter().enumerate() {
|
||||
let edge = edges.get(e as usize).ok_or("edge reference")?;
|
||||
let (curve, interval) = match &edge.form {
|
||||
Some((c, i)) => (c, *i),
|
||||
_ => (&edge.curve, edge.interval),
|
||||
};
|
||||
let given = match given {
|
||||
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 });
|
||||
}
|
||||
uses.push(u);
|
||||
}
|
||||
Ok(uses)
|
||||
}
|
||||
|
||||
/// A spline surface's parameter box: its knot ranges.
|
||||
fn natural_box(s: &BSurface) -> Option<[[f64; 2]; 2]> {
|
||||
match s.natural() {
|
||||
[Natural::Range(a, b), Natural::Range(c, d)] if [a, b, c, d].iter().all(|x| x.is_finite()) => Some([[a, b], [c, d]]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The loop run the other way.
|
||||
fn reverse(uses: &mut [(u32, bool)]) {
|
||||
uses.reverse();
|
||||
|
||||
Reference in new issue
Block a user