From 3557e3c563b8a16bf9e6ca2eae79aaac5220e1cc Mon Sep 17 00:00:00 2001 From: jyviko <2501648+jyviko@users.noreply.github.com> Date: Thu, 22 Oct 2026 08:46:55 -0400 Subject: [PATCH] Wave 205/509: kernel: union_all, one SMLib union of many bodies checked once, history over every operand (and 3 more) 4 commits, squashed; the originals stay reachable from tag archive/merge-main-develop. - 2ffbbc74d jyviko: step: a cone within the file's uncertainty of its limit plane over the face is read as that plane - 0185ccc1e jyviko: solidcraft-smlib: Brep::union_all, the union of many bodies in one SMLib call - 0213c3dfa jyviko: kernel: union_all, one SMLib union of many bodies checked once, history over every operand - 83d965f30 jyviko: doc: a join into one target and an intersection's tools are one union_all call Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ --- crates/doc/src/eval.rs | 49 +++++----------- crates/kernel/src/lib.rs | 2 +- crates/kernel/src/ops.rs | 19 +++++- crates/kernel/src/planar_sources.rs | 17 +++--- crates/kernel/src/smlib_boolean.rs | 89 ++++++++++++++++++++++------- crates/smlib/src/ffi/ops.rs | 15 ++++- crates/smlib/src/lib.rs | 2 +- crates/smlib/src/ops.rs | 16 ++++++ crates/step/src/topology.rs | 2 +- crates/step/src/topology/swept.rs | 48 ++++++++++++++-- crates/step/src/topology_tests.rs | 4 +- 11 files changed, 185 insertions(+), 78 deletions(-) diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 714f86232..77e05dd94 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -2699,29 +2699,22 @@ fn sheet_boolean_changes(body: &Body, tools: &[Body], op: Operation) -> Result) -> Result> { if tools.len() > 1000 || tools.iter().fold(0usize, |n, t| n.saturating_add(t.body.face_count())) > 16_384 { return Err(DocError::Invalid("intersection tools exceed the bounded geometry budget".into())); } - let mut groups = tools; - while groups.len() > 1 { - let mut next = Vec::new(); - let mut iter = groups.into_iter(); - while let Some(a) = iter.next() { - match iter.next() { - Some(b) => { - let u = kernel::boolean(&a.body, &b.body, BoolOp::Union)? - .ok_or_else(|| DocError::Invalid("intersection tool union is empty".into()))?; - next.push(Traced::step(u, &[&a, &b])); - } - None => next.push(a), - } - } - groups = next; + if tools.len() < 2 { + return Ok(tools); } - Ok(groups) + Ok(vec![union_all(&tools.iter().collect::>())?]) +} + +/// The union of `operands` (traced bodies) in one kernel call, keeping their lineage. +fn union_all(operands: &[&Traced]) -> Result { + let bodies: Vec<&Body> = operands.iter().map(|t| &t.body).collect(); + Ok(Traced::step(kernel::union_all(&bodies)?, operands)) } /// After a cut handled some sheet bodies as flat machining, apply it to the other targets. @@ -2923,26 +2916,14 @@ fn apply_traced_with( Ok(Traced::step(u, &[a, b])) }; // One target takes every tool, whichever it meets: the result is the union of all of - // them, made in a balanced tree of unions so that each body is in about log2(n) of - // them, instead of the target growing by one tool at a time and taking part, ever - // larger, in every one (n tools cost n²). + // them in one kernel call, checked once. if let [keep] = live.as_slice() && tools.len() > 1 { let Some(base) = state.body(keep).map(ModelBody::traced) else { return Ok(()) }; - let mut level: Vec = std::iter::once(base).chain(tools).collect(); - while level.len() > 1 { - let mut next = Vec::with_capacity(level.len().div_ceil(2)); - let mut it = level.into_iter(); - while let Some(a) = it.next() { - next.push(match it.next() { - Some(b) => union(&a, &b)?, - None => a, - }); - } - level = next; - } - if let (Some(acc), Some(mb)) = (level.pop(), state.bodies.iter_mut().find(|b| b.name == *keep)) { + let operands: Vec<&Traced> = std::iter::once(&base).chain(&tools).collect(); + let acc = union_all(&operands)?; + if let Some(mb) = state.bodies.iter_mut().find(|b| b.name == *keep) { *mb = ModelBody::traced_new(mb.name.clone(), acc, mb.feature); } return Ok(()); diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index 77436d8dd..75bf79663 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -188,7 +188,7 @@ pub use meshbody::{MAX_TRIANGLES, mesh_body}; pub use native::{body_from_smlib, smlib_body}; pub use native::{brep_record, decode_native_body, encode_native_body, native_preview_mesh}; pub use offset::with_same_surface; -pub use ops::{BoolOp, boolean, half_space, join_apart, place_matrix, split_by_plane, transform, transform_matrix, union_apart}; +pub use ops::{BoolOp, boolean, half_space, join_apart, place_matrix, split_by_plane, transform, transform_matrix, union_all, union_apart}; pub use point_path::{ PathPiece, PointPath, SpaceBezier, curve_path, edge_path, face_section_along, iso_curves, project_onto_face, sketch_record_curve, sweep_point_path_with, diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rs index 676a5de70..1f1ce9832 100644 --- a/crates/kernel/src/ops.rs +++ b/crates/kernel/src/ops.rs @@ -29,16 +29,31 @@ pub fn boolean(a: &Body, b: &Body, op: BoolOp) -> Result> { }) } +/// The union of `bodies` (at least one) in one SMLib call, each body taking part in about +/// log2(n) of its unions, the result checked once. A result SMLib's check refuses is an error. +/// +/// The result carries its exact history over `bodies` in order, as [`boolean`]'s does, and +/// what the operands' faces stood for (their regularization protection and the planar roles on +/// supports it kept). +pub fn union_all(bodies: &[&Body]) -> Result { + crate::profile::timed(crate::profile::Kind::Boolean, || { + if bodies.is_empty() { + return Err(KernelError::Invalid("a union of no bodies".into())); + } + guard("SMLib union", || crate::smlib_boolean::smlib_union_all(bodies))?.with_preserved_union_planar_sources(bodies) + }) +} + /// A boolean's result with what its operands' faces stood for carried over: regularization /// protection and the planar construction and shell roles on supports it kept. fn with_operand_roles(a: &Body, b: &Body, op: BoolOp, r: Result>) -> Result> { let r = r.map(|result| result.map(|body| body.inherit_regularization_protection(a).inherit_regularization_protection(b))); match op { BoolOp::Cut => r.and_then(|result| result.map(|body| body.with_preserved_boolean_planar_sources(a, b, true)).transpose()), - BoolOp::Union => r.and_then(|result| result.map(|body| body.with_preserved_union_planar_sources(a, b)).transpose()), + BoolOp::Union => r.and_then(|result| result.map(|body| body.with_preserved_union_planar_sources(&[a, b])).transpose()), // Every face of an intersection lies on one operand's face, as a union's does: the same // roles carry over (#565). - BoolOp::Intersect => r.and_then(|result| result.map(|body| body.with_preserved_union_planar_sources(a, b)).transpose()), + BoolOp::Intersect => r.and_then(|result| result.map(|body| body.with_preserved_union_planar_sources(&[a, b])).transpose()), } } diff --git a/crates/kernel/src/planar_sources.rs b/crates/kernel/src/planar_sources.rs index 61ad9722d..af081a1f5 100644 --- a/crates/kernel/src/planar_sources.rs +++ b/crates/kernel/src/planar_sources.rs @@ -151,15 +151,15 @@ impl Body { self_.map_planar_sources(&[input], None, Some(tool), &[], constructed) } - /// Retain exact construction and shell roles through a Union from both operands, only on - /// unchanged supports. Coplanar supports of the two operands carry distinct identities, so - /// a face merged from both stays without a role. - pub(crate) fn with_preserved_union_planar_sources(self, a: &Body, b: &Body) -> Result { - let self_ = self.inherit_regularization_protection(a).inherit_regularization_protection(b); - if ![a, b].iter().any(|input| input.face_sources().is_some_and(|sources| sources.iter().flatten().any(|s| boolean_source(s, true)))) { + /// Retain exact construction and shell roles through a Union from every operand, only on + /// unchanged supports. Coplanar supports of different operands carry distinct identities, so + /// a face merged from several stays without a role. + pub(crate) fn with_preserved_union_planar_sources(self, operands: &[&Body]) -> Result { + let self_ = operands.iter().fold(self, |body, operand| body.inherit_regularization_protection(operand)); + if !operands.iter().any(|input| input.face_sources().is_some_and(|sources| sources.iter().flatten().any(|s| boolean_source(s, true)))) { return Ok(self_); } - self_.map_planar_sources(&[a, b], None, None, &[], true) + self_.map_planar_sources(operands, None, None, &[], true) } fn map_planar_sources(mut self, inputs: &[&Body], shell: Option, blocker: Option<&Body>, open: &[Vec3], constructed: bool) -> Result { @@ -172,7 +172,8 @@ impl Body { if inputs.iter().all(|input| input.face_sources().is_none()) { return Ok(self); } - if inputs.len() > 2 + // Each body at most 16 384 faces, and the inputs together at most two such bodies' worth. + if inputs.iter().fold(0usize, |n, input| n.saturating_add(input.face_count())) > 2 * 16_384 || inputs.iter().any(|input| input.face_count() > 16_384) || self.face_count() > 16_384 || blocker.is_some_and(|b| b.face_count() > 16_384) diff --git a/crates/kernel/src/smlib_boolean.rs b/crates/kernel/src/smlib_boolean.rs index 719cacca5..87f41d0d3 100644 --- a/crates/kernel/src/smlib_boolean.rs +++ b/crates/kernel/src/smlib_boolean.rs @@ -4,7 +4,7 @@ //! ([`crate::history::History`]'s contract). A result SMLib's own check or the record's geometry //! check refuses is an error, never a body. -pub(crate) use smlib::boolean as smlib_boolean; +pub(crate) use smlib::{boolean as smlib_boolean, union_all as smlib_union_all}; mod smlib { use solidcraft_smlib::{BooleanOp, CheckLevel}; @@ -34,6 +34,54 @@ mod smlib { BoolOp::Intersect => BooleanOp::Intersect, }; let Some(r) = ta.boolean(&tb, kind).map_err(|e| failed("operation", e))? else { return Ok(None) }; + checked(&r, &[&sa, &sb])?; + let (body, or) = body_from_smlib_ordered(&r)?; + let history = match (oa, ob, or) { + (Some(oa), Some(ob), Some(or)) => r.history().map_err(|e| failed("history", e))?.history(&[oa, ob], &or).map(Some).unwrap_or_else(|e| { + log::debug!(target: "smlib", "boolean history: {e}"); + None + }), + _ => None, + }; + Ok(Some(with_history(body, history, a, b))) + } + + /// The union of `bodies` in one SMLib call, each tagged as its own operand, checked once: + /// the result's history is over `bodies` in order. At least one body. + pub(crate) fn union_all(bodies: &[&Body]) -> Result { + if bodies.len() > solidcraft_smlib::MAX_UNION_BREPS { + return Err(KernelError::Invalid(format!("a union takes at most {} bodies", solidcraft_smlib::MAX_UNION_BREPS))); + } + let mut operands = Vec::with_capacity(bodies.len()); + let mut tagged = Vec::with_capacity(bodies.len()); + let mut orders = Some(Vec::with_capacity(bodies.len())); + for (i, body) in bodies.iter().enumerate() { + body.require_brep("a union")?; + let (s, order) = smlib_body_ordered(body)?; + tagged.push(s.tagged(i).map_err(|e| failed("tag", e))?); + operands.push(s); + orders = orders.zip(order).map(|(mut v, o)| { + v.push(o); + v + }); + } + let refs: Vec<&solidcraft_smlib::Brep> = tagged.iter().collect(); + let r = solidcraft_smlib::Brep::union_all(&refs).map_err(|e| failed("operation", e))?; + let operand_refs: Vec<&solidcraft_smlib::Brep> = operands.iter().collect(); + checked(&r, &operand_refs)?; + let (body, or) = body_from_smlib_ordered(&r)?; + let history = match (orders, or) { + (Some(orders), Some(or)) => r.history().map_err(|e| failed("history", e))?.history(&orders, &or).map(Some).unwrap_or_else(|e| { + log::debug!(target: "smlib", "union history: {e}"); + None + }), + _ => None, + }; + Ok(body.with_checked_history(history, &record::counts(bodies))) + } + + /// An error unless SMLib's check accepts `r`, the result of combining `operands`. + fn checked(r: &solidcraft_smlib::Brep, operands: &[&solidcraft_smlib::Brep]) -> Result<()> { // Solids touching each other along an edge or at a vertex come back as one non-manifold // body, which the export splits into separate solids: SMLib's check is of those, imported // as given (its check of the touching arrangement itself refuses the radial order of @@ -46,29 +94,26 @@ mod smlib { let split = solidcraft_smlib::Brep::from_record(&record, true).map_err(|e| failed("the separate solids", e))?; split.check(CheckLevel::All).map_err(|e| failed("check", e))? }; - if !check.is_valid() { - // Whether an operand failed it already says whose the fault is. - let operands: Vec<&str> = [("the first operand", &sa), ("the second operand", &sb)] - .into_iter() - .filter(|(_, s)| s.check(CheckLevel::All).is_ok_and(|c| !c.is_valid())) - .map(|(name, _)| name) - .collect(); - let what = if operands.is_empty() { - "SMLib's check refuses the result".to_string() - } else { - format!("SMLib's check refuses the result ({} already fails it)", operands.join(" and ")) - }; - return Err(failed(&what, check)); + if check.is_valid() { + return Ok(()); } - let (body, or) = body_from_smlib_ordered(&r)?; - let history = match (oa, ob, or) { - (Some(oa), Some(ob), Some(or)) => r.history().map_err(|e| failed("history", e))?.history(&[oa, ob], &or).map(Some).unwrap_or_else(|e| { - log::debug!(target: "smlib", "boolean history: {e}"); - None - }), - _ => None, + // Whether an operand failed it already says whose the fault is. + let failing: Vec = operands + .iter() + .enumerate() + .filter(|(_, s)| s.check(CheckLevel::All).is_ok_and(|c| !c.is_valid())) + .map(|(i, _)| match (operands.len(), i) { + (2, 0) => "the first operand".to_string(), + (2, _) => "the second operand".to_string(), + _ => format!("operand {i}"), + }) + .collect(); + let what = if failing.is_empty() { + "SMLib's check refuses the result".to_string() + } else { + format!("SMLib's check refuses the result ({} already fails it)", failing.join(" and ")) }; - Ok(Some(with_history(body, history, a, b))) + Err(failed(&what, check)) } /// `body` with `history` where it describes `body` made from `a` and `b`. diff --git a/crates/smlib/src/ffi/ops.rs b/crates/smlib/src/ffi/ops.rs index 248086e4b..47c055c6b 100644 --- a/crates/smlib/src/ffi/ops.rs +++ b/crates/smlib/src/ffi/ops.rs @@ -1,4 +1,4 @@ -//! The operations block of `capi/include/smlib.h` (`smlib_boolean`, `smlib_boolean2d`, `smlib_fillet`, +//! The operations block of `capi/include/smlib.h` (`smlib_boolean`, `smlib_boolean_union_all`, `smlib_boolean2d`, `smlib_fillet`, //! `smlib_chamfer`, `smlib_blend`, `smlib_fillet_variable`, `smlib_chamfer_sides`, `smlib_shell`, `smlib_offset_faces`, //! `smlib_thicken`, `smlib_draft`, `smlib_merge_faces`, `smlib_brep_solid_count`, `smlib_imprint`; the fork's `capi/src/smlib_ops.cpp`), declared by //! hand. Part of the FFI boundary, like its parent: called only through @@ -48,6 +48,7 @@ type PickFn = unsafe extern "C" fn(*const RawBrep, *const f64, i64, f64, f64, *m #[cfg(feature = "native")] unsafe extern "C" { fn smlib_boolean(a: *const RawBrep, b: *const RawBrep, op: i32, out: *mut *mut RawBrep) -> i32; + fn smlib_boolean_union_all(breps: *const *const RawBrep, n: i64, out: *mut *mut RawBrep) -> i32; fn smlib_boolean2d(a: *const RawBrep, b: *const RawBrep, op: i32, out: *mut *mut RawBrep) -> i32; fn smlib_brep_solid_count(brep: *const RawBrep, out: *mut i64) -> i32; fn smlib_imprint(body: *const RawBrep, tool: *const RawBrep, out: *mut *mut RawBrep) -> i32; @@ -149,6 +150,13 @@ pub fn boolean(a: &Handle, b: &Handle, op: i32) -> Result { new_brep(|out| unsafe { smlib_boolean(a.raw(), b.raw(), op, out) }) } +#[cfg(feature = "native")] +pub fn boolean_union_all(breps: &[&Handle]) -> Result { + let raw: Vec<*const RawBrep> = breps.iter().map(|h| h.raw()).collect(); + let n = i64::try_from(raw.len()).map_err(|_| ERR_ARG)?; + new_brep(|out| unsafe { smlib_boolean_union_all(raw.as_ptr(), n, out) }) +} + #[cfg(feature = "native")] pub fn boolean2d(a: &Handle, b: &Handle, op: i32) -> Result { new_brep(|out| unsafe { smlib_boolean2d(a.raw(), b.raw(), op, out) }) @@ -315,6 +323,11 @@ pub fn boolean(_: &Handle, _: &Handle, _: i32) -> Result { Err(NOT_BUILT) } +#[cfg(not(feature = "native"))] +pub fn boolean_union_all(_: &[&Handle]) -> Result { + Err(NOT_BUILT) +} + #[cfg(not(feature = "native"))] pub fn boolean2d(_: &Handle, _: &Handle, _: i32) -> Result { Err(NOT_BUILT) diff --git a/crates/smlib/src/lib.rs b/crates/smlib/src/lib.rs index e832683ae..8b683d17f 100644 --- a/crates/smlib/src/lib.rs +++ b/crates/smlib/src/lib.rs @@ -31,7 +31,7 @@ pub mod trim; pub use check::{CheckLevel, CheckReport}; pub use measure::{MEASURE_ACCURACY, MassProperties}; -pub use ops::{Blend, BooleanOp, ChamferSecond, MAX_POINTS}; +pub use ops::{Blend, BooleanOp, ChamferSecond, MAX_POINTS, MAX_UNION_BREPS}; /// Why an SMLib call failed. #[derive(Clone, Debug, PartialEq)] diff --git a/crates/smlib/src/ops.rs b/crates/smlib/src/ops.rs index 866d65b89..0e18c4d71 100644 --- a/crates/smlib/src/ops.rs +++ b/crates/smlib/src/ops.rs @@ -41,6 +41,9 @@ pub enum ChamferSecond { Angle(f64), } +/// Most bodies [`Brep::union_all`] takes (the C API's limit). +pub const MAX_UNION_BREPS: usize = 100_000; + /// Most points one selection may hold (the C API's limit). pub const MAX_POINTS: usize = 4096; @@ -71,6 +74,19 @@ impl Brep { } } + /// The union of `breps` in one call: they are unioned pairwise, level by level, so none takes + /// part in more than about log2(n) unions. The result is as [`Brep::boolean`]'s; operands + /// tagged each with its own number ([`Brep::tagged`]) give a result whose [`Brep::history`] + /// names them. At least one body and at most [`MAX_UNION_BREPS`]. + pub fn union_all(breps: &[&Brep]) -> Result { + init()?; + if breps.is_empty() || breps.len() > MAX_UNION_BREPS { + return Err(error(ffi::ERR_ARG)); + } + let handles: Vec<&ffi::Handle> = breps.iter().map(|b| &b.0).collect(); + ffi::ops::boolean_union_all(&handles).map(Brep).map_err(error) + } + /// `self` and `other`, sheets of planar faces on one plane ([`Brep::planar_faces`]), combined /// as regions of that plane by `op`: `None` when the result is empty. The result's edges are /// the inputs' own curves, split where they cross. diff --git a/crates/step/src/topology.rs b/crates/step/src/topology.rs index 3a2c599e8..a0bd2a8b0 100644 --- a/crates/step/src/topology.rs +++ b/crates/step/src/topology.rs @@ -580,7 +580,7 @@ impl<'b, 'a> Builder<'b, 'a> { return Err(format!("face #{id}: {}", unsupported("a face without an edge loop"))); } let extent = self.extent(&loops)?; - let (surface, reversed) = swept::map_surface(&step_surface, &extent).map_err(|m| format!("face #{id}: {m}"))?; + let (surface, reversed) = swept::map_surface(&step_surface, &extent, self.tol).map_err(|m| format!("face #{id}: {m}"))?; // Loops relative to the record's natural normal: the face's normal is STEP's surface // normal when same_sense, and the record's is STEP's unless `reversed`. let sense = same_sense != reversed; diff --git a/crates/step/src/topology/swept.rs b/crates/step/src/topology/swept.rs index aee6ee9e8..b043aff46 100644 --- a/crates/step/src/topology/swept.rs +++ b/crates/step/src/topology/swept.rs @@ -482,10 +482,12 @@ fn offset(s: BSurface, d: f64) -> R { /// A face's surface as a schema surface, and whether the record's natural normal is opposite /// STEP's surface normal (an extruded circle or revolved circle read as a cylinder or torus, -/// whose natural normals point away from their axes); `ext` bounds swept surfaces' profiles. -pub(super) fn map_surface(s: &Surface, ext: &Extent) -> R<(BSurface, bool)> { +/// whose natural normals point away from their axes); `ext` bounds swept surfaces' profiles, +/// and a cone that stays within `tol` (the file's distance uncertainty) of its limit plane +/// over `ext` is read as that plane. +pub(super) fn map_surface(s: &Surface, ext: &Extent, tol: f64) -> R<(BSurface, bool)> { let mut reversed = false; - let s = map_surface_in(s, ext, 0, &mut reversed)?; + let s = map_surface_in(s, ext, tol, 0, &mut reversed)?; Ok((s, reversed)) } @@ -538,7 +540,7 @@ fn canonical(s: &Surface, reversed: &mut bool) -> Option { } } -fn map_surface_in(s: &Surface, ext: &Extent, depth: usize, reversed: &mut bool) -> R { +fn map_surface_in(s: &Surface, ext: &Extent, tol: f64, depth: usize, reversed: &mut bool) -> R { if depth > MAX_NESTING { return Err("surfaces nested too deeply".into()); } @@ -549,6 +551,9 @@ fn map_surface_in(s: &Surface, ext: &Extent, depth: usize, reversed: &mut bool) Surface::Plane { position } => BSurface::Plane { origin: position.origin, u_axis: position.ref_direction, v_axis: position.y() }, Surface::Cylinder { position, radius } => BSurface::Cylinder { frame: frame(position), radius: *radius }, Surface::Cone { position, radius, semi_angle } => { + if let Some(plane) = flat_cone(position, *radius, *semi_angle, ext, tol, reversed) { + return Ok(plane); + } if !(*radius >= 0.0) || !(semi_angle.abs() > 1e-12 && semi_angle.abs() < FRAC_PI_2) { return Err(unsupported(format!("a cone of radius {radius} and semi-angle {semi_angle}"))); } @@ -563,17 +568,48 @@ fn map_surface_in(s: &Surface, ext: &Extent, depth: usize, reversed: &mut bool) } Surface::DegenerateTorus { .. } => return Err(unsupported("DEGENERATE_TOROIDAL_SURFACE")), Surface::BSpline(b) => super::map_bspline_surface(b)?, - Surface::RectangularTrimmed { basis, .. } => map_surface_in(basis, ext, depth + 1, reversed)?, + Surface::RectangularTrimmed { basis, .. } => map_surface_in(basis, ext, tol, depth + 1, reversed)?, Surface::Revolution { profile, axis } => revolution(profile, axis, ext)?, Surface::Extrusion { profile, direction, magnitude } => extrusion(profile, *direction, *magnitude, ext)?, Surface::Offset { basis, distance, .. } => { // Along STEP's normal: the record's, or its opposite. - let b = map_surface_in(basis, ext, depth + 1, reversed)?; + let b = map_surface_in(basis, ext, tol, depth + 1, reversed)?; offset(b, if *reversed { -*distance } else { *distance })? } }) } +/// A cone written for a plane (a semi-angle a whisker short of 90°, as exporters write one) as +/// that plane: the plane through the placement's origin across its axis, the cone's limit as +/// its angle opens to 90°. The cone's height above it is `(rho - radius) cot a` at parameter +/// radius `rho`, monotone in `rho` away from the apex: over the face it stays within the +/// heights of the boundary points and, should the face hold the axis, the apex's +/// (`radius cot a`). `None` unless that deviation is within `tol`. STEP's normal there is +/// `-rho tan a` along the axis, so the record's (the axis) is opposite STEP's where +/// `rho tan a > 0`. +fn flat_cone(position: &Placement, radius: f64, semi_angle: f64, ext: &Extent, tol: f64, reversed: &mut bool) -> Option { + let (o, k) = (v3(position.origin), v3(position.axis).normalized()?); + let cot = semi_angle.cos() / semi_angle.sin(); + let mut deviation = (radius * cot).abs(); + let mut widest: Option<(f64, f64)> = None; + for p in &ext.points { + let d = *p - o; + let h = d.dot(k); + deviation = deviation.max(h.abs()); + let r = (d - k * h).len(); + if widest.is_none_or(|(w, _)| r > w) { + widest = Some((r, h)); + } + } + let (_, h) = widest?; + if !(deviation <= tol) { + return None; + } + // The parameter radius at the widest boundary point (it keeps one sign off the apex). + *reversed ^= (radius + h * semi_angle.tan()) * semi_angle.tan() > 0.0; + Some(BSurface::Plane { origin: position.origin, u_axis: position.ref_direction, v_axis: position.y() }) +} + /// The STEP parameters of `ps` and `pe` on a hyperbola or parabola. pub(super) fn open_conic_params(c: &Curve, ps: P3, pe: P3) -> R<(f64, f64)> { match (planar_param(c, v3(ps)), planar_param(c, v3(pe))) { diff --git a/crates/step/src/topology_tests.rs b/crates/step/src/topology_tests.rs index f4e166c2d..e5ba31def 100644 --- a/crates/step/src/topology_tests.rs +++ b/crates/step/src/topology_tests.rs @@ -906,7 +906,7 @@ fn same_surface(data: &str, us: (f64, f64), vs: (f64, f64)) -> BSurface { .flat_map(|i| (0..=n).map(move |j| (us.0 + (us.1 - us.0) * i as f64 / n as f64, vs.0 + (vs.1 - vs.0) * j as f64 / n as f64))) .collect(); let ext = swept::Extent { points: grid.iter().map(|&(u, v)| v3(s.point(u, v).unwrap())).collect(), seam: Vec::new() }; - let (record, reversed) = swept::map_surface(&s, &ext).unwrap(); + let (record, reversed) = swept::map_surface(&s, &ext, DEFAULT_TOLERANCE).unwrap(); record.natural(); let eval = SurfaceEval::new(&record).unwrap(); for &(u, v) in &grid { @@ -1003,7 +1003,7 @@ fn swept_and_offset_surfaces_are_the_files_own() { "#1=CARTESIAN_POINT('',(0.,0.,0.));#2=DIRECTION('',(0.,0.,1.));#3=DIRECTION('',(1.,0.,0.));#4=AXIS2_PLACEMENT_3D('',#1,#2,#3);{data}\n" )); let s = crate::read::Reader::new(&exch, crate::read::Units::default()).surface(10).unwrap(); - let e = swept::map_surface(&s, &ext).unwrap_err(); + let e = swept::map_surface(&s, &ext, DEFAULT_TOLERANCE).unwrap_err(); assert!(e.contains(why), "{data}: {e}"); } }