diff --git a/crates/kernel/src/step.rs b/crates/kernel/src/step.rs index 1f6d343e6..f298e3d11 100644 --- a/crates/kernel/src/step.rs +++ b/crates/kernel/src/step.rs @@ -1,97 +1,5 @@ -use truck_modeling as mt; -use truck_stepio::out; - +use crate::Result; use crate::body::Body; -use crate::{KernelError, Result, guard}; - -/// Intersection-curve edges (from booleans) as cubic B-splines through the exact curve: STEP -/// readers get plain 3D geometry that lies on both faces, and the file does not repeat the two -/// surfaces for every such edge. -fn plain_curves(b: &Body) -> Result { - let s = crate::ops::placed_topology(&b.solid, mt::Matrix4::from_scale(1.0))?; - let size = b.size(); - let mut seen = std::collections::HashSet::new(); - for e in s.edge_iter() { - if !seen.insert(e.id()) { - continue; - } - if let mt::Curve::IntersectionCurve(ic) = e.curve() - && let Some(c) = hermite_through(&ic, size * 1e-4) - { - e.set_curve(mt::Curve::BSplineCurve(c)); - } - } - Ok(s) -} - -/// A C¹ cubic B-spline through exact points of `c` spaced so that chords deviate at most `tol` -/// (Catmull–Rom tangents over chord length; the cubic is far closer than the chords). -fn hermite_through(c: &C, tol: f64) -> Option> -where - C: mt::ParametricCurve + mt::BoundedCurve + mt::ParameterDivision1D, -{ - use mt::{InnerSpace, MetricSpace}; - let (_, pts) = c.parameter_division(c.range_tuple(), tol); - let pts: Vec = pts.into_iter().fold(Vec::new(), |mut v: Vec, p| { - if v.last().is_none_or(|q| q.distance(p) > tol * 1e-3) { - v.push(p); - } - v - }); - let n = pts.len().checked_sub(1).filter(|n| *n >= 1 && *n < 1_000_000)?; - let mut u = vec![0.0; n + 1]; - for i in 1..=n { - u[i] = u[i - 1] + pts[i].distance(pts[i - 1]); - } - let tangent = |i: usize| { - let (a, b) = (i.saturating_sub(1), (i + 1).min(n)); - (pts[b] - pts[a]) / (u[b] - u[a]) - }; - let mut ctrl = vec![pts[0]]; - let mut knots = vec![u[0]; 4]; - for i in 0..n { - let h = u[i + 1] - u[i]; - ctrl.push(pts[i] + tangent(i) * (h / 3.0)); - ctrl.push(pts[i + 1] - tangent(i + 1) * (h / 3.0)); - ctrl.push(pts[i + 1]); - knots.extend(std::iter::repeat_n(u[i + 1], if i + 1 == n { 4 } else { 3 })); - } - if ctrl.iter().any(|p| !(p.x.is_finite() && p.y.is_finite() && p.z.is_finite())) || tangent(0).magnitude() == 0.0 { - return None; - } - mt::BSplineCurve::try_new(mt::KnotVec::from(knots), ctrl).ok() -} - -/// truck's STEP text for the given bodies (geometry and topology; product data is ours). -pub(crate) fn truck_step(bodies: &[&Body], system: &str) -> Result { - if bodies.is_empty() { - return Err(KernelError::Invalid("nothing to export".into())); - } - for b in bodies { - b.require_brep("STEP export")?; - } - guard("step export", || { - let cs: Vec<_> = bodies.iter().map(|b| plain_curves(b).map(|solid| solid.compress())).collect::>()?; - let models: out::StepModels<_, _, _> = cs.iter().collect(); - let header = out::StepHeaderDescriptor { organization_system: system.to_owned(), ..Default::default() }; - written(&out::CompleteStepDisplay::new(models, header)) - }) -} - -/// The text of truck's STEP writer, or an error. The writer refuses some geometry by returning -/// `fmt::Error` after a line saying why; `to_string` would turn that into a panic (caught by -/// `guard` on the desktop, but the browser build aborts on any panic). -fn written(display: &impl std::fmt::Display) -> Result { - use std::fmt::Write; - let mut text = String::new(); - match write!(text, "{display}") { - Ok(()) => Ok(text), - Err(_) => { - let why = text.lines().last().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')).unwrap_or("unsupported geometry"); - Err(KernelError::Failed(format!("not supported yet: STEP export of this body ({why})"))) - } - } -} /// STEP (ISO 10303-21, AP242) text for the given bodies as one part (`Body1`…, with the /// bodies' colours). diff --git a/crates/kernel/src/step_in/brep.rs b/crates/kernel/src/step_in/brep.rs deleted file mode 100644 index 37591e5ac..000000000 --- a/crates/kernel/src/step_in/brep.rs +++ /dev/null @@ -1,663 +0,0 @@ -//! STEP topology (ISO 10303-42 topology entities) to kernel solids: breps, shells, faces, loops, -//! edges and vertices. A face that cannot be built is left out and reported; the rest of the -//! body is still imported (as an open body when a face is missing). - -use std::collections::HashMap; - -use mt::{BoundedCurve, InnerSpace, MetricSpace, ParametricCurve, ParametricSurface}; -use truck_modeling as mt; - -use super::Ctx; -use super::geom::{self, R, entity}; -use super::p21::Param; -use crate::guard; - -/// Most faces in one body. -const MAX_FACES: usize = 500_000; -/// Most edges in one loop. -const MAX_LOOP: usize = 100_000; -/// Most boundary loops on one face. Each bound clones its edge handles into a new wire and the -/// face extent then samples nine points per edge, so one face listing the same 100,000-edge -/// loop a million times would hold 1e11 handles. -const MAX_BOUNDS: usize = 10_000; - -/// A body read from a brep entity. -pub(crate) struct BrepOut { - pub solid: mt::Solid, - /// Faces left out (with the reason). - pub failed: Vec, - /// The shells are closed (a solid) rather than open (missing faces, or a surface model). - pub closed: bool, - /// Faces read from the file (before band faces are split for the kernel). - pub file_faces: usize, - /// The file face of each kernel face, in face order. - pub face_origin: Vec, -} - -#[derive(Default)] -struct Builder { - vertices: HashMap, - edges: HashMap>, - poly_edges: HashMap<(u64, u64), mt::Edge>, - faces: usize, -} - -fn refs(p: Option<&Param>) -> Vec { - p.and_then(Param::as_list).map(|v| v.iter().filter_map(Param::as_ref_id).collect()).unwrap_or_default() -} - -fn rid(p: Option<&Param>, what: &str) -> R { - p.and_then(Param::as_ref_id).ok_or_else(|| format!("{what}: expected a reference")) -} - -/// A contractible outer loop whose winding opposes the surface's parameter normal. -/// Samples follow the wire through periodic seams; a loop that winds around a surface is -/// not a disk in parameter space and must retain the file's sense. -/// The point of a cone (a surface revolved from a line that meets its axis) when `ring`, a -/// face's only loop, goes once round the axis without touching it: the face then reaches the -/// point. `None` for any other surface or loop. -fn enclosed_apex(surface: &mt::Surface, ring: &mt::Wire, tol: f64) -> Option { - use mt::Transform as _; - let mt::Surface::RevolutedCurve(proc) = surface else { return None }; - let rc = proc.entity(); - let mt::Curve::Line(line) = rc.entity_curve() else { return None }; - let (o, axis) = (rc.origin(), rc.axis().normalize()); - // The rotation applied to the revolved surface, applied to its axis and profile too. - let m = proc.transform(); - let (o, axis) = (m.transform_point(o), m.transform_vector(axis).normalize()); - let (p0, p1) = (m.transform_point(line.0), m.transform_point(line.1)); - let radius = |p: mt::Point3| (p - o).cross(axis).magnitude(); - let (r0, r1) = (radius(p0), radius(p1)); - if !((r0 - r1).abs() > 1e-9 * (r0 + r1)) { - return None; - } - let apex = p0 + (p1 - p0) * (r0 / (r0 - r1)); - if !(radius(apex) <= tol.max(1e-9) * 10.0) { - return None; - } - // Once round the axis, staying clear of it. - let x = (p0 - o) - axis * (p0 - o).dot(axis); - let x = if x.magnitude() > tol { x.normalize() } else { return None }; - let y = axis.cross(x); - let mut turned = 0.0; - let mut last: Option = None; - let mut first: Option = None; - for edge in ring.edge_iter() { - let c = edge.oriented_curve(); - let (t0, t1) = c.range_tuple(); - for k in 0..16 { - let q = c.subs(t0 + (t1 - t0) * f64::from(k) / 16.0); - if radius(q) <= tol { - return None; - } - let d = q - o; - let ang = d.dot(y).atan2(d.dot(x)); - if let Some(l) = last { - let mut step = ang - l; - step -= (step / std::f64::consts::TAU).round() * std::f64::consts::TAU; - turned += step; - } else { - first = Some(ang); - } - last = Some(ang); - } - } - if let (Some(l), Some(f)) = (last, first) { - let mut step = f - l; - step -= (step / std::f64::consts::TAU).round() * std::f64::consts::TAU; - turned += step; - } - ((turned.abs() - std::f64::consts::TAU).abs() < 0.1).then_some(apex) -} - -fn reversed_outer(surface: &mt::Surface, wire: &mt::Wire, tol: f64) -> bool { - if let mt::Surface::RevolutedCurve(proc) = surface { - let rc = proc.entity(); - let curve = rc.entity_curve(); - let on_axis = |p: mt::Point3| (p - rc.origin()).cross(rc.axis()).magnitude() <= tol; - // A compact support has two legitimate sides of a closed trim (a sphere's - // hemispheres, for example); its winding must choose the side, not repair it. - if (on_axis(curve.front()) && on_axis(curve.back())) || curve.front().distance(curve.back()) <= tol { - return false; - } - } - let periods = truck_meshalgo::tessellation::surface_periods(surface); - let mut first = None::<[f64; 2]>; - let mut previous = None::<[f64; 2]>; - let (mut area, mut magnitude) = (0.0, 0.0); - for edge in wire.edge_iter() { - let curve = edge.oriented_curve(); - let (a, b) = curve.range_tuple(); - for k in 0..8 { - let point = curve.subs(a + (b - a) * f64::from(k) / 8.0); - let hint = previous.map(|p| (p[0], p[1])); - let valid = |&(u, v): &(f64, f64)| u.is_finite() && v.is_finite() && surface.subs(u, v).distance(point) <= tol; - let Some((u, v)) = truck_meshalgo::tessellation::project_trim_point(surface, point, hint, tol).filter(valid) else { - return false; - }; - // A pole has no unique parameter in its collapsed direction. Its arbitrary - // search result cannot determine the winding of an outer loop. - let (du, dv) = (surface.uder(u, v), surface.vder(u, v)); - if du.cross(dv).magnitude2() <= 1e-12 * (du.magnitude2() + dv.magnitude2()).powi(2) { - return false; - } - let mut p = [u, v]; - let origin = *first.get_or_insert(p); - if let Some(prev) = previous { - for (d, x) in p.iter_mut().enumerate() { - if let Some(period) = periods.get(d).copied().flatten().filter(|p| *p > 0.0) { - *x -= ((*x - prev[d]) / period).round() * period; - } - } - let cross = (prev[0] - origin[0]) * (p[1] - origin[1]) - (p[0] - origin[0]) * (prev[1] - origin[1]); - area += cross; - magnitude += cross.abs(); - } - previous = Some(p); - } - } - let (Some(first), Some(last)) = (first, previous) else { return false }; - if periods.iter().enumerate().any(|(d, p)| p.is_some_and(|p| (first[d] - last[d]).abs() > p * 0.5)) { - return false; - } - area < -16.0 * f64::EPSILON * magnitude -} - -impl Builder { - fn vertex(&mut self, cx: &Ctx, id: u64) -> R { - if let Some(v) = self.vertices.get(&id) { - return Ok(v.clone()); - } - let e = entity(cx, id)?; - if e.name() != "VERTEX_POINT" { - return Err(format!("#{id}: expected VERTEX_POINT, found {}", e.name())); - } - let p = geom::point(cx, rid(e.params().get(1), "VERTEX_POINT")?)?; - let v = mt::Vertex::new(p); - self.vertices.insert(id, v.clone()); - Ok(v) - } - - /// Kernel edges (start to end) of an EDGE_CURVE. - fn edge_curve(&mut self, cx: &Ctx, id: u64) -> R> { - if let Some(e) = self.edges.get(&id) { - return Ok(e.clone()); - } - let e = entity(cx, id)?; - if e.name() != "EDGE_CURVE" { - return Err(format!("#{id}: unsupported edge {}", e.name())); - } - let p = e.params(); - let (vs_id, ve_id) = (rid(p.get(1), "edge start")?, rid(p.get(2), "edge end")?); - let vs = self.vertex(cx, vs_id)?; - let ve = self.vertex(cx, ve_id)?; - let sense = p.get(4).and_then(Param::as_bool).unwrap_or(true); - let g = geom::curve(cx, rid(p.get(3), "edge geometry")?, 0)?; - let closed = vs_id == ve_id; - let pieces = - guard("step edge", || geom::edge_pieces(&g, vs.point(), ve.point(), sense, closed, cx.tol, cx.snap).map_err(crate::KernelError::Failed)) - .map_err(|e| e.to_string())?; - let n = pieces.len(); - let mut out = Vec::with_capacity(n); - let mut cur = vs.clone(); - for (i, c) in pieces.into_iter().enumerate() { - let next = if i + 1 == n { ve.clone() } else { mt::Vertex::new(c.back()) }; - out.push(mt::Edge::new_unchecked(&cur, &next, c)); - cur = next; - } - self.edges.insert(id, out.clone()); - Ok(out) - } - - /// Edges of an ORIENTED_EDGE (or a bare EDGE_CURVE) in loop order. - fn oriented_edge(&mut self, cx: &Ctx, id: u64, depth: usize) -> R> { - if depth > 4 { - return Err("oriented edges nested too deeply".into()); - } - let e = entity(cx, id)?; - match e.name() { - "ORIENTED_EDGE" => { - let p = e.params(); - let inner = self.oriented_edge(cx, rid(p.get(3), "ORIENTED_EDGE")?, depth + 1)?; - if p.get(4).and_then(Param::as_bool).unwrap_or(true) { Ok(inner) } else { Ok(inner.iter().rev().map(mt::Edge::inverse).collect()) } - } - _ => self.edge_curve(cx, id), - } - } - - fn poly_loop(&mut self, cx: &Ctx, pts: &[u64]) -> R> { - let n = pts.len(); - if !(3..=MAX_LOOP).contains(&n) { - return Err(format!("polygon loop with {n} points")); - } - let mut verts = Vec::with_capacity(n); - for &id in pts { - if let Some(v) = self.vertices.get(&id) { - verts.push(v.clone()); - } else { - let v = mt::Vertex::new(geom::point(cx, id)?); - self.vertices.insert(id, v.clone()); - verts.push(v); - } - } - let mut out = Vec::with_capacity(n); - for i in 0..n { - let (Some(&a), Some(&b)) = (pts.get(i), pts.get((i + 1) % n)) else { continue }; - if let Some(e) = self.poly_edges.get(&(b, a)) { - out.push(e.inverse()); - continue; - } - let (Some(va), Some(vb)) = (verts.get(i), verts.get((i + 1) % n)) else { continue }; - if va.point().distance(vb.point()) < 1e-12 { - return Err("polygon loop with repeated points".into()); - } - let e = mt::Edge::try_new(va, vb, mt::Curve::Line(mt::Line(va.point(), vb.point()))).map_err(|e| format!("polygon edge: {e}"))?; - self.poly_edges.insert((a, b), e.clone()); - out.push(e); - } - Ok(out) - } - - /// A face bound as a wire (oriented by the bound's orientation), or `None` for a vertex loop. - fn bound(&mut self, cx: &Ctx, id: u64) -> R> { - let b = entity(cx, id)?; - if !matches!(b.name(), "FACE_BOUND" | "FACE_OUTER_BOUND") { - return Err(format!("#{id}: unsupported face bound {}", b.name())); - } - let lp_id = rid(b.params().get(1), "face bound loop")?; - let orient = b.params().get(2).and_then(Param::as_bool).unwrap_or(true); - let lp = entity(cx, lp_id)?; - let edges = match lp.name() { - "EDGE_LOOP" => { - let ids = refs(lp.params().get(1)); - if ids.is_empty() || ids.len() > MAX_LOOP { - return Err(format!("edge loop with {} edges", ids.len())); - } - let mut v = Vec::new(); - for oe in ids { - v.extend(self.oriented_edge(cx, oe, 0)?); - } - v - } - "POLY_LOOP" => self.poly_loop(cx, &refs(lp.params().get(1)))?, - "VERTEX_LOOP" => return Ok(None), - n => return Err(format!("unsupported loop {n}")), - }; - let mut w: mt::Wire = edges.into(); - if !w.is_closed() { - return Err("face boundary is not a closed loop".into()); - } - if !orient { - w.invert(); - } - Ok(Some(w)) - } - - /// A face (ADVANCED_FACE, FACE_SURFACE, ORIENTED_FACE or a polygonal FACE). - fn face(&mut self, cx: &Ctx, id: u64, depth: usize) -> R { - if depth > 4 { - return Err("oriented faces nested too deeply".into()); - } - self.faces += 1; - if self.faces > MAX_FACES { - return Err(format!("more than {MAX_FACES} faces")); - } - let e = entity(cx, id)?; - let p = e.params(); - if e.name() == "ORIENTED_FACE" { - let mut f = self.face(cx, rid(p.get(2), "ORIENTED_FACE")?, depth + 1)?; - if !p.get(3).and_then(Param::as_bool).unwrap_or(true) { - f.invert(); - } - return Ok(f); - } - if !matches!(e.name(), "ADVANCED_FACE" | "FACE_SURFACE" | "FACE") { - return Err(format!("unsupported face {}", e.name())); - } - let bounds = refs(p.get(1)); - if bounds.len() > MAX_BOUNDS { - return Err(format!("a face with more than {MAX_BOUNDS} boundary loops")); - } - let mut wires = Vec::new(); - let mut outer = None; - let mut edges = 0usize; - for b in bounds { - if let Some(w) = self.bound(cx, b)? { - if entity(cx, b)?.name() == "FACE_OUTER_BOUND" { - outer = Some(wires.len()); - } - edges = edges.saturating_add(w.len()); - if edges > MAX_LOOP { - return Err(format!("a face with more than {MAX_LOOP} boundary edges")); - } - wires.push(w); - } - } - if wires.is_empty() { - return Err("face without boundary edges".into()); - } - let extent: Vec = wires - .iter() - .flat_map(|w| w.edge_iter()) - .flat_map(|e| { - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - (0..=8).map(move |i| c.subs(t0 + (t1 - t0) * i as f64 / 8.0)).collect::>() - }) - .collect(); - // Seam edges: used twice by the face's loops. - let mut uses: HashMap = HashMap::new(); - for e in wires.iter().flat_map(|w| w.edge_iter()) { - *uses.entry(e.id()).or_default() += 1; - } - let mut seen = std::collections::HashSet::new(); - let seam: Vec = wires - .iter() - .flat_map(|w| w.edge_iter()) - .filter(|e| uses.get(&e.id()).copied().unwrap_or(0) > 1 && seen.insert(e.id())) - .flat_map(|e| { - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - (0..=8).map(move |i| c.subs(t0 + (t1 - t0) * i as f64 / 8.0)).collect::>() - }) - .collect(); - let mut surface = if e.name() == "FACE" { - crate::plane_fit::plane_through(&extent).map(mt::Surface::Plane).ok_or("polygonal face without a plane")? - } else { - let sid = rid(p.get(2), "face geometry")?; - let sense = p.get(3).and_then(Param::as_bool).unwrap_or(true); - guard("step surface", || geom::surface(cx, sid, &extent, &seam, sense, 0).map_err(crate::KernelError::Failed)) - .map_err(|e| e.to_string())? - }; - // An explicit outer bound encloses the face. Some exporters give its surface the - // opposite sense; treating that loop as a hole meshes the rest of the supporting - // cylinder instead. Match the surface to the outer loop without reversing - // shared topological edges. Winding loops (bands and pole seams) are left alone. - if e.name() != "FACE" && seam.is_empty() && outer.and_then(|i| wires.get(i)).is_some_and(|w| reversed_outer(&surface, w, cx.tol)) { - let sid = rid(p.get(2), "face geometry")?; - let sense = p.get(3).and_then(Param::as_bool).unwrap_or(true); - surface = guard("step surface orientation", || geom::surface(cx, sid, &extent, &seam, !sense, 0).map_err(crate::KernelError::Failed)) - .map_err(|e| e.to_string())?; - } - // A cone face bounded only by a ring round its axis (no vertex at the point, or a - // VERTEX_LOOP there, which has no edges) covers the cone up to its point. Its surface - // was spanned over the ring alone, a sliver at the base; it is spanned to the apex, - // and the ring is joined to the apex by a seam line out and back, as a cone with a - // seam is written. - let (mut wires, mut surface) = (wires, surface); - if e.name() != "FACE" - && seam.is_empty() - && let [ring] = wires.as_slice() - && let Some(apex) = enclosed_apex(&surface, ring, cx.tol) - && let Some(first) = ring.edge_iter().next() - { - let v = first.front().clone(); - let a = mt::Vertex::new(apex); - let line = mt::Edge::new_unchecked(&v, &a, mt::Curve::Line(mt::Line(v.point(), apex))); - let mut to_apex = extent.clone(); - to_apex.push(apex); - let seam_line = [v.point(), apex]; - let sid = rid(p.get(2), "face geometry")?; - let sense = p.get(3).and_then(Param::as_bool).unwrap_or(true); - let spanned = - guard("step cone to its point", || geom::surface(cx, sid, &to_apex, &seam_line, sense, 0).map_err(crate::KernelError::Failed)) - .map_err(|e| e.to_string())?; - let mut edges: Vec = ring.edge_iter().cloned().collect(); - edges.push(line.clone()); - edges.push(line.inverse()); - wires = vec![edges.into()]; - surface = spanned; - } - // Loops on a surface of revolution start away from the axis: a pole (cone apex, sphere - // pole) has no definite rotation parameter, and the mesher takes the first point's - // parameter as the anchor for the rest of the loop. - let wires: Vec = match &surface { - mt::Surface::RevolutedCurve(rc) => { - let (o, a) = (rc.entity().origin(), rc.entity().axis()); - let dist = |e: &mt::Edge| { - let v = e.front().point() - o; - (v - a * v.dot(a)).magnitude() - }; - wires - .into_iter() - .map(|w| { - let edges: Vec = w.edge_iter().cloned().collect(); - let start = edges.iter().enumerate().max_by(|x, y| dist(x.1).total_cmp(&dist(y.1))).map(|(i, _)| i).unwrap_or(0); - edges.iter().skip(start).chain(edges.iter().take(start)).cloned().collect::>().into() - }) - .collect() - } - // A loop passing a vertex twice (a figure eight through a pole, as written for a - // torus whose tube touches its axis) starts at a vertex it passes once. - _ => wires - .into_iter() - .map(|w| { - let edges: Vec = w.edge_iter().cloned().collect(); - // Counted once: a loop may hold 100,000 edges, and asking per edge how - // often its front vertex appears would scan them all again each time. - let mut fronts: HashMap<_, usize> = HashMap::new(); - for e in &edges { - *fronts.entry(e.front().id()).or_default() += 1; - } - let passes = |e: &mt::Edge| fronts.get(&e.front().id()).copied().unwrap_or(0); - match edges.first().map(passes) { - Some(n) if n > 1 => { - let start = edges.iter().position(|e| passes(e) == 1).unwrap_or(0); - edges.iter().skip(start).chain(edges.iter().take(start)).cloned().collect::>().into() - } - _ => w, - } - }) - .collect(), - }; - match mt::Face::try_new(wires.clone(), surface.clone()) { - Ok(f) => Ok(f), - // Faces on periodic surfaces run along a seam edge twice: valid in STEP. - Err(truck_topology::errors::Error::NotSimpleWire) => Ok(mt::Face::new_unchecked(wires, surface)), - Err(e) => Err(format!("face: {e}")), - } - } - - fn shell(&mut self, cx: &Ctx, id: u64, failed: &mut Vec) -> R<(mt::Shell, bool, usize, Vec)> { - let e = entity(cx, id)?; - let p = e.params(); - let (faces, flip, closed) = match e.name() { - "CLOSED_SHELL" => (refs(p.get(1)), false, true), - "OPEN_SHELL" => (refs(p.get(1)), false, false), - "ORIENTED_CLOSED_SHELL" | "ORIENTED_OPEN_SHELL" => { - let inner = entity(cx, rid(p.get(2), "oriented shell")?)?; - (refs(inner.params().get(1)), !p.get(3).and_then(Param::as_bool).unwrap_or(true), e.name() == "ORIENTED_CLOSED_SHELL") - } - n => return Err(format!("unsupported shell {n}")), - }; - if faces.len() > MAX_FACES { - return Err(format!("shell with {} faces", faces.len())); - } - let mut out = Vec::with_capacity(faces.len()); - let mut origin = Vec::with_capacity(faces.len()); - for f in faces { - match self.face(cx, f, 0) { - Ok(mut face) => { - if flip { - face.invert(); - } - out.push(face); - origin.push(f); - } - Err(err) => { - if self.faces > MAX_FACES { - return Err(err); - } - failed.push(format!("face #{f}: {err}")); - } - } - } - if out.is_empty() { - return Err("no face could be imported".into()); - } - let read = out.len(); - let ball = match (out.as_slice(), origin.as_slice()) { - ([face], [file_face]) => whole_sphere(cx, *file_face, face).map(|patches| (*file_face, patches)), - _ => None, - }; - if let Some((file_face, patches)) = ball { - origin = vec![file_face; patches.len()]; - out = patches; - } - let out = super::split::split_bands(out, &mut origin, failed, cx.tol); - Ok((out.into(), closed, read, origin)) - } -} - -/// A ball written as one face on a sphere bounded only by its seam, run out and back from pole -/// to pole. Truck meshes a face on a revolved surface in parameter space, where that loop -/// encloses nothing, so the ball is built as the kernel's own sphere instead: six patches with -/// no pole or seam inside them (`build::sphere_patch_faces`), turned inside out for a void. -/// `None` for any other face. -fn whole_sphere(cx: &Ctx, file_face: u64, face: &mt::Face) -> Option> { - use mt::{ParametricSurface3D, SearchParameter}; - let surface = entity(cx, file_face).ok()?.params().get(2).and_then(Param::as_ref_id)?; - if entity(cx, surface).ok()?.name() != "SPHERICAL_SURFACE" { - return None; - } - let wires = face.boundaries(); - let edges: Vec<&mt::Edge> = wires.iter().flat_map(|w| w.edge_iter()).collect(); - let mut uses: HashMap = HashMap::new(); - let mut poles: Vec = Vec::new(); - for e in &edges { - *uses.entry(e.id()).or_default() += 1; - for v in [e.front(), e.back()] { - if !poles.iter().any(|p| p.id() == v.id()) { - poles.push(v.clone()); - } - } - } - // Every edge a seam (used once each way), and the two vertices it joins are the poles. - if uses.is_empty() || uses.values().any(|n| *n != 2) { - return None; - } - let [a, b] = poles.as_slice() else { return None }; - let (a, b) = (a.point(), b.point()); - let center = a + (b - a) * 0.5; - let radius = a.distance(b) * 0.5; - let tol = cx.tol.max(radius * 1e-6); - // The seam is a meridian: all of it on the sphere whose diameter joins the poles. - let samples = |e: &&mt::Edge| { - let c = e.curve(); - let (t0, t1) = c.range_tuple(); - (0..=8).map(move |i| c.subs(t0 + (t1 - t0) * i as f64 / 8.0)) - }; - if !(radius.is_finite() && radius > tol) || !edges.iter().flat_map(samples).all(|p| (p.distance(center) - radius).abs() <= tol) { - return None; - } - // Ball or void: the face's normal at the middle of the seam, against the way out of the centre. - let probe = edges.first().and_then(|e| samples(e).nth(4))?; - let oriented = face.oriented_surface(); - let (u, v) = oriented.search_parameter(probe, mt::SPHint2D::None, 100)?; - let outward = oriented.normal(u, v).dot(probe - center) > 0.0; - let z = (crate::body::from_p3(a) - crate::body::from_p3(b)).normalized()?; - let x = z.any_perp(); - let c = crate::body::from_p3(center); - let mut patches = guard("step sphere", || crate::build::sphere_patch_faces(c, radius, [x, z.cross(x), z])).ok()?; - if !outward { - for f in &mut patches { - f.invert(); - } - } - Some(patches) -} - -/// Read a solid-like representation item: MANIFOLD_SOLID_BREP, BREP_WITH_VOIDS, FACETED_BREP, -/// or a SHELL_BASED_SURFACE_MODEL (closed shells give solids, open ones open bodies). -pub(crate) fn read_item(cx: &Ctx, id: u64) -> R { - let e = entity(cx, id)?; - let p = e.params(); - let mut b = Builder::default(); - let mut failed = Vec::new(); - let mut shells = Vec::new(); - let mut closed = true; - let mut file_faces = 0; - // The file face each kernel face comes from (in face order). - let mut face_origin = Vec::new(); - match e.name() { - "MANIFOLD_SOLID_BREP" | "FACETED_BREP" | "BREP_WITH_VOIDS" => { - let (s, c, n, o) = b.shell(cx, rid(p.get(1), "brep outer shell")?, &mut failed)?; - closed &= c; - file_faces += n; - shells.push(s); - face_origin.extend(o); - if e.name() == "BREP_WITH_VOIDS" { - for v in refs(p.get(2)) { - match b.shell(cx, v, &mut failed) { - Ok((s, c, n, o)) => { - closed &= c; - file_faces += n; - shells.push(s); - face_origin.extend(o); - } - Err(err) => failed.push(format!("void shell #{v}: {err}")), - } - } - } - } - "SHELL_BASED_SURFACE_MODEL" => { - for s in refs(p.get(1)) { - match b.shell(cx, s, &mut failed) { - Ok((s, c, n, o)) => { - closed &= c; - file_faces += n; - shells.push(s); - face_origin.extend(o); - } - Err(err) => failed.push(format!("shell #{s}: {err}")), - } - } - } - n => return Err(format!("unsupported item {n}")), - } - if shells.is_empty() { - return Err(failed.first().cloned().unwrap_or_else(|| "no shells".into())); - } - // `mt::Solid::try_new` only checks each shell (non-empty, connected, closed, no singular - // vertex) and hands the shells back unchanged (truck-topology 0.6.0), so the same checks run - // here on the borrowed shells. The successful path used to clone every face, edge, vertex, - // curve and surface to keep a copy that was then dropped. - let checked = guard("step solid", || { - for shell in &shells { - if shell.is_empty() { - return Err(crate::KernelError::Failed("empty shell".into())); - } - if !shell.is_connected() { - return Err(crate::KernelError::Failed("shell is not connected".into())); - } - if shell.shell_condition() != mt::ShellCondition::Closed { - return Err(crate::KernelError::Failed("shell is not closed".into())); - } - if !shell.singular_vertices().is_empty() { - return Err(crate::KernelError::Failed("shell is not manifold".into())); - } - } - Ok(()) - }); - if checked.is_err() { - closed = false; - } - // A void's faces face into the cavity, out of the material: it encloses volume of the - // opposite sign to the outer shell. The ORIENTED_CLOSED_SHELL flag alone doesn't say so: - // some exporters write .F. over a shell already facing into the cavity (#3730), others .T. - // A void enclosing volume of the outer shell's sign is turned inside out. - if e.name() == "BREP_WITH_VOIDS" - && checked.is_ok() - && let Some((outer, voids)) = shells.split_first_mut() - && let Some(outside) = crate::body::shell_volume(outer) - { - for void in voids { - if crate::body::shell_volume(void).is_some_and(|v| v * outside > 0.0) { - for face in void.face_iter_mut() { - face.invert(); - } - } - } - } - Ok(BrepOut { solid: mt::Solid::new_unchecked(shells), failed, closed, file_faces, face_origin }) -} diff --git a/crates/kernel/src/step_in/conic_tests.rs b/crates/kernel/src/step_in/conic_tests.rs index 5e76a3e60..abbe11896 100644 --- a/crates/kernel/src/step_in/conic_tests.rs +++ b/crates/kernel/src/step_in/conic_tests.rs @@ -4,10 +4,6 @@ use std::f64::consts::{FRAC_PI_4, PI}; -use mt::{BoundedCurve, InnerSpace, ParametricCurve}; -use truck_modeling as mt; - -use super::geom::{Frame, hyperbola_arc, parabola_arc}; use super::*; use crate::{measure, step_export}; @@ -18,47 +14,6 @@ const CONTEXT: &str = "#90=ADVANCED_BREP_SHAPE_REPRESENTATION('',(#81),#91);\n#9 /// Height of the cone pieces: the 45° cone `x² + y² = z²` up to `z = H`. const H: f64 = 10.0; -#[test] -fn extruded_ellipse_seam_uses_profile_angles_for_oblique_sweeps() { - use mt::{MetricSpace, ParametricSurface}; - - let text = format!( - "{HEAD} -#1=CARTESIAN_POINT('',(10.,-20.,3.)); -#2=DIRECTION('',(0.,0.,1.)); -#3=DIRECTION('',(1.,0.,0.)); -#4=AXIS2_PLACEMENT_3D('',#1,#2,#3); -#5=ELLIPSE('',#4,9.,4.); -#6=DIRECTION('',(0.5,0.25,1.)); -#7=VECTOR('',#6,1.); -#8=SURFACE_OF_LINEAR_EXTRUSION('',#5,#7); -{TAIL}" - ); - let ex = p21::parse(&text).unwrap(); - let cx = Ctx { ex: &ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 }; - let origin = mt::Point3::new(10.0, -20.0, 3.0); - let d = mt::Vector3::new(0.5, 0.25, 1.0).normalize(); - let point = |angle: f64, h: f64| origin + mt::Vector3::new(9.0 * angle.cos(), 4.0 * angle.sin(), 0.0) + d * h; - let extent: Vec<_> = [-0.04, 0.0, 0.04].into_iter().flat_map(|a| [point(a, 0.0), point(a, 10.0)]).collect(); - for seam in [Vec::new(), vec![point(-0.04, 0.0), point(-0.04, 10.0)]] { - let surface = geom::surface(&cx, 8, &extent, &seam, true, 0).unwrap(); - for i in 0..=16 { - for j in 0..=4 { - let q = surface.subs(i as f64 / 16.0, j as f64 / 4.0) - origin; - let q = q - d * (q.z / d.z); - assert!(((q.x / 9.0).powi(2) + (q.y / 4.0).powi(2) - 1.0).abs() < 1e-12); - } - } - let start = surface.subs(0.0, 0.5); - let q = start - d * ((start.z - origin.z) / d.z); - if seam.is_empty() { - assert!(q.distance(point(std::f64::consts::PI, 0.0)) < 1e-9); - } else { - assert!(q.distance(point(-0.04, 0.0)) < 1e-9); - } - } -} - fn rel(a: f64, b: f64) -> f64 { (a - b).abs() / b.abs().max(1e-9) } @@ -190,34 +145,6 @@ fn parabola_bounded_faces_import() { assert!(rel(v, want) < 1e-4, "schema 4: {v} vs {want}"); } -/// The kernel curves lie exactly on the conics, end to end, whichever way they run. -#[test] -fn conic_arcs_are_exact() { - let f = Frame { o: mt::Point3::new(1.0, 2.0, 3.0), x: mt::Vector3::unit_y(), y: mt::Vector3::unit_z(), z: mt::Vector3::unit_x() }; - let local = |p: mt::Point3| ((p - f.o).dot(f.x), (p - f.o).dot(f.y), (p - f.o).dot(f.z)); - for (t0, t1) in [(-1.5, 2.0), (3.0, -0.25), (0.0, 7.5)] { - let c = hyperbola_arc(&f, 3.0, 2.0, t0, t1); - let (s0, s1) = c.range_tuple(); - for i in 0..=200 { - let (x, y, z) = local(c.subs(s0 + (s1 - s0) * i as f64 / 200.0)); - assert!((x * x / 9.0 - y * y / 4.0 - 1.0).abs() < 1e-9 && x > 0.0 && z.abs() < 1e-12, "{x} {y}"); - } - let (x, y, _) = local(c.subs(s0)); - assert!((x - 3.0 * f64::cosh(t0)).abs() < 1e-9 && (y - 2.0 * f64::sinh(t0)).abs() < 1e-9); - let (x, y, _) = local(c.subs(s1)); - assert!((x - 3.0 * f64::cosh(t1)).abs() < 1e-9 && (y - 2.0 * f64::sinh(t1)).abs() < 1e-9); - - let c = parabola_arc(&f, 1.5, t0, t1); - let (s0, s1) = c.range_tuple(); - for i in 0..=200 { - let (x, y, z) = local(c.subs(s0 + (s1 - s0) * i as f64 / 200.0)); - assert!((y * y - 4.0 * 1.5 * x).abs() < 1e-9 * (1.0 + x.abs()) && z.abs() < 1e-12, "{x} {y}"); - } - let (x, y, _) = local(c.subs(s1)); - assert!((x - 1.5 * t1 * t1).abs() < 1e-9 && (y - 3.0 * t1).abs() < 1e-9); - } -} - /// Hostile conics are errors (the face is reported and left out), never panics. #[test] fn hostile_conics_never_panic() { diff --git a/crates/kernel/src/step_in/geom.rs b/crates/kernel/src/step_in/geom.rs deleted file mode 100644 index e5f27f320..000000000 --- a/crates/kernel/src/step_in/geom.rs +++ /dev/null @@ -1,1237 +0,0 @@ -//! STEP geometry (ISO 10303-42 entities) to kernel curves and surfaces. -//! -//! Points, placements, lines, conics (ellipses, hyperbolas and parabolas), B-splines (plain and rational), elementary surfaces and -//! swept surfaces, with exact offsets of planes, cylinders, cones, spheres and regular tori. -//! Free-form offsets and offsets through collapsed radii remain explicit import warnings. -//! Edge curves are trimmed to their vertices here, so every kernel edge runs -//! exactly from its start vertex to its end vertex. Lengths are scaled to millimetres while -//! reading. - -use std::f64::consts::{FRAC_PI_2, PI, TAU}; - -use mt::{BoundedCurve, Cut, InnerSpace, Invertible, MetricSpace, ParametricCurve, ParametricSurface3D, SearchNearestParameter}; -use solidcraft_geom::Ring; -use truck_modeling as mt; - -use super::Ctx; -use super::p21::{Entity, Param}; - -/// Geometry nesting we follow (trimmed curve of a surface curve of …). -const MAX_GEOM_DEPTH: usize = 8; -/// Most control points in one B-spline (per direction product for surfaces). -const MAX_CTRL: usize = 1_000_000; -const MAX_COORD: f64 = 1e9; - -pub(crate) type R = std::result::Result; - -/// An orthonormal frame (AXIS2_PLACEMENT_3D). -#[derive(Clone, Copy, Debug)] -pub(crate) struct Frame { - pub o: mt::Point3, - pub x: mt::Vector3, - pub y: mt::Vector3, - pub z: mt::Vector3, -} - -impl Frame { - pub fn matrix(&self) -> mt::Matrix4 { - mt::Matrix4::from_cols(self.x.extend(0.0), self.y.extend(0.0), self.z.extend(0.0), self.o.to_homogeneous()) - } - fn at(&self, cx: f64, cy: f64, cz: f64) -> mt::Point3 { - self.o + self.x * cx + self.y * cy + self.z * cz - } -} - -/// A curve before trimming. -#[derive(Clone, Debug)] -pub(crate) enum CurveGeo { - Line { - p: mt::Point3, - d: mt::Vector3, - }, - /// Ellipse (`a == b` for circles) in the frame's XY plane. - Conic { - f: Frame, - a: f64, - b: f64, - }, - /// Hyperbola branch `o + a·cosh t·x + b·sinh t·y` in the frame's XY plane. - Hyperbola { - f: Frame, - a: f64, - b: f64, - }, - /// Parabola `o + focal·(t²·x + 2t·y)` in the frame's XY plane. - Parabola { - f: Frame, - focal: f64, - }, - BSpline(mt::BSplineCurve), - Nurbs(mt::NurbsCurve), -} - -pub(crate) fn entity<'a>(cx: &Ctx<'a>, id: u64) -> R<&'a Entity> { - cx.ex.get(id).ok_or_else(|| format!("missing entity #{id}")) -} - -fn ent_of<'a>(cx: &Ctx<'a>, p: Option<&Param>, what: &str) -> R<(u64, &'a Entity)> { - let id = p.and_then(Param::as_ref_id).ok_or_else(|| format!("{what}: expected a reference"))?; - Ok((id, entity(cx, id)?)) -} - -fn num(p: Option<&Param>, what: &str) -> R { - let x = p.and_then(Param::as_f64).ok_or_else(|| format!("{what}: expected a number"))?; - if x.is_finite() && x.abs() < MAX_COORD { Ok(x) } else { Err(format!("{what}: {x} out of range")) } -} - -fn length(cx: &Ctx, p: Option<&Param>, what: &str) -> R { - Ok(num(p, what)? * cx.len) -} - -pub(crate) fn point(cx: &Ctx, id: u64) -> R { - let e = entity(cx, id)?; - if e.name() != "CARTESIAN_POINT" { - return Err(format!("#{id}: expected CARTESIAN_POINT, found {}", e.name())); - } - let c = e.params().get(1).and_then(Param::as_list).ok_or("CARTESIAN_POINT without coordinates")?; - let g = |i: usize| -> R { if i < c.len() { num(c.get(i), "coordinate") } else { Ok(0.0) } }; - if c.is_empty() || c.len() > 3 { - return Err(format!("#{id}: point with {} coordinates", c.len())); - } - Ok(mt::Point3::new(g(0)?, g(1)?, g(2)?) * cx.len) -} - -pub(super) fn direction(cx: &Ctx, id: u64) -> R { - let e = entity(cx, id)?; - if e.name() != "DIRECTION" { - return Err(format!("#{id}: expected DIRECTION, found {}", e.name())); - } - let c = e.params().get(1).and_then(Param::as_list).ok_or("DIRECTION without ratios")?; - let g = |i: usize| -> R { if i < c.len() { num(c.get(i), "direction") } else { Ok(0.0) } }; - let v = mt::Vector3::new(g(0)?, g(1)?, g(2)?); - let m = v.magnitude(); - if m > 1e-12 && m.is_finite() { Ok(v / m) } else { Err(format!("#{id}: zero direction")) } -} - -fn any_perpendicular(z: mt::Vector3) -> mt::Vector3 { - let a = if z.x.abs() < 0.9 { mt::Vector3::unit_x() } else { mt::Vector3::unit_y() }; - let x = a - z * a.dot(z); - x / x.magnitude() -} - -/// AXIS2_PLACEMENT_3D (or 2D, as a frame in the XY plane). -pub(crate) fn frame(cx: &Ctx, id: u64) -> R { - let e = entity(cx, id)?; - let p = e.params(); - let o = point(cx, p.get(1).and_then(Param::as_ref_id).ok_or("placement without location")?)?; - let (z, rf) = match e.name() { - "AXIS2_PLACEMENT_3D" => { - let z = match p.get(2).and_then(Param::as_ref_id) { - Some(d) => direction(cx, d)?, - None => mt::Vector3::unit_z(), - }; - (z, p.get(3).and_then(Param::as_ref_id)) - } - "AXIS2_PLACEMENT_2D" => (mt::Vector3::unit_z(), p.get(2).and_then(Param::as_ref_id)), - n => return Err(format!("#{id}: expected AXIS2_PLACEMENT_3D, found {n}")), - }; - let x = match rf { - Some(d) => { - let r = direction(cx, d)?; - let x = r - z * r.dot(z); - if x.magnitude() > 1e-9 { x / x.magnitude() } else { any_perpendicular(z) } - } - None => any_perpendicular(z), - }; - Ok(Frame { o, x, y: z.cross(x), z }) -} - -/// AXIS1_PLACEMENT: origin and unit axis. -pub(crate) fn axis1(cx: &Ctx, id: u64) -> R<(mt::Point3, mt::Vector3)> { - let e = entity(cx, id)?; - let p = e.params(); - let o = point(cx, p.get(1).and_then(Param::as_ref_id).ok_or("axis without location")?)?; - let d = match p.get(2).and_then(Param::as_ref_id) { - Some(d) => direction(cx, d)?, - None => mt::Vector3::unit_z(), - }; - Ok((o, d)) -} - -/// `expected` is the knot count the control points and degree imply. Multiplicities are -/// expanded into one value each, so the sum has to be checked before the expansion: 20 million -/// knots of multiplicity 64 would build a 10 GB vector that the length check then rejects, and -/// an allocation failure aborts the process where an error does not. -fn knot_vec(mults: Option<&Param>, knots: Option<&Param>, expected: usize) -> R { - let m: Vec = mults - .and_then(Param::as_list) - .ok_or("B-spline without knot multiplicities")? - .iter() - .map(|x| x.as_i64().filter(|v| (1..=64).contains(v)).map(|v| v as usize).ok_or_else(|| "bad knot multiplicity".to_string())) - .collect::>()?; - let k: Vec = knots.and_then(Param::as_list).ok_or("B-spline without knots")?.iter().map(|x| num(Some(x), "knot")).collect::>()?; - if m.len() != k.len() || k.is_empty() || k.windows(2).any(|w| w.first() > w.get(1)) { - return Err("inconsistent knot vector".into()); - } - if m.len() > expected || m.iter().try_fold(0usize, |a, v| a.checked_add(*v)) != Some(expected) { - return Err("knot multiplicities do not match the control points".into()); - } - mt::KnotVec::from_single_multi(spanning_one(k), m).map_err(|e| format!("knot vector: {e}")) -} - -/// Shortest parameter range a spline is read with. -const MIN_KNOT_RANGE: f64 = 1.0; - -/// `knots` stretched, when they span less than [`MIN_KNOT_RANGE`], to span exactly that from the -/// same first knot. A STEP writer may parameterize a spline over any range (some write a few -/// millionths, as if in metres of a part drawn in millimetres), and the kernel tells parameters -/// apart only to a fixed tolerance (1e-6): over such a range it took distinct knots for one, and -/// trimming an edge to its vertices dropped a control point. Stretching the knots changes the -/// parameters, never the curve (every point is where it was), and nothing read from the file -/// refers to them: edges are trimmed by their vertices. -fn spanning_one(knots: Vec) -> Vec { - let (Some(&first), Some(&last)) = (knots.first(), knots.last()) else { return knots }; - let range = last - first; - if !(range > 0.0 && range < MIN_KNOT_RANGE) { - return knots; - } - let scale = MIN_KNOT_RANGE / range; - let mut out: Vec = knots.iter().map(|k| first + (k - first) * scale).collect(); - // The last knot exactly at the end of the range (the product can miss it by a rounding). - if let Some(k) = out.last_mut() { - *k = first + MIN_KNOT_RANGE; - } - out -} - -fn generated_knots(kind: &str, n_ctrl: usize, degree: usize) -> R { - if n_ctrl <= degree { - return Err("too few control points".into()); - } - let n = n_ctrl + degree + 1; - let v: Vec = match kind { - "BEZIER" => { - if n_ctrl != degree + 1 { - // Piecewise Bézier: segments of `degree` with full interior multiplicity. - let segs = (n_ctrl - 1) / degree.max(1); - if segs * degree + 1 != n_ctrl { - return Err("Bezier control point count".into()); - } - let mut v = vec![0.0; degree + 1]; - for s in 1..segs { - v.extend(std::iter::repeat_n(s as f64, degree)); - } - v.extend(std::iter::repeat_n(segs as f64, degree + 1)); - v - } else { - let mut v = vec![0.0; degree + 1]; - v.extend(std::iter::repeat_n(1.0, degree + 1)); - v - } - } - "UNIFORM" => (0..n).map(|i| i as f64 - degree as f64).collect(), - _ => { - // Quasi-uniform: clamped ends, uniform interior. - let inner = n_ctrl - degree; - let mut v = vec![0.0; degree + 1]; - v.extend((1..inner).map(|i| i as f64)); - v.extend(std::iter::repeat_n(inner as f64, degree + 1)); - v - } - }; - Ok(mt::KnotVec::from(v)) -} - -/// The ends of the part of a knot vector where a B-spline of `degree` is defined, when its end -/// knots repeat fewer than `degree + 1` times (an unclamped or periodic knot vector, as -/// OpenCascade writes closed B-splines and `UNIFORM_*` curves and surfaces have): only between -/// knot `degree` and knot `len - degree - 1` do the basis functions sum to one. `None` for a -/// clamped vector, whose whole range is the domain, and for one whose domain is a point. -fn unclamped_ends(kv: &mt::KnotVec, degree: usize) -> Option<(Option, Option)> { - let n = kv.len(); - if n < 2 * (degree + 1) || !(kv[n - 1 - degree] - kv[degree] > mt::TOLERANCE) { - return None; - } - let lo = (kv.multiplicity(0) <= degree).then(|| kv[degree]); - let hi = (kv.multiplicity(n - 1) <= degree).then(|| kv[n - 1 - degree]); - (lo.is_some() || hi.is_some()).then_some((lo, hi)) -} - -/// `c` restricted to its domain, with clamped ends (exact: knots are inserted at the domain's -/// ends and the control points beyond them dropped). The kernel takes a B-spline's whole knot -/// range as its parameter range, and an unclamped curve evaluated outside its domain leaves -/// its control polygon (a rational one divides by zero at the outermost knots). -fn clamped_curve + mt::Tolerance>(mut c: mt::BSplineCurve

) -> mt::BSplineCurve

{ - let Some((lo, hi)) = unclamped_ends(c.knot_vec(), c.degree()) else { return c }; - if let Some(lo) = lo { - c = c.cut(lo); - } - if let Some(hi) = hi { - let _ = c.cut(hi); - } - c -} - -/// [`clamped_curve`] for a surface, in each direction whose knot vector is unclamped. -fn clamped_surface + mt::Tolerance>(mut s: mt::BSplineSurface

) -> mt::BSplineSurface

{ - if let Some((lo, hi)) = unclamped_ends(s.uknot_vec(), s.udegree()) { - if let Some(lo) = lo { - s = s.ucut(lo); - } - if let Some(hi) = hi { - let _ = s.ucut(hi); - } - } - if let Some((lo, hi)) = unclamped_ends(s.vknot_vec(), s.vdegree()) { - if let Some(lo) = lo { - s = s.vcut(lo); - } - if let Some(hi) = hi { - let _ = s.vcut(hi); - } - } - s -} - -fn weights_list(p: Option<&Param>) -> R> { - p.and_then(Param::as_list) - .ok_or("rational B-spline without weights")? - .iter() - .map(|w| num(Some(w), "weight").and_then(|w| if w > 0.0 { Ok(w) } else { Err("non-positive weight".into()) })) - .collect() -} - -fn bspline_curve(cx: &Ctx, e: &Entity) -> R { - // Common part (B_SPLINE_CURVE): degree, control points, form, closed, self-intersect. - let (base, knots, kind): (Vec, Option<(Option<&Param>, Option<&Param>)>, &str) = if e.is_complex() { - let b = e.record("B_SPLINE_CURVE").ok_or("complex curve without B_SPLINE_CURVE")?; - let mut base = vec![Param::Str(String::new())]; - base.extend(b.iter().cloned()); - let k = e.record("B_SPLINE_CURVE_WITH_KNOTS").map(|k| (k.first(), k.get(1))); - let kind = if e.has("BEZIER_CURVE") { - "BEZIER" - } else if e.has("UNIFORM_CURVE") { - "UNIFORM" - } else { - "QUASI" - }; - (base, k, kind) - } else { - let p = e.params(); - let k = (e.name() == "B_SPLINE_CURVE_WITH_KNOTS").then(|| (p.get(6), p.get(7))); - let kind = match e.name() { - "BEZIER_CURVE" => "BEZIER", - "UNIFORM_CURVE" => "UNIFORM", - _ => "QUASI", - }; - (p.to_vec(), k, kind) - }; - let degree = base.get(1).and_then(Param::as_i64).filter(|d| (1..=32).contains(d)).ok_or("bad B-spline degree")? as usize; - let ctrl_ids = base.get(2).and_then(Param::as_list).ok_or("B-spline without control points")?; - if ctrl_ids.len() > MAX_CTRL { - return Err("B-spline with too many control points".into()); - } - let ctrl: Vec = ctrl_ids.iter().map(|c| point(cx, c.as_ref_id().ok_or("bad control point")?)).collect::>()?; - let kv = match knots { - Some((m, k)) => knot_vec(m, k, ctrl.len() + degree + 1)?, - None => generated_knots(kind, ctrl.len(), degree)?, - }; - if kv.len() != ctrl.len() + degree + 1 { - return Err(format!("B-spline knot count {} does not match {} control points of degree {degree}", kv.len(), ctrl.len())); - } - let bsp = mt::BSplineCurve::try_new(kv, ctrl).map_err(|e| format!("B-spline: {e}"))?; - match e.record("RATIONAL_B_SPLINE_CURVE") { - Some(r) => { - let w = weights_list(r.first())?; - let n = mt::NurbsCurve::::try_from_bspline_and_weights(bsp, w).map_err(|e| format!("rational B-spline: {e}"))?; - Ok(CurveGeo::Nurbs(mt::NurbsCurve::new(clamped_curve(n.into_non_rationalized())))) - } - None => Ok(CurveGeo::BSpline(clamped_curve(bsp))), - } -} - -/// A STEP curve entity (unbounded or bounded). -pub(crate) fn curve(cx: &Ctx, id: u64, depth: usize) -> R { - if depth > MAX_GEOM_DEPTH { - return Err("curve definitions nested too deeply".into()); - } - let e = entity(cx, id)?; - let p = e.params(); - if e.is_complex() { - return bspline_curve(cx, e); - } - match e.name() { - "LINE" => { - let pt = point(cx, p.get(1).and_then(Param::as_ref_id).ok_or("LINE without point")?)?; - let (_, v) = ent_of(cx, p.get(2), "LINE vector")?; - let d = direction(cx, v.params().get(1).and_then(Param::as_ref_id).ok_or("VECTOR without direction")?)?; - Ok(CurveGeo::Line { p: pt, d }) - } - "CIRCLE" => { - let f = frame(cx, p.get(1).and_then(Param::as_ref_id).ok_or("CIRCLE without placement")?)?; - let r = length(cx, p.get(2), "radius")?; - if r <= 0.0 { - return Err("circle radius must be positive".into()); - } - Ok(CurveGeo::Conic { f, a: r, b: r }) - } - "ELLIPSE" => { - let f = frame(cx, p.get(1).and_then(Param::as_ref_id).ok_or("ELLIPSE without placement")?)?; - let (a, b) = (length(cx, p.get(2), "semi axis")?, length(cx, p.get(3), "semi axis")?); - if a <= 0.0 || b <= 0.0 { - return Err("ellipse axes must be positive".into()); - } - Ok(CurveGeo::Conic { f, a, b }) - } - "HYPERBOLA" => { - let f = frame(cx, p.get(1).and_then(Param::as_ref_id).ok_or("HYPERBOLA without placement")?)?; - let (a, b) = (length(cx, p.get(2), "semi axis")?, length(cx, p.get(3), "semi imaginary axis")?); - if a <= 0.0 || b <= 0.0 { - return Err("hyperbola axes must be positive".into()); - } - Ok(CurveGeo::Hyperbola { f, a, b }) - } - "PARABOLA" => { - let f = frame(cx, p.get(1).and_then(Param::as_ref_id).ok_or("PARABOLA without placement")?)?; - let focal = length(cx, p.get(2), "focal distance")?; - if focal == 0.0 { - return Err("parabola focal distance must not be zero".into()); - } - Ok(CurveGeo::Parabola { f, focal }) - } - "B_SPLINE_CURVE_WITH_KNOTS" | "BEZIER_CURVE" | "UNIFORM_CURVE" | "QUASI_UNIFORM_CURVE" => bspline_curve(cx, e), - "POLYLINE" => { - let pts: Vec = p - .get(1) - .and_then(Param::as_list) - .ok_or("POLYLINE without points")? - .iter() - .map(|c| point(cx, c.as_ref_id().ok_or("bad polyline point")?)) - .collect::>()?; - if pts.len() < 2 || pts.len() > MAX_CTRL { - return Err("polyline point count".into()); - } - let mut k = vec![0.0]; - k.extend((0..pts.len()).map(|i| i as f64)); - k.push((pts.len() - 1) as f64); - Ok(CurveGeo::BSpline(mt::BSplineCurve::try_new(mt::KnotVec::from(k), pts).map_err(|e| format!("polyline: {e}"))?)) - } - "TRIMMED_CURVE" => curve(cx, p.get(1).and_then(Param::as_ref_id).ok_or("TRIMMED_CURVE without basis")?, depth + 1), - "SURFACE_CURVE" | "SEAM_CURVE" | "INTERSECTION_CURVE" | "BOUNDED_SURFACE_CURVE" => { - curve(cx, p.get(1).and_then(Param::as_ref_id).ok_or("surface curve without 3D curve")?, depth + 1) - } - n => Err(format!("unsupported curve {n}")), - } -} - -/// Rational quadratic NURBS arc of an ellipse from angle `t0` over `sweep > 0`. -pub(crate) fn conic_arc(f: &Frame, a: f64, b: f64, t0: f64, sweep: f64) -> mt::NurbsCurve { - let n = ((sweep / FRAC_PI_2).ceil() as usize).clamp(1, 8); - let dt = sweep / n as f64; - let w = (dt * 0.5).cos(); - let at = |c: f64, s: f64| f.at(a * c, b * s, 0.0); - let mut ctrl = Vec::with_capacity(2 * n + 1); - let p0 = at(t0.cos(), t0.sin()); - ctrl.push(p0.to_homogeneous()); - let mut knots = vec![0.0, 0.0, 0.0]; - for i in 0..n { - let ta = t0 + dt * i as f64; - let tm = ta + dt * 0.5; - let tb = ta + dt; - let m = at(tm.cos() / w, tm.sin() / w); - ctrl.push(mt::Vector4::new(m.x * w, m.y * w, m.z * w, w)); - ctrl.push(at(tb.cos(), tb.sin()).to_homogeneous()); - let k = (i + 1) as f64 / n as f64; - knots.push(k); - knots.push(k); - } - // Last knot pair becomes the clamped end (multiplicity 3). - knots.push(1.0); - mt::NurbsCurve::new(mt::BSplineCurve::new(mt::KnotVec::from(knots), ctrl)) -} - -/// Largest hyperbola parameter step one rational quadratic piece spans (keeps its weight -/// `cosh(step / 2)` near 1). -const HYPERBOLA_STEP: f64 = 1.0; - -/// Exact rational quadratic NURBS of the hyperbola branch from parameter `t0` to `t1` (either -/// order): pieces whose middle control point is the meeting point of the end tangents, weighted -/// `cosh` of the half step (the hyperbolic counterpart of [`conic_arc`]). -pub(crate) fn hyperbola_arc(f: &Frame, a: f64, b: f64, t0: f64, t1: f64) -> mt::NurbsCurve { - let n = (((t1 - t0).abs() / HYPERBOLA_STEP).ceil() as usize).clamp(1, 64); - let dt = (t1 - t0) / n as f64; - let w = (dt * 0.5).cosh(); - let at = |c: f64, s: f64| f.at(a * c, b * s, 0.0); - let mut ctrl = Vec::with_capacity(2 * n + 1); - ctrl.push(at(t0.cosh(), t0.sinh()).to_homogeneous()); - let mut knots = vec![0.0, 0.0, 0.0]; - for i in 0..n { - let ta = t0 + dt * i as f64; - let tm = ta + dt * 0.5; - let tb = ta + dt; - let m = at(tm.cosh() / w, tm.sinh() / w); - ctrl.push(mt::Vector4::new(m.x * w, m.y * w, m.z * w, w)); - ctrl.push(at(tb.cosh(), tb.sinh()).to_homogeneous()); - let k = (i + 1) as f64 / n as f64; - knots.push(k); - knots.push(k); - } - knots.push(1.0); - mt::NurbsCurve::new(mt::BSplineCurve::new(mt::KnotVec::from(knots), ctrl)) -} - -/// The parabola from parameter `t0` to `t1` (either order): one quadratic Bézier, exact. -pub(crate) fn parabola_arc(f: &Frame, focal: f64, t0: f64, t1: f64) -> mt::BSplineCurve { - let at = |t: f64| f.at(focal * t * t, 2.0 * focal * t, 0.0); - // The end tangents meet above the parameter midpoint: o + focal·(t0·t1, t0 + t1). - let mid = f.at(focal * t0 * t1, focal * (t0 + t1), 0.0); - mt::BSplineCurve::new(mt::KnotVec::bezier_knot(2), vec![at(t0), mid, at(t1)]) -} - -/// Parameter of the open conic at `p`, a point on (or within `tol` of) the curve. -fn open_conic_param(g: &CurveGeo, p: mt::Point3, tol: f64) -> R { - let (t, q) = match g { - CurveGeo::Hyperbola { f, a, b } => { - let t = ((p - f.o).dot(f.y) / b).asinh(); - (t, f.at(a * t.cosh(), b * t.sinh(), 0.0)) - } - CurveGeo::Parabola { f, focal } => { - let t = (p - f.o).dot(f.y) / (2.0 * focal); - (t, f.at(focal * t * t, 2.0 * focal * t, 0.0)) - } - _ => return Err("not an open conic".into()), - }; - let d = q.distance(p); - if !t.is_finite() || !(d <= tol) { - return Err(format!( - "edge vertex is {d:.3e} mm off its {} curve", - if matches!(g, CurveGeo::Parabola { .. }) { "parabola" } else { "hyperbola" } - )); - } - Ok(t) -} - -/// The open conic between parameters `t0` and `t1` as a kernel curve. -fn open_conic_curve(g: &CurveGeo, t0: f64, t1: f64) -> R { - match g { - CurveGeo::Hyperbola { f, a, b } => Ok(mt::Curve::NurbsCurve(hyperbola_arc(f, *a, *b, t0, t1))), - CurveGeo::Parabola { f, focal } => Ok(mt::Curve::BSplineCurve(parabola_arc(f, *focal, t0, t1))), - _ => Err("not an open conic".into()), - } -} - -fn conic_angle(f: &Frame, a: f64, b: f64, p: mt::Point3) -> f64 { - let d = p - f.o; - (d.dot(f.y) / b).atan2(d.dot(f.x) / a) -} - -/// Parameter of the curve point nearest to `p`, and its distance. -fn nearest_param(c: &C, p: mt::Point3) -> Option<(f64, f64)> -where - C: ParametricCurve + BoundedCurve + SearchNearestParameter, -{ - let (t0, t1) = c.range_tuple(); - let n = 256; - let mut best = (t0, f64::INFINITY); - for i in 0..=n { - let t = t0 + (t1 - t0) * i as f64 / n as f64; - let d = c.subs(t).distance(p); - if d < best.1 { - best = (t, d); - } - } - if let Some(t) = c.search_nearest_parameter(p, best.0, 64) { - let t = t.clamp(t0, t1); - let d = c.subs(t).distance(p); - if d < best.1 { - best = (t, d); - } - } - best.1.is_finite().then_some(best) -} - -/// Sub-curve on `[a, b]` (inside the curve's range). -fn sub_curve(c: &C, a: f64, b: f64) -> C { - let (t0, t1) = c.range_tuple(); - let eps = (t1 - t0).abs() * 1e-9; - let mut out = c.clone(); - if a > t0 + eps { - out = out.cut(a); - } - if b < t1 - eps { - let _ = out.cut(b); - } - out -} - -/// Pieces of a spline edge from `ps` to `pe` (two pieces for a closed edge). The vertices may -/// be up to `snap` off the curve; `tol` decides whether the curve closes on itself. -fn spline_pieces(c: &C, ps: mt::Point3, pe: mt::Point3, sense: bool, closed: bool, tol: f64, snap: f64) -> R> -where - C: ParametricCurve + BoundedCurve + SearchNearestParameter + Cut + Clone + Invertible, -{ - let (t0, t1) = c.range_tuple(); - let (ts, ds) = nearest_param(c, ps).ok_or("spline evaluation failed")?; - let (te, de) = nearest_param(c, pe).ok_or("spline evaluation failed")?; - if !(ds <= snap && de <= snap) { - return Err(format!("edge vertices are {:.3e} mm off their curve", ds.max(de))); - } - let span = t1 - t0; - let near = |a: f64, b: f64| (a - b).abs() <= span * 1e-7; - let mut pieces = if closed { - // Whole closed curve starting at the vertex. - if near(ts, t0) || near(ts, t1) { - let m = t0 + span * 0.5; - vec![sub_curve(c, t0, m), sub_curve(c, m, t1)] - } else { - vec![sub_curve(c, ts, t1), sub_curve(c, t0, ts)] - } - } else { - let (mut a, mut b) = if sense { (ts, te) } else { (te, ts) }; - // A closed curve traversed across its seam. - if a >= b && c.subs(t0).distance(c.subs(t1)) <= tol { - if near(b, t0) { - b = t1; - } else if near(a, t1) { - a = t0; - } else { - let mut v = vec![sub_curve(c, a, t1), sub_curve(c, t0, b)]; - if !sense { - v.reverse(); - v.iter_mut().for_each(|x| x.invert()); - } - return Ok(v); - } - } - if b - a <= span * 1e-9 { - return Err("degenerate spline edge".into()); - } - vec![sub_curve(c, a, b)] - }; - if !sense { - pieces.reverse(); - pieces.iter_mut().for_each(|x| x.invert()); - } - Ok(pieces) -} - -/// Moves one end of a spline piece (`back`: its end, else its start) onto its vertex `p` by -/// the control point that end sits on, so the piece meets the vertex exactly and keeps its -/// shape away from that end. A piece whose end is not a control point (an unclamped spline) is -/// left as it is. -fn pin_end(c: &mut mt::Curve, p: mt::Point3, back: bool) { - let end = if back { c.back() } else { c.front() }; - let d = p - end; - if !(d.magnitude2() > 0.0) { - return; - } - let at_end = |q: mt::Point3| q.distance(end) <= mt::TOLERANCE; - match c { - mt::Curve::BSplineCurve(b) => { - let cp = if back { b.control_points_mut().last() } else { b.control_points_mut().next() }; - if let Some(q) = cp.filter(|q| at_end(**q)) { - *q += d; - } - } - mt::Curve::NurbsCurve(n) => { - let cp = if back { n.control_points_mut().last() } else { n.control_points_mut().next() }; - if let Some(q) = cp.filter(|q| q.w != 0.0 && at_end(mt::Point3::from_homogeneous(**q))) { - *q = (mt::Point3::from_homogeneous(*q) + d).to_homogeneous() * q.w; - } - } - _ => {} - } -} - -/// Kernel curves for an edge from `ps` to `pe`: one piece, or two for a closed edge (so no -/// kernel edge starts and ends at the same vertex). A spline or open-conic edge's ends are -/// moved onto vertices up to `snap` off its curve, so the pieces meet the vertices exactly. -pub(crate) fn edge_pieces(g: &CurveGeo, ps: mt::Point3, pe: mt::Point3, sense: bool, closed: bool, tol: f64, snap: f64) -> R> { - let mut pieces = curve_pieces(g, ps, pe, sense, closed, tol, snap)?; - if matches!(g, CurveGeo::BSpline(_) | CurveGeo::Nurbs(_) | CurveGeo::Hyperbola { .. } | CurveGeo::Parabola { .. }) { - if let Some(c) = pieces.first_mut() { - pin_end(c, ps, false); - } - if let Some(c) = pieces.last_mut() { - pin_end(c, pe, true); - } - } - Ok(pieces) -} - -fn curve_pieces(g: &CurveGeo, ps: mt::Point3, pe: mt::Point3, sense: bool, closed: bool, tol: f64, snap: f64) -> R> { - match g { - CurveGeo::Line { .. } => { - if closed { - return Err("closed straight edge".into()); - } - Ok(vec![mt::Curve::Line(mt::Line(ps, pe))]) - } - CurveGeo::Conic { f, a, b } => { - let (a, b) = (*a, *b); - let ts = conic_angle(f, a, b, ps); - let te = conic_angle(f, a, b, pe); - let mut sweep = if sense { te - ts } else { ts - te }; - sweep = sweep.rem_euclid(TAU); - if closed || sweep < 1e-12 { - sweep = TAU; - } - let pieces: Vec<(f64, f64)> = if sweep > PI * 1.5 { vec![(0.0, sweep * 0.5), (sweep * 0.5, sweep)] } else { vec![(0.0, sweep)] }; - Ok(pieces - .into_iter() - .map(|(s0, s1)| { - if sense { - mt::Curve::NurbsCurve(conic_arc(f, a, b, ts + s0, s1 - s0)) - } else { - let mut c = conic_arc(f, a, b, ts - s1, s1 - s0); - c.invert(); - mt::Curve::NurbsCurve(c) - } - }) - .collect()) - } - CurveGeo::Hyperbola { .. } | CurveGeo::Parabola { .. } => { - if closed { - return Err("closed edge on an open conic".into()); - } - // The curve is open, so the edge is the parameters between its vertices: rising - // for the same sense, falling for the opposite one. - let (ts, te) = (open_conic_param(g, ps, snap)?, open_conic_param(g, pe, snap)?); - let scale = 1.0 + ts.abs().max(te.abs()); - if (te - ts).abs() <= 1e-9 * scale { - return Err("degenerate conic edge".into()); - } - Ok(vec![open_conic_curve(g, ts, te)?]) - } - CurveGeo::BSpline(c) => Ok(spline_pieces(c, ps, pe, sense, closed, tol, snap)?.into_iter().map(mt::Curve::BSplineCurve).collect()), - CurveGeo::Nurbs(c) => Ok(spline_pieces(c, ps, pe, sense, closed, tol, snap)?.into_iter().map(mt::Curve::NurbsCurve).collect()), - } -} - -/// A bounded kernel curve for a swept surface's profile (lines are bounded by `extent`). -fn bounded_curve(g: &CurveGeo, extent: &[mt::Point3]) -> R { - Ok(match g { - CurveGeo::Line { p, d } => { - let (lo, hi) = span_along(extent, *p, *d); - mt::Curve::Line(mt::Line(*p + *d * lo, *p + *d * hi)) - } - CurveGeo::Conic { f, a, b } => mt::Curve::NurbsCurve(conic_arc(f, *a, *b, 0.0, TAU)), - CurveGeo::Hyperbola { f, .. } | CurveGeo::Parabola { f, .. } => { - // Bounded by the face's points (their parameters along the curve), with a margin. - let along = |q: &mt::Point3| match g { - CurveGeo::Hyperbola { b, .. } => ((q - f.o).dot(f.y) / b).asinh(), - CurveGeo::Parabola { focal, .. } => (q - f.o).dot(f.y) / (2.0 * focal), - _ => 0.0, - }; - let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY); - for t in extent.iter().map(along).filter(|t| t.is_finite()) { - lo = lo.min(t); - hi = hi.max(t); - } - let (lo, hi) = if lo < hi { (lo - (hi - lo) * 0.25 - 1e-3, hi + (hi - lo) * 0.25 + 1e-3) } else { (-1.0, 1.0) }; - open_conic_curve(g, lo, hi)? - } - CurveGeo::BSpline(c) => mt::Curve::BSplineCurve(c.clone()), - CurveGeo::Nurbs(c) => mt::Curve::NurbsCurve(c.clone()), - }) -} - -/// Range of `(q - o)·d` over the points, widened by a margin. -fn span_along(pts: &[mt::Point3], o: mt::Point3, d: mt::Vector3) -> (f64, f64) { - let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY); - for q in pts { - let t = (q - o).dot(d); - lo = lo.min(t); - hi = hi.max(t); - } - if !(lo.is_finite() && hi.is_finite()) { - return (-1.0, 1.0); - } - let m = (hi - lo) * 0.25 + 1e-3; - (lo - m, hi + m) -} - -/// The angle shared by all the given angles (within 1e-4 rad), if there are any. -fn common_angle(angles: impl Iterator) -> Option { - let (mut sx, mut sy, mut n) = (0.0, 0.0, 0usize); - let mut all = Vec::new(); - for a in angles { - sx += a.cos(); - sy += a.sin(); - n += 1; - all.push(a); - } - if n == 0 { - return None; - } - let m = sy.atan2(sx); - let close = all.iter().all(|a| { - let d = (a - m).rem_euclid(TAU); - d.min(TAU - d) < 1e-4 - }); - close.then_some(m) -} - -/// Middle and width of the largest gap between angles (radians, any range). -fn largest_gap(angles: &[f64]) -> Option<(f64, f64)> { - let mut a: Vec = angles.iter().map(|x| x.rem_euclid(TAU)).filter(|x| x.is_finite()).collect(); - if a.is_empty() { - return None; - } - a.sort_by(f64::total_cmp); - let (mut best, mut mid) = (0.0, 0.0); - let a = Ring::new(a); - for (i, (&x, &y)) in a.edges().enumerate() { - let gap = if i + 1 == a.len() { y + TAU - x } else { y - x }; - if gap > best { - best = gap; - mid = x + gap * 0.5; - } - } - Some((mid, best)) -} - -/// The frame turned about its Z axis so that its X axis (the parameter seam of a revolved -/// surface) lies in the widest angular gap of the face boundary. -fn seam_frame(f: &Frame, extent: &[mt::Point3], seam: &[mt::Point3]) -> Frame { - // A seam edge of the face along the rotation: the parameter seam must be there. - if let Some(m) = common_angle(seam.iter().filter_map(|p| { - let d = p - f.o; - let (x, y) = (d.dot(f.x), d.dot(f.y)); - (x.hypot(y) > 1e-6 * (1.0 + d.magnitude())).then(|| y.atan2(x)) - })) { - let x = f.x * m.cos() + f.y * m.sin(); - return Frame { o: f.o, x, y: f.z.cross(x), z: f.z }; - } - let az: Vec = extent - .iter() - .filter_map(|p| { - let d = p - f.o; - let (x, y) = (d.dot(f.x), d.dot(f.y)); - (x.hypot(y) > 1e-9).then(|| y.atan2(x)) - }) - .collect(); - match largest_gap(&az) { - Some((m, gap)) if gap > 1e-3 => { - let x = f.x * m.cos() + f.y * m.sin(); - Frame { o: f.o, x, y: f.z.cross(x), z: f.z } - } - _ => *f, - } -} - -/// Length of the mean unit direction from the frame origin to the points (1: all in one -/// direction, 0: spread all round). -fn mean_direction(f: &Frame, pts: &[mt::Point3]) -> f64 { - let dirs: Vec = pts - .iter() - .filter_map(|p| { - let d = p - f.o; - let m = d.magnitude(); - (m > 1e-12).then(|| d / m) - }) - .collect(); - if dirs.is_empty() { - return 0.0; - } - (dirs.iter().fold(mt::Vector3::new(0.0, 0.0, 0.0), |a, d| a + d) / dirs.len() as f64).magnitude() -} - -/// Polar axis for a sphere: far from every boundary point, and (for a face concentrated on -/// one side) with both poles outside the face, so every loop closes in parameter space. -fn sphere_axis(f: &Frame, extent: &[mt::Point3]) -> mt::Vector3 { - let dirs: Vec = extent - .iter() - .filter_map(|p| { - let d = p - f.o; - let m = d.magnitude(); - (m > 1e-12).then(|| d / m) - }) - .collect(); - if dirs.is_empty() { - return f.z; - } - let mean = dirs.iter().fold(mt::Vector3::new(0.0, 0.0, 0.0), |a, d| a + d) / dirs.len() as f64; - let concentrated = mean.magnitude() > 0.3; - let mhat = if concentrated { mean / mean.magnitude() } else { mean }; - let n = 400; - let golden = PI * (3.0 - 5f64.sqrt()); - let mut best = (f64::NEG_INFINITY, f.z); - // Half of a Fibonacci sphere (an axis and its opposite are the same poles). - for i in 0..n { - let z = 1.0 - (i as f64 + 0.5) / n as f64; - let r = (1.0 - z * z).max(0.0).sqrt(); - let t = golden * i as f64; - let a = mt::Vector3::new(r * t.cos(), r * t.sin(), z); - if concentrated && a.dot(mhat).abs() > 0.35 { - continue; - } - let score = dirs.iter().map(|d| 1.0 - d.dot(a).abs()).fold(f64::INFINITY, f64::min); - if score > best.0 { - best = (score, a); - } - } - best.1 -} - -/// Tube angle of a point on a torus. -fn tube_angle(f: &Frame, big: f64, p: mt::Point3) -> f64 { - let d = p - f.o; - let z = d.dot(f.z); - let rho = (d - f.z * z).magnitude(); - z.atan2(rho - big) -} - -/// A straight profile of a surface of revolution, bounded by the face: boundary points are -/// turned into the profile's meridian plane and projected onto the line, and the line stops at -/// the axis (beyond it the surface would fold over itself). -fn revolved_line(p: mt::Point3, d: mt::Vector3, o: mt::Point3, axis: mt::Vector3, extent: &[mt::Point3]) -> R { - let radial = |q: mt::Point3| { - let v = q - o; - v - axis * v.dot(axis) - }; - // The meridian half-plane of the profile. - let e = { - let r = radial(p); - let r2 = radial(p + d); - let r = if r.magnitude() >= r2.magnitude() { r } else { r2 }; - if r.magnitude() < 1e-12 { - return Err("profile line on the axis".into()); - } - r / r.magnitude() - }; - let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY); - for q in extent { - let v = q - o; - let h = v.dot(axis); - let r = radial(*q).magnitude(); - let t = (o + axis * h + e * r - p).dot(d); - lo = lo.min(t); - hi = hi.max(t); - } - if !(lo.is_finite() && hi.is_finite()) { - return Err("surface of revolution without extent".into()); - } - let m = (hi - lo) * 0.02 + 1e-6; - let (mut lo, mut hi) = (lo - m, hi + m); - // Where the line meets the axis (radial component along e vanishes). - let de = d.dot(e); - if de.abs() > 1e-12 { - let t_axis = -(p - o).dot(e) / de; - // The meridian half-plane has a non-negative radius along `e`. - if de > 0.0 { - lo = lo.max(t_axis); - } else { - hi = hi.min(t_axis); - } - } - if hi - lo <= 1e-12 { - return Err("degenerate surface of revolution".into()); - } - Ok(mt::Curve::Line(mt::Line(p + d * lo, p + d * hi))) -} - -fn revolved(curve: mt::Curve, o: mt::Point3, axis: mt::Vector3) -> mt::Surface { - mt::Surface::RevolutedCurve(mt::Processor::new(mt::RevolutedCurve::by_revolution(curve, o, axis))) -} - -/// A surface of revolution whose normal at the profile point `(u, 0)` points along `expected`. -/// The rotation is reversed rather than the surface inverted: truck's inverted `Processor` -/// swaps the parameters but not the search hints, which breaks meshing. -pub(crate) fn revolved_oriented(curve: mt::Curve, o: mt::Point3, axis: mt::Vector3, u: f64, expected: mt::Vector3) -> mt::Surface { - let s = revolved(curve.clone(), o, axis); - if s.normal(u, 0.0).dot(expected) >= 0.0 { - return s; - } - revolved(curve, o, -axis) -} - -pub(crate) fn bspline_surface(cx: &Ctx, e: &Entity) -> R { - let (base, knots, kind): (Vec, Option<[Option<&Param>; 4]>, &str) = if e.is_complex() { - let b = e.record("B_SPLINE_SURFACE").ok_or("complex surface without B_SPLINE_SURFACE")?; - let mut base = vec![Param::Str(String::new())]; - base.extend(b.iter().cloned()); - let k = e.record("B_SPLINE_SURFACE_WITH_KNOTS").map(|k| [k.first(), k.get(1), k.get(2), k.get(3)]); - let kind = if e.has("BEZIER_SURFACE") { - "BEZIER" - } else if e.has("UNIFORM_SURFACE") { - "UNIFORM" - } else { - "QUASI" - }; - (base, k, kind) - } else { - let p = e.params(); - let k = (e.name() == "B_SPLINE_SURFACE_WITH_KNOTS").then(|| [p.get(8), p.get(9), p.get(10), p.get(11)]); - let kind = match e.name() { - "BEZIER_SURFACE" => "BEZIER", - "UNIFORM_SURFACE" => "UNIFORM", - _ => "QUASI", - }; - (p.to_vec(), k, kind) - }; - let deg = |i: usize| base.get(i).and_then(Param::as_i64).filter(|d| (1..=32).contains(d)).map(|d| d as usize).ok_or("bad B-spline degree"); - let (du, dv) = (deg(1)?, deg(2)?); - let rows = base.get(3).and_then(Param::as_list).ok_or("B-spline surface without control points")?; - let mut ctrl: Vec> = Vec::with_capacity(rows.len()); - let mut total = 0usize; - for r in rows { - let r = r.as_list().ok_or("bad control point row")?; - total += r.len(); - if total > MAX_CTRL { - return Err("B-spline surface with too many control points".into()); - } - ctrl.push(r.iter().map(|c| point(cx, c.as_ref_id().ok_or("bad control point")?)).collect::>()?); - } - let nu = ctrl.len(); - let nv = ctrl.first().map(Vec::len).unwrap_or(0); - if nu == 0 || ctrl.iter().any(|r| r.len() != nv) { - return Err("ragged B-spline control net".into()); - } - let (ku, kv) = match knots { - Some([mu, mv, ku, kv]) => (knot_vec(mu, ku, nu + du + 1)?, knot_vec(mv, kv, nv + dv + 1)?), - None => (generated_knots(kind, nu, du)?, generated_knots(kind, nv, dv)?), - }; - if ku.len() != nu + du + 1 || kv.len() != nv + dv + 1 { - return Err("B-spline surface knot counts do not match the control net".into()); - } - let bsp = mt::BSplineSurface::try_new((ku, kv), ctrl).map_err(|e| format!("B-spline surface: {e}"))?; - match e.record("RATIONAL_B_SPLINE_SURFACE") { - Some(r) => { - let w: Vec> = r - .first() - .and_then(Param::as_list) - .ok_or("rational surface without weights")? - .iter() - .map(|row| weights_list(Some(row))) - .collect::>()?; - if w.len() != nu || w.iter().any(|r| r.len() != nv) { - return Err("weights do not match the control net".into()); - } - let n = mt::NurbsSurface::::try_from_bspline_and_weights(bsp, w).map_err(|e| format!("rational surface: {e}"))?; - Ok(mt::Surface::NurbsSurface(mt::NurbsSurface::new(clamped_surface(n.into_non_rationalized())))) - } - None => Ok(mt::Surface::BSplineSurface(clamped_surface(bsp))), - } -} - -/// Resolve exact analytic offsets. Each intermediate offset is checked: an invalid inner -/// offset must not become valid merely because an outer offset cancels its distance. -/// Entity attributes follow ISO 10303-42 (`basis_surface`, `distance`, `self_intersect`). -fn offset_basis(cx: &Ctx, id: u64, depth: usize) -> R<(u64, f64)> { - if depth > MAX_GEOM_DEPTH { - return Err("surface definitions nested too deeply".into()); - } - let e = entity(cx, id)?; - if e.name() != "OFFSET_SURFACE" { - return Ok((id, 0.0)); - } - let p = e.params(); - let basis = p.get(1).and_then(Param::as_ref_id).ok_or("offset surface without basis")?; - let distance = length(cx, p.get(2), "offset distance")?; - if !matches!(p.get(3).and_then(Param::as_enum), Some("T" | "F" | "U")) { - return Err("offset surface without a logical self_intersect flag".into()); - } - let (basis, inner) = offset_basis(cx, basis, depth + 1)?; - let offset = inner + distance; - if !offset.is_finite() || offset.abs() >= MAX_COORD { - return Err("offset distance out of range after unit conversion".into()); - } - let e = entity(cx, basis)?; - let p = e.params(); - match e.name() { - "PLANE" => {} - "CYLINDRICAL_SURFACE" | "SPHERICAL_SURFACE" => { - let radius = length(cx, p.get(2), "radius")?; - if radius <= 0.0 || !(1e-9..MAX_COORD).contains(&(radius + offset)) { - return Err("offset surface collapses or reverses its radius".into()); - } - } - "CONICAL_SURFACE" => { - let radius = length(cx, p.get(2), "radius")?; - let angle = num(p.get(3), "semi angle")? * cx.ang; - if radius < 0.0 || !(angle.abs() > 1e-9 && angle.abs() < FRAC_PI_2 - 1e-9) || !(0.0..MAX_COORD).contains(&(radius + offset / angle.cos())) - { - return Err("offset cone has an invalid reference radius or angle".into()); - } - } - "TOROIDAL_SURFACE" => { - let major = length(cx, p.get(2), "major radius")?; - let minor = length(cx, p.get(3), "minor radius")?; - if minor <= 0.0 || major <= minor || major >= MAX_COORD || !(1e-9..major).contains(&(minor + offset)) { - return Err("offset torus collapses or becomes self-intersecting".into()); - } - } - _ if offset == 0.0 => {} - n => return Err(format!("unsupported OFFSET_SURFACE basis surface {n}")), - } - Ok((basis, offset)) -} - -/// A STEP surface entity as a kernel surface whose normal is the STEP surface normal. -/// `extent` holds points of the face boundary (bounds the analytic surfaces' parameter ranges). -/// `sense` false gives the opposite normal (a face with `same_sense = .F.`). -/// `seam` holds points of the face's seam edges (edges its loops use twice). -pub(crate) fn surface(cx: &Ctx, id: u64, extent: &[mt::Point3], seam: &[mt::Point3], sense: bool, depth: usize) -> R { - let sign = if sense { 1.0 } else { -1.0 }; - let flip = |mut s: mt::Surface| { - if !sense { - s.invert(); - } - s - }; - if depth > MAX_GEOM_DEPTH { - return Err("surface definitions nested too deeply".into()); - } - let (id, offset) = offset_basis(cx, id, depth)?; - let e = entity(cx, id)?; - if e.is_complex() { - return bspline_surface(cx, e).map(flip); - } - let p = e.params(); - let placement = || -> R { frame(cx, p.get(1).and_then(Param::as_ref_id).ok_or("surface without placement")?) }; - match e.name() { - "PLANE" => { - let f = placement()?; - let o = f.o + f.z * offset; - Ok(flip(mt::Surface::Plane(mt::Plane::new(o, o + f.x, o + f.y)))) - } - "CYLINDRICAL_SURFACE" => { - let f = seam_frame(&placement()?, extent, seam); - let r = length(cx, p.get(2), "radius")? + offset; - if r <= 0.0 { - return Err("cylinder radius must be positive".into()); - } - let (lo, hi) = span_along(extent, f.o, f.z); - let line = mt::Curve::Line(mt::Line(f.at(r, 0.0, lo), f.at(r, 0.0, hi))); - Ok(revolved_oriented(line, f.o, f.z, 0.5, f.x * sign)) - } - "CONICAL_SURFACE" => { - let f = seam_frame(&placement()?, extent, seam); - let basis_r = length(cx, p.get(2), "radius")?; - let a = num(p.get(3), "semi angle")? * cx.ang; - let r = basis_r + offset / a.cos(); - if r < 0.0 || !(a.abs() > 1e-9 && a.abs() < FRAC_PI_2 - 1e-9) { - return Err("bad cone".into()); - } - let t = a.tan(); - let (mut lo, mut hi) = span_along(extent, f.o, f.z); - // Stop at the apex. - let apex = -r / t; - if t > 0.0 { - lo = lo.max(apex); - } else { - hi = hi.min(apex); - } - if hi - lo <= 1e-9 { - return Err("cone face has no extent".into()); - } - let line = mt::Curve::Line(mt::Line(f.at(r + lo * t, 0.0, lo), f.at(r + hi * t, 0.0, hi))); - Ok(revolved_oriented(line, f.o, f.z, 0.5, (f.x * a.cos() - f.z * a.sin()) * sign)) - } - "SPHERICAL_SURFACE" => { - let f = placement()?; - let r = length(cx, p.get(2), "radius")? + offset; - if r <= 0.0 { - return Err("sphere radius must be positive".into()); - } - // With seam edges the file's own parameterisation fits the loops; else pick poles - // away from the boundary. - // A small patch (a corner blend) gets poles away from it even when the file runs a - // seam through it: a seam ending at a pole on the patch boundary leaves the mesher - // no way to tell the patch from the rest of the sphere. - let f = if seam.is_empty() || mean_direction(&f, extent) > 0.3 { - let z = sphere_axis(&f, extent); - let x = any_perpendicular(z); - seam_frame(&Frame { o: f.o, x, y: z.cross(x), z }, extent, seam) - } else { - seam_frame(&f, extent, seam) - }; - let half = Frame { o: f.o, x: f.x, y: f.z, z: -f.y }; - let arc = conic_arc(&half, r, r, -FRAC_PI_2, PI); - let um = (arc.range_tuple().0 + arc.range_tuple().1) * 0.5; - Ok(revolved_oriented(mt::Curve::NurbsCurve(arc), f.o, f.z, um, f.x * sign)) - } - "TOROIDAL_SURFACE" => { - let f = placement()?; - let (big, small) = (length(cx, p.get(2), "major radius")?, length(cx, p.get(3), "minor radius")? + offset); - if small <= 0.0 || big < 0.0 { - return Err("bad torus radii".into()); - } - // Seam edges either run around the axis (constant tube angle) or around the tube - // (constant azimuth); each fixes one parameter seam. - let tube_seam: Vec = - seam.iter().copied().filter(|p| common_angle(std::iter::once(tube_angle(&f, big, *p))).is_some()).collect(); - let phis_seam = common_angle(tube_seam.iter().map(|p| tube_angle(&f, big, *p))); - let az_seam: Vec = if phis_seam.is_some() { Vec::new() } else { seam.to_vec() }; - let f = seam_frame(&f, extent, &az_seam); - let phis: Vec = extent.iter().map(|p| tube_angle(&f, big, *p)).collect(); - let phi0 = match (phis_seam, largest_gap(&phis)) { - (Some(m), _) => m, - (None, Some((m, _))) => m, - (None, None) => 0.0, - }; - let tube = Frame { o: f.at(big, 0.0, 0.0), x: f.x, y: f.z, z: -f.y }; - let circle = conic_arc(&tube, small, small, phi0, TAU); - let u0 = circle.range_tuple().0; - let outward = f.x * phi0.cos() + f.z * phi0.sin(); - Ok(revolved_oriented(mt::Curve::NurbsCurve(circle), f.o, f.z, u0, outward * sign)) - } - "B_SPLINE_SURFACE_WITH_KNOTS" | "BEZIER_SURFACE" | "UNIFORM_SURFACE" | "QUASI_UNIFORM_SURFACE" => bspline_surface(cx, e).map(flip), - "SURFACE_OF_REVOLUTION" => { - let g = curve(cx, p.get(1).and_then(Param::as_ref_id).ok_or("revolution without profile")?, depth + 1)?; - let (o, axis) = axis1(cx, p.get(2).and_then(Param::as_ref_id).ok_or("revolution without axis")?)?; - let profile = match &g { - CurveGeo::Line { p, d } => revolved_line(*p, *d, o, axis, extent)?, - _ => bounded_curve(&g, extent)?, - }; - // ISO 10303-42 parameterises a surface of revolution by the angle u and the profile - // v, so its normal is ∂S/∂angle × ∂S/∂profile: the opposite of truck's revolution - // (profile first). Strict readers take it this way. Reversed sense turns it back. - Ok(revolved(profile, o, -axis * sign)) - } - "SURFACE_OF_LINEAR_EXTRUSION" => { - let g = curve(cx, p.get(1).and_then(Param::as_ref_id).ok_or("extrusion without profile")?, depth + 1)?; - let (_, v) = ent_of(cx, p.get(2), "extrusion vector")?; - let d = direction(cx, v.params().get(1).and_then(Param::as_ref_id).ok_or("VECTOR without direction")?)?; - let profile = match &g { - CurveGeo::Conic { f, a, b } if d.dot(f.z).abs() > 1e-12 => { - // Keep the closed profile's parameter seam outside the trim. Otherwise a - // tooth tip crossing it can mesh as almost the whole extruded ellipse. - let dz = d.dot(f.z); - let angle = |p: &mt::Point3| { - let q = p - f.o; - let q = q - d * (q.dot(f.z) / dz); - (q.dot(f.y) / b).atan2(q.dot(f.x) / a) - }; - let start = common_angle(seam.iter().map(angle)) - .or_else(|| largest_gap(&extent.iter().map(angle).collect::>()).map(|(mid, _)| mid)) - .unwrap_or(0.0); - mt::Curve::NurbsCurve(conic_arc(f, *a, *b, start, TAU)) - } - _ => bounded_curve(&g, extent)?, - }; - let nurbs: mt::NurbsCurve = match profile { - mt::Curve::Line(l) => mt::BSplineCurve::new(mt::KnotVec::bezier_knot(1), vec![l.0, l.1]).into(), - mt::Curve::BSplineCurve(c) => c.into(), - mt::Curve::NurbsCurve(c) => c, - mt::Curve::IntersectionCurve(_) => return Err("unsupported extrusion profile".into()), - }; - let (t0, t1) = nurbs.range_tuple(); - let profile: Vec = (0..=32).map(|i| nurbs.subs(t0 + (t1 - t0) * i as f64 / 32.0)).collect(); - let (plo, phi) = span_along(&profile, mt::Point3::new(0.0, 0.0, 0.0), d); - let (elo, ehi) = span_along(extent, mt::Point3::new(0.0, 0.0, 0.0), d); - let (lo, hi) = (elo - phi, ehi - plo); - let bsp = nurbs.into_non_rationalized(); - let shift = |w: &mt::Vector4, s: f64| mt::Vector4::new(w.x + d.x * s * w.w, w.y + d.y * s * w.w, w.z + d.z * s * w.w, w.w); - let ctrl: Vec> = bsp.control_points().iter().map(|w| vec![shift(w, lo), shift(w, hi)]).collect(); - let s = - mt::BSplineSurface::try_new((bsp.knot_vec().clone(), mt::KnotVec::bezier_knot(1)), ctrl).map_err(|e| format!("extrusion: {e}"))?; - Ok(flip(mt::Surface::NurbsSurface(mt::NurbsSurface::new(s)))) - } - "RECTANGULAR_TRIMMED_SURFACE" | "CURVE_BOUNDED_SURFACE" => { - surface(cx, p.get(1).and_then(Param::as_ref_id).ok_or("trimmed surface without basis")?, extent, seam, sense, depth + 1) - } - n => Err(format!("unsupported surface {n}")), - } -} diff --git a/crates/kernel/src/step_in/mod.rs b/crates/kernel/src/step_in/mod.rs index ec7828015..26b8d050f 100644 --- a/crates/kernel/src/step_in/mod.rs +++ b/crates/kernel/src/step_in/mod.rs @@ -1,28 +1,23 @@ //! STEP import (ISO 10303-21 files, AP203/AP214/AP242 geometry). //! //! Our own reader, written from the public standards: [`p21`] parses the exchange structure, -//! [`geom`] and [`brep`] turn geometry and topology into kernel solids, and this module walks -//! the product structure (products, shape representations, assemblies with their placements, -//! units, colours). STEP files are untrusted: every count and nesting depth is capped, every -//! truck call runs under [`guard`], and what cannot be read becomes a warning rather than a -//! failure wherever the rest of the file is still usable. +//! [`solidcraft_step::topology`] reads each solid into its schema 4 record, which SMLib takes +//! as the body ([`parallel`]), and this module walks the product structure (products, shape +//! representations, assemblies with their placements, units, colours). STEP files are +//! untrusted: every count and nesting depth is capped, and what cannot be read becomes a +//! warning rather than a failure wherever the rest of the file is still usable. -mod brep; -pub(crate) mod geom; pub(crate) mod p21; mod parallel; -pub(crate) mod split; use std::collections::{BTreeMap, HashMap, HashSet}; use std::sync::Arc; -use mt::EuclideanSpace as _; use serde::{Deserialize, Serialize}; -use truck_modeling as mt; +use solidcraft_step::read::R; use crate::body::Body; -use crate::{KernelError, Result, guard}; -use geom::R; +use crate::{KernelError, Result}; use p21::{Entity, Exchange, Param}; /// Deepest assembly nesting followed. @@ -99,48 +94,21 @@ struct Planned { /// Where the solids of a batch go: their placement and names. struct Batch { - m: mt::Matrix4, + m: M4, path: Vec, product: String, instance: Option, } -/// Reading context: the file and the units of the representation being read. -pub(crate) struct Ctx<'a> { - pub ex: &'a Exchange, - /// Millimetres per file length unit. - pub len: f64, - /// Radians per file angle unit. - pub ang: f64, - /// Vertex-on-curve tolerance (mm). - pub tol: f64, -} +/// The units of a representation context (GLOBAL_UNIT_ASSIGNED_CONTEXT) and its distance +/// uncertainty (mm) as the file states it. +type Units = solidcraft_step::units::Context; -#[derive(Clone, Copy)] -struct Units { - len: f64, - ang: f64, - tol: f64, - /// The context's own distance uncertainty (mm), as the file states it (SMLib's reads take it). - #[cfg_attr(not(feature = "smlib"), allow(dead_code))] - uncertainty: Option, -} - -const DEFAULT_UNITS: Units = Units { len: 1.0, ang: 1.0, tol: 0.01, uncertainty: None }; - -/// Units of a representation context (GLOBAL_UNIT_ASSIGNED_CONTEXT, uncertainty), read by -/// [`solidcraft_step::units::context`]; the vertex-on-curve tolerance is ten times the -/// uncertainty (at least 1e-3 mm), else a hundredth of the length unit, within [1e-4, 1] mm. +/// Units of a representation context, read by [`solidcraft_step::units::context`] (millimetres +/// and radians when the file names none). fn context_units(ex: &Exchange, ctx: Option, cache: &mut HashMap) -> Units { - let Some(id) = ctx else { return DEFAULT_UNITS }; - if let Some(u) = cache.get(&id) { - return *u; - } - let c = solidcraft_step::units::context(ex, id); - let tol = c.uncertainty.map(|t| (t * 10.0).max(1e-3)).unwrap_or(c.units.len * 1e-2).clamp(1e-4, 1.0); - let u = Units { len: c.units.len, ang: c.units.ang, tol, uncertainty: c.uncertainty }; - cache.insert(id, u); - u + let Some(id) = ctx else { return Units::default() }; + *cache.entry(id).or_insert_with(|| solidcraft_step::units::context(ex, id)) } /// Items and context of a representation entity. @@ -157,18 +125,48 @@ fn representation(e: &Entity) -> Option<(Vec, Option)> { Some((items, p.get(2).and_then(Param::as_ref_id))) } -fn mat_mul(a: &mt::Matrix4, b: &mt::Matrix4) -> mt::Matrix4 { - a * b +/// A placement: a column-major 4×4 matrix (columns 0–2 the images of x, y and z, column 3 the +/// translation), millimetres. +type M4 = [[f64; 4]; 4]; + +const IDENTITY: M4 = [[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]]; + +/// `a · b`. +fn mat_mul(a: &M4, b: &M4) -> M4 { + let mut out = [[0.0; 4]; 4]; + for (col, out_col) in out.iter_mut().enumerate() { + for (row, cell) in out_col.iter_mut().enumerate() { + *cell = (0..4).map(|k| a[k][row] * b[col][k]).sum(); + } + } + out } -fn to_array(m: &mt::Matrix4) -> [[f64; 4]; 4] { - [[m.x.x, m.x.y, m.x.z, m.x.w], [m.y.x, m.y.y, m.y.z, m.y.w], [m.z.x, m.z.y, m.z.z, m.z.w], [m.w.x, m.w.y, m.w.z, m.w.w]] +/// The inverse of a rigid placement (an orthonormal rotation and a translation): the rotation +/// transposed, and the translation taken back through it. +fn rigid_inverse(m: &M4) -> M4 { + let mut out = IDENTITY; + for (i, col) in out.iter_mut().take(3).enumerate() { + for (j, cell) in col.iter_mut().take(3).enumerate() { + *cell = m[j][i]; + } + } + for i in 0..3 { + out[3][i] = -(0..3).map(|k| m[i][k] * m[3][k]).sum::(); + } + out } -/// Inverse of a rigid placement matrix (orthonormal rotation + translation). -fn rigid_inverse(m: &mt::Matrix4) -> mt::Matrix4 { - use mt::SquareMatrix; - m.invert().unwrap_or_else(mt::Matrix4::identity) +fn translation(t: [f64; 3]) -> M4 { + let mut m = IDENTITY; + m[3] = [t[0], t[1], t[2], 1.0]; + m +} + +/// The matrix of an AXIS2_PLACEMENT: its frame's axes and origin. +fn frame_matrix(p: &solidcraft_step::geom::Placement) -> M4 { + let (x, y, z, o) = (p.ref_direction, p.y(), p.axis, p.origin); + [[x[0], x[1], x[2], 0.0], [y[0], y[1], y[2], 0.0], [z[0], z[1], z[2], 0.0], [o[0], o[1], o[2], 1.0]] } struct Reader { @@ -197,7 +195,7 @@ struct Reader { once: HashSet, /// An item placed more than once: its first instance's display, shared by every instance /// (with the placement that first instance had), so the part is meshed once. - shown: HashMap, mt::Matrix4)>, + shown: HashMap, M4)>, /// How many planned solids place each item. uses: HashMap, /// An item placed more than once: read and oriented where the file defines it, so each @@ -489,15 +487,16 @@ impl Reader { context_units(&self.ex, ctx, &mut self.units) } - fn placement_matrix(&mut self, item: u64, u: Units) -> R { - let cx = Ctx { ex: &self.ex, len: u.len, ang: u.ang, tol: u.tol }; - let e = geom::entity(&cx, item)?; + /// The placement an item states: an AXIS2_PLACEMENT's frame, or a + /// CARTESIAN_TRANSFORMATION_OPERATOR_3D's origin. + fn placement_matrix(&mut self, item: u64, u: Units) -> R { + let reader = solidcraft_step::read::Reader::new(&self.ex, u.units); + let e = self.ex.get(item).ok_or_else(|| format!("missing entity #{item}"))?; if e.name() == "CARTESIAN_TRANSFORMATION_OPERATOR_3D" { - let p = e.params(); - let o = geom::point(&cx, p.get(4).and_then(Param::as_ref_id).ok_or("transformation without origin")?)?; - return Ok(mt::Matrix4::from_translation(o.to_homogeneous().truncate())); + let o = reader.point(e.params().get(4).and_then(Param::as_ref_id).ok_or("transformation without origin")?)?; + return Ok(translation(o)); } - Ok(geom::frame(&cx, item)?.matrix()) + Ok(frame_matrix(&reader.frame(item)?)) } /// Representations of a product (its own shape representations and those linked to them). @@ -535,7 +534,7 @@ impl Reader { } /// Bodies of a representation's items (following mapped items), placed by `m`. - fn rep_bodies(&mut self, rep: u64, m: &mt::Matrix4, path: &[String], product: &str, instance: Option<&str>, out: &mut Vec, depth: usize) { + fn rep_bodies(&mut self, rep: u64, m: &M4, path: &[String], product: &str, instance: Option<&str>, out: &mut Vec, depth: usize) { if depth > MAX_ASSEMBLY_DEPTH { self.warn("mapped items nested too deeply"); return; @@ -660,7 +659,7 @@ impl Reader { Some(part) => parallel::Source::Oriented(part.clone()), None => parallel::Source::Item { item, units }, }; - let placement = self.batches.get(p.batch).map_or(mt::Matrix4::from_scale(1.0), |b| b.m); + let placement = self.batches.get(p.batch).map_or(IDENTITY, |b| b.m); sources.push((i, item)); jobs.push(parallel::Job { source, placement, check_mesh: !self.unmeshed_checked.contains(&item) }); } @@ -715,11 +714,11 @@ impl Reader { // Every instance of a part placed more than once shows its first instance's // mesh, placed (the first one too: meshing its own would mesh the part twice). let body = match self.shown.get(&item) { - Some((shared, first)) => body.with_display_of(shared.clone(), to_array(&mat_mul(&m, &rigid_inverse(first)))), + Some((shared, first)) => body.with_display_of(shared.clone(), mat_mul(&m, &rigid_inverse(first))), None if self.uses.get(&item).is_some_and(|n| *n > 1) => { let shared = Arc::new(crate::body::SharedDisplay::new(body.clone())); self.shown.insert(item, (shared.clone(), m)); - body.with_display_of(shared, to_array(&mt::Matrix4::from_scale(1.0))) + body.with_display_of(shared, IDENTITY) } None => body, }; @@ -780,10 +779,10 @@ impl Reader { } /// Placement of a child occurrence in its parent. - fn occurrence_matrix(&mut self, nauo: u64, child_reps: &[u64]) -> mt::Matrix4 { - let Some(&rel) = self.placements.get(&nauo) else { return mt::Matrix4::from_scale(1.0) }; + fn occurrence_matrix(&mut self, nauo: u64, child_reps: &[u64]) -> M4 { + let Some(&rel) = self.placements.get(&nauo) else { return IDENTITY }; let ex = self.ex.clone(); - let r = (|| -> R { + let r = (|| -> R { let e = ex.get(rel).ok_or("missing placement")?; let rr = e.record("REPRESENTATION_RELATIONSHIP").ok_or("placement without representations")?; let (r1, r2) = @@ -814,23 +813,14 @@ impl Reader { Ok(m) => m, Err(e) => { self.warn(format!("component placement #{rel}: {e} (placed at the origin)")); - mt::Matrix4::from_scale(1.0) + IDENTITY } } } - fn node( - &mut self, - pd: u64, - local: mt::Matrix4, - world: mt::Matrix4, - path: &[String], - instance: Option<&str>, - depth: usize, - stack: &mut Vec, - ) -> StepNode { + fn node(&mut self, pd: u64, local: M4, world: M4, path: &[String], instance: Option<&str>, depth: usize, stack: &mut Vec) -> StepNode { let name = self.product_name(pd); - let mut node = StepNode { name: name.clone(), transform: to_array(&local), bodies: Vec::new(), children: Vec::new() }; + let mut node = StepNode { name: name.clone(), transform: local, bodies: Vec::new(), children: Vec::new() }; if self.stop() { return node; } @@ -869,96 +859,29 @@ impl Reader { } } -/// Check a STEP file's structure: it parses, no entity id is defined twice, every reference -/// names a defined entity, nothing but root entities (relationships, definitions, -/// presentation) is left unreferenced, and ids are dense (`#1`…`#n`). Returns the entity count. -/// Faces whose boundary runs the wrong way round their normal, as a strict reader -/// sees them: each face's normal is its surface's own parametric normal (∂S/∂u × ∂S/∂v, ISO -/// 10303-42), reversed when `same_sense` is false, and the outer loop must run counter-clockwise -/// seen from that side. Checked on faces whose loop spans a clear direction (patches, not bands -/// around a closed surface). Returns one message per bad face. +/// Faces whose boundary runs the wrong way round their normal, as a strict reader sees them: +/// each face's normal is its surface's own parametric normal (∂S/∂u × ∂S/∂v, ISO 10303-42), +/// reversed when `same_sense` is false, and the outer loop must run counter-clockwise seen from +/// that side. These are the faces the STEP reader turns over ([`solidcraft_step::topology`]), +/// numbered as the solid's body numbers them. Returns one message per bad face; an error when +/// the file does not parse or has no solid the reader can read. pub fn step_orientation_errors(text: &str) -> std::result::Result, String> { - use mt::{BoundedCurve, InnerSpace, ParametricCurve, ParametricSurface3D, SearchNearestParameter}; - let imp = step_import(text).map_err(|e| e.to_string())?; + let ex = p21::parse(text)?; + let read = solidcraft_step::topology::read_solids(&ex); + 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))); + } let mut out = Vec::new(); - for b in &imp.bodies { - let r = guard("orientation check", || { - let mut bad = Vec::new(); - for (fi, f) in b.body.solid.face_iter().enumerate() { - let bounds = f.boundaries(); - // Patches only: a face with several loops (a band between two rings, a face with - // holes) has no single loop direction to compare. - let [w] = bounds.as_slice() else { continue }; - // Only revolutions (cylinders, cones, spheres, tori: closed surfaces, where a loop - // read the wrong way round silently gives the rest of the surface). On free-form - // strips the loop's normals vary too much for this test; the round trips' volume - // checks cover those. - if !matches!(f.surface(), mt::Surface::RevolutedCurve(_)) { - continue; - } - // A loop through a vertex twice (a figure eight round a pole) has no single direction. - let fronts: std::collections::HashSet<_> = w.edge_iter().map(|e| e.front().id()).collect(); - if fronts.len() != w.len() { - continue; - } - let pts: Vec = w - .edge_iter() - .flat_map(|e| { - let c = e.oriented_curve(); - let (t0, t1) = c.range_tuple(); - (0..16).map(move |i| c.subs(t0 + (t1 - t0) * i as f64 / 16.0)).collect::>() - }) - .collect(); - let n = pts.len(); - if n < 3 { - continue; - } - let mut newell = mt::Vector3::new(0.0, 0.0, 0.0); - let mut c = mt::Vector3::new(0.0, 0.0, 0.0); - let mut span: f64 = 0.0; - for i in 0..n { - let (Some(a), Some(q)) = (pts.get(i), pts.get((i + 1) % n)) else { continue }; - newell += (a.to_vec()).cross(q.to_vec()); - c += a.to_vec(); - span = span.max((a - pts[0]).magnitude()); - } - let c = mt::Point3::from_vec(c / n as f64); - // Bands round a closed surface have no clear loop direction. - if !(newell.magnitude() > 0.05 * span * span) { - continue; - } - // The face normal averaged along the loop (each loop point is on the surface; - // the loop's centroid can be nearer the wrong side of a curved face). - let s = f.oriented_surface(); - let mut normal = mt::Vector3::new(0.0, 0.0, 0.0); - let mut count = 0usize; - for p in &pts { - if let Some(uv) = s.search_nearest_parameter(*p, None, 100) { - let n = s.normal(uv.0, uv.1); - if n.x.is_finite() && n.y.is_finite() && n.z.is_finite() { - normal += n; - count += 1; - } - } - } - let _ = c; - // Only patches clearly to one side of their loop are judged: a loop on a closed - // surface (a sphere's cube-face square) bounds either part. - if count == 0 || normal.magnitude() < 0.7 * count as f64 { - continue; - } - if normal.dot(newell) < 0.0 { - bad.push(format!("{}: face {fi} runs clockwise around its normal", b.name)); - } - } - Ok(bad) - }) - .map_err(|e| e.to_string())?; - out.extend(r); + for solid in &read.solids { + let name = if solid.name.trim().is_empty() { format!("solid #{}", solid.item) } else { solid.name.trim().to_string() }; + out.extend(solid.turned.iter().map(|f| format!("{name}: face {f} runs clockwise around its normal"))); } Ok(out) } +/// Check a STEP file's structure: it parses, no entity id is defined twice, every reference +/// names a defined entity, nothing but root entities (relationships, definitions, +/// presentation) is left unreferenced, and ids are dense (`#1`…`#n`). Returns the entity count. pub fn step_validate(text: &str) -> std::result::Result { let ex = p21::parse(text)?; if let Some(d) = ex.duplicates.first() { @@ -1129,7 +1052,7 @@ impl StepReading { let mut roots: Vec = ex.entities.iter().filter(|(id, e)| e.name() == "PRODUCT_DEFINITION" && !child_pds.contains(id)).map(|(id, _)| *id).collect(); roots.sort(); - let identity = mt::Matrix4::from_scale(1.0); + let identity = IDENTITY; let mut tree = Vec::new(); for pd in roots { tree.push(rd.node(pd, identity, identity, &[], None, 0, &mut Vec::new())); @@ -1155,7 +1078,7 @@ impl StepReading { for r in loose { rd.rep_bodies(r, &identity, &[], "Import", None, &mut bodies, 0); } - tree.push(StepNode { name: "Import".into(), transform: to_array(&identity), bodies, children: Vec::new() }); + tree.push(StepNode { name: "Import".into(), transform: identity, bodies, children: Vec::new() }); } let single = workers <= 1; Ok(StepReading { rd, tree, key, small: text.len() <= KEEP_SMALL_BYTES, single }) diff --git a/crates/kernel/src/step_in/p21.rs b/crates/kernel/src/step_in/p21.rs index 969606bd0..fd850160f 100644 --- a/crates/kernel/src/step_in/p21.rs +++ b/crates/kernel/src/step_in/p21.rs @@ -1,6 +1,6 @@ //! The Part 21 parser lives in `solidcraft-step`; this reads with the kernel's progress watch. -pub use solidcraft_step::p21::{Entity, Exchange, Param, Record}; +pub use solidcraft_step::p21::{Entity, Exchange, Param}; struct Watched(std::sync::Arc); diff --git a/crates/kernel/src/step_in/parallel.rs b/crates/kernel/src/step_in/parallel.rs index ec7008eaa..a3332e119 100644 --- a/crates/kernel/src/step_in/parallel.rs +++ b/crates/kernel/src/step_in/parallel.rs @@ -1,18 +1,13 @@ //! Bounded desktop preparation of independent imported bodies, collected in file order. use std::sync::Arc; -use super::{Body, Ctx, Exchange, KernelError, Units, brep, guard, mt}; +use super::{Body, Exchange, IDENTITY, KernelError, M4, Units}; pub(super) struct Job { pub source: Source, /// Where the body goes (its instance's placement in the assembly). - pub placement: mt::Matrix4, + pub placement: M4, pub check_mesh: bool, - /// The file's point-on-surface tolerance (`super::Units::tol`) for the representation this - /// solid was read from: how far its boundaries may lie off their surfaces (mm). The body - /// keeps it, so the tessellator holds an imported boundary to the file's own uncertainty - /// rather than to a fraction of the part's size (see `crate::body::Body::boundary_tol`). - pub tol: f64, } /// What a job places: a solid item to read from the file (and orient), or a part an earlier @@ -66,51 +61,31 @@ pub(super) fn workers() -> usize { fn prepare(ex: &Exchange, job: &Job) -> Prepared { let (part, read) = match &job.source { Source::Oriented(part) => (part.clone(), None), - Source::Item { item, units } if smlib_backend() => { + Source::Item { item, units } => { let (part, read) = smlib_part(ex, *item, *units)?; (Arc::new(part), Some(read)) } - Source::Item { item, units } => { - let cx = Ctx { ex, len: units.len, ang: units.ang, tol: units.tol, snap: units.snap }; - let out = guard("step brep", || brep::read_item(&cx, *item).map_err(KernelError::Failed)) - .map_err(|e| Failure { read: true, msg: e.to_string().trim_start_matches("the operation failed: ").to_string() })?; - // Orient once where the file defines the solid; each placement then takes its - // orientation from the matrix instead of meshing the whole part again. - let body = guard("STEP body preparation", || Body::new(out.solid)).map_err(|e| Failure { read: false, msg: e.to_string() })?; - // The file's tolerance is set on the part itself, before anything meshes it: the - // unmeshed-face count below is the import's own warning and must judge the body by - // the file's uncertainty too, and every placement of the part carries the figure on. - let body = body.with_boundary_tol(Some(job.tol)); - (Arc::new(Part { body, closed: out.closed, file_faces: out.file_faces, face_origin: out.face_origin }), Some(out.failed)) - } }; - guard("STEP body preparation", || { - let body = part.body.placed(&job.placement)?; - // Counted where the orientation mesh already counted them (a placement meshes the - // same faces), and on the part, which carries the file's tolerance. - let missing = if job.check_mesh { part.body.unmeshed_faces() } else { 0 }; - Ok((body, missing)) - }) - .map(|(body, missing)| Made { body, missing, part, read }) - .map_err(|e| Failure { read: false, msg: e.to_string() }) + let body = placed(&part.body, &job.placement).map_err(|e| Failure { read: false, msg: e.to_string() })?; + // Counted on the part (a placement meshes the same faces). + let missing = if job.check_mesh { part.body.unmeshed_faces() } else { 0 }; + Ok(Made { body, missing, part, read }) } -/// Whether solids are read into SMLib ([`crate::backend`]). A setting this build can't honour -/// reads them on neither kernel: [`smlib_part`] then says why. -fn smlib_backend() -> bool { - !matches!(crate::backend(), Ok(crate::Backend::Truck)) +/// The part's body where its instance goes: the very same body at the identity (it keeps the +/// SMLib body the read made), else its record moved there. +fn placed(body: &Body, m: &M4) -> crate::Result { + if *m == IDENTITY { + return Ok(body.clone()); + } + Ok(crate::ops::transform_matrix(body, *m)?.without_history()) } -/// A solid item read with the STEP reader into its schema 4 record, then into SMLib (healed -/// where SMLib's check refuses it as given), 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; there is no -/// other kernel to fall back on. -#[cfg(feature = "smlib")] +/// A solid item read with the STEP reader into its schema 4 record, then into SMLib as given, +/// 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), Failure> { - crate::backend().map_err(|e| Failure { read: true, msg: e.to_string() })?; - let context = - solidcraft_step::units::Context { units: solidcraft_step::read::Units { len: units.len, ang: units.ang }, uncertainty: units.uncertainty }; - let solid = solidcraft_step::topology::read_solid(ex, item, context).map_err(|msg| Failure { read: true, msg })?; + let solid = solidcraft_step::topology::read_solid(ex, item, units).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)?; @@ -133,11 +108,6 @@ pub(super) fn smlib_part(ex: &Exchange, item: u64, units: Units) -> std::result: Ok((part, solid.notes)) } -#[cfg(not(feature = "smlib"))] -pub(super) fn smlib_part(_: &Exchange, _: u64, _: Units) -> std::result::Result<(Part, Vec), Failure> { - Err(Failure { read: true, msg: crate::backend().err().map_or_else(|| "this build has no SMLib".into(), |e| e.to_string()) }) -} - /// Prepare `jobs`, the results in the jobs' order. Solids still to read and orient (the slow /// part) are shared out between up to `workers` threads, each taking the next job when it is /// done with one, so one large part does not hold up the rest. diff --git a/crates/kernel/src/step_in/split.rs b/crates/kernel/src/step_in/split.rs deleted file mode 100644 index 509c046c1..000000000 --- a/crates/kernel/src/step_in/split.rs +++ /dev/null @@ -1,582 +0,0 @@ -//! Splitting band faces that wrap all the way around a closed, non-periodic parameter direction. -//! -//! A STEP face may run once around a closed surface and close its loop with a seam edge used -//! twice (a pipe segment of a torus, a revolved B-spline band). Truck meshes faces in parameter -//! space and only treats the rotation of a revolved surface as periodic, so such a face is cut -//! in two along the parameter line opposite its seam; the ring edges it crosses are cut in every -//! face that uses them. - -use std::collections::HashMap; - -use mt::{BoundedCurve, BoundedSurface, InnerSpace, Invertible, MetricSpace, ParametricCurve, ParametricSurface, SearchNearestParameter}; -use truck_modeling as mt; - -use super::geom::{Frame, R, conic_arc}; - -/// How far a band's ring edge may lie off its surface, as a fraction of the body, for a body that -/// declares no accuracy of its own. -const RING_OFF_SURFACE: f64 = 1e-3; - -/// Samples per edge when looking for the split crossing. -const SAMPLES: usize = 48; - -/// Which surface parameter wraps around. -#[derive(Clone, Copy, Debug, PartialEq)] -enum Dir { - U, - V, -} - -fn uv_of(s: &mt::Surface, p: mt::Point3) -> Option<(f64, f64)> { - s.search_nearest_parameter(p, None, 100).filter(|(u, v)| u.is_finite() && v.is_finite()) -} - -fn coord(d: Dir, uv: (f64, f64)) -> f64 { - match d { - Dir::U => uv.0, - Dir::V => uv.1, - } -} - -/// The direction the split line runs along (the one that does not wrap). -fn along(d: Dir) -> Dir { - match d { - Dir::U => Dir::V, - Dir::V => Dir::U, - } -} - -/// The closed, non-periodic direction of a surface with its range; with `periodic`, a revolved -/// surface's turn around its axis too. -fn closed_dirs(s: &mt::Surface, periodic: bool) -> Vec<(Dir, f64, f64)> { - match s { - mt::Surface::RevolutedCurve(p) => { - let c = p.entity().entity_curve(); - let (t0, t1) = c.range_tuple(); - let mut out = Vec::new(); - if c.front().distance(c.back()) < 1e-7 * (1.0 + c.front().to_homogeneous().truncate().magnitude()) { - out.push((Dir::U, t0, t1)); - } - if periodic { - out.extend(turn_dir(s)); - } - out - } - mt::Surface::BSplineSurface(_) | mt::Surface::NurbsSurface(_) => { - let ((u0, u1), (v0, v1)) = match s { - mt::Surface::BSplineSurface(b) => b.range_tuple(), - mt::Surface::NurbsSurface(n) => n.range_tuple(), - _ => return vec![], - }; - let size = (0..=4) - .flat_map(|i| (0..=4).map(move |j| (i, j))) - .map(|(i, j)| s.subs(u0 + (u1 - u0) * i as f64 / 4.0, v0 + (v1 - v0) * j as f64 / 4.0).to_homogeneous().truncate().magnitude()) - .fold(1.0, f64::max); - let tol = size * 1e-7; - let mut out = Vec::new(); - if (0..=8).all(|k| { - let v = v0 + (v1 - v0) * k as f64 / 8.0; - s.subs(u0, v).distance(s.subs(u1, v)) < tol - }) { - out.push((Dir::U, u0, u1)); - } - if (0..=8).all(|k| { - let u = u0 + (u1 - u0) * k as f64 / 8.0; - s.subs(u, v0).distance(s.subs(u, v1)) < tol - }) { - out.push((Dir::V, v0, v1)); - } - out - } - mt::Surface::Plane(_) => vec![], - } -} - -/// The parameter that turns a revolved surface around its axis, over one turn. -fn turn_dir(s: &mt::Surface) -> Option<(Dir, f64, f64)> { - let mt::Surface::RevolutedCurve(p) = s else { return None }; - let (t0, t1) = p.entity().entity_curve().range_tuple(); - let tau = std::f64::consts::TAU; - let ts: Vec = (0..=4).map(|i| t0 + (t1 - t0) * f64::from(i) / 4.0).collect(); - [Dir::V, Dir::U].into_iter().find_map(|d| { - let at = |w: f64, t: f64| match d { - Dir::V => s.subs(t, w), - Dir::U => s.subs(w, t), - }; - let scale = ts.iter().map(|t| at(0.0, *t).to_homogeneous().truncate().magnitude()).fold(1.0, f64::max); - let closes = ts.iter().all(|t| at(0.0, *t).distance(at(tau, *t)) < scale * 1e-9); - let turns = ts.iter().any(|t| at(0.0, *t).distance(at(std::f64::consts::PI, *t)) > scale * 1e-6); - (closes && turns).then_some((d, 0.0, tau)) - }) -} - -fn samples(c: &mt::Curve, n: usize) -> Vec<(f64, mt::Point3)> { - let (t0, t1) = c.range_tuple(); - (0..=n).map(|i| t0 + (t1 - t0) * i as f64 / n as f64).map(|t| (t, c.subs(t))).collect() -} - -/// Where a ring chain crosses `w = mid`: (edge index in the chain, parameter on the edge's -/// absolute curve, point). -fn crossing(s: &mt::Surface, d: Dir, chain: &[mt::Edge], mid: f64, period: f64) -> R<(usize, f64, mt::Point3)> { - for (k, e) in chain.iter().enumerate() { - let c = e.curve(); - let pts = samples(&c, SAMPLES); - let ws: Vec> = pts.iter().map(|(_, p)| uv_of(s, *p).map(|uv| coord(d, uv))).collect(); - for i in 0..SAMPLES { - let (Some(Some(wa)), Some(Some(wb)), Some((ta, _)), Some((tb, _))) = (ws.get(i), ws.get(i + 1), pts.get(i), pts.get(i + 1)) else { - continue; - }; - if (wb - wa).abs() > period * 0.5 || (wa - mid) * (wb - mid) > 0.0 { - continue; - } - // Bisection on the curve parameter. - let (mut lo, mut hi, mut flo) = (*ta, *tb, wa - mid); - for _ in 0..60 { - let m = 0.5 * (lo + hi); - let Some(w) = uv_of(s, c.subs(m)).map(|uv| coord(d, uv)) else { break }; - let f = w - mid; - if (f - flo).abs() > period * 0.5 { - break; - } - if f * flo <= 0.0 { - hi = m; - } else { - lo = m; - flo = f; - } - } - let t = 0.5 * (lo + hi); - return Ok((k, t, c.subs(t))); - } - } - Err("no crossing with the split line".into()) -} - -/// Iso-parameter edge curve `w = mid` from `q1` to `q2`. `tol` is how far a ring edge may lie off -/// the surface the split line lies on: a STEP file writes the surface and the curves bounding it -/// to the file's own declared uncertainty only, so the line is matched to the surface points -/// below `q1` and `q2`, not to them. -fn iso_curve(s: &mt::Surface, d: Dir, mid: f64, q1: mt::Point3, q2: mt::Point3, seam: &[mt::Point3], tol: f64) -> R { - match s { - // Across the turn of a cylinder or cone: a straight line along it. - mt::Surface::RevolutedCurve(_) if turn_dir(s).is_some_and(|t| t.0 == d) => { - let m = q1 + (q2 - q1) * 0.5; - let on = uv_of(s, m).is_some_and(|(u, v)| s.subs(u, v).distance(m) < 1e-7 * (1.0 + q1.distance(q2))); - if on && q1.distance(q2) > 1e-9 { - Ok(mt::Curve::Line(mt::Line(q1, q2))) - } else { - Err("a revolved face that is not straight along its axis".into()) - } - } - mt::Surface::RevolutedCurve(p) => { - // A circle around the axis, turning opposite to the seam (which runs from the q2 - // side to the q1 side). - let (o, a) = (p.entity().origin(), p.entity().axis()); - let az = |x: mt::Point3, f: &Frame| { - let v = x - f.o; - v.dot(f.y).atan2(v.dot(f.x)) - }; - let c = o + a * (q1 - o).dot(a); - let r = (q1 - c).magnitude(); - if !(r > 1e-9) { - return Err("split line on the axis".into()); - } - let x = (q1 - c) / r; - let f = Frame { o: c, x, y: a.cross(x), z: a }; - let mut seam_turn = 0.0; - for w in seam.windows(2) { - if let (Some(p0), Some(p1)) = (w.first(), w.get(1)) { - let d = az(*p1, &f) - az(*p0, &f); - seam_turn += (d + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI; - } - } - let sweep = -seam_turn; - if sweep.abs() < 1e-9 { - return Err("degenerate split line".into()); - } - let f = if sweep > 0.0 { f } else { Frame { o: c, x, y: -a.cross(x), z: -a } }; - let arc = conic_arc(&f, r, r, 0.0, sweep.abs()); - if arc.back().distance(q2) > (1e-6 * (1.0 + r)).max(tol) { - return Err("split line does not reach the other ring".into()); - } - Ok(mt::Curve::NurbsCurve(arc)) - } - mt::Surface::BSplineSurface(_) | mt::Surface::NurbsSurface(_) => { - let hom: mt::BSplineSurface = match s { - mt::Surface::BSplineSurface(b) => mt::BSplineSurface::new( - b.knot_vecs().clone(), - b.control_points().iter().map(|row| row.iter().map(|p| p.to_homogeneous()).collect()).collect(), - ), - mt::Surface::NurbsSurface(n) => n.non_rationalized().clone(), - _ => return Err("unsupported surface".into()), - }; - let iso = mt::Curve::NurbsCurve(iso_bsp(&hom, mid, d == Dir::V)?); - let (t0, t1) = iso.range_tuple(); - // Where the split line comes nearest `p`: the point on the surface below `p` (the - // line runs on the surface, `p` only within the file's tolerance of it), looked for - // from its own surface parameter and from a scan of the whole line. - let near = |p: mt::Point3| { - let foot = uv_of(s, p).filter(|uv| s.subs(uv.0, uv.1).distance(p) <= tol); - let target = foot.map_or(p, |uv| s.subs(uv.0, uv.1)); - let mut best = (t0, f64::INFINITY); - for i in 0..=256 { - let t = t0 + (t1 - t0) * i as f64 / 256.0; - let dd = iso.subs(t).distance(target); - if dd < best.1 { - best = (t, dd); - } - } - let seeds = foot.map(|uv| coord(along(d), uv)).into_iter().chain(iso.search_nearest_parameter(target, best.0, 64)); - for t in seeds { - let t = t.clamp(t0, t1); - let dd = iso.subs(t).distance(target); - if dd <= best.1 { - best = (t, dd); - } - } - best - }; - let ((ta, da), (tb, db)) = (near(q1), near(q2)); - let scale = 1.0 + q1.to_homogeneous().truncate().magnitude(); - if da > 1e-5 * scale || db > 1e-5 * scale || (ta - tb).abs() < 1e-12 { - return Err("split line does not reach the rings".into()); - } - let (lo, hi) = if ta < tb { (ta, tb) } else { (tb, ta) }; - let mut c = iso; - let eps = (t1 - t0) * 1e-9; - if lo > t0 + eps { - c = mt::Cut::cut(&mut c, lo); - } - if hi < t1 - eps { - let _ = mt::Cut::cut(&mut c, hi); - } - if ta > tb { - c.invert(); - } - Ok(c) - } - mt::Surface::Plane(_) => Err("planes do not wrap".into()), - } -} - -/// The iso-curve of a homogeneous B-spline surface at `v = w` (`along_u`) or `u = w`. -pub(crate) fn iso_bsp(b: &mt::BSplineSurface, w: f64, along_u: bool) -> R> { - let (ku, kv) = b.knot_vecs(); - let ctrl = b.control_points(); - let nu = ctrl.len(); - let nv = ctrl.first().map(Vec::len).unwrap_or(0); - let zero = mt::Vector4::new(0.0, 0.0, 0.0, 0.0); - let pts: Vec = if along_u { - let deg = kv.len().checked_sub(nv + 1).ok_or("bad knot vector")?; - let basis = kv.try_bspline_basis_functions(deg, w).map_err(|e| e.to_string())?; - ctrl.iter().map(|row| row.iter().zip(&basis).fold(zero, |acc, (p, f)| acc + *p * *f)).collect() - } else { - let deg = ku.len().checked_sub(nu + 1).ok_or("bad knot vector")?; - let basis = ku.try_bspline_basis_functions(deg, w).map_err(|e| e.to_string())?; - (0..nv).map(|j| ctrl.iter().zip(&basis).fold(zero, |acc, (row, f)| acc + row.get(j).copied().unwrap_or(zero) * *f)).collect() - }; - let knots = if along_u { ku.clone() } else { kv.clone() }; - mt::BSplineCurve::try_new(knots, pts).map(mt::NurbsCurve::new).map_err(|e| e.to_string()) -} - -type Cut = (mt::Edge, (mt::Edge, mt::Edge)); - -/// Split a chain at parameter `t` of its edge `k` (absolute curve): the edges before and after -/// the split point, the edge cut (unless the point is an existing vertex) and the split vertex. -fn split_chain(chain: &[mt::Edge], k: usize, t: f64, q: mt::Point3) -> R<(Vec, Vec, Option, mt::Vertex)> { - let e = chain.get(k).ok_or("bad crossing")?; - let (t0, t1) = e.curve().range_tuple(); - let eps = (t1 - t0).abs() * 1e-7; - let at_front = (t - t0).abs() <= eps; - let at_back = (t - t1).abs() <= eps; - if at_front || at_back { - // The split point is a vertex already: split the chain between edges. - let v = if at_front { e.absolute_front().clone() } else { e.absolute_back().clone() }; - let first_end = at_front != e.orientation(); // the point is this edge's end in loop order - let cut_at = if first_end { k + 1 } else { k }; - let before = chain.iter().take(cut_at).cloned().collect(); - let after = chain.iter().skip(cut_at).cloned().collect(); - return Ok((before, after, None, v)); - } - let v = mt::Vertex::new(q); - let (a, b) = e.cut_with_parameter(&v, t).ok_or("cannot cut a ring edge at the split line")?; - let mut before: Vec = chain.iter().take(k).cloned().collect(); - before.push(a.clone()); - let mut after = vec![b.clone()]; - after.extend(chain.iter().skip(k + 1).cloned()); - Ok((before, after, Some((e.clone(), (a, b))), v)) -} - -struct Plan { - /// Edge cuts: (edge as used in the band's loop, its two pieces in that loop's order). - cuts: Vec, - faces: (mt::Face, mt::Face), -} - -/// How to cut `face` in two along the line opposite its seam. `periodic` also cuts a face that -/// runs round the turn of a revolved surface (see [`closed_dirs`]). `tol` is how far a ring edge -/// of the face may lie off the surface it bounds (see [`iso_curve`]). -fn plan(face: &mt::Face, periodic: bool, tol: f64) -> R> { - let s = face.surface(); - let wires = face.absolute_boundaries().clone(); - let mut uses: HashMap = HashMap::new(); - for e in wires.iter().flat_map(|w| w.edge_iter()) { - *uses.entry(e.id()).or_default() += 1; - } - let is_seam = |e: &mt::Edge| uses.get(&e.id()).copied().unwrap_or(0) > 1; - if !wires.iter().flat_map(|w| w.edge_iter()).any(is_seam) { - return Ok(None); - } - // The closed direction whose boundary carries the seam. - let seam_pts: Vec = - wires.iter().flat_map(|w| w.edge_iter()).filter(|e| is_seam(e)).flat_map(|e| samples(&e.curve(), 4).into_iter().map(|x| x.1)).collect(); - let Some((d, w0, w1)) = closed_dirs(&s, periodic).into_iter().find(|(d, w0, w1)| { - let p = w1 - w0; - seam_pts.iter().all(|q| uv_of(&s, *q).map(|uv| coord(*d, uv)).is_some_and(|w| (w - w0).abs().min((w - w1).abs()) < p * 1e-4)) - }) else { - return Ok(None); - }; - let (period, mid) = (w1 - w0, 0.5 * (w0 + w1)); - let outer_idx = wires.iter().position(|w| w.edge_iter().any(is_seam)).ok_or("no seam loop")?; - if wires.iter().enumerate().any(|(i, w)| i != outer_idx && w.edge_iter().any(is_seam)) { - return Err("seam edges in several loops".into()); - } - let outer: Vec = wires.get(outer_idx).ok_or("no seam loop")?.edge_iter().cloned().collect(); - let n = outer.len(); - let start = (0..n) - .find(|&i| outer.get(i).is_some_and(is_seam) && outer.get((i + n - 1) % n).is_some_and(|e| !is_seam(e))) - .ok_or("loop made only of seam edges")?; - let rot: Vec = (0..n).filter_map(|i| outer.get((start + i) % n).cloned()).collect(); - let mut chains: Vec<(bool, Vec)> = Vec::new(); - for e in rot { - let seam = is_seam(&e); - match chains.last_mut() { - Some((s0, c)) if *s0 == seam => c.push(e), - _ => chains.push((seam, vec![e])), - } - } - // A cone's tip: the seam runs from the ring to the apex and straight back. - if let [(true, sm), (false, ring)] = chains.as_slice() { - return apex_plan(face, &s, (d, mid, period), sm, ring, &wires, outer_idx, tol).map(Some); - } - let [(true, s1), (false, r1), (true, s2), (false, r2)] = chains.as_slice() else { - return Err(format!("unsupported seam loop layout ({} runs)", chains.len())); - }; - let s2_ids: Vec = s2.iter().rev().map(mt::Edge::id).collect(); - if s1.iter().map(mt::Edge::id).collect::>() != s2_ids { - return Err("seam edges are not used back and forth".into()); - } - let (k1, t1, q1) = crossing(&s, d, r1, mid, period)?; - let (k2, t2, q2) = crossing(&s, d, r2, mid, period)?; - let seam_line: Vec = s1.iter().flat_map(|e| samples(&e.oriented_curve(), 16).into_iter().map(|x| x.1)).collect(); - let iso = iso_curve(&s, d, mid, q1, q2, &seam_line, tol)?; - let (r1a, r1b, c1, v1) = split_chain(r1, k1, t1, q1)?; - let (r2a, r2b, c2, v2) = split_chain(r2, k2, t2, q2)?; - let e_split = mt::Edge::new_unchecked(&v1, &v2, iso); - // Face A: split, rest of ring 2, seam, start of ring 1. Face B: the other half. - let mut wa: Vec = vec![e_split.clone()]; - wa.extend(r2b); - wa.extend(s1.iter().cloned()); - wa.extend(r1a.iter().cloned()); - let mut wb: Vec = vec![e_split.inverse()]; - wb.extend(r1b); - wb.extend(s2.iter().cloned()); - wb.extend(r2a); - let wire_a: mt::Wire = wa.into(); - let wire_b: mt::Wire = wb.into(); - if !wire_a.is_closed() || !wire_b.is_closed() { - return Err("split loops do not close".into()); - } - // Holes go to the half that holds them. - let side_a = r1a - .iter() - .flat_map(|e| samples(&e.oriented_curve(), 4)) - .filter_map(|(_, p)| uv_of(&s, p).map(|uv| coord(d, uv))) - .find(|w| (w - mid).abs() > period * 1e-3) - .map(|w| w < mid) - .ok_or("cannot place the split halves")?; - let (mut ha, mut hb) = (vec![wire_a], vec![wire_b]); - for (i, w) in wires.iter().enumerate() { - if i == outer_idx { - continue; - } - let ws: Vec = w.edge_iter().flat_map(|e| samples(&e.curve(), 4)).filter_map(|(_, p)| uv_of(&s, p).map(|uv| coord(d, uv))).collect(); - if ws.iter().all(|x| (*x < mid) == side_a) { - ha.push(w.clone()); - } else if ws.iter().all(|x| (*x < mid) != side_a) { - hb.push(w.clone()); - } else { - return Err("a hole crosses the split line".into()); - } - } - let mut fa = mt::Face::new_unchecked(ha, s.clone()); - let mut fb = mt::Face::new_unchecked(hb, s); - if !face.orientation() { - fa.invert(); - fb.invert(); - } - Ok(Some(Plan { cuts: c1.into_iter().chain(c2).collect(), faces: (fa, fb) })) -} - -/// Split a face closing at an apex (loop: seam out to the apex, seam back, the ring) along the -/// iso-line opposite the seam, from the ring to the apex. -fn apex_plan( - face: &mt::Face, - s: &mt::Surface, - (d, mid, period): (Dir, f64, f64), - sm: &[mt::Edge], - ring: &[mt::Edge], - wires: &[mt::Wire], - outer_idx: usize, - tol: f64, -) -> R { - let h = sm.len() / 2; - if !sm.len().is_multiple_of(2) || h == 0 { - return Err("seam edges are not used back and forth".into()); - } - let (out, back) = (sm.get(..h).ok_or("seam")?, sm.get(h..).ok_or("seam")?); - if out.iter().map(mt::Edge::id).collect::>() != back.iter().rev().map(mt::Edge::id).collect::>() { - return Err("seam edges are not used back and forth".into()); - } - let apex = out.last().ok_or("seam")?.back().clone(); - let (k, t, q) = crossing(s, d, ring, mid, period)?; - let seam_line: Vec = out.iter().flat_map(|e| samples(&e.oriented_curve(), 16).into_iter().map(|x| x.1)).collect(); - let iso = iso_curve(s, d, mid, q, apex.point(), &seam_line, tol)?; - let (ra, rb, c, vq) = split_chain(ring, k, t, q)?; - let e = mt::Edge::new_unchecked(&vq, &apex, iso); - // Face A: out to the apex, down the split line, the ring's second part; face B the rest. - let mut wa: Vec = out.to_vec(); - wa.push(e.inverse()); - wa.extend(rb.iter().cloned()); - let mut wb: Vec = vec![e]; - wb.extend(back.iter().cloned()); - wb.extend(ra); - let (wire_a, wire_b): (mt::Wire, mt::Wire) = (wa.into(), wb.into()); - if !wire_a.is_closed() || !wire_b.is_closed() { - return Err("split loops do not close".into()); - } - let side_a = rb - .iter() - .flat_map(|e| samples(&e.oriented_curve(), 4)) - .filter_map(|(_, p)| uv_of(s, p).map(|uv| coord(d, uv))) - .find(|w| (w - mid).abs() > period * 1e-3) - .map(|w| w < mid) - .ok_or("cannot place the split halves")?; - let (mut ha, mut hb) = (vec![wire_a], vec![wire_b]); - for (i, w) in wires.iter().enumerate() { - if i == outer_idx { - continue; - } - let ws: Vec = w.edge_iter().flat_map(|e| samples(&e.curve(), 4)).filter_map(|(_, p)| uv_of(s, p).map(|uv| coord(d, uv))).collect(); - if ws.iter().all(|x| (*x < mid) == side_a) { - ha.push(w.clone()); - } else if ws.iter().all(|x| (*x < mid) != side_a) { - hb.push(w.clone()); - } else { - return Err("a hole crosses the split line".into()); - } - } - let mut fa = mt::Face::new_unchecked(ha, s.clone()); - let mut fb = mt::Face::new_unchecked(hb, s.clone()); - if !face.orientation() { - fa.invert(); - fb.invert(); - } - Ok(Plan { cuts: c.into_iter().collect(), faces: (fa, fb) }) -} - -/// Replace cut edges in a face's loops. -fn recut(face: &mt::Face, cuts: &[(mt::Edge, (mt::Edge, mt::Edge))]) -> mt::Face { - let touches = face.absolute_boundaries().iter().flat_map(|w| w.edge_iter()).any(|e| cuts.iter().any(|(c, _)| c.id() == e.id())); - if !touches { - return face.clone(); - } - let wires: Vec = face - .absolute_boundaries() - .iter() - .map(|w| { - let mut out: Vec = Vec::new(); - for e in w.edge_iter() { - match cuts.iter().find(|(c, _)| c.id() == e.id()) { - Some((c, (a, b))) if c.orientation() == e.orientation() => out.extend([a.clone(), b.clone()]), - Some((_, (a, b))) => out.extend([b.inverse(), a.inverse()]), - None => out.push(e.clone()), - } - } - out.into() - }) - .collect(); - let mut f = mt::Face::new_unchecked(wires, face.surface()); - if !face.orientation() { - f.invert(); - } - f -} - -/// A copy of `body` whose faces that run once round a cylinder or cone along a seam edge -/// (as STEP files have them) are each cut in two along the line opposite the seam, the way the -/// kernel builds such walls itself; the boolean cannot always intersect the whole ones. `None` -/// when the body has no such face, or one can't be cut. -pub(crate) fn split_seams(body: &crate::Body) -> Option { - let seamed = |f: &mt::Face| { - let mut seen = std::collections::HashSet::new(); - f.absolute_boundaries().iter().flat_map(|w| w.edge_iter()).any(|e| !seen.insert(e.id())) - }; - if !body.solid.face_iter().any(seamed) { - return None; - } - // How far a ring edge of such a face may lie off the surface it bounds (see `iso_curve`): - // the file's own declared uncertainty for a body read from one, else a thousandth of the body. - let tol = body.boundary_tol.unwrap_or(body.size() * RING_OFF_SURFACE).max(1e-6); - let mut shells: Vec = Vec::new(); - for sh in body.solid.boundaries() { - let mut faces: Vec = sh.face_iter().cloned().collect(); - let n = faces.len(); - for i in 0..n { - let Some(face) = faces.get(i).cloned() else { continue }; - if !seamed(&face) { - continue; - } - let p = crate::guard("seam split", || plan(&face, true, tol).map_err(crate::KernelError::Failed)).ok()??; - faces = faces.iter().map(|f| recut(f, &p.cuts)).collect(); - if let Some(slot) = faces.get_mut(i) { - *slot = p.faces.0; - } - faces.push(p.faces.1); - } - shells.push(faces.into()); - } - let solid = mt::Solid::try_new(shells).ok()?; - let b = crate::Body::new(solid).ok()?; - b.validity().is_empty().then_some(b) -} - -/// Split every band face of a shell (see the module docs). Faces that cannot be split stay as -/// they are and are reported. -/// -/// `tol` is the file's point-on-surface tolerance (`step_in::mod::Units::tol`): 10x the file's -/// declared uncertainty, floored at 1 µm and clamped to [1e-4, 1] mm. A ring edge is written to -/// within this distance of the surface it bounds, so it is how far `iso_curve` may accept a -/// crossing point as lying on the surface. -pub(crate) fn split_bands(mut faces: Vec, origin: &mut Vec, warnings: &mut Vec, tol: f64) -> Vec { - let n = faces.len(); - for i in 0..n { - let Some(face) = faces.get(i).cloned() else { continue }; - match crate::guard("step band split", || plan(&face, false, tol).map_err(crate::KernelError::Failed)) { - Ok(Some(p)) => { - faces = faces.iter().map(|f| recut(f, &p.cuts)).collect(); - if let Some(slot) = faces.get_mut(i) { - *slot = p.faces.0; - } - faces.push(p.faces.1); - // The second piece comes from the same file face. - let o = origin.get(i).copied().unwrap_or(0); - origin.push(o); - } - Ok(None) => {} - Err(e) => warnings - .push(format!("face wrapping around a closed surface kept whole: {}", e.to_string().trim_start_matches("the operation failed: "))), - } - } - faces -} diff --git a/crates/kernel/src/step_in/tests.rs b/crates/kernel/src/step_in/tests.rs index 30604932f..0ac89ee15 100644 --- a/crates/kernel/src/step_in/tests.rs +++ b/crates/kernel/src/step_in/tests.rs @@ -164,15 +164,14 @@ fn benchmark_independent_step_solids() { let start = std::time::Instant::now(); let ex = p21::parse(&text).unwrap(); let parse = start.elapsed(); - let cx = Ctx { ex: &ex, len: 1.0, ang: 1.0, tol: 0.01 }; let mut items: Vec<_> = ex.entities.iter().filter(|(_, e)| e.name() == "MANIFOLD_SOLID_BREP").map(|(id, _)| *id).collect(); items.sort(); let start = std::time::Instant::now(); - let solids: Vec<_> = items.iter().map(|id| guard("benchmark read", || brep::read_item(&cx, *id).map_err(KernelError::Failed)).unwrap()).collect(); + let solids: Vec<_> = items.iter().map(|id| solidcraft_step::topology::read_solid(&ex, *id, Units::default()).unwrap()).collect(); let read = start.elapsed(); let start = std::time::Instant::now(); for solid in solids { - std::hint::black_box(Body::new(solid.solid).unwrap().unmeshed_faces()); + std::hint::black_box(Body::from_record(solid.brep).unwrap().unmeshed_faces()); } println!( "STEP_PHASE parse_ms={:.3} brep_ms={:.3} body_ms={:.3}", @@ -266,8 +265,8 @@ fn parallel_body_preparation_reports_errors_in_place_and_preserves_placement() { let body = cylinder(Vec3::new(2.0, 2.0, 0.0), Vec3::Z, 2.0, 4.0).unwrap(); let ex = p21::parse(&step_export(&[&body], "test").unwrap()).unwrap(); let solid = *ex.entities.iter().find(|(_, e)| e.name() == "MANIFOLD_SOLID_BREP").map(|(id, _)| id).unwrap(); - let units = DEFAULT_UNITS; - let placement = mt::Matrix4::from_translation(mt::Vector3::new(10.0, 20.0, 30.0)); + let units = Units::default(); + let placement = translation([10.0, 20.0, 30.0]); // The second item is not in the file. let jobs: Vec<_> = [solid, 999_999_999, solid, solid] .into_iter() @@ -329,7 +328,7 @@ fn parallel_import_does_not_prepare_past_body_budget_with_duplicates_or_mapped_i reader.bodies = vec![seed.clone(); MAX_BODIES - 2]; reader.node_items.insert(2000); let mut out = Vec::new(); - reader.rep_bodies(60, &mt::Matrix4::from_scale(1.0), &[], "Budget", None, &mut out, 0); + reader.rep_bodies(60, &IDENTITY, &[], "Budget", None, &mut out, 0); assert!(reader.oriented.is_empty() && reader.unreadable.is_empty(), "the walk only plans the solids"); while reader.convert_next(workers == 1) {} let out = reader.remap(&out); @@ -355,8 +354,8 @@ fn round_trip(b: &Body) -> StepImport { let (m0, m1) = (measure(b).unwrap(), measure(&imp.bodies[0].body).unwrap()); assert!(rel(m1.volume, m0.volume) < 1e-3, "volume {} vs {}", m1.volume, m0.volume); assert!(rel(m1.area, m0.area) < 1e-3, "area {} vs {}", m1.area, m0.area); - // Pieces of one analytic surface are written as one face (volume and area above check - // that nothing was lost). + // The file has no more faces than the body (volume and area above check that nothing was + // lost). assert!(imp.bodies[0].file_faces <= b.face_count()); assert!(imp.bodies[0].closed); imp @@ -383,11 +382,9 @@ fn round_trip_features() { round_trip(&donut[0]); } -/// Robustness seed 17: a thin three-quarter tube shelled with its bottom open. truck writes each -/// wall as three quarter-turn B-spline pieces; the export merges them into one 270° face and must -/// write that face's cylinder, not the first piece's quarter sheet. The seam direction came from -/// the mean direction of the face's vertices, which is zero at 0°, 90°, 180° and 270°, so the -/// merged face kept the quarter sheet and read back about 7% short with no warning. +/// Robustness seed 17: a thin three-quarter tube shelled with its bottom open reads back whole +/// (an export once wrote a 270° wall on a quarter of its surface, and the part read back about +/// 7% short with no warning). #[test] fn shelled_three_quarter_tube_round_trips() { let rect = @@ -427,72 +424,6 @@ fn imported_bodies_take_features() { const HEAD: &str = "ISO-10303-21;\nHEADER;\nFILE_DESCRIPTION((''),'2;1');\nFILE_NAME('t','',(''),(''),'','hand','');\nFILE_SCHEMA(('AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }'));\nENDSEC;\nDATA;\n"; const TAIL: &str = "ENDSEC;\nEND-ISO-10303-21;\n"; -/// Original fixtures: elementary basis surfaces plus offsets, with no external CAD files. -fn offset_geometry(definition: &str, offset: &str, len: f64, sense: bool, points: &[mt::Point3]) -> crate::Result { - let text = format!( - "{HEAD}#1=CARTESIAN_POINT('',(0.,0.,0.));\n#2=AXIS2_PLACEMENT_3D('',#1,$,$);\n#3={definition};\n#4=OFFSET_SURFACE('',#3,{offset},.U.);\n{TAIL}" - ); - let ex = p21::parse(&text).unwrap(); - let cx = Ctx { ex: &ex, len, ang: 1.0, tol: 1e-6 }; - crate::guard("test offset surface", || geom::surface(&cx, 4, points, &[], sense, 0).map_err(KernelError::Failed)) -} - -#[test] -fn offset_surface_analytic_geometry_and_orientation() { - use mt::{InnerSpace, MetricSpace, ParametricSurface, ParametricSurface3D, SearchNearestParameter}; - let angle: f64 = 0.4; - let cases = [ - ("PLANE('',#2)".to_string(), mt::Point3::new(2.0, 3.0, 1.0), mt::Vector3::unit_z()), - ("CYLINDRICAL_SURFACE('',#2,5.)".to_string(), mt::Point3::new(6.0, 0.0, 2.0), mt::Vector3::unit_x()), - ("SPHERICAL_SURFACE('',#2,5.)".to_string(), mt::Point3::new(6.0, 0.0, 0.0), mt::Vector3::unit_x()), - ("TOROIDAL_SURFACE('',#2,10.,2.)".to_string(), mt::Point3::new(13.0, 0.0, 0.0), mt::Vector3::unit_x()), - ( - format!("CONICAL_SURFACE('',#2,5.,{angle})"), - mt::Point3::new(5.0 + 1.0 / angle.cos() + 2.0 * angle.tan(), 0.0, 2.0), - mt::Vector3::new(angle.cos(), 0.0, -angle.sin()), - ), - ]; - for (definition, point, normal) in cases { - for sense in [true, false] { - let extent = [point, point + mt::Vector3::unit_z()]; - let surface = offset_geometry(&definition, "1.", 1.0, sense, &extent).unwrap(); - let uv = surface.search_nearest_parameter(point, None, 100).unwrap(); - assert!(surface.subs(uv.0, uv.1).distance(point) < 1e-6, "{definition}"); - assert!(surface.normal(uv.0, uv.1).dot(normal) * if sense { 1.0 } else { -1.0 } > 0.99, "{definition}, sense {sense}"); - } - } - let p = mt::Point3::new(40.0, 0.0, 2.0); - let surface = offset_geometry("CYLINDRICAL_SURFACE('',#2,5.)", "-1.", 10.0, true, &[p, p + mt::Vector3::unit_z()]).unwrap(); - let uv = surface.search_nearest_parameter(p, None, 100).unwrap(); - assert!(surface.subs(uv.0, uv.1).distance(p) < 1e-6); -} - -#[test] -fn offset_surfaces_nested_and_hostile() { - let points = [mt::Point3::new(0.0, 0.0, 0.0), mt::Point3::new(0.0, 0.0, 1.0)]; - for (basis, offset) in [ - ("CYLINDRICAL_SURFACE('',#2,5.)", "-5."), - ("SPHERICAL_SURFACE('',#2,5.)", "-6."), - ("TOROIDAL_SURFACE('',#2,10.,2.)", "8."), - ("TOROIDAL_SURFACE('',#2,10.,2.)", "-2."), - ("CONICAL_SURFACE('',#2,5.,0.4)", "-10."), - ("PLANE('',#2)", "1.E100"), - ("PLANE('',#2)", "$"), - ] { - assert!(offset_geometry(basis, offset, 1.0, true, &points).is_err(), "{basis}, {offset}"); - } - let text = format!("{HEAD}#1=OFFSET_SURFACE('',#1,1.,.F.);{TAIL}"); - let ex = p21::parse(&text).unwrap(); - let cx = Ctx { ex: &ex, len: 1.0, ang: 1.0, tol: 1e-6 }; - assert!(geom::surface(&cx, 1, &points, &[], true, 0).unwrap_err().contains("nested too deeply")); - let text = format!( - "{HEAD}#1=CARTESIAN_POINT('',(0.,0.,0.));#2=AXIS2_PLACEMENT_3D('',#1,$,$);#3=CYLINDRICAL_SURFACE('',#2,5.);#4=OFFSET_SURFACE('',#3,-6.,.F.);#5=OFFSET_SURFACE('',#4,6.,.F.);{TAIL}" - ); - let ex = p21::parse(&text).unwrap(); - let cx = Ctx { ex: &ex, len: 1.0, ang: 1.0, tol: 1e-6 }; - assert!(geom::surface(&cx, 5, &points, &[], true, 0).is_err()); -} - #[test] fn offset_surface_cube_import_is_closed_and_editable() { // Move each basis plane half a file unit inward; nested quarter-unit offsets @@ -743,9 +674,7 @@ fn instanced_assembly_of(parts: u64, n: u64) -> String { fn instanced_parts_are_oriented_once() { let n = 24; let t = instanced_assembly(n); - crate::body::ORIENTED.with(|c| c.set(0)); let imp = step_import_with_workers(&t, 1).unwrap(); - assert_eq!(crate::body::ORIENTED.with(|c| c.get()), 1, "one distinct part"); assert_eq!(imp.bodies.len(), n as usize); assert!(imp.warnings.is_empty(), "{:?}", imp.warnings); for (k, b) in imp.bodies.iter().enumerate() { @@ -776,9 +705,7 @@ fn distinct_parts_convert_together_across_instances() { let threaded = reading.finish().unwrap(); assert_eq!(threaded.bodies.len(), n as usize); assert!(threaded.warnings.is_empty(), "{:?}", threaded.warnings); - crate::body::ORIENTED.with(|c| c.set(0)); let serial = step_import_with_workers(&t, 1).unwrap(); - assert_eq!(crate::body::ORIENTED.with(|c| c.get()), 2, "two parts"); assert_same_import(&serial, &threaded); assert_eq!(threaded.bodies[1].name, "Cube1"); assert_eq!(threaded.bodies[1].path, vec!["Assembly".to_string(), "Block1".to_string()]); @@ -1108,7 +1035,7 @@ fn hostile_boundaries_mesh_in_bounded_time() { /// A cylinder written as a surface of revolution, oriented the ISO 10303-42 way (normal /// ∂S/∂angle × ∂S/∂profile, outward here, so `same_sense` .T.). Strict readers read such faces this -/// way; reading them with truck's profile-first normal turned faces inside out. +/// way; reading them with the profile's parameter first turned faces inside out. #[test] fn surface_of_revolution_sense_follows_iso() { let mut t = String::from(HEAD); @@ -1156,7 +1083,7 @@ fn horn_torus_written_as_one_spline_face() { } /// Booleans and blends build the same body every time, so an export is byte-identical from -/// run to run (truck used to emit a boolean's faces in hash order of their addresses). The +/// 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. #[test] fn tee_fillet_exports_byte_identical() { @@ -1313,8 +1240,7 @@ fn knot_multiplicities_are_checked_before_they_are_expanded() { }; let read = |text: &str| { let ex = p21::parse(text).unwrap(); - let cx = Ctx { ex: &ex, len: 1.0, ang: 1.0, tol: 1e-6 }; - geom::curve(&cx, 3, 0) + solidcraft_step::read::Reader::new(&ex, Default::default()).curve(3).map(|_| ()) }; let error = read(&curve(1_000_000, 64)).unwrap_err(); // This diagnostic comes from the check before expansion; wall-clock time depends on CI load. @@ -1559,46 +1485,6 @@ fn periodic_knot_tube(first: u64, x: f64, r: f64, h: f64) -> (String, u64) { (s, face) } -/// A B-spline whose end knots repeat fewer than degree + 1 times (an unclamped knot vector, -/// as OpenCascade writes closed curves and surfaces) is defined only between knot `degree` -/// and knot `len - degree - 1`. Read over the whole knot range, the circle and the tube went -/// on past their domain, and the rational ones divided by zero at the outermost knots. -#[test] -fn periodic_knot_bsplines_are_read_on_their_domain() { - use mt::{BoundedCurve, ParametricCurve, ParametricSurface}; - let (r, h) = (1.7, 1.5); - let (tube, face) = periodic_knot_tube(100, 0.0, r, h); - let (circle, row) = circle_net(10, 0.0, r, 0.0); - let text = format!( - "{HEAD}{tube}{circle}#30=(BOUNDED_CURVE()B_SPLINE_CURVE(2,({}),.CIRCULAR_ARC.,.T.,.F.)B_SPLINE_CURVE_WITH_KNOTS(({PERIODIC_MULTS}),({PERIODIC_KNOTS}),.UNSPECIFIED.)CURVE()GEOMETRIC_REPRESENTATION_ITEM()RATIONAL_B_SPLINE_CURVE(({CIRCLE_WEIGHTS}))REPRESENTATION_ITEM(''));\n{TAIL}", - row.join(",") - ); - let ex = p21::parse(&text).unwrap(); - let cx = Ctx { ex: &ex, len: 1.0, ang: 1.0, tol: 1e-6 }; - let pi = std::f64::consts::PI; - let on_tube = |p: mt::Point3| (p.x.hypot(p.y) - r).abs() < 1e-9 && p.z > -1e-9 && p.z < h + 1e-9; - - let surface_id = ex.get(face).and_then(|e| e.params().get(2)).and_then(Param::as_ref_id).unwrap(); - let surface = geom::bspline_surface(&cx, ex.get(surface_id).unwrap()).unwrap(); - let (Some((u0, u1)), Some((v0, v1))) = surface.try_range_tuple() else { panic!("unbounded surface") }; - assert!(u0.abs() < 1e-12 && (u1 - h / r).abs() < 1e-12, "u range {u0} .. {u1}"); - assert!((v0 + pi).abs() < 1e-9 && (v1 - pi).abs() < 1e-9, "v range {v0} .. {v1}"); - for i in 0..=8 { - for j in 0..=16 { - let (u, v) = (u0 + (u1 - u0) * i as f64 / 8.0, v0 + (v1 - v0) * j as f64 / 16.0); - assert!(on_tube(surface.subs(u, v)), "S({u}, {v}) = {:?}", surface.subs(u, v)); - } - } - - let geom::CurveGeo::Nurbs(curve) = geom::curve(&cx, 30, 0).unwrap() else { panic!("not a rational B-spline") }; - let (t0, t1) = curve.range_tuple(); - assert!((t0 + pi).abs() < 1e-9 && (t1 - pi).abs() < 1e-9, "curve range {t0} .. {t1}"); - for j in 0..=16 { - let t = t0 + (t1 - t0) * j as f64 / 16.0; - assert!(on_tube(curve.subs(t)), "C({t}) = {:?}", curve.subs(t)); - } -} - /// Two such tubes far apart in one body: the body's size sets a chord tolerance coarse beside /// the tubes, and meshing a face at it divided the surface's whole parameter box, whose /// corners lay outside the domain. The division never converged there (#1374's recursion), @@ -1824,80 +1710,13 @@ fn step_conformance_parts_read_back_their_exact_shape() { } } -/// A schema 4 record as truck's adapter builds it: truck holds a plane by three points, the -/// same plane within a rounding. -fn truck_ready(record: &solidcraft_geom::brep::Brep) -> solidcraft_geom::brep::Brep { - let mut record = record.clone(); - for f in &mut record.faces { - if let solidcraft_geom::brep::Surface::Plane { origin, u_axis, v_axis } = f.surface { - let at = |d: [f64; 3]| [origin[0] + d[0], origin[1] + d[1], origin[2] + d[2]]; - f.surface = solidcraft_geom::brep::Surface::PlaneThrough { origin, u_point: at(u_axis), v_point: at(v_axis) }; - } - } - record -} - /// The volume of the one solid `solidcraft_step::topology` reads from `text` into schema 4, -/// built back into a truck body: negative when its faces point into its material. +/// 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); assert!(r.failures.is_empty() && r.solids.len() == 1, "{:?}", r.failures); - let solid = crate::native::solid_of_record(truck_ready(&r.solids[0].brep)).unwrap(); - let sign = solid.boundaries().iter().map(crate::body::shell_volume).sum::>().unwrap().signum(); - sign * measure(&crate::body::Body::new(solid).unwrap()).unwrap().volume -} - -/// Each STEP file in `SOLIDCRAFT_STEP_CORPUS`: bodies, faces, edges and volume as truck -/// imports it and as `solidcraft_step::topology` reads it into schema 4 records (built back into -/// truck solids for their volume, signed: negative means faces turned into the material). -/// Counts may differ where truck splits faces (bands, balls) or edges and where schema 4 adds -/// seams; volumes are coarse meshes' (1% of the size). This reports, it does not judge. Run -/// with `--ignored --nocapture`. -#[test] -#[ignore = "needs SOLIDCRAFT_STEP_CORPUS"] -fn corpus_truck_and_schema_4_counts() { - let Ok(dir) = std::env::var("SOLIDCRAFT_STEP_CORPUS") else { return }; - let mut paths: Vec<_> = std::fs::read_dir(&dir).into_iter().flatten().flatten().map(|e| e.path()).collect(); - paths.sort(); - let volume = |s: &mt::Solid| s.boundaries().iter().map(crate::body::shell_volume).sum::>(); - for path in paths.iter().filter(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case("step") || e.eq_ignore_ascii_case("stp"))) { - let text = std::fs::read_to_string(path).unwrap_or_default(); - let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); - let truck = match step_import(&text) { - Ok(imp) => { - // A body per instance: count each STEP item once. - let mut seen = HashSet::new(); - let once: Vec<&ImportedBody> = imp.bodies.iter().filter(|b| seen.insert(b.source_item)).collect(); - let (f, e) = once.iter().fold((0, 0), |(f, e), b| (f + b.body.face_count(), e + b.body.edge_count())); - let v: f64 = once.iter().filter_map(|b| volume(&b.body.solid)).sum(); - format!("{} bodies, {f} faces, {e} edges, volume {v:.4}", once.len()) - } - Err(e) => format!("failed: {e}"), - }; - let ex = match solidcraft_step::p21::parse(&text) { - Ok(ex) => ex, - Err(e) => { - println!("{name}: parse failed: {e}"); - continue; - } - }; - let r = solidcraft_step::topology::read_solids(&ex); - let (f, e) = r.solids.iter().fold((0, 0), |(f, e), s| (f + s.brep.faces.len(), e + s.brep.edges.len())); - let (mut v, mut unbuilt) = (0.0, Vec::new()); - for s in &r.solids { - match crate::native::solid_of_record(truck_ready(&s.brep)) { - Ok(solid) => v += volume(&solid).unwrap_or(f64::NAN), - Err(err) => unbuilt.push(err.to_string()), - } - } - println!( - "{name}: truck {truck}; schema 4 {} solids ({} refused), {f} faces, {e} edges, volume {v:.4}{}", - r.solids.len(), - r.failures.len(), - if unbuilt.is_empty() { String::new() } else { format!(" ({} not built by truck: {})", unbuilt.len(), unbuilt[0]) } - ); - } + measure(&Body::from_record(r.solids[0].brep.clone()).unwrap()).unwrap().volume } /// The step-conformance parts read into SMLib (`SOLIDCRAFT_KERNEL=smlib`): the STEP reader's diff --git a/crates/kernel/src/step_out.rs b/crates/kernel/src/step_out.rs index ce1851ce8..33957fd33 100644 --- a/crates/kernel/src/step_out.rs +++ b/crates/kernel/src/step_out.rs @@ -1,20 +1,19 @@ //! STEP (ISO 10303-21) export: AP242 product structure, assemblies, names and colours. //! -//! Each body's B-rep is written by truck's STEP writer (geometry and topology only), read back -//! with our Part 21 parser and copied into a file we assemble ourselves: one header and -//! context, a product per part with its shape representation, named solids, surface colours, -//! and assemblies as next-assembly-usage occurrences placed by item-defined transformations -//! (the structure the CAx-IF recommends and our reader follows). Identical geometric entities -//! (points, directions, placements, curves, surfaces) are written once and referenced; ids are -//! dense from `#1`. +//! Each body's record is written as it is, the exact B-rep, by +//! [`solidcraft_step::write::topology`]: its material regions as solids, its open shells as a +//! surface model. Around it this writes one header and context, a product per part with its +//! shape representation, named solids, surface and face colours, and assemblies as +//! next-assembly-usage occurrences placed by item-defined transformations (the structure the +//! CAx-IF recommends and our reader follows). Identical geometric entities (points, directions, +//! placements, curves, surfaces) are written once and referenced; ids are dense from `#1`. -use std::collections::HashMap; use std::fmt::Write as _; -use solidcraft_geom::Vec3; +use solidcraft_step::p21::Param; +use solidcraft_step::write::{GeomWriter, Writer, string, topology}; use crate::body::Body; -use crate::step_in::p21::{self, Param}; use crate::{KernelError, Result}; /// A named, optionally coloured body to export (coordinates in its part's frame, mm). @@ -45,1547 +44,20 @@ pub struct StepHeader { pub description: String, } -/// Entities whose identity is topological: never merged even when their text is equal. -const TOPOLOGY: &[&str] = &[ - "VERTEX_POINT", - "EDGE_CURVE", - "ORIENTED_EDGE", - "EDGE_LOOP", - "FACE_BOUND", - "FACE_OUTER_BOUND", - "FACE_SURFACE", - "ADVANCED_FACE", - "ORIENTED_FACE", - "CLOSED_SHELL", - "OPEN_SHELL", - "ORIENTED_CLOSED_SHELL", - "MANIFOLD_SOLID_BREP", - "BREP_WITH_VOIDS", -]; +/// The least distance uncertainty written (mm). +const MIN_UNCERTAINTY: f64 = 1e-6; -fn real(x: f64) -> String { - if !x.is_finite() { - return "0.".into(); - } - let s = format!("{x:?}"); - match s.split_once('e') { - Some((m, e)) => { - let m = if m.contains('.') { m.to_string() } else { format!("{m}.") }; - format!("{m}E{e}") - } - None if s.contains('.') => s, - None => format!("{s}."), - } +fn s(text: &str) -> Param { + Param::Str(text.to_string()) +} +fn r(id: u64) -> Param { + Param::Ref(id) +} +fn refs(ids: &[u64]) -> Param { + Param::List(ids.iter().map(|i| r(*i)).collect()) } -/// A STEP string literal (quotes doubled, non-ASCII as `\X2\` UTF-16 runs). -fn string(s: &str) -> String { - let mut o = String::from("'"); - for c in s.chars() { - match c { - '\'' => o.push_str("''"), - '\\' => o.push_str("\\\\"), - c if c.is_ascii() && !c.is_ascii_control() => o.push(c), - c if c.is_ascii_control() => {} - c => { - o.push_str("\\X2\\"); - let mut buf = [0u16; 2]; - for u in c.encode_utf16(&mut buf) { - let _ = write!(o, "{u:04X}"); - } - o.push_str("\\X0\\"); - } - } - } - o.push('\''); - o -} - -fn param(p: &Param, map: &HashMap, o: &mut String) -> std::result::Result<(), String> { - match p { - Param::Int(i) => { - let _ = write!(o, "{i}"); - } - Param::Real(x) => o.push_str(&real(*x)), - Param::Str(s) => o.push_str(&string(s)), - Param::Enum(e) => { - let _ = write!(o, ".{e}."); - } - Param::Ref(r) => { - let n = map.get(r).ok_or_else(|| format!("dangling reference #{r}"))?; - let _ = write!(o, "#{n}"); - } - Param::List(v) => { - o.push('('); - params(v, map, o)?; - o.push(')'); - } - Param::Typed(name, v) => { - o.push_str(name); - o.push('('); - params(v, map, o)?; - o.push(')'); - } - Param::Binary(b) => { - let _ = write!(o, "\"{b}\""); - } - Param::Null => o.push('$'), - Param::Derived => o.push('*'), - } - Ok(()) -} - -fn params(v: &[Param], map: &HashMap, o: &mut String) -> std::result::Result<(), String> { - for (i, p) in v.iter().enumerate() { - if i > 0 { - o.push(','); - } - param(p, map, o)?; - } - Ok(()) -} - -/// The DATA section under construction. -#[derive(Default)] -struct Out { - lines: Vec, - /// Geometry text → id (shared entities). - shared: HashMap, - /// Surfaces written with the opposite normal to the one they replace. - flipped: std::collections::HashSet, - /// B-spline cylinder and cone sheets of the body being copied to write as analytic surfaces, - /// with the direction of their parameter seam. - merged: HashMap, - /// B-spline sheets of the body being copied to write cut down to their faces. - trimmed: HashMap, - /// Faces of the body being copied: exchange id → written id. - faces_out: HashMap, -} - -impl Out { - fn add(&mut self, text: impl Into) -> u64 { - self.lines.push(text.into()); - self.lines.len() as u64 - } - /// Add, or reuse an identical earlier entity (geometry only). - fn add_shared(&mut self, text: String) -> u64 { - if let Some(id) = self.shared.get(&text) { - return *id; - } - let id = self.add(text.clone()); - self.shared.insert(text, id); - id - } - fn point(&mut self, p: [f64; 3]) -> u64 { - self.add_shared(format!("CARTESIAN_POINT('',({},{},{}))", real(p[0]), real(p[1]), real(p[2]))) - } - fn direction(&mut self, d: [f64; 3]) -> u64 { - self.add_shared(format!("DIRECTION('',({},{},{}))", real(d[0]), real(d[1]), real(d[2]))) - } - fn write_analytic(&mut self, a: &Analytic) -> u64 { - match a.kind { - AnalyticKind::Plane { o, z, x } => { - let ax = self.placement(o, z, x); - self.add_shared(format!("PLANE('',#{ax})")) - } - AnalyticKind::Cylinder { o, z, x, r } => { - let ax = self.placement(o, z, x); - self.add_shared(format!("CYLINDRICAL_SURFACE('',#{ax},{})", real(r))) - } - AnalyticKind::Cone { o, z, x, r, angle } => { - let ax = self.placement(o, z, x); - self.add_shared(format!("CONICAL_SURFACE('',#{ax},{},{})", real(r), real(angle))) - } - AnalyticKind::Sphere { o, z, x, r } => { - let ax = self.placement(o, z, x); - self.add_shared(format!("SPHERICAL_SURFACE('',#{ax},{})", real(r))) - } - AnalyticKind::Torus { o, z, x, big, small } => { - let ax = self.placement(o, z, x); - self.add_shared(format!("TOROIDAL_SURFACE('',#{ax},{},{})", real(big), real(small))) - } - AnalyticKind::HornTorus { o, z, x, big, small } => { - // Nine-point rational quadratic circles (quarter arcs, corner weights √½): the - // tube from the pole round and back, and the turn about z from x. - let y = cross(z, x); - let ring = |k: usize| { - let ang = std::f64::consts::FRAC_PI_4 * k as f64; - let (scale, w) = if k % 2 == 1 { (std::f64::consts::SQRT_2, std::f64::consts::FRAC_1_SQRT_2) } else { (1.0, 1.0) }; - (ang.cos() * scale, ang.sin() * scale, w) - }; - let (mut rows, mut weights) = (Vec::new(), Vec::new()); - for i in 0..9 { - let (ci, si, wi) = ring(i); - let (rho, h) = (big - small * ci, small * si); - let (mut row, mut wrow) = (Vec::new(), Vec::new()); - for j in 0..9 { - let (cj, sj, wj) = ring(j); - let pt = add(add(o, mul(z, h)), add(mul(x, rho * cj), mul(y, rho * sj))); - row.push(format!("#{}", self.point(pt))); - wrow.push(real(wi * wj)); - } - rows.push(format!("({})", row.join(","))); - weights.push(format!("({})", wrow.join(","))); - } - self.add_shared(format!( - "(BOUNDED_SURFACE()B_SPLINE_SURFACE(2,2,({}),.UNSPECIFIED.,.T.,.T.,.F.)B_SPLINE_SURFACE_WITH_KNOTS((3,2,2,2,3),(3,2,2,2,3),(0.,0.25,0.5,0.75,1.),(0.,0.25,0.5,0.75,1.),.UNSPECIFIED.)GEOMETRIC_REPRESENTATION_ITEM()RATIONAL_B_SPLINE_SURFACE(({}))REPRESENTATION_ITEM('')SURFACE())", - rows.join(","), - weights.join(",") - )) - } - } - } - /// A B-spline (or NURBS) surface; `None` for other surfaces. - fn write_sheet(&mut self, s: &truck_modeling::Surface) -> Option { - use truck_modeling::Surface; - let (rows, weights, (ku, kv), (du, dv)): (Vec>, Option>>, _, _) = match s { - Surface::BSplineSurface(b) => ( - b.control_points().iter().map(|r| r.iter().map(|p| [p.x, p.y, p.z]).collect()).collect(), - None, - b.knot_vecs().clone(), - (b.udegree(), b.vdegree()), - ), - Surface::NurbsSurface(n) => { - let b = n.non_rationalized(); - let rows: Option>> = b - .control_points() - .iter() - .map(|r| r.iter().map(|p| (p.w.abs() > 1e-300).then(|| [p.x / p.w, p.y / p.w, p.z / p.w])).collect()) - .collect(); - ( - rows?, - Some(b.control_points().iter().map(|r| r.iter().map(|p| p.w).collect()).collect()), - b.knot_vecs().clone(), - (b.udegree(), b.vdegree()), - ) - } - _ => return None, - }; - let net = rows - .iter() - .map(|r| format!("({})", r.iter().map(|p| format!("#{}", self.point(*p))).collect::>().join(","))) - .collect::>() - .join(","); - let list = |v: Vec| v.join(","); - let ((ku, mu), (kv, mv)) = (ku.to_single_multi(), kv.to_single_multi()); - let knots = format!( - "({}),({}),({}),({}),.UNSPECIFIED.", - list(mu.iter().map(|m| m.to_string()).collect()), - list(mv.iter().map(|m| m.to_string()).collect()), - list(ku.iter().map(|k| real(*k)).collect()), - list(kv.iter().map(|k| real(*k)).collect()), - ); - let base = format!("{du},{dv},({net}),.UNSPECIFIED.,.U.,.U.,.U."); - Some(match weights { - None => self.add_shared(format!("B_SPLINE_SURFACE_WITH_KNOTS('',{base},{knots})")), - Some(w) => { - let w = w.iter().map(|r| format!("({})", list(r.iter().map(|x| real(*x)).collect()))).collect::>().join(","); - self.add_shared(format!( - "(BOUNDED_SURFACE()B_SPLINE_SURFACE({base})B_SPLINE_SURFACE_WITH_KNOTS({knots})GEOMETRIC_REPRESENTATION_ITEM()RATIONAL_B_SPLINE_SURFACE(({w}))REPRESENTATION_ITEM('')SURFACE())" - )) - } - }) - } - fn placement(&mut self, o: [f64; 3], z: [f64; 3], x: [f64; 3]) -> u64 { - let (po, dz, dx) = (self.point(o), self.direction(z), self.direction(x)); - self.add_shared(format!("AXIS2_PLACEMENT_3D('',#{po},#{dz},#{dx})")) - } - - /// Copy a solid entity of a parsed file and everything it uses; returns its new id. - fn copy_solid(&mut self, ex: &p21::Exchange, root: u64, name: &str) -> std::result::Result { - let mut map: HashMap = HashMap::new(); - let seams = horn_seams(ex); - // Iterative post-order walk (children before parents). - let mut stack: Vec<(u64, bool)> = vec![(root, false)]; - let mut guard = 0usize; - while let Some((id, done)) = stack.pop() { - guard += 1; - if guard > 50_000_000 { - return Err("solid too large".into()); - } - if map.contains_key(&id) { - continue; - } - let e = ex.get(id).ok_or_else(|| format!("missing #{id}"))?; - // Revolutions with analytic profiles become cylinders, cones, spheres, tori and - // planes (what other systems recognise), with the face sense corrected. - if !done - && e.name() == "SURFACE_OF_REVOLUTION" - && let Some(mut a) = analytic_revolution(ex, e) - { - if let AnalyticKind::HornTorus { x, .. } = &mut a.kind - && let Some(s) = seams.get(&id) - { - *x = *s; - } - let new = self.write_analytic(&a); - if a.flip { - self.flipped.insert(new); - } - map.insert(id, new); - continue; - } - // Flat B-spline sheets are planes; ruled ones become cylinders and cones when - // `analytic_sheets` chose them (their pieces merged, or a lone piece's edges allow). - if !done - && let Some(a) = planar_bspline(ex, e).map(|kind| Analytic { kind, flip: false }).or_else(|| { - let seam = self.merged.get(&id)?; - let mut a = ruled_bspline(ex, e)?; - if let AnalyticKind::Cylinder { x, .. } | AnalyticKind::Cone { x, .. } = &mut a.kind { - *x = *seam; - } - Some(a) - }) - { - let new = self.write_analytic(&a); - if a.flip { - self.flipped.insert(new); - } - map.insert(id, new); - continue; - } - if !done && let Some(sheet) = self.trimmed.get(&id).cloned() { - let new = self.write_sheet(&sheet).ok_or_else(|| format!("cannot write the cut sheet #{id}"))?; - map.insert(id, new); - continue; - } - if !done { - stack.push((id, true)); - let mut refs = Vec::new(); - fn collect(p: &Param, out: &mut Vec) { - match p { - Param::Ref(r) => out.push(*r), - Param::List(v) | Param::Typed(_, v) => v.iter().for_each(|x| collect(x, out)), - _ => {} - } - } - e.records.iter().flat_map(|r| &r.params).for_each(|p| collect(p, &mut refs)); - stack.extend(refs.into_iter().filter(|r| !map.contains_key(r)).map(|r| (r, false))); - continue; - } - let mut text = String::new(); - let is_root = id == root; - if e.is_complex() { - text.push('('); - for r in &e.records { - text.push_str(&r.name); - text.push('('); - params(&r.params, &map, &mut text)?; - text.push(')'); - } - text.push(')'); - } else { - // Advanced breps use advanced faces (same attributes as truck's face surfaces). - let ename = if e.name() == "FACE_SURFACE" { "ADVANCED_FACE" } else { e.name() }; - text.push_str(ename); - text.push('('); - let mut ps = e.params().to_vec(); - if is_root && let Some(first) = ps.first_mut() { - *first = Param::Str(name.to_string()); - } - // A face on a surface written with the opposite normal flips its sense. - if ename == "ADVANCED_FACE" - && ps.get(2).and_then(Param::as_ref_id).and_then(|g| map.get(&g)).is_some_and(|g| self.flipped.contains(g)) - && let Some(Param::Enum(sense)) = ps.get_mut(3) - { - *sense = if sense == "T" { "F".into() } else { "T".into() }; - } - params(&ps, &map, &mut text)?; - text.push(')'); - } - let topo = TOPOLOGY.contains(&e.name()); - let new = if topo { self.add(text) } else { self.add_shared(text) }; - map.insert(id, new); - if matches!(e.name(), "FACE_SURFACE" | "ADVANCED_FACE") { - self.faces_out.insert(id, new); - } - } - map.get(&root).copied().ok_or_else(|| "solid not copied".into()) - } -} - -/// An analytic surface found behind a surface of revolution. -#[derive(Clone, Copy)] -struct Analytic { - kind: AnalyticKind, - /// The analytic surface's normal is opposite to the revolution's (ISO 10303-42 normals). - flip: bool, -} - -#[derive(Clone, Copy)] -enum AnalyticKind { - Plane { - o: V3, - z: V3, - x: V3, - }, - Cylinder { - o: V3, - z: V3, - x: V3, - r: f64, - }, - Cone { - o: V3, - z: V3, - x: V3, - r: f64, - angle: f64, - }, - Sphere { - o: V3, - z: V3, - x: V3, - r: f64, - }, - Torus { - o: V3, - z: V3, - x: V3, - big: f64, - small: f64, - }, - /// A torus whose tube reaches its axis (a horn torus, as a tight sweep makes): no valid - /// TOROIDAL_SURFACE, so a rational B-spline (tube angle from the pole at the axis, then the - /// turn from x), as other systems write it. x is the turn's parameter seam. - HornTorus { - o: V3, - z: V3, - x: V3, - big: f64, - small: f64, - }, -} - -type V3 = [f64; 3]; - -fn sub(a: V3, b: V3) -> V3 { - [a[0] - b[0], a[1] - b[1], a[2] - b[2]] -} -fn add(a: V3, b: V3) -> V3 { - [a[0] + b[0], a[1] + b[1], a[2] + b[2]] -} -fn mul(a: V3, k: f64) -> V3 { - [a[0] * k, a[1] * k, a[2] * k] -} -fn dot(a: V3, b: V3) -> f64 { - a[0] * b[0] + a[1] * b[1] + a[2] * b[2] -} -fn cross(a: V3, b: V3) -> V3 { - [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] -} -fn norm(a: V3) -> f64 { - dot(a, a).sqrt() -} -fn unit(a: V3) -> Option { - let n = norm(a); - (n > 1e-12 && n.is_finite()).then(|| mul(a, 1.0 / n)) -} - -/// Circle through three points: centre, radius, unit normal. -fn circle3(a: V3, b: V3, c: V3) -> Option<(V3, f64, V3)> { - let (ab, ac) = (sub(b, a), sub(c, a)); - let n = cross(ab, ac); - let n2 = dot(n, n); - if !(n2 > 1e-24) { - return None; - } - let t = add(mul(cross(n, ab), dot(ac, ac)), mul(cross(ac, n), dot(ab, ab))); - let center = add(a, mul(t, 0.5 / n2)); - Some((center, norm(sub(a, center)), unit(n)?)) -} - -/// The analytic surface a surface of revolution is, if its profile is a line or a circular arc -/// in a plane through the axis. -fn analytic_revolution(ex: &p21::Exchange, e: &p21::Entity) -> Option { - use crate::step_in::geom::{self, CurveGeo}; - use truck_modeling::{BoundedCurve, ParametricCurve}; - let cx = crate::step_in::Ctx { ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 }; - let p = e.params(); - let (ao, ad) = geom::axis1(&cx, p.get(2)?.as_ref_id()?).ok()?; - let (oa, a) = ([ao.x, ao.y, ao.z], [ad.x, ad.y, ad.z]); - let g = geom::curve(&cx, p.get(1)?.as_ref_id()?, 0).ok()?; - let radial = |q: V3| { - let v = sub(q, oa); - sub(v, mul(a, dot(v, a))) - }; - let on_axis = |q: V3| add(oa, mul(a, dot(sub(q, oa), a))); - // Profile samples and tangents. - let eval: Box V3> = match &g { - CurveGeo::Line { p, d } => { - let (p, d) = ([p.x, p.y, p.z], [d.x, d.y, d.z]); - Box::new(move |t| add(p, mul(d, t))) - } - CurveGeo::BSpline(c) => { - let c = c.clone(); - let (t0, t1) = c.range_tuple(); - Box::new(move |s| { - let q = c.subs(t0 + (t1 - t0) * s); - [q.x, q.y, q.z] - }) - } - CurveGeo::Nurbs(c) => { - let c = c.clone(); - let (t0, t1) = c.range_tuple(); - Box::new(move |s| { - let q = c.subs(t0 + (t1 - t0) * s); - [q.x, q.y, q.z] - }) - } - CurveGeo::Conic { .. } | CurveGeo::Hyperbola { .. } | CurveGeo::Parabola { .. } => return None, - }; - // A sample point off the axis, its revolution normal (∂S/∂angle × ∂S/∂profile). - let sample = - [0.37, 0.61, 0.23, 0.79].into_iter().map(|t| (eval(t), sub(eval(t + 1e-4), eval(t - 1e-4)))).find(|(q, _)| norm(radial(*q)) > 1e-6)?; - let (q, dq) = sample; - let n_rev = cross(cross(a, sub(q, oa)), dq); - let eq = unit(radial(q))?; - let (kind, n_an) = match &g { - CurveGeo::Line { d, .. } => { - let d = unit([d.x, d.y, d.z])?; - // Coplanar with the axis? - if dot(cross(d, a), eq).abs() > 1e-9 { - return None; - } - let (da, dr) = (dot(d, a), dot(d, eq)); - if dr.abs() < 1e-12 { - let r = norm(radial(q)); - (AnalyticKind::Cylinder { o: oa, z: a, x: eq, r }, eq) - } else if da.abs() < 1e-12 { - (AnalyticKind::Plane { o: on_axis(q), z: a, x: eq }, a) - } else { - // Open the cone along +z: the radius grows that way. - let z = if dr * da > 0.0 { a } else { mul(a, -1.0) }; - let angle = (dr.abs() / da.abs()).atan(); - let r = norm(radial(q)); - let n = sub(mul(eq, angle.cos()), mul(z, angle.sin())); - (AnalyticKind::Cone { o: on_axis(q), z, x: eq, r, angle }, n) - } - } - _ => { - let (c, r, nc) = circle3(eval(0.0), eval(0.5), eval(1.0))?; - // Every sample on the circle, the circle's plane through the axis. - if (0..=8).any(|i| (norm(sub(eval(i as f64 / 8.0), c)) - r).abs() > 1e-7 * (1.0 + r)) { - return None; - } - if dot(nc, a).abs() > 1e-9 || dot(sub(c, oa), nc).abs() > 1e-7 * (1.0 + r) { - return None; - } - let big = norm(radial(c)); - if big < 1e-9 * (1.0 + r) { - (AnalyticKind::Sphere { o: c, z: a, x: eq, r }, sub(q, c)) - } else { - let ec = unit(radial(c))?; - let o = on_axis(c); - if (big - r).abs() <= 1e-6 * (1.0 + r) { - (AnalyticKind::HornTorus { o, z: a, x: mul(ec, -1.0), big: r, small: r }, sub(q, add(o, mul(eq, r)))) - } else if big < r { - // A spindle torus (tube crossing the axis) stays a surface of revolution. - return None; - } else { - (AnalyticKind::Torus { o, z: a, x: ec, big, small: r }, sub(q, add(o, mul(eq, big)))) - } - } - } - }; - let flip = dot(n_rev, n_an) < 0.0; - if !dot(n_rev, n_an).is_finite() || dot(n_rev, n_an).abs() < 1e-12 { - return None; - } - Some(Analytic { kind, flip }) -} - -/// Two analytic surfaces are the same surface (same kind, frame-independent parameters). -fn same_analytic(a: &AnalyticKind, b: &AnalyticKind) -> bool { - let close = |x: f64, y: f64| (x - y).abs() <= 1e-7 * (1.0 + x.abs().max(y.abs())); - let same_pt = |p: V3, q: V3| norm(sub(p, q)) <= 1e-7 * (1.0 + norm(p)); - let parallel = |p: V3, q: V3| norm(cross(p, q)) <= 1e-9; - let on_line = |p: V3, o: V3, d: V3| norm(cross(sub(p, o), d)) <= 1e-7 * (1.0 + norm(p)); - match (a, b) { - (AnalyticKind::Cylinder { o, z, r, .. }, AnalyticKind::Cylinder { o: o2, z: z2, r: r2, .. }) => { - parallel(*z, *z2) && on_line(*o2, *o, *z) && close(*r, *r2) - } - (AnalyticKind::Cone { o, z, r, angle, .. }, AnalyticKind::Cone { o: o2, z: z2, r: r2, angle: a2, .. }) => { - // Same apex, axis direction and angle. - let apex = |o: V3, z: V3, r: f64, an: f64| sub(o, mul(z, r / an.tan())); - dot(*z, *z2) > 1.0 - 1e-9 && close(*angle, *a2) && same_pt(apex(*o, *z, *r, *angle), apex(*o2, *z2, *r2, *a2)) - } - (AnalyticKind::Sphere { o, r, .. }, AnalyticKind::Sphere { o: o2, r: r2, .. }) => same_pt(*o, *o2) && close(*r, *r2), - (AnalyticKind::Torus { o, z, big, small, .. }, AnalyticKind::Torus { o: o2, z: z2, big: b2, small: s2, .. }) => { - same_pt(*o, *o2) && parallel(*z, *z2) && close(*big, *b2) && close(*small, *s2) - } - (AnalyticKind::HornTorus { o, z, big, .. }, AnalyticKind::HornTorus { o: o2, z: z2, big: b2, .. }) => { - same_pt(*o, *o2) && parallel(*z, *z2) && close(*big, *b2) - } - (AnalyticKind::Plane { o, z, .. }, AnalyticKind::Plane { o: o2, z: z2, .. }) => { - parallel(*z, *z2) && dot(sub(*o2, *o), *z).abs() <= 1e-7 * (1.0 + norm(*o)) - } - _ => false, - } -} - -/// The outward normal sign of a face relative to its analytic surface's normal. -fn face_normal_sign(a: &AnalyticKind, z_written: V3, flip: bool, sense: bool) -> f64 { - // Planes compare their written normal directly; the others are always outward-normal kinds. - let base = match a { - AnalyticKind::Plane { z, .. } => dot(*z, z_written).signum(), - _ => 1.0, - }; - base * if flip != sense { 1.0 } else { -1.0 } -} - -/// A B-spline surface that is flat (a sheet swept along a line, as truck makes for extrusions): -/// the plane with the surface's own normal, so it can be written as a PLANE. -fn planar_bspline(ex: &p21::Exchange, e: &p21::Entity) -> Option { - use truck_modeling::{BoundedSurface, ParametricSurface, ParametricSurface3D}; - if !(e.has("B_SPLINE_SURFACE") || e.name() == "B_SPLINE_SURFACE_WITH_KNOTS") { - return None; - } - let cx = crate::step_in::Ctx { ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 }; - let s = crate::step_in::geom::bspline_surface(&cx, e).ok()?; - let (ctrl, (u0, u1), (v0, v1)) = match &s { - truck_modeling::Surface::BSplineSurface(b) => { - (b.control_points().iter().flatten().map(|p| [p.x, p.y, p.z]).collect::>(), b.range_tuple().0, b.range_tuple().1) - } - truck_modeling::Surface::NurbsSurface(n) => { - let pts = n.non_rationalized().control_points().iter().flatten().map(|p| [p.x / p.w, p.y / p.w, p.z / p.w]).collect::>(); - let (ru, rv) = n.range_tuple(); - (pts, ru, rv) - } - _ => return None, - }; - let (um, vm) = ((u0 + u1) / 2.0, (v0 + v1) / 2.0); - let n = s.normal(um, vm); - let z = unit([n.x, n.y, n.z])?; - let o = s.subs(um, vm); - let o = [o.x, o.y, o.z]; - let du = s.uder(um, vm); - let x = unit(sub([du.x, du.y, du.z], mul(z, dot([du.x, du.y, du.z], z))))?; - let size = ctrl.iter().map(|p| norm(sub(*p, o))).fold(0.0, f64::max); - // Every control point on the plane (a flat net gives a flat surface, rational or not). - if ctrl.iter().any(|p| dot(sub(*p, o), z).abs() > 1e-9 * (1.0 + size)) { - return None; - } - Some(AnalyticKind::Plane { o, z, x }) -} - -/// A B-spline surface that is a circular cylinder or cone: straight rulings between two coaxial -/// circles or arcs (or an arc and the cone's apex), as truck makes for extruded round profiles, -/// rounds along straight edges and countersinks. With its normal direction relative to the -/// surface's outward normal. -fn ruled_bspline(ex: &p21::Exchange, e: &p21::Entity) -> Option { - use truck_modeling::{ParametricSurface, ParametricSurface3D}; - if !(e.has("B_SPLINE_SURFACE") || e.name() == "B_SPLINE_SURFACE_WITH_KNOTS") { - return None; - } - let cx = crate::step_in::Ctx { ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 }; - let s = crate::step_in::geom::bspline_surface(&cx, e).ok()?; - let (Some((u0, u1)), Some((v0, v1))) = s.try_range_tuple() else { return None }; - let at = |u: f64, v: f64| { - let p = s.subs(u, v); - [p.x, p.y, p.z] - }; - // Which parameter runs along the rulings: straight from one end to the other at every point - // of the profile. - for along_v in [true, false] { - let point = |t: f64, w: f64| if along_v { at(u0 + (u1 - u0) * t, v0 + (v1 - v0) * w) } else { at(u0 + (u1 - u0) * w, v0 + (v1 - v0) * t) }; - let grid: Vec> = (0..=4).map(|m| (0..=8).map(|k| point(k as f64 / 8.0, m as f64 / 4.0)).collect()).collect(); - let (Some(p0), Some(p1)) = (grid.first(), grid.last()) else { continue }; - let Some(&first) = p0.first() else { continue }; - let scale = grid.iter().flatten().map(|p| norm(sub(*p, first))).fold(0.0, f64::max); - let tol = 1e-7 * (1.0 + scale); - let straight = (0..=8).all(|k| { - let (Some(&a), Some(&b)) = (p0.get(k), p1.get(k)) else { return false }; - let Some(d) = unit(sub(b, a)) else { return false }; - grid.iter().all(|row| row.get(k).is_some_and(|q| norm(cross(sub(*q, a), d)) <= tol)) - }); - if !straight { - continue; - } - // Each end: a circle (centre, radius, axis) or a single point (a cone's apex). - let ring = |prof: &[V3]| -> Option<(V3, f64, Option)> { - let &a = prof.first()?; - if prof.iter().all(|p| norm(sub(*p, a)) <= tol) { - return Some((a, 0.0, None)); - } - let (&b, &c, &h) = (prof.get(4)?, prof.get(8)?, prof.get(2)?); - let (centre, r, n) = circle3(a, b, c).or_else(|| circle3(a, h, b))?; - prof.iter().all(|p| (norm(sub(*p, centre)) - r).abs() <= tol).then_some((centre, r, Some(n))) - }; - let ((c0, r0, n0), (c1, r1, n1)) = (ring(p0)?, ring(p1)?); - let axis = unit(sub(c1, c0))?; - if [n0, n1].iter().flatten().any(|n| norm(cross(*n, axis)) > 1e-7) || (n0.is_none() && n1.is_none()) { - return None; - } - let height = norm(sub(c1, c0)); - // The radius grows along z (a cylinder keeps the sweep's direction). - let (o, z, r, angle) = if (r1 - r0).abs() <= tol { - (c0, axis, r0, 0.0) - } else if r1 > r0 { - (c1, axis, r1, ((r1 - r0) / height).atan()) - } else { - (c0, mul(axis, -1.0), r0, ((r0 - r1) / height).atan()) - }; - let radius_at = |q: V3| r + dot(sub(q, o), z) * angle.tan(); - let radial = |q: V3| { - let v = sub(q, o); - sub(v, mul(z, dot(v, z))) - }; - if grid.iter().flatten().any(|q| (norm(radial(*q)) - radius_at(*q)).abs() > tol) { - return None; - } - // The surface's own normal against the outward one, mid-face. - let (um, vm) = ((u0 + u1) / 2.0, (v0 + v1) / 2.0); - let nn = s.normal(um, vm); - let q = at(um, vm); - let eq = unit(radial(q))?; - let outward = sub(mul(eq, angle.cos()), mul(z, angle.sin())); - let flip = dot([nn.x, nn.y, nn.z], outward) < 0.0; - // The parameter seam opposite the middle of the sheet, away from its edges. - let x = mul(eq, -1.0); - let kind = if angle == 0.0 { AnalyticKind::Cylinder { o, z, x, r } } else { AnalyticKind::Cone { o, z, x, r, angle } }; - return Some(Analytic { kind, flip }); - } - None -} - -/// A B-spline surface that is really a plane, a cylinder or a cone. -fn analytic_bspline(ex: &p21::Exchange, e: &p21::Entity) -> Option { - planar_bspline(ex, e).map(|kind| Analytic { kind, flip: false }).or_else(|| ruled_bspline(ex, e)) -} - -/// Every edge of a face on a cylinder or cone is a circle square to its axis or one of its -/// rulings (a line along the axis, or through a cone's apex). Faces bounded by other curves (a -/// hole crossing a tube wall) keep their B-spline sheet: readers lay those curves out far more -/// slowly on the analytic surface than on the sheet they came with. -fn square_or_ruled(ex: &p21::Exchange, fe: &p21::Entity, kind: &AnalyticKind) -> bool { - let (z, apex) = match *kind { - AnalyticKind::Cylinder { z, .. } => (z, None), - AnalyticKind::Cone { o, z, r, angle, .. } if angle.tan() > 1e-12 => (z, Some(sub(o, mul(z, r / angle.tan())))), - _ => return false, - }; - face_edges(ex, fe).is_some_and(|ls| { - ls.iter().flatten().all(|(x, _)| { - edge_samples(ex, *x).is_some_and(|pts| { - let Some(&q0) = pts.first() else { return false }; - let tol = 1e-7 * (1.0 + norm(q0)); - let ruling = match apex { - None => pts.iter().all(|q| norm(cross(sub(*q, q0), z)) <= tol), - Some(a) => pts.iter().all(|q| norm(cross(sub(*q, a), sub(q0, a))) <= tol * (1.0 + norm(sub(q0, a)))), - }; - ruling || pts.iter().all(|q| dot(sub(*q, q0), z).abs() <= tol) - }) - }) - }) -} - -/// Points along an edge's curve (its ends for a line, None for a conic it cannot sample). -fn edge_samples(ex: &p21::Exchange, edge: u64) -> Option> { - edge_points(ex, edge, 4) -} - -/// `n + 1` points along an edge's curve, ends included (its ends for a line, None for a conic it -/// cannot sample). -fn edge_points(ex: &p21::Exchange, edge: u64, n: usize) -> Option> { - use truck_modeling::{BoundedCurve, ParametricCurve}; - let p = ex.get(edge)?.params(); - let ends = [vertex_point(ex, p.get(1)?.as_ref_id()?)?, vertex_point(ex, p.get(2)?.as_ref_id()?)?]; - let cx = crate::step_in::Ctx { ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 }; - let sample = |f: &dyn Fn(f64) -> truck_modeling::Point3, (t0, t1): (f64, f64)| { - (0..=n).map(|k| f(t0 + (t1 - t0) * k as f64 / n.max(1) as f64)).map(|q| [q.x, q.y, q.z]).collect::>() - }; - match crate::step_in::geom::curve(&cx, p.get(3)?.as_ref_id()?, 0).ok()? { - crate::step_in::geom::CurveGeo::Line { .. } => Some(ends.to_vec()), - crate::step_in::geom::CurveGeo::BSpline(c) => Some(sample(&|t| c.subs(t), c.range_tuple())), - crate::step_in::geom::CurveGeo::Nurbs(c) => Some(sample(&|t| c.subs(t), c.range_tuple())), - crate::step_in::geom::CurveGeo::Conic { .. } - | crate::step_in::geom::CurveGeo::Hyperbola { .. } - | crate::step_in::geom::CurveGeo::Parabola { .. } => None, - } -} - -fn vertex_point(ex: &p21::Exchange, v: u64) -> Option { - let p = ex.get(ex.get(v)?.params().get(1)?.as_ref_id()?)?; - let c = p.params().get(1)?.as_list()?; - Some([c.first()?.as_f64()?, c.get(1)?.as_f64()?, c.get(2)?.as_f64()?]) -} - -/// For each horn torus revolution, a turn direction away from its faces (the B-spline's -/// parameter seam must not cross them): opposite their vertices' mean direction about the axis. -fn horn_seams(ex: &p21::Exchange) -> HashMap { - let mut out = HashMap::new(); - for fe in ex.entities.values() { - if !matches!(fe.name(), "FACE_SURFACE" | "ADVANCED_FACE") { - continue; - } - let Some(sid) = fe.params().get(2).and_then(Param::as_ref_id) else { continue }; - let Some(se) = ex.get(sid).filter(|e| e.name() == "SURFACE_OF_REVOLUTION") else { continue }; - let Some(Analytic { kind: AnalyticKind::HornTorus { o, z, .. }, .. }) = analytic_revolution(ex, se) else { continue }; - let Some(loops) = face_edges(ex, fe) else { continue }; - let mut mean = [0.0; 3]; - for (e, _) in loops.iter().flatten() { - for k in [1, 2] { - let Some(q) = ex.get(*e).and_then(|e| e.params().get(k)).and_then(Param::as_ref_id).and_then(|v| vertex_point(ex, v)) else { - continue; - }; - let v = sub(q, o); - if let Some(r) = unit(sub(v, mul(z, dot(v, z)))) { - mean = add(mean, r); - } - } - } - if let Some(m) = unit(mean) { - out.insert(sid, mul(m, -1.0)); - } - } - out -} - -/// Zero-length edges (truck sweeps a profile point on the axis into one) removed and their -/// vertices joined: other systems reject a pole written as an ordinary edge. -fn collapse_short_edges(ex: &mut p21::Exchange) { - let ends = |e: &p21::Entity| Some((e.params().get(1)?.as_ref_id()?, e.params().get(2)?.as_ref_id()?)); - let mut join: HashMap = HashMap::new(); - let mut dead = std::collections::HashSet::new(); - let mut ids: Vec = ex.entities.iter().filter(|(_, e)| e.name() == "EDGE_CURVE").map(|(i, _)| *i).collect(); - ids.sort(); - for id in ids { - let Some(e) = ex.get(id) else { continue }; - let Some((a, b)) = ends(e) else { continue }; - let (Some(pa), Some(pb)) = (vertex_point(ex, a), vertex_point(ex, b)) else { continue }; - if a == b || norm(sub(pa, pb)) > 1e-6 * (1.0 + norm(pa)) { - continue; - } - // The curve itself must be short too (not a whole circle between two coincident vertices). - let short = e.params().get(3).and_then(Param::as_ref_id).and_then(|c| { - use truck_modeling::{BoundedCurve, ParametricCurve}; - let cx = crate::step_in::Ctx { ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 }; - let mid = match crate::step_in::geom::curve(&cx, c, 0).ok()? { - crate::step_in::geom::CurveGeo::Line { .. } => return Some(true), - crate::step_in::geom::CurveGeo::BSpline(c) => c.subs((c.range_tuple().0 + c.range_tuple().1) / 2.0), - crate::step_in::geom::CurveGeo::Nurbs(c) => c.subs((c.range_tuple().0 + c.range_tuple().1) / 2.0), - crate::step_in::geom::CurveGeo::Conic { .. } - | crate::step_in::geom::CurveGeo::Hyperbola { .. } - | crate::step_in::geom::CurveGeo::Parabola { .. } => return Some(false), - }; - Some(norm(sub([mid.x, mid.y, mid.z], pa)) <= 1e-6 * (1.0 + norm(pa))) - }); - if short != Some(true) { - continue; - } - let find = |join: &HashMap, mut v: u64| { - while let Some(n) = join.get(&v) { - v = *n; - } - v - }; - let (ra, rb) = (find(&join, a), find(&join, b)); - if ra != rb { - join.insert(rb, ra); - } - dead.insert(id); - } - if dead.is_empty() { - return; - } - // A loop made only of such edges (a pole loop) keeps them all. - let oe_edge = |ex: &p21::Exchange, oe: &Param| oe.as_ref_id().and_then(|o| ex.get(o)).and_then(|o| o.params().get(3)).and_then(Param::as_ref_id); - let loops: Vec = ex.entities.iter().filter(|(_, e)| e.name() == "EDGE_LOOP").map(|(i, _)| *i).collect(); - for l in &loops { - let Some(list) = ex.get(*l).and_then(|e| e.params().get(1)).and_then(Param::as_list) else { continue }; - if list.iter().all(|oe| oe_edge(ex, oe).is_some_and(|e| dead.contains(&e))) { - return; - } - } - for l in loops { - let Some(list) = ex.get(l).and_then(|e| e.params().get(1)).and_then(Param::as_list) else { continue }; - let kept: Vec = list.iter().filter(|oe| !oe_edge(ex, oe).is_some_and(|e| dead.contains(&e))).cloned().collect(); - if let Some(r) = ex.entities.get_mut(&l).and_then(|e| e.records.first_mut()) - && let Some(slot) = r.params.get_mut(1) - { - *slot = Param::List(kept); - } - } - let find = |mut v: u64| { - while let Some(n) = join.get(&v) { - v = *n; - } - v - }; - for e in ex.entities.values_mut() { - if e.name() != "EDGE_CURVE" { - continue; - } - if let Some(r) = e.records.first_mut() { - for k in [1, 2] { - if let Some(slot) = r.params.get_mut(k) - && let Some(v) = slot.as_ref_id() - { - *slot = Param::Ref(find(v)); - } - } - } - } -} - -/// Oriented edges (edge id, forward) of a face's bounds. -fn face_edges(ex: &p21::Exchange, face: &p21::Entity) -> Option>> { - let mut loops = Vec::new(); - for b in face.params().get(1)?.as_list()? { - let fb = ex.get(b.as_ref_id()?)?; - let lp = ex.get(fb.params().get(1)?.as_ref_id()?)?; - if lp.name() != "EDGE_LOOP" { - return None; - } - let orient = fb.params().get(2)?.as_bool()?; - let mut v = Vec::new(); - for oe in lp.params().get(1)?.as_list()? { - let oe = ex.get(oe.as_ref_id()?)?; - if oe.name() != "ORIENTED_EDGE" { - return None; - } - v.push((oe.params().get(3)?.as_ref_id()?, oe.params().get(4)?.as_bool()?)); - } - if !orient { - v.reverse(); - v.iter_mut().for_each(|e| e.1 = !e.1); - } - loops.push(v); - } - Some(loops) -} - -/// Faces that truck splits (a revolution in two or three turns) joined back into one face per -/// analytic surface, by dropping the edges between them. Faces whose union would lose all its -/// edges, or whose leftover edges do not close into loops, stay apart. Returns the surfaces of -/// merged faces. -fn merge_split_faces(ex: &mut p21::Exchange, paint: &mut HashMap, keep: &[Vec]) -> std::collections::HashSet { - // An edge on a line the user split along: every sample within a hair of the polyline. - let on_split = |ex: &p21::Exchange, e: u64| -> bool { - let Some(pts) = edge_samples(ex, e) else { return false }; - let pts: Vec = pts.iter().map(|q| Vec3::new(q[0], q[1], q[2])).collect(); - crate::heal::on_split_line(&pts, keep) - }; - let mut merged_surfaces = std::collections::HashSet::new(); - let mut next = ex.entities.keys().max().copied().unwrap_or(0) + 1; - let shells: Vec = ex.entities.iter().filter(|(_, e)| matches!(e.name(), "CLOSED_SHELL" | "OPEN_SHELL")).map(|(i, _)| *i).collect(); - // Each surface's analytic form, worked out once (merged faces keep a piece's surface). - let mut cache: HashMap> = HashMap::new(); - for sh in shells { - for _round in 0..64 { - let Some(faces) = ex - .get(sh) - .and_then(|e| e.params().get(1)) - .and_then(Param::as_list) - .map(|l| l.iter().filter_map(Param::as_ref_id).collect::>()) - else { - break; - }; - // Analytic description and normal sign of each face on a revolution. - let info: Vec> = faces - .iter() - .map(|f| { - let fe = ex.get(*f)?; - if !matches!(fe.name(), "FACE_SURFACE" | "ADVANCED_FACE") { - return None; - } - let sid = fe.params().get(2)?.as_ref_id()?; - let an = (*cache.entry(sid).or_insert_with(|| { - let se = ex.get(sid)?; - match se.name() { - "SURFACE_OF_REVOLUTION" => analytic_revolution(ex, se), - // Coplanar pieces (a face split where a mirrored half was glued on). - "PLANE" => { - let cx = crate::step_in::Ctx { ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 }; - let f = crate::step_in::geom::frame(&cx, se.params().get(1)?.as_ref_id()?).ok()?; - let v = |a: truck_modeling::Vector3| [a.x, a.y, a.z]; - Some(Analytic { kind: AnalyticKind::Plane { o: [f.o.x, f.o.y, f.o.z], z: v(f.z), x: v(f.x) }, flip: false }) - } - // Pieces of a B-spline cylinder or cone merge only when their edges - // are circles square to the axis and rulings (an extruded hole). - _ => analytic_bspline(ex, se).filter(|a| match a.kind { - AnalyticKind::Cylinder { .. } | AnalyticKind::Cone { .. } => square_or_ruled(ex, fe, &a.kind), - _ => true, - }), - } - }))?; - let sense = fe.params().get(3)?.as_bool()?; - let z = match an.kind { - AnalyticKind::Plane { z, .. } => z, - _ => [0.0; 3], - }; - let sign = face_normal_sign(&an.kind, z, an.flip, sense); - // Planes: normalise to one written direction for comparisons. - Some((an.kind, sign)) - }) - .collect(); - let mut merged = false; - 'pairs: for i in 0..faces.len() { - for j in (i + 1)..faces.len() { - let (Some(Some((ka, sa))), Some(Some((kb, sb)))) = (info.get(i), info.get(j)) else { continue }; - if !same_analytic(ka, kb) { - continue; - } - let plane_dir = |k: &AnalyticKind| match k { - AnalyticKind::Plane { z, .. } => *z, - _ => [0.0, 0.0, 1.0], - }; - let (na, nb) = (mul(plane_dir(ka), *sa), mul(plane_dir(kb), *sb)); - if dot(na, nb) <= 0.0 { - continue; - } - let (Some(&fa), Some(&fb)) = (faces.get(i), faces.get(j)) else { continue }; - // Faces of different colours stay apart. - if paint.get(&fa) != paint.get(&fb) { - continue; - } - let (Some(ea), Some(eb)) = (ex.get(fa).and_then(|f| face_edges(ex, f)), ex.get(fb).and_then(|f| face_edges(ex, f))) else { - continue; - }; - let all: Vec<(u64, bool)> = ea.into_iter().chain(eb).flatten().collect(); - let shared: std::collections::HashSet = - all.iter().filter(|(e, d)| all.iter().any(|(e2, d2)| e2 == e && d2 != d)).map(|(e, _)| *e).collect(); - if shared.is_empty() || shared.iter().any(|e| on_split(ex, *e)) { - continue; - } - // Chain oriented edges into loops by vertices (None: they do not close). - let ends = |(e, d): (u64, bool)| -> Option<(u64, u64)> { - let p = ex.get(e)?.params(); - let (s0, s1) = (p.get(1)?.as_ref_id()?, p.get(2)?.as_ref_id()?); - Some(if d { (s0, s1) } else { (s1, s0) }) - }; - let chain = |mut pool: Vec<(u64, bool)>| -> Option>> { - let mut loops = Vec::new(); - while let Some(first) = pool.pop() { - let (start, mut at) = ends(first)?; - let mut lp = vec![first]; - while at != start { - if lp.len() > 100_000 { - return None; - } - let k = pool.iter().position(|x| ends(*x).is_some_and(|(s, _)| s == at))?; - let x = pool.remove(k); - at = ends(x)?.1; - lp.push(x); - } - loops.push(lp); - } - Some(loops) - }; - // A full turn keeps one shared edge as the face's seam, used both ways (as other - // systems write cylinders and cone tips); otherwise the shared edges go. - // (A horn torus band needs no seam: its rings meet at the pole.) - let mut loops = None; - if shared.len() >= 2 && !matches!(ka, AnalyticKind::HornTorus { .. } | AnalyticKind::Plane { .. }) { - // Without the shared edges: one ring (a cone tip) or two (a band). The seam - // runs from a vertex on the first ring to the second ring (or the apex) and - // back: ring A, seam, ring B, seam reversed. - let rest: Vec<(u64, bool)> = all.iter().copied().filter(|(e, _)| !shared.contains(e)).collect(); - if let Some(rings) = chain(rest).filter(|r| matches!(r.len(), 1 | 2)) { - let starts_at = |ring: &Vec<(u64, bool)>, v: u64| ring.iter().position(|x| ends(*x).is_some_and(|(a, _)| a == v)); - let on_axis = |v: u64| { - let (o, z) = match ka { - AnalyticKind::Cone { o, z, .. } | AnalyticKind::Sphere { o, z, .. } => (*o, *z), - _ => return false, - }; - vertex_point(ex, v).is_some_and(|q| norm(cross(sub(q, o), z)) <= 1e-6 * (1.0 + norm(q))) - }; - let rotated = - |ring: &Vec<(u64, bool)>, k: usize| ring.iter().skip(k).chain(ring.iter().take(k)).copied().collect::>(); - // Whether a ring leaves its first vertex turning anticlockwise about a - // cylinder's or cone's axis (the way its angle parameter grows). - let turns_with_angle = |ring: &[(u64, bool)]| -> Option { - let (o, z) = match ka { - AnalyticKind::Cylinder { o, z, .. } | AnalyticKind::Cone { o, z, .. } => (*o, *z), - _ => return None, - }; - let &(edge, dir) = ring.first()?; - let start = vertex_point(ex, ends((edge, dir))?.0)?; - let mut pts = edge_points(ex, edge, 4)?; - if ex.get(edge)?.params().get(4)?.as_bool()? != dir { - pts.reverse(); - } - let radial = |q: V3| { - let v = sub(q, o); - sub(v, mul(z, dot(v, z))) - }; - let turn = dot(cross(radial(start), radial(*pts.get(1)?)), z); - (turn != 0.0).then_some(turn > 0.0) - }; - let mut cands: Vec = shared.iter().copied().collect(); - cands.sort(); - 'seam: for keep in cands { - for &(e, d) in all.iter().filter(|(e, _)| *e == keep) { - let Some((a, b)) = ends((e, d)) else { continue }; - let (Some(ra), Some(ka0)) = (rings.first(), rings.first().and_then(|r| starts_at(r, a))) else { continue }; - let mut lp = rotated(ra, ka0); - let mut back = (e, !d); - match rings.get(1) { - Some(rb) => { - let Some(kb) = starts_at(rb, b) else { continue }; - let ring_b = rotated(rb, kb); - // Readers put a seam's first use on the side where the - // angle starts, so the ring after it must turn the way - // the angle grows; else that ring and the seam's other - // use go first (#3394). - if turns_with_angle(&ring_b) == Some(false) { - let ring_a = std::mem::replace(&mut lp, ring_b); - lp.push((e, !d)); - lp.extend(ring_a); - back = (e, d); - } else { - lp.push((e, d)); - lp.extend(ring_b); - } - } - // A cone tip (or a sphere's pole cap): the seam's far end is - // the apex on the axis, off the ring. - None if starts_at(ra, b).is_none() && on_axis(b) => lp.push((e, d)), - None => continue, - } - lp.push(back); - loops = Some(vec![lp]); - break 'seam; - } - } - } - } - let planar = matches!(ka, AnalyticKind::Plane { .. }); - if loops.is_none() && planar { - // A plane needs no seam: an annulus keeps its two rings, a face with a hole - // its hole. The largest loop goes first (the outer bound). - let rest: Vec<(u64, bool)> = all.iter().copied().filter(|(e, _)| !shared.contains(e)).collect(); - loops = chain(rest).map(|mut l| { - let size = |lp: &Vec<(u64, bool)>| { - let pts: Vec = lp.iter().filter_map(|x| ends(*x).and_then(|(a, _)| vertex_point(ex, a))).collect(); - let mut lo = [f64::INFINITY; 3]; - let mut hi = [f64::NEG_INFINITY; 3]; - for p in &pts { - for k in 0..3 { - lo[k] = lo[k].min(p[k]); - hi[k] = hi[k].max(p[k]); - } - } - norm(sub(hi, lo)) - }; - l.sort_by(|a, b| size(b).total_cmp(&size(a))); - l - }); - } - if loops.is_none() && !planar { - let rest: Vec<(u64, bool)> = all.iter().copied().filter(|(e, _)| !shared.contains(e)).collect(); - loops = chain(rest) - .map(|mut l| { - // Rings meeting at a vertex (both ends of a horn torus band meet at - // its pole) form one figure-eight loop through it. - while l.len() > 1 { - let Some(second) = l.pop() else { break }; - let at = l.iter().enumerate().find_map(|(li, lp)| { - lp.iter().enumerate().find_map(|(k, x)| { - let v = ends(*x)?.1; - let s = second.iter().position(|y| ends(*y).is_some_and(|(a, _)| a == v))?; - Some((li, k, s)) - }) - }); - let Some((li, k, s)) = at else { - l.push(second); - break; - }; - let mut second = second; - second.rotate_left(s); - if let Some(lp) = l.get_mut(li) { - for (n, x) in second.into_iter().enumerate() { - lp.insert(k + 1 + n, x); - } - } - } - l - }) - .filter(|l| l.len() == 1); - } - let Some(loops) = loops else { continue }; - // A loop of seams only (a whole sphere) bounds nothing: keep the faces apart. - if loops.iter().all(|l| l.iter().all(|(e, _)| l.iter().filter(|(e2, _)| e2 == e).count() > 1)) { - continue; - } - // Write the merged face. - let mut bounds = Vec::new(); - for lp in loops { - let mut oes = Vec::new(); - for (e, d) in lp { - let id = next; - next += 1; - ex.entities.insert( - id, - p21::Entity { - records: vec![p21::Record { - name: "ORIENTED_EDGE".into(), - params: vec![ - Param::Str(String::new()), - Param::Derived, - Param::Derived, - Param::Ref(e), - Param::Enum(if d { "T" } else { "F" }.into()), - ], - }], - }, - ); - oes.push(Param::Ref(id)); - } - let lid = next; - next += 1; - ex.entities.insert( - lid, - p21::Entity { - records: vec![p21::Record { name: "EDGE_LOOP".into(), params: vec![Param::Str(String::new()), Param::List(oes)] }], - }, - ); - let bid = next; - next += 1; - ex.entities.insert( - bid, - p21::Entity { - records: vec![p21::Record { - name: "FACE_BOUND".into(), - params: vec![Param::Str(String::new()), Param::Ref(lid), Param::Enum("T".into())], - }], - }, - ); - bounds.push(Param::Ref(bid)); - } - let Some(old) = ex.get(fa).cloned() else { continue }; - let mut params = old.params().to_vec(); - if let Some(slot) = params.get_mut(1) { - *slot = Param::List(bounds); - } - let nid = next; - next += 1; - if let Some(sid) = params.get(2).and_then(Param::as_ref_id) { - merged_surfaces.insert(sid); - } - ex.entities.insert(nid, p21::Entity { records: vec![p21::Record { name: old.name().to_string(), params }] }); - if let Some(look) = paint.remove(&fa) { - paint.remove(&fb); - paint.insert(nid, look); - } - let new_list: Vec = faces.iter().filter(|f| **f != fb).map(|f| Param::Ref(if *f == fa { nid } else { *f })).collect(); - if let Some(she) = ex.entities.get_mut(&sh) - && let Some(r) = she.records.first_mut() - && let Some(slot) = r.params.get_mut(1) - { - *slot = Param::List(new_list); - } - merged = true; - break 'pairs; - } - } - if !merged { - break; - } - } - } - merged_surfaces -} - -/// B-spline cylinder and cone sheets written as CYLINDRICAL_SURFACE and CONICAL_SURFACE (the -/// sheet covers only its own piece, and a fillet's may reach far past it), with the direction of -/// the parameter seam: on the face's seam edge for a full turn, else in the middle of the gap the -/// face leaves (`gap_middle`), else opposite the face's middle. -/// Sheets under faces merged from pieces always; a lone piece when its edges are circles square -/// to the axis and rulings. (Faces replaced by merges stay in the exchange unreferenced: only the -/// shells' faces count.) -fn analytic_sheets(ex: &p21::Exchange, merged_surfaces: &std::collections::HashSet) -> HashMap { - let live: Vec = ex - .entities - .values() - .filter_map(|e| if matches!(e.name(), "CLOSED_SHELL" | "OPEN_SHELL") { e.params().get(1).and_then(Param::as_list) } else { None }) - .flatten() - .filter_map(Param::as_ref_id) - .collect(); - let mut out = HashMap::new(); - for e in live.iter().filter_map(|f| ex.get(*f)) { - let Some(sid) = e.params().get(2).and_then(Param::as_ref_id) else { continue }; - if out.contains_key(&sid) { - continue; - } - let Some(Analytic { kind, .. }) = ex.get(sid).and_then(|se| ruled_bspline(ex, se)) else { - continue; - }; - let (AnalyticKind::Cylinder { o, z, .. } | AnalyticKind::Cone { o, z, .. }) = kind else { continue }; - if !merged_surfaces.contains(&sid) && !square_or_ruled(ex, e, &kind) { - continue; - } - let Some(loops) = face_edges(ex, e) else { continue }; - let radial = |q: V3| { - let v = sub(q, o); - sub(v, mul(z, dot(v, z))) - }; - let seam = loops - .iter() - .flat_map(|l| l.iter().map(move |(x, _)| (l, *x))) - .find(|(l, x)| l.iter().filter(|(y, _)| y == x).count() > 1) - .map(|(_, x)| x); - // (A cone tip's seam has one end at the apex, on the axis.) - let seam_dir = seam.and_then(|edge| { - let p = ex.get(edge)?.params(); - [p.get(1), p.get(2)].into_iter().filter_map(|v| vertex_point(ex, v?.as_ref_id()?)).find_map(|q| unit(radial(q))) - }); - let x = match seam_dir.or_else(|| gap_middle(ex, &loops, z, &radial)) { - Some(x) => Some(x), - None => { - // No single gap to find (a half turn has two corners, a tube cut in pieces - // several). Points along the edges, not just their ends: the corners of a half - // turn (a slot's round end) point both ways and cancel out (#1198). The sheet's - // own middle where even those do. - let mean = loops - .iter() - .flatten() - .filter_map(|(edge, _)| edge_samples(ex, *edge)) - .flatten() - .filter_map(|q| unit(radial(q))) - .fold([0.0; 3], add); - let (AnalyticKind::Cylinder { x: middle, .. } | AnalyticKind::Cone { x: middle, .. }) = kind else { continue }; - Some(unit(mul(mean, -1.0)).unwrap_or(middle)) - } - }; - if let Some(x) = x { - out.insert(sid, x); - } - } - out -} - -/// The middle of the one angular gap that a face on a cylinder or cone leaves around its axis -/// `z`. The face's boundary vertices are sorted by angle; each two neighbours are joined by one -/// of its edges except across the gap (a 270° face split at 0°, 90°, 180° and 270° leaves -/// 270°–360°). None unless there are three angles or more and exactly one gap: two vertices can -/// be joined either way round. -fn gap_middle(ex: &p21::Exchange, loops: &[Vec<(u64, bool)>], z: V3, radial: &impl Fn(V3) -> V3) -> Option { - use std::f64::consts::TAU; - let mut edges: Vec<(V3, V3)> = Vec::new(); - for (e, _) in loops.iter().flatten() { - let p = ex.get(*e)?.params(); - let (a, b) = (vertex_point(ex, p.get(1)?.as_ref_id()?)?, vertex_point(ex, p.get(2)?.as_ref_id()?)?); - edges.push((unit(radial(a))?, unit(radial(b))?)); - } - let e1 = edges.first()?.0; - let e2 = unit(cross(z, e1))?; - let angle = |d: V3| dot(d, e2).atan2(dot(d, e1)).rem_euclid(TAU); - let close = |a: f64, b: f64| { - let d = (a - b).rem_euclid(TAU); - d < 1e-6 || TAU - d < 1e-6 - }; - let mut angles: Vec = Vec::new(); - for (a, b) in &edges { - for t in [angle(*a), angle(*b)] { - if !angles.iter().any(|s| close(*s, t)) { - angles.push(t); - } - } - } - if angles.len() < 3 { - return None; - } - angles.sort_by(f64::total_cmp); - let joined = |s: f64, t: f64| { - edges.iter().any(|(a, b)| { - let (x, y) = (angle(*a), angle(*b)); - (close(x, s) && close(y, t)) || (close(x, t) && close(y, s)) - }) - }; - let n = angles.len(); - let gaps: Vec<(f64, f64)> = (0..n).filter_map(|i| Some((*angles.get(i)?, *angles.get((i + 1) % n)?))).filter(|(s, t)| !joined(*s, *t)).collect(); - let [(s, t)] = gaps[..] else { return None }; - let m = s + (t - s).rem_euclid(TAU) / 2.0; - unit(add(mul(e1, m.cos()), mul(e2, m.sin()))) -} - -/// Margin left round a face when its sheet is cut down to it, as a share of the face's own -/// parameter range on each side. -const SHEET_MARGIN: f64 = 0.02; - -/// B-spline sheets that reach well past the one face on them, cut down to that face's parameter -/// range (and a margin), so readers bound the part by its faces (#1198): a round's sheet runs on -/// past both ends of the edge it rounds, and when a later cut crosses the round, the crossing edge -/// keeps it from being written as a cylinder (see `square_or_ruled`). Sheets written as analytic -/// surfaces, flat ones, sheets under several faces, and those whose face's edges do not all lie -/// on the piece cut out (a face across a closed sheet's seam) are left alone. -fn trimmed_sheets(ex: &p21::Exchange, analytic: &HashMap) -> HashMap { - let live: Vec = ex - .entities - .values() - .filter_map(|e| if matches!(e.name(), "CLOSED_SHELL" | "OPEN_SHELL") { e.params().get(1).and_then(Param::as_list) } else { None }) - .flatten() - .filter_map(Param::as_ref_id) - .collect(); - let mut users: HashMap = HashMap::new(); - for e in live.iter().filter_map(|f| ex.get(*f)) { - if let Some(sid) = e.params().get(2).and_then(Param::as_ref_id) { - *users.entry(sid).or_default() += 1; - } - } - let mut out = HashMap::new(); - for e in live.iter().filter_map(|f| ex.get(*f)) { - let Some(sid) = e.params().get(2).and_then(Param::as_ref_id) else { continue }; - if users.get(&sid) != Some(&1) || analytic.contains_key(&sid) { - continue; - } - let Some(se) = ex.get(sid) else { continue }; - if !(se.has("B_SPLINE_SURFACE") || se.name() == "B_SPLINE_SURFACE_WITH_KNOTS") || planar_bspline(ex, se).is_some() { - continue; - } - let Some(pts) = face_edges(ex, e).and_then(|ls| ls.iter().flatten().map(|(x, _)| edge_points(ex, *x, 16)).collect::>>()) else { - continue; - }; - let pts: Vec = pts.into_iter().flatten().collect(); - let cx = crate::step_in::Ctx { ex, len: 1.0, ang: 1.0, tol: 1e-6, snap: 1e-6 }; - let Ok(sheet) = crate::step_in::geom::bspline_surface(&cx, se) else { continue }; - if let Ok(Some(cut)) = crate::guard("STEP sheet trim", || Ok(trim_sheet(&sheet, &pts))) { - out.insert(sid, cut); - } - } - out -} - -/// `sheet` cut down to the parameter range `pts` (points on it) cover, with [`SHEET_MARGIN`]; -/// `None` when that would not make it much smaller, or when a point is not on the piece cut out. -fn trim_sheet(sheet: &truck_modeling::Surface, pts: &[V3]) -> Option { - use truck_modeling::{ParametricSurface, SearchNearestParameter, Surface}; - let (Some((u0, u1)), Some((v0, v1))) = sheet.try_range_tuple() else { return None }; - // Edges made by intersecting surfaces are fitted to them, a micron or so off the sheet; a - // point on the wrong piece of it is far further. - let (lo, hi) = pts.iter().fold(([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]), |(lo, hi), p| { - ([lo[0].min(p[0]), lo[1].min(p[1]), lo[2].min(p[2])], [hi[0].max(p[0]), hi[1].max(p[1]), hi[2].max(p[2])]) - }); - let tol = 1e-3 + 1e-4 * norm(sub(hi, lo)); - let near = |s: &Surface, p: V3| -> Option<(f64, f64)> { - let q = truck_modeling::Point3::new(p[0], p[1], p[2]); - let (u, v) = s.search_nearest_parameter(q, None, 100)?; - let r = s.subs(u, v); - (norm(sub([r.x, r.y, r.z], p)) <= tol).then_some((u, v)) - }; - let (mut ua, mut ub, mut va, mut vb) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY); - for p in pts { - let (u, v) = near(sheet, *p)?; - (ua, ub, va, vb) = (ua.min(u), ub.max(u), va.min(v), vb.max(v)); - } - let (du, dv) = ((ub - ua) * SHEET_MARGIN, (vb - va) * SHEET_MARGIN); - let (ua, ub, va, vb) = ((ua - du).max(u0), (ub + du).min(u1), (va - dv).max(v0), (vb + dv).min(v1)); - // Worth it only where a parameter keeps less than four fifths of its range. - let keeps = |a: f64, b: f64, lo: f64, hi: f64| (b - a) / (hi - lo); - if !(ua < ub && va < vb) || (keeps(ua, ub, u0, u1) > 0.8 && keeps(va, vb, v0, v1) > 0.8) { - return None; - } - // The piece between the new ends: `ucut` keeps what lies before the cut and returns the rest. - macro_rules! cut { - ($s:expr) => {{ - let mut s = $s.clone(); - if ua > u0 { - s = s.ucut(ua); - } - if ub < u1 { - s.ucut(ub); - } - if va > v0 { - s = s.vcut(va); - } - if vb < v1 { - s.vcut(vb); - } - s - }}; - } - let piece = match sheet { - Surface::BSplineSurface(b) => Surface::BSplineSurface(cut!(b)), - Surface::NurbsSurface(n) => Surface::NurbsSurface(cut!(n)), - _ => return None, - }; - pts.iter().all(|p| near(&piece, *p).is_some()).then_some(piece) -} - -/// The B-rep entities of one body as truck writes them, parsed, the B-spline sheets to write -/// as cylinders and cones (see `analytic_sheets`) and those to write cut down to their faces -/// (see `trimmed_sheets`). Without `merge` the file is truck's, as is. -fn brep_exchange(b: &Body, merge: bool) -> Result<(p21::Exchange, HashMap, HashMap, HashMap)> { - let text = crate::step::truck_step(&[b], "SolidCraft")?; - let mut ex = p21::parse(&text).map_err(|e| KernelError::Failed(format!("STEP export: {e}")))?; - collapse_short_edges(&mut ex); - // Face colours by exchange face: truck writes each shell's faces in the body's face order. - let mut paint = HashMap::new(); - if let Some(p) = b.paint() - && !p.faces.is_empty() - { - let mut shells: Vec = ex.entities.iter().filter(|(_, e)| matches!(e.name(), "CLOSED_SHELL" | "OPEN_SHELL")).map(|(i, _)| *i).collect(); - shells.sort(); - let faces: Vec = shells.iter().filter_map(|s| ex.get(*s)?.params().get(1)?.as_list()).flatten().filter_map(Param::as_ref_id).collect(); - for f in &p.faces { - if let Some(id) = faces.get(f.face) { - paint.insert(*id, (f.color, f.opacity)); - } - } - } - let before = shell_face_count(&ex); - let keep = b.split_lines().map(|l| l.as_slice()).unwrap_or(&[]); - let (sheets, trimmed) = if merge { - let merged = merge_split_faces(&mut ex, &mut paint, keep); - let sheets = analytic_sheets(&ex, &merged); - let trimmed = trimmed_sheets(&ex, &sheets); - // Lone sheets rewritten as analytic surfaces, or cut down, count as changes to check too. - MERGES.with(|m| m.set(m.get() + sheets.keys().filter(|s| !merged.contains(s)).count() + trimmed.len())); - (sheets, trimmed) - } else { - Default::default() - }; - MERGES.with(|m| m.set(m.get() + before.saturating_sub(shell_face_count(&ex)))); - Ok((ex, sheets, trimmed, paint)) -} - -/// The separate pieces of a body for export, each keeping its face colours: a body of several -/// lumps (a plate and the islands a cut left inside its holes, such as letter counters) is -/// several solids, never one solid whose other pieces are written as voids. A body in one -/// piece, or one whose pieces cannot be told apart, is itself. -fn export_lumps(b: &Body) -> Vec { - if b.mesh.is_some() || b.solid.boundaries().len() < 2 { - return vec![b.clone()]; - } - let lumps = match b.lumps() { - Ok(l) if l.len() > 1 => l, - _ => return vec![b.clone()], - }; - let index: HashMap<_, usize> = b.solid.face_iter().enumerate().map(|(i, f)| (f.id(), i)).collect(); - lumps - .into_iter() - .map(|lump| { - let paint = b.paint().map(|p| crate::body::Paint { - opacity: p.opacity, - faces: lump - .solid - .face_iter() - .enumerate() - .filter_map(|(k, f)| { - let i = index.get(&f.id())?; - p.faces.iter().find(|fp| fp.face == *i).map(|fp| crate::body::FacePaint { face: k, ..fp.clone() }) - }) - .collect(), - }); - lump.with_color(b.color()).with_split_lines(b.split_lines().cloned()).with_paint(paint) - }) - .collect() -} - -/// Faces in the exchange's shells (fewer after merging). -fn shell_face_count(ex: &p21::Exchange) -> usize { - ex.entities - .values() - .filter(|e| matches!(e.name(), "CLOSED_SHELL" | "OPEN_SHELL")) - .filter_map(|e| e.params().get(1).and_then(Param::as_list)) - .map(<[Param]>::len) - .sum() -} - -/// A face's own colour (0..1) and opacity. -type FaceLook = ([f32; 3], f32); - +/// The placement's origin, z and x axes; refused unless it is a rotation and a translation. fn rigid_frame(m: &[[f64; 4]; 4]) -> Result<([f64; 3], [f64; 3], [f64; 3])> { let x = [m[0][0], m[0][1], m[0][2]]; let y = [m[1][0], m[1][1], m[1][2]]; @@ -1601,27 +73,6 @@ fn rigid_frame(m: &[[f64; 4]; 4]) -> Result<([f64; 3], [f64; 3], [f64; 3])> { /// STEP text (AP242) for products with bodies and assembly placements; `root` is the top product. pub fn step_export_products(products: &[ExportProduct], root: usize, header: &StepHeader) -> Result { - MERGES.with(|m| m.set(0)); - let text = products_text(products, root, header, true)?; - // Faces merged per surface, and sheets rewritten as cylinders and cones, must read back as - // cleanly as truck's pieces (a merge can leave a loop the reader cannot lay out); otherwise - // the pieces are written as truck made them. Without a change there is nothing to check. - let clean = |t: &str| crate::step_in::step_import(t).is_ok_and(|i| i.warnings.is_empty()); - if MERGES.with(|m| m.get()) > 0 && !clean(&text) { - let plain = products_text(products, root, header, false)?; - if clean(&plain) { - return Ok(plain); - } - } - Ok(text) -} - -thread_local! { - /// Faces merged and sheets rewritten while writing the current export. - static MERGES: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -fn products_text(products: &[ExportProduct], root: usize, header: &StepHeader, merge: bool) -> Result { if products.is_empty() || root >= products.len() { return Err(KernelError::Invalid("nothing to export".into())); } @@ -1649,121 +100,131 @@ fn products_text(products: &[ExportProduct], root: usize, header: &StepHeader, m if cyclic(products, root, &mut Vec::new()) { return Err(KernelError::Invalid("the component tree is recursive".into())); } - - let mut o = Out::default(); - let app = o.add("APPLICATION_CONTEXT('managed model based 3d engineering')"); - o.add(format!("APPLICATION_PROTOCOL_DEFINITION('international standard','ap242_managed_model_based_3d_engineering',2014,#{app})")); - let pctx = o.add(format!("PRODUCT_CONTEXT('',#{app},'mechanical')")); - let pdctx = o.add(format!("PRODUCT_DEFINITION_CONTEXT('part definition',#{app},'design')")); - let mm = o.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))"); - let rad = o.add("(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.))"); - let sr = o.add("(NAMED_UNIT(*)SI_UNIT($,.STERADIAN.)SOLID_ANGLE_UNIT())"); - let unc = o.add(format!("UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(1.E-06),#{mm},'distance_accuracy_value','confusion accuracy')")); - let ctx = o.add(format!( - "(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#{unc}))GLOBAL_UNIT_ASSIGNED_CONTEXT((#{mm},#{rad},#{sr}))REPRESENTATION_CONTEXT('Context #1','3D Context with UNIT and UNCERTAINTY'))" - )); - let origin = o.placement([0.0; 3], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]); - - // Products (only those reachable from the root). + // Products reachable from the root. let mut reach = vec![false; products.len()]; let mut todo = vec![root]; while let Some(p) = todo.pop() { - if let Some(r) = reach.get_mut(p) - && !*r + if let Some(seen) = reach.get_mut(p) + && !*seen { - *r = true; + *seen = true; if let Some(x) = products.get(p) { todo.extend(x.children.iter().map(|(c, _, _)| *c)); } } } + let reached: Vec<(usize, &ExportProduct)> = products.iter().enumerate().filter(|(i, _)| reach.get(*i).copied().unwrap_or(false)).collect(); + // The context states the models' accuracy: the loosest of their records' tolerances. + let uncertainty = + reached.iter().flat_map(|(_, p)| &p.bodies).map(|b| b.body.record().tolerance).filter(|t| t.is_finite()).fold(MIN_UNCERTAINTY, f64::max); + + let mut w = Writer::new(); + let app = w.add_distinct("APPLICATION_CONTEXT", &[s("managed model based 3d engineering")]); + w.add_distinct( + "APPLICATION_PROTOCOL_DEFINITION", + &[s("international standard"), s("ap242_managed_model_based_3d_engineering"), Param::Int(2014), r(app)], + ); + let pctx = w.add_distinct("PRODUCT_CONTEXT", &[s(""), r(app), s("mechanical")]); + let pdctx = w.add_distinct("PRODUCT_DEFINITION_CONTEXT", &[s("part definition"), r(app), s("design")]); + let mm = w.add_complex(&[ + ("LENGTH_UNIT", vec![]), + ("NAMED_UNIT", vec![Param::Derived]), + ("SI_UNIT", vec![Param::Enum("MILLI".into()), Param::Enum("METRE".into())]), + ]); + let rad = w.add_complex(&[ + ("NAMED_UNIT", vec![Param::Derived]), + ("PLANE_ANGLE_UNIT", vec![]), + ("SI_UNIT", vec![Param::Null, Param::Enum("RADIAN".into())]), + ]); + let sr = w.add_complex(&[ + ("NAMED_UNIT", vec![Param::Derived]), + ("SI_UNIT", vec![Param::Null, Param::Enum("STERADIAN".into())]), + ("SOLID_ANGLE_UNIT", vec![]), + ]); + let unc = w.add_distinct( + "UNCERTAINTY_MEASURE_WITH_UNIT", + &[Param::Typed("LENGTH_MEASURE".into(), vec![Param::Real(uncertainty)]), r(mm), s("distance_accuracy_value"), s("confusion accuracy")], + ); + let ctx = w.add_complex(&[ + ("GEOMETRIC_REPRESENTATION_CONTEXT", vec![Param::Int(3)]), + ("GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT", vec![refs(&[unc])]), + ("GLOBAL_UNIT_ASSIGNED_CONTEXT", vec![refs(&[mm, rad, sr])]), + ("REPRESENTATION_CONTEXT", vec![s("Context #1"), s("3D Context with UNIT and UNCERTAINTY")]), + ]); + let origin = GeomWriter::new(&mut w).placement(&solidcraft_step::geom::Placement { + origin: [0.0; 3], + axis: [0.0, 0.0, 1.0], + ref_direction: [1.0, 0.0, 0.0], + }); + + // Placements of children inside each parent, made before the parent's representation. + let mut placements: Vec> = vec![Vec::new(); products.len()]; + for &(pi, p) in &reached { + for (_, m, _) in &p.children { + let (t, z, x) = rigid_frame(m)?; + let mut g = GeomWriter::new(&mut w); + let (pt, dz, dx) = (g.point(t), g.direction(z), g.direction(x)); + // Its own entity: it is an item of the parent's representation. + let a = w.add_distinct("AXIS2_PLACEMENT_3D", &[s(""), r(pt), r(dz), r(dx)]); + if let Some(v) = placements.get_mut(pi) { + v.push(a); + } + } + } let mut pd = vec![0u64; products.len()]; let mut shape_rep = vec![0u64; products.len()]; let mut product_ids = Vec::new(); let mut styled = Vec::new(); - let mut child_items: Vec> = vec![Vec::new(); products.len()]; - // Placements of children inside each parent, made before the parent's representation. - let mut placements: Vec> = vec![Vec::new(); products.len()]; - for (pi, p) in products.iter().enumerate() { - if !reach.get(pi).copied().unwrap_or(false) { - continue; - } - for (_, m, _) in &p.children { - let (t, z, x) = rigid_frame(m)?; - let (pt, dz, dx) = (o.point(t), o.direction(z), o.direction(x)); - // Its own entity: it is an item of the parent's representation. - let a = o.add(format!("AXIS2_PLACEMENT_3D('',#{pt},#{dz},#{dx})")); - if let Some(v) = placements.get_mut(pi) { - v.push(a); - } - if let Some(v) = child_items.get_mut(pi) { - v.push(a); - } - } - } - for (pi, p) in products.iter().enumerate() { - if !reach.get(pi).copied().unwrap_or(false) { - continue; - } + for &(pi, p) in &reached { let name = if p.name.trim().is_empty() { "Part".to_string() } else { p.name.clone() }; - let prod = o.add(format!("PRODUCT({},{},'',(#{pctx}))", string(&name), string(&name))); + let prod = w.add_distinct("PRODUCT", &[s(&name), s(&name), s(""), refs(&[pctx])]); product_ids.push(prod); - let pdf = o.add(format!("PRODUCT_DEFINITION_FORMATION('','',#{prod})")); - let d = o.add(format!("PRODUCT_DEFINITION('design','',#{pdf},#{pdctx})")); - let pds = o.add(format!("PRODUCT_DEFINITION_SHAPE('','',#{d})")); + let pdf = w.add_distinct("PRODUCT_DEFINITION_FORMATION", &[s(""), s(""), r(prod)]); + let d = w.add_distinct("PRODUCT_DEFINITION", &[s("design"), s(""), r(pdf), r(pdctx)]); + let pds = w.add_distinct("PRODUCT_DEFINITION_SHAPE", &[s(""), s(""), r(d)]); let mut items = vec![origin]; - items.extend(child_items.get(pi).cloned().unwrap_or_default()); - let item_list = items.iter().map(|i| format!("#{i}")).collect::>().join(","); - let srep = o.add(format!("SHAPE_REPRESENTATION({},({item_list}),#{ctx})", string(&name))); - o.add(format!("SHAPE_DEFINITION_REPRESENTATION(#{pds},#{srep})")); + items.extend(placements.get(pi).into_iter().flatten().copied()); + let srep = w.add_distinct("SHAPE_REPRESENTATION", &[s(&name), refs(&items), r(ctx)]); + w.add_distinct("SHAPE_DEFINITION_REPRESENTATION", &[r(pds), r(srep)]); if let Some(slot) = pd.get_mut(pi) { *slot = d; } if let Some(slot) = shape_rep.get_mut(pi) { *slot = srep; } - if !p.bodies.is_empty() { - let mut solids = Vec::new(); - for b in &p.bodies { - for lump in export_lumps(b.body) { - let (ex, merged, trimmed, face_paint) = brep_exchange(&lump, merge)?; - o.merged = merged; - o.trimmed = trimmed; - o.faces_out.clear(); - let mut roots: Vec = - ex.entities.iter().filter(|(_, e)| matches!(e.name(), "MANIFOLD_SOLID_BREP" | "BREP_WITH_VOIDS")).map(|(i, _)| *i).collect(); - roots.sort(); - for r in roots { - let id = o.copy_solid(&ex, r, &b.name).map_err(|e| KernelError::Failed(format!("STEP export: {e}")))?; - solids.push(id); - let opacity = lump.paint().map(|p| p.opacity).unwrap_or(1.0); - if let Some(c) = b.color { - styled.push(style(&mut o, id, c, opacity)); - } - } - // Faces with colours of their own. - let mut painted: Vec<(u64, ([f32; 3], f32))> = - face_paint.into_iter().filter_map(|(f, look)| Some((*o.faces_out.get(&f)?, look))).collect(); - painted.sort_by_key(|(f, _)| *f); - for (f, (c, op)) in painted { - styled.push(style(&mut o, f, c, op)); - } + let (mut solids, mut sheets) = (Vec::new(), Vec::new()); + for b in &p.bodies { + let written = topology::brep(&mut GeomWriter::new(&mut w), b.body.record(), &b.name) + .map_err(|e| KernelError::Failed(format!("STEP export of '{}': {e}", b.name)))?; + let opacity = b.body.paint().map_or(1.0, |p| p.opacity); + let items: Vec = written.solids.iter().copied().chain(written.sheets).collect(); + if let Some(c) = b.color { + for item in &items { + styled.push(style(&mut w, *item, c, opacity)); } } - let list = solids.iter().chain(std::iter::once(&origin)).map(|i| format!("#{i}")).collect::>().join(","); - let absr = o.add(format!("ADVANCED_BREP_SHAPE_REPRESENTATION({},({list}),#{ctx})", string(&name))); - o.add(format!("SHAPE_REPRESENTATION_RELATIONSHIP('','',#{srep},#{absr})")); + // Faces with colours of their own. + for f in b.body.paint().map(|p| p.faces.as_slice()).unwrap_or(&[]) { + if let Some(&face) = written.faces.get(f.face).filter(|id| **id != 0) { + styled.push(style(&mut w, face, f.color, f.opacity)); + } + } + solids.extend(written.solids); + sheets.extend(written.sheets); + } + for (kind, list) in [("ADVANCED_BREP_SHAPE_REPRESENTATION", solids), ("MANIFOLD_SURFACE_SHAPE_REPRESENTATION", sheets)] { + if list.is_empty() { + continue; + } + let rep = w.add_distinct(kind, &[s(&name), refs(&[list, vec![origin]].concat()), r(ctx)]); + w.add_distinct("SHAPE_REPRESENTATION_RELATIONSHIP", &[s(""), s(""), r(srep), r(rep)]); } } if !product_ids.is_empty() { - let list = product_ids.iter().map(|i| format!("#{i}")).collect::>().join(","); - o.add(format!("PRODUCT_RELATED_PRODUCT_CATEGORY('part','',({list}))")); + w.add_distinct("PRODUCT_RELATED_PRODUCT_CATEGORY", &[s("part"), s(""), refs(&product_ids)]); } // Assembly occurrences. - for (pi, p) in products.iter().enumerate() { - if !reach.get(pi).copied().unwrap_or(false) { - continue; - } + for &(pi, p) in &reached { for (k, (ci, _, oname)) in p.children.iter().enumerate() { let (Some(&parent_pd), Some(&child_pd), Some(&parent_sr), Some(&child_sr), Some(&target)) = (pd.get(pi), pd.get(*ci), shape_rep.get(pi), shape_rep.get(*ci), placements.get(pi).and_then(|v| v.get(k))) @@ -1775,57 +236,56 @@ fn products_text(products: &[ExportProduct], root: usize, header: &StepHeader, m } else { oname.clone() }; - let nauo = o.add(format!("NEXT_ASSEMBLY_USAGE_OCCURRENCE({},{},'',#{parent_pd},#{child_pd},$)", string(&nm), string(&nm))); - let pds = o.add(format!("PRODUCT_DEFINITION_SHAPE('','',#{nauo})")); - let idt = o.add(format!("ITEM_DEFINED_TRANSFORMATION('','',#{origin},#{target})")); - let rr = o.add(format!( - "(REPRESENTATION_RELATIONSHIP('','',#{child_sr},#{parent_sr})REPRESENTATION_RELATIONSHIP_WITH_TRANSFORMATION(#{idt})SHAPE_REPRESENTATION_RELATIONSHIP())" - )); - o.add(format!("CONTEXT_DEPENDENT_SHAPE_REPRESENTATION(#{rr},#{pds})")); + let nauo = w.add_distinct("NEXT_ASSEMBLY_USAGE_OCCURRENCE", &[s(&nm), s(&nm), s(""), r(parent_pd), r(child_pd), Param::Null]); + let pds = w.add_distinct("PRODUCT_DEFINITION_SHAPE", &[s(""), s(""), r(nauo)]); + let idt = w.add_distinct("ITEM_DEFINED_TRANSFORMATION", &[s(""), s(""), r(origin), r(target)]); + let rr = w.add_complex(&[ + ("REPRESENTATION_RELATIONSHIP", vec![s(""), s(""), r(child_sr), r(parent_sr)]), + ("REPRESENTATION_RELATIONSHIP_WITH_TRANSFORMATION", vec![r(idt)]), + ("SHAPE_REPRESENTATION_RELATIONSHIP", vec![]), + ]); + w.add_distinct("CONTEXT_DEPENDENT_SHAPE_REPRESENTATION", &[r(rr), r(pds)]); } } if !styled.is_empty() { - let list = styled.iter().map(|i| format!("#{i}")).collect::>().join(","); - o.add(format!("MECHANICAL_DESIGN_GEOMETRIC_PRESENTATION_REPRESENTATION('',({list}),#{ctx})")); + w.add_distinct("MECHANICAL_DESIGN_GEOMETRIC_PRESENTATION_REPRESENTATION", &[s(""), refs(&styled), r(ctx)]); } - let mut s = String::new(); - s.push_str("ISO-10303-21;\nHEADER;\n"); + let mut text = String::new(); + text.push_str("ISO-10303-21;\nHEADER;\n"); let description = if header.description.is_empty() { "SolidCraft model" } else { header.description.as_str() }; - let _ = writeln!(s, "FILE_DESCRIPTION(({}),'2;1');", string(description)); + let _ = writeln!(text, "FILE_DESCRIPTION(({}),'2;1');", string(description)); let _ = writeln!( - s, + text, "FILE_NAME({},{},({}),({}),'SolidCraft','SolidCraft','');", string(&header.file_name), string(&header.time_stamp), string(&header.author), string(&header.organization) ); - s.push_str("FILE_SCHEMA(('AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { 1 0 10303 442 1 1 4 }'));\nENDSEC;\nDATA;\n"); - for (i, l) in o.lines.iter().enumerate() { - let _ = writeln!(s, "#{}={l};", i + 1); - } - s.push_str("ENDSEC;\nEND-ISO-10303-21;\n"); - Ok(s) + text.push_str("FILE_SCHEMA(('AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { 1 0 10303 442 1 1 4 }'));\nENDSEC;\nDATA;\n"); + text.push_str(&w.data()); + text.push_str("ENDSEC;\nEND-ISO-10303-21;\n"); + Ok(text) } -/// A surface colour for a solid (STYLED_ITEM chain). -fn style(o: &mut Out, item: u64, c: [f32; 3], opacity: f32) -> u64 { - let rgb = o.add_shared(format!("COLOUR_RGB('',{},{},{})", real(c[0] as f64), real(c[1] as f64), real(c[2] as f64))); - let fasc = o.add_shared(format!("FILL_AREA_STYLE_COLOUR('',#{rgb})")); - let fas = o.add_shared(format!("FILL_AREA_STYLE('',(#{fasc}))")); - let ssfa = o.add_shared(format!("SURFACE_STYLE_FILL_AREA(#{fas})")); +/// A surface colour for an item (STYLED_ITEM chain; the styles are shared). +fn style(w: &mut Writer, item: u64, c: [f32; 3], opacity: f32) -> u64 { + let rgb = w.add("COLOUR_RGB", &[s(""), Param::Real(c[0] as f64), Param::Real(c[1] as f64), Param::Real(c[2] as f64)]); + let fasc = w.add("FILL_AREA_STYLE_COLOUR", &[s(""), r(rgb)]); + let fas = w.add("FILL_AREA_STYLE", &[s(""), refs(&[fasc])]); + let ssfa = w.add("SURFACE_STYLE_FILL_AREA", &[r(fas)]); // See-through looks add a transparency (1 = invisible) to the side style. let sides = if opacity < 1.0 { - let tr = o.add_shared(format!("SURFACE_STYLE_TRANSPARENT({})", real((1.0 - opacity as f64).clamp(0.0, 1.0)))); - format!("#{ssfa},#{tr}") + let tr = w.add("SURFACE_STYLE_TRANSPARENT", &[Param::Real((1.0 - opacity as f64).clamp(0.0, 1.0))]); + vec![ssfa, tr] } else { - format!("#{ssfa}") + vec![ssfa] }; - let sss = o.add_shared(format!("SURFACE_SIDE_STYLE('',({sides}))")); - let ssu = o.add_shared(format!("SURFACE_STYLE_USAGE(.BOTH.,#{sss})")); - let psa = o.add_shared(format!("PRESENTATION_STYLE_ASSIGNMENT((#{ssu}))")); - o.add(format!("STYLED_ITEM('color',(#{psa}),#{item})")) + let sss = w.add("SURFACE_SIDE_STYLE", &[s(""), refs(&sides)]); + let ssu = w.add("SURFACE_STYLE_USAGE", &[Param::Enum("BOTH".into()), r(sss)]); + let psa = w.add("PRESENTATION_STYLE_ASSIGNMENT", &[refs(&[ssu])]); + w.add_distinct("STYLED_ITEM", &[s("color"), refs(&[psa]), r(item)]) } /// STEP text for bodies of one part (names `Body1`…). @@ -1846,6 +306,9 @@ pub fn step_export_bodies(bodies: &[ExportBody], header: &StepHeader) -> Result< #[cfg(test)] mod tests { use super::*; + use solidcraft_geom::Vec3; + use solidcraft_step::p21; + use solidcraft_step::write::real; #[test] fn islands_are_solids_of_their_own_not_voids() { @@ -1875,63 +338,6 @@ mod tests { assert_eq!(text.matches("BREP_WITH_VOIDS").count(), 1, "{text}"); } - /// #3394: a plate on four tapered legs and a straight peg. Each leg's cone and the peg's - /// cylinder are written as one face whose loop runs ring, seam, ring, seam. Readers put the - /// seam's first use on the side where the surface's angle starts and lay the next ring out - /// from there, so that ring must turn the way the angle grows (anticlockwise about the - /// written axis); three of the legs came out the other way and other readers dropped their - /// sides. - #[test] - fn seam_loops_turn_the_way_the_angle_grows() { - use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; - let plate = crate::box_solid(Vec3::new(-60.0, -40.0, 0.0), Vec3::new(60.0, 40.0, 10.0)).unwrap(); - let mut b = plate; - for (x, y) in [(-45.0, -30.0), (45.0, -30.0), (45.0, 30.0), (-45.0, 30.0)] { - let disc = Region2 { outer: Loop2::circle(Vec2::new(x, y), 5.0), holes: vec![] }; - let leg = crate::extrude_tapered(&Plane::XY, &disc, 20.0, -1.0, 2f64.to_radians()).unwrap(); - b = crate::boolean(&b, &leg, crate::BoolOp::Union).unwrap().unwrap(); - } - let peg = crate::cylinder(Vec3::new(0.0, 0.0, 10.0), Vec3::Z, 4.0, 8.0).unwrap(); - b = crate::boolean(&b, &peg, crate::BoolOp::Union).unwrap().unwrap(); - let text = crate::step_export(&[&b], "test").unwrap(); - let ex = p21::parse(&text).unwrap(); - let mut seamed = 0; - for face in ex.entities.values().filter(|e| e.name() == "ADVANCED_FACE") { - let surface = ex.get(face.params().get(2).unwrap().as_ref_id().unwrap()).unwrap(); - if !matches!(surface.name(), "CONICAL_SURFACE" | "CYLINDRICAL_SURFACE") { - continue; - } - let frame = ex.get(surface.params().get(1).unwrap().as_ref_id().unwrap()).unwrap(); - let o = triple(&ex, frame.params().get(1).unwrap().as_ref_id().unwrap()); - let z = triple(&ex, frame.params().get(2).unwrap().as_ref_id().unwrap()); - for lp in face_edges(&ex, face).unwrap() { - let Some(i) = lp.iter().position(|(e, _)| lp.iter().filter(|(f, _)| f == e).count() == 2) else { continue }; - let &(edge, dir) = lp.get((i + 1) % lp.len()).unwrap(); - let p = ex.get(edge).unwrap().params(); - let (v0, v1) = (p.get(1).unwrap().as_ref_id().unwrap(), p.get(2).unwrap().as_ref_id().unwrap()); - let mut pts = edge_points(&ex, edge, 4).unwrap(); - if p.get(4).unwrap().as_bool().unwrap() != dir { - pts.reverse(); - } - let start = vertex_point(&ex, if dir { v0 } else { v1 }).unwrap(); - let radial = |q: V3| { - let v = sub(q, o); - sub(v, mul(z, dot(v, z))) - }; - let turn = dot(cross(radial(start), radial(pts[1])), z); - assert!(turn > 0.0, "face #{:?}: the ring after the seam turns against the angle", face.params().first()); - seamed += 1; - } - } - assert_eq!(seamed, 5, "{text}"); - } - - /// A CARTESIAN_POINT's or DIRECTION's three numbers. - fn triple(ex: &p21::Exchange, id: u64) -> V3 { - let c = ex.get(id).unwrap().params().get(1).unwrap().as_list().unwrap(); - [c[0].as_f64().unwrap(), c[1].as_f64().unwrap(), c[2].as_f64().unwrap()] - } - #[test] fn numbers_and_strings() { assert_eq!(real(1.0), "1.0");