From f7c8ff94ff59d821deb258827a14e4b01c5da247 Mon Sep 17 00:00:00 2001 From: Brett Lawson Date: Thu, 29 Oct 2026 01:14:52 +0100 Subject: [PATCH] Offset: face picks on the working copy read its proven owners (solidcore#1440) The working copy every operation makes (copy_of: api_brep_copy naming its objects in their own key domain) has no naming scheme of its own, so BrepIdentity::of_brep gave it the arena's identities, which name none of its geometry owners: every face's closest-point solve failed with InvalidInput ("edge owner is not in source B-rep"). pick_faces and leaves_cavity now key the live view by BrepQuery::of_brep(..).effective_identity(), which reads the owners the copy records. Not a solidcore defect. The failure stayed hidden because answer() turned every solidcore error but Unported into "no answer". The capi skips a query only when it returns a status other than SM_SUCCESS, so answer() (now in core.rs) skips only SolidError::Upstream and SolidError::Nlib and fails on anything else. The same rule replaces the swallowing in convert.rs (ClassifyEdgeCurve, the plane map, AnalyticOfNurbs) and sweep.rs (sm_DraftHasCorner's angle). Tests: faces_are_picked_on_the_box_and_on_its_working_copy (closed-form distances on the body, on copy_of's copy, and by the maintainers' usage; the copy under the arena's identities is an error) and a_solidcore_error_in_a_pick_is_an_error. The #1440 offset and sweep cases run; shell_cylinder_open_top waits on a stray rim vertex in the shell. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SdcgExNEwfR9CX2RAzp2Pt --- crates/smlib/src/core.rs | 13 +++ crates/smlib/src/core/blend.rs | 15 +--- crates/smlib/src/core/boolean.rs | 2 +- crates/smlib/src/core/convert.rs | 124 ++++++++++++++++++-------- crates/smlib/src/core/offset.rs | 24 +++-- crates/smlib/src/core/offset_tests.rs | 117 +++++++++++++++++++++--- crates/smlib/src/core/sweep.rs | 16 ++-- crates/smlib/src/core/sweep_tests.rs | 2 - 8 files changed, 233 insertions(+), 80 deletions(-) diff --git a/crates/smlib/src/core.rs b/crates/smlib/src/core.rs index 2c98012de..2b3d77eee 100644 --- a/crates/smlib/src/core.rs +++ b/crates/smlib/src/core.rs @@ -160,6 +160,19 @@ pub(crate) fn run(call: &'static str, f: impl FnOnce(&mut Kernel) -> std::res } } +/// A call the capi checks for `SM_SUCCESS`, treating any other status as no answer: an SMLib +/// status (solidcore's [`SolidError::Upstream`](solidcore::SolidError::Upstream), or NLib's +/// [`SolidError::Nlib`](solidcore::SolidError::Nlib)) is `None`. Every other solidcore error +/// (unported code, invalid input to an adapter, a missing record...) is not a status the C++ +/// path returns, so it fails the call instead of hiding as a skipped entity. +pub(crate) fn answer(r: std::result::Result) -> std::result::Result, solidcore::SolidError> { + match r { + Ok(v) => Ok(Some(v)), + Err(solidcore::SolidError::Upstream { .. } | solidcore::SolidError::Nlib { .. }) => Ok(None), + Err(e) => Err(e), + } +} + /// Runs `f` on the kernel and `body`, locking the kernel first. pub(crate) fn with_body( call: &'static str, diff --git a/crates/smlib/src/core/blend.rs b/crates/smlib/src/core/blend.rs index 161c45f46..7158660e1 100644 --- a/crates/smlib/src/core/blend.rs +++ b/crates/smlib/src/core/blend.rs @@ -48,7 +48,7 @@ use solidcore::topology::face::p2 as face_p2; use solidcore::topology::{Brep, EdgeId, EdgeuseId, FaceId, FaceuseId, VertexId, edge, vertex}; use super::boolean::copy_of; -use super::{Body, run}; +use super::{Body, answer, run}; use crate::{Blend, ChamferSecond, Error, MAX_POINTS, Result}; /// The capi's statuses as SolidCraft errors: an operation's own result. @@ -97,8 +97,8 @@ pub(super) enum Miss { /// `smlib_pick::pick`: the entity nearest each point, each once, with the index of the point that /// first picked it. A point picks none when the nearest is farther than `tol`, and is ambiguous /// when the second nearest is within `tol` too and nearer than the first by at most `model_tol`. -/// An entity whose distance cannot be measured is skipped, as the capi skips a failed query -/// (solidcore's refusal of unported code is not skipped: it fails the pick). +/// An entity whose distance query returns a status other than success is skipped, as the capi +/// skips it ([`answer`]); any other solidcore error fails the pick. pub(super) fn pick( all: &[T], points: &[[f64; 3]], @@ -137,15 +137,6 @@ pub(super) fn pick( Ok(Ok((picked, first))) } -/// A query's failure the capi treats as no answer; solidcore's unported code still fails. -pub(super) fn answer(r: solidcore::Result) -> solidcore::Result> { - match r { - Ok(v) => Ok(Some(v)), - Err(e) if e.is_unported() => Err(e), - Err(_) => Ok(None), - } -} - /// `pick_edges` (`edge_distance`: `SmApiEdgeClosestPoint`). fn pick_edges(k: &Kernel, b: &Brep, points: &[[f64; 3]], tol: f64) -> solidcore::Result, Vec), Miss>> { let all = brep_p1::edges(b, None)?; diff --git a/crates/smlib/src/core/boolean.rs b/crates/smlib/src/core/boolean.rs index 021b9d48a..58230ac7e 100644 --- a/crates/smlib/src/core/boolean.rs +++ b/crates/smlib/src/core/boolean.rs @@ -47,7 +47,7 @@ fn named(entity: EntityRef, domain: u64) -> ObjectRef { /// `copy_of` (smlib_ops.cpp, smlib_imprint.cpp): `SmApiBrepCopy`, a copy that owns its geometry. /// A plain `Clone` is not one: its geometry keeps the source's owners. Copy `n` (from 1) names /// its objects in key domain `n`. -pub(super) fn copy_of(k: &mut Kernel, b: &Brep, n: u64) -> SolidResult { +pub(crate) fn copy_of(k: &mut Kernel, b: &Brep, n: u64) -> SolidResult { let target = move |e| named(e, n.saturating_mul(100_000_000)); let mut state = p2::ArenaNotifyState::new(&Brep::new()); let mut env = state.env(None); diff --git a/crates/smlib/src/core/convert.rs b/crates/smlib/src/core/convert.rs index 536ef5370..33aaf596a 100644 --- a/crates/smlib/src/core/convert.rs +++ b/crates/smlib/src/core/convert.rs @@ -55,7 +55,7 @@ use crate::flat::*; use crate::import::Arrays; use crate::{Error, Result}; -use super::{Body, run, with_body}; +use super::{Body, answer, run, with_body}; // ---- shared ------------------------------------------------------------------------------------ @@ -415,18 +415,34 @@ fn edge_curve_as_bspline<'c>(k: &Kernel, c: &'c Curve, ivl: &Extent1d, approx_to /// `center + s * axis`), circle or ellipse (over `[d_min, d_max]` degrees, its NURBS parameter /// then set to that interval with its notification, `EditParameterization`). fn build_analytic_edge_curve(k: &Kernel, ty: i64, d_min: f64, d_max: f64, center: Point3, axis: Vec3, refd: Vec3, r1: f64, r2: f64) -> Result { + analytic_edge_curve(k, ty, d_min, d_max, center, axis, refd, r1, r2).map_err(|(call, e)| sc(call)(e)) +} + +/// [`build_analytic_edge_curve`] with solidcore's own error, and the call that gave it. +#[allow(clippy::too_many_arguments)] // BuildAnalyticEdgeCurve's +fn analytic_edge_curve( + k: &Kernel, + ty: i64, + d_min: f64, + d_max: f64, + center: Point3, + axis: Vec3, + refd: Vec3, + r1: f64, + r2: f64, +) -> std::result::Result { if ty == CURVE_LINE_I { return Ok(Curve::from(Line::create_canonical(center, axis))); } let mut placement = Axis2Placement::default(); - placement.set_canonical(center, refd, axis.cross(refd)).map_err(sc("SmAxis2Placement::SetCanonical"))?; + placement.set_canonical(center, refd, axis.cross(refd)).map_err(|e| ("SmAxis2Placement::SetCanonical", e))?; let degrees = Extent1d::from_min_max(d_min, d_max); let mut e = if ty == CURVE_CIRCLE_I { - Ellipse::create_canonical_circle(k, &placement, r1, Some(°rees), None).map_err(sc("SmCircle::CreateCanonical"))? + Ellipse::create_canonical_circle(k, &placement, r1, Some(°rees), None).map_err(|e| ("SmCircle::CreateCanonical", e))? } else { - Ellipse::create_canonical(k, &placement, r1, r2, Some(°rees), None).map_err(sc("SmEllipse::CreateCanonical"))? + Ellipse::create_canonical(k, &placement, r1, r2, Some(°rees), None).map_err(|e| ("SmEllipse::CreateCanonical", e))? }; - e.edit_parameterization(k, °rees, true, None).map_err(sc("SmEllipse::EditParameterization"))?; + e.edit_parameterization(k, °rees, true, None).map_err(|e| ("SmEllipse::EditParameterization", e))?; Ok(Curve::from(e)) } @@ -466,12 +482,15 @@ const NURBS_EXPORT: EdgeExport = EdgeExport { /// `ClassifyEdgeCurve`: a circle, ellipse or line kept as its kind when the curve the import /// builds from it ([`build_analytic_edge_curve`]) matches it pointwise at the edge's ends and /// along the STEP parameter; anything else NURBS. A curve whose STEP parameter runs against its -/// NURBS one goes with its axis reversed and its range negated. -fn classify_edge_curve(k: &Kernel, c: Option<&Curve>, ivl: &Extent1d) -> EdgeExport { - c.and_then(|c| classify(k, c, ivl)).unwrap_or(NURBS_EXPORT) +/// NURBS one goes with its axis reversed and its range negated. A call that returns a status +/// other than success makes the edge NURBS, as there ([`answer`]); any other solidcore error +/// fails the export. +fn classify_edge_curve(k: &Kernel, c: Option<&Curve>, ivl: &Extent1d) -> Result { + let Some(c) = c else { return Ok(NURBS_EXPORT) }; + Ok(classify(k, c, ivl).map_err(sc("ClassifyEdgeCurve"))?.unwrap_or(NURBS_EXPORT)) } -fn classify(k: &Kernel, c: &Curve, ivl: &Extent1d) -> Option { +fn classify(k: &Kernel, c: &Curve, ivl: &Extent1d) -> std::result::Result, SolidError> { let mut e = NURBS_EXPORT; match c.kind() { CurveKind::Ellipse(el) => { @@ -489,12 +508,18 @@ fn classify(k: &Kernel, c: &Curve, ivl: &Extent1d) -> Option { e.center = can.point; e.axis = can.vector; } - _ => return None, + _ => return Ok(None), } - let mut s0 = c.convert_t_from_nurbs_to_step(k, ivl.min()).ok()?; - let mut s1 = c.convert_t_from_nurbs_to_step(k, ivl.max()).ok()?; + let mut s0 = { + let Some(x) = answer(c.convert_t_from_nurbs_to_step(k, ivl.min()))? else { return Ok(None) }; + x + }; + let mut s1 = { + let Some(x) = answer(c.convert_t_from_nurbs_to_step(k, ivl.max()))? else { return Ok(None) }; + x + }; if !s0.is_finite() || !s1.is_finite() { - return None; + return Ok(None); } // sNew = sign * sOld + shift let (mut sign, mut shift) = (1.0, 0.0); @@ -505,18 +530,18 @@ fn classify(k: &Kernel, c: &Curve, ivl: &Extent1d) -> Option { e.axis = Vec3::new(-e.axis.x, -e.axis.y, -e.axis.z); } if !(s1 > s0) { - return None; + return Ok(None); } if e.ty == CURVE_LINE_I { if s0.abs() > INFINITE_PARAMETER || s1.abs() > INFINITE_PARAMETER { - return None; + return Ok(None); } (e.lo, e.sm_lo, e.hi, e.sm_hi) = (s0, s0, s1, s1); } else { // SmCircle/SmEllipse::CreateCanonical take intervals within [-360, 360] degrees. (Not // in the C++: angles past a million degrees are refused, bounding the loops below.) if s1 - s0 > 360.0 + 1e-9 || s0.abs() > 1.0e6 || s1.abs() > 1.0e6 { - return None; + return Ok(None); } while s1 > 360.0 + 1e-9 { s0 -= 360.0; @@ -529,7 +554,7 @@ fn classify(k: &Kernel, c: &Curve, ivl: &Extent1d) -> Option { shift += 360.0; } if s1 > 360.0 + 1e-9 { - return None; + return Ok(None); } e.lo = deg2rad(s0); e.hi = deg2rad(s1); @@ -538,9 +563,20 @@ fn classify(k: &Kernel, c: &Curve, ivl: &Extent1d) -> Option { e.sm_hi = radians_to_smlib_degrees(e.hi); } - let built = build_analytic_edge_curve(k, e.ty, e.sm_lo, e.sm_hi, e.center, e.axis, e.refd, e.r1, e.r2).ok()?; - let a = c.evaluate_point(k, ivl.min()).ok()?; - let b = c.evaluate_point(k, ivl.max()).ok()?; + let built = { + let Some(x) = answer(analytic_edge_curve(k, e.ty, e.sm_lo, e.sm_hi, e.center, e.axis, e.refd, e.r1, e.r2).map_err(|(_, e)| e))? else { + return Ok(None); + }; + x + }; + let a = { + let Some(x) = answer(c.evaluate_point(k, ivl.min()))? else { return Ok(None) }; + x + }; + let b = { + let Some(x) = answer(c.evaluate_point(k, ivl.max()))? else { return Ok(None) }; + x + }; let tol = 1e-9 * (1.0 + e.r1 + e.r2 + a.max_dimension() + b.max_dimension()); let mut affine = true; for step in 0..=8 { @@ -548,24 +584,42 @@ fn classify(k: &Kernel, c: &Curve, ivl: &Extent1d) -> Option { // the same point by the STEP parameter of each curve let s_new = e.sm_lo + f * (e.sm_hi - e.sm_lo); let s_old = (s_new - shift) * sign; - let t_old = c.convert_t_from_step_to_nurbs(k, s_old).ok()?; - let t_new = built.convert_t_from_step_to_nurbs(k, s_new).ok()?; - let p_old = c.evaluate_point(k, t_old).ok()?; - let p_new = built.evaluate_point(k, t_new).ok()?; + let t_old = { + let Some(x) = answer(c.convert_t_from_step_to_nurbs(k, s_old))? else { return Ok(None) }; + x + }; + let t_new = { + let Some(x) = answer(built.convert_t_from_step_to_nurbs(k, s_new))? else { return Ok(None) }; + x + }; + let p_old = { + let Some(x) = answer(c.evaluate_point(k, t_old))? else { return Ok(None) }; + x + }; + let p_new = { + let Some(x) = answer(built.evaluate_point(k, t_new))? else { return Ok(None) }; + x + }; if !(p_old.distance(p_new) <= tol) { - return None; + return Ok(None); } // the same point by each edge's NURBS parameter, affinely matched - let q_old = c.evaluate_point(k, ivl.min() + f * (ivl.max() - ivl.min())).ok()?; - let q_new = built.evaluate_point(k, e.sm_lo + f * (e.sm_hi - e.sm_lo)).ok()?; + let q_old = { + let Some(x) = answer(c.evaluate_point(k, ivl.min() + f * (ivl.max() - ivl.min())))? else { return Ok(None) }; + x + }; + let q_new = { + let Some(x) = answer(built.evaluate_point(k, e.sm_lo + f * (e.sm_hi - e.sm_lo)))? else { return Ok(None) }; + x + }; let d = q_old.distance(q_new); if (step == 0 || step == 8) && !(d <= tol) { - return None; // the ends must match exactly as the edge's vertices do + return Ok(None); // the ends must match exactly as the edge's vertices do } affine = affine && d <= tol; } e.affine = affine; - Some(e) + Ok(Some(e)) } /// `WriteEdgeCurve`: one edge's kind, range and geometry. A circle or ellipse also goes with its @@ -752,7 +806,7 @@ fn flat_from_brep(k: &mut Kernel, b: &mut Brep) -> Result { let edge_curve = |i: usize| -> Result> { edge::curve(b, get(&edge_ids, i)?).map_err(sc("SmEdge::GetCurve")) }; let mut exports = Vec::with_capacity(bd.edges.len()); for (i, ed) in bd.edges.iter().enumerate() { - exports.push(classify_edge_curve(k, edge_curve(i)?, &ed.interval)); + exports.push(classify_edge_curve(k, edge_curve(i)?, &ed.interval)?); } // Regions @@ -826,9 +880,9 @@ fn flat_from_brep(k: &mut Kernel, b: &mut Brep) -> Result { let mut q = [Point2::new(0.0, 0.0); 3]; let mut ok = true; for (qk, at) in q.iter_mut().zip([Point2::new(0.0, 0.0), Point2::new(1.0, 0.0), Point2::new(0.0, 1.0)]) { - match surface.convert_uv_from_nurbs_to_step(k, at) { - Ok(st) => *qk = Point2::new(st.x * scale.x, st.y * scale.y), - Err(_) => { + match answer(surface.convert_uv_from_nurbs_to_step(k, at)).map_err(sc("SmSurface::ConvertUVFromNURBSToSTEP"))? { + Some(st) => *qk = Point2::new(st.x * scale.x, st.y * scale.y), + None => { ok = false; break; } @@ -1879,9 +1933,9 @@ fn same_nurbs(a: &NurbSurface, b: &NurbSurface, tol: f64) -> bool { /// only when its NURBS is `nurbs` (the face's trims are in its parameters). fn analytic_of_nurbs(k: &Kernel, nurbs: &BSplineSurface, ty: i64, tol: f64) -> Result> { let found: Option = if ty == SURFACE_CONE_I { - Cone::is_nurb_surface_cone(k, nurbs, 1.0).ok().flatten().map(Surface::from) + answer(Cone::is_nurb_surface_cone(k, nurbs, 1.0)).map_err(sc("SmCone::IsNurbSurfaceCone"))?.flatten().map(Surface::from) } else if ty == SURFACE_SPHERE_I { - Sphere::is_nurb_surface_sphere(k, nurbs, 1.0).ok().flatten().map(Surface::from) + answer(Sphere::is_nurb_surface_sphere(k, nurbs, 1.0)).map_err(sc("SmSphere::IsNurbSurfaceSphere"))?.flatten().map(Surface::from) } else if ty == SURFACE_CYLINDER_I { return Err(unported("SmCylinder::IsNurbSurfaceCylinder")); } else if ty == SURFACE_TORUS_I { diff --git a/crates/smlib/src/core/offset.rs b/crates/smlib/src/core/offset.rs index c897ab854..aae52abd8 100644 --- a/crates/smlib/src/core/offset.rs +++ b/crates/smlib/src/core/offset.rs @@ -28,7 +28,7 @@ use solidcore::offset::offset_executive::p2::{ OffsetNotifications, OffsetOptions, ShellCopyIdentities, ShellOptions, api_offset_brep_full, api_shell_brep_full, }; use solidcore::query::api_queries::{BrepRef, face_bounding_box, face_classify_uv, face_closest_point_in_shape, face_internal_point}; -use solidcore::query::brep::{BrepIdentity, LiveBrepObjects}; +use solidcore::query::brep::{BrepIdentity, BrepQuery, LiveBrepObjects}; use solidcore::surface::surface::SurfaceKind; use solidcore::sweep::topology_sweep::store::SweepIdentities; use solidcore::topology::brep::{p1 as brep_p1, p2 as brep_p2, p3 as brep_p3}; @@ -36,8 +36,8 @@ use solidcore::topology::face::p2 as face_p2; use solidcore::topology::topology::{NotifyRecords, Topology}; use solidcore::topology::{Brep, BrepId, EdgeId, FaceId, FaceuseId, RegionId}; -use super::Body; -use super::blend::{Miss, answer, on_copy, p3, pick, points_ok, status as blend_status, tolerance_ok}; +use super::blend::{Miss, on_copy, p3, pick, points_ok, status as blend_status, tolerance_ok}; +use super::{Body, answer}; use crate::{Error, Result}; /// The capi's statuses as SolidCraft errors: an operation's own result. @@ -116,13 +116,17 @@ impl FaceSet { } } -/// The live view of `b` the closest-point solves read. -fn live<'a>(b: &'a mut Brep, identity: &'a BrepIdentity<'static>) -> solidcore::Result> { +/// The live view of `b` the closest-point solves read, under `identity`: `query`'s effective +/// identity ([`BrepQuery::effective_identity`]). A working copy (`copy_of`) has no naming +/// scheme of its own, so `BrepIdentity::of_brep` gives it the arena's identities, which name +/// none of its geometry owners (`copy_of`'s keys, recorded on the copy as proven owners): every +/// face and edge then drops out of a solve (solidcore#1440 was this). +fn live<'a, 'i>(b: &'a mut Brep, identity: &'a BrepIdentity<'i>) -> solidcore::Result> { LiveBrepObjects::new(b, identity, None) } -/// `pick_faces` (`face_distance`: `SmApiFaceClosestPoint`; a face whose distance cannot be -/// measured is skipped). +/// `pick_faces` (`face_distance`: `SmApiFaceClosestPoint`; a face whose query returns a status +/// other than success is skipped, [`answer`]). pub(super) fn pick_faces(k: &mut Kernel, b: &mut Brep, points: &[[f64; 3]], tol: f64) -> solidcore::Result, Miss>> { let all = brep_p1::faces(b, None)?; let model_tol = b.tolerance(); @@ -130,7 +134,8 @@ pub(super) fn pick_faces(k: &mut Kernel, b: &mut Brep, points: &[[f64; 3]], tol: for &f in &all { shapes.push(answer(Shape::new(k, &(ONE, &*b), &[], &[(ONE, f)], &[], &[]))?); } - let identity = BrepIdentity::of_brep(b); + let query = BrepQuery::of_brep(b); + let identity = query.effective_identity(); let objects = live(b, &identity)?; let k: &Kernel = k; let indices: Vec = (0..all.len()).collect(); @@ -214,7 +219,8 @@ fn leaves_cavity(k: &mut Kernel, b: &mut Brep, open: &[FaceId], wall: f64) -> so } } } - let identity = BrepIdentity::of_brep(b); + let query = BrepQuery::of_brep(b); + let identity = query.effective_identity(); let objects = live(b, &identity)?; let k: &Kernel = k; // A step of `h` inward from a sample ends at a ball's centre when no face is nearer to it diff --git a/crates/smlib/src/core/offset_tests.rs b/crates/smlib/src/core/offset_tests.rs index 4522f16d4..a3cdde5b2 100644 --- a/crates/smlib/src/core/offset_tests.rs +++ b/crates/smlib/src/core/offset_tests.rs @@ -376,26 +376,26 @@ macro_rules! cases { } cases!( - shell_box_open_top: ignore = "solidcore#1440: the topology point solve misses faces, so SmApiFaceClosestPoint picks no face (solidcore#1440)", - shell_box_closed: ignore = "solidcore#1440: the topology point solve misses faces, so leaves_cavity finds no cavity (solidcore#1440)", + shell_box_open_top, + shell_box_closed, shell_box_closed_outward, - shell_box_outward: ignore = "solidcore#1440: the topology point solve misses faces, so SmApiFaceClosestPoint picks no face (solidcore#1440)", - shell_cylinder_open_top: ignore = "solidcore#1440: the topology point solve misses faces, so SmApiFaceClosestPoint picks no face (solidcore#1440)", - shell_too_thick: ignore = "solidcore#1440: the topology point solve misses faces, so SmApiFaceClosestPoint picks no face (solidcore#1440)", - shell_walls_touch: ignore = "solidcore#1440: no face pick (solidcore#1440); walls that meet are 1027, not WALLS_TOUCH until fork a759622 is ported (solidcore#1442)", - shell_pick_near_nothing: ignore = "solidcore#1440: the topology point solve misses faces, so SmApiFaceClosestPoint picks no face (solidcore#1440)", - shell_pick_ambiguous: ignore = "solidcore#1440: the topology point solve misses faces, so SmApiFaceClosestPoint picks no face (solidcore#1440)", + shell_box_outward, + shell_cylinder_open_top: ignore = "the shell leaves the inner rim circle split at a vertex 1e-5 off it and the inner floor circle a spline (7 edges, 5 vertices; C++ 6, 4): the volume is 3.5e-7 off; cause not yet found", + shell_too_thick, + shell_walls_touch: ignore = "walls that meet are 1027, not WALLS_TOUCH until fork a759622 is ported (solidcore#1442)", + shell_pick_near_nothing, + shell_pick_ambiguous, thicken_plate, thicken_plate_symmetric, thicken_a_solid, offset_sheet_plate, offset_sheet_quarter_cylinder: ignore = "solidcore#1441: an offset surface does not export, no SmSurface::ApproximateSurface (solidcore#1441)", offset_sheet_a_solid, - offset_faces_top_out: ignore = "solidcore#1440: no face pick (solidcore#1440); no SmOffsetFacesExecutive, fork a96ce9f (solidcore#1060)", - offset_faces_through: ignore = "solidcore#1440: the topology point solve misses faces, so SmApiFaceClosestPoint picks no face (solidcore#1440)", - draft_box_sides: ignore = "solidcore#1440: no face pick (solidcore#1440); no SmBrep::LocalOperation (solidcore PR #1427)", - draft_a_curved_face: ignore = "solidcore#1440: the topology point solve misses faces, so SmApiFaceClosestPoint picks no face (solidcore#1440)", - draft_a_face_across_the_pull: ignore = "solidcore#1440: the topology point solve misses faces, so SmApiFaceClosestPoint picks no face (solidcore#1440)", + offset_faces_top_out: ignore = "no SmOffsetFacesExecutive, fork a96ce9f (solidcore#1060)", + offset_faces_through, + draft_box_sides: ignore = "no SmBrep::LocalOperation (solidcore PR #1427)", + draft_a_curved_face, + draft_a_face_across_the_pull, ); /// The capi's argument checks, before any kernel call. @@ -429,3 +429,94 @@ fn the_body_stays_as_it_was() { assert_eq!(r.0, [6, 12, 8]); assert!(rel(r.1, ABC) < 1e-12, "{}", r.1); } + +/// The distance from `p` to each face of `b` (`SmApiFaceClosestPoint`), under `identity`. +fn face_distances( + k: &mut solidcore::kernel::Kernel, + b: &mut solidcore::topology::Brep, + identity: &solidcore::query::brep::BrepIdentity<'_>, + p: Vec3, +) -> solidcore::Result> { + use solidcore::geom::object::Shape as Sh; + use solidcore::query::api_queries::face_closest_point_in_shape; + use solidcore::query::brep::LiveBrepObjects; + use solidcore::topology::BrepId; + let one = BrepId::from_index(0); + let mut out = Vec::new(); + for f in solidcore::topology::brep::p1::faces(b, None)? { + let shape = Sh::new(k, &(one, &*b), &[], &[(one, f)], &[], &[])?; + let objects = LiveBrepObjects::new(b, identity, None)?; + let c = face_closest_point_in_shape(k, &shape, &objects, (one, f), p)?; + out.push((c.distance, c.point)); + } + Ok(out) +} + +/// The closed form for (15, 10, 20) above the 30 x 20 x 10 box at the origin, face by face of +/// `create_box`: bottom 20, top 10, the x sides sqrt(15^2 + 10^2), the y sides sqrt(10^2 + 10^2). +fn box_face_distances_are_exact(what: &str, d: &[(f64, Vec3)]) { + let want = [20.0, 10.0, 325f64.sqrt(), 325f64.sqrt(), 200f64.sqrt(), 200f64.sqrt()]; + assert_eq!(d.len(), want.len(), "{what}: faces"); + for (i, (&(got, _), want)) in d.iter().zip(want).enumerate() { + assert!((got - want).abs() < 1e-9, "{what}: face {i} at {got}, want {want}"); + } + let top = d[1].1; + assert!((top.x - 15.0).abs() < 1e-9 && (top.y - 10.0).abs() < 1e-9 && (top.z - 10.0).abs() < 1e-9, "{what}: top {top:?}"); +} + +/// Picking faces on a solidcore box: on the body itself, on the working copy every operation +/// makes (`copy_of`), and by solidcore's recommended usage, each face's distance is the closed +/// form and the top face is picked. The copy names its geometry owners in its own key domain +/// with no naming scheme of its own, so the body's identities (`BrepIdentity::of_brep`: the +/// arena's) name none of them; the copy's proven owners (`BrepQuery::effective_identity`) do +/// (solidcore#1440 was this). Under the arena's identities the solve fails, and the failure is +/// an error, not a skipped face. +#[test] +fn faces_are_picked_on_the_box_and_on_its_working_copy() { + use solidcore::SolidError; + use solidcore::query::brep::{BrepIdentity, BrepQuery}; + let p = Vec3::new(15.0, 10.0, 20.0); + let on_top = [[15.0, 10.0, 10.0]]; + run("pick", |k| { + let mut b = solidcore::primitive::api_primitives::create_box(k, Vec3::new(0.0, 0.0, 0.0), 30.0, 20.0, 10.0)?; + let mut w = super::boolean::copy_of(k, &b, 1)?; + let mut faces = Vec::new(); + for (what, x) in [("the body", &mut b), ("its copy", &mut w)] { + let query = BrepQuery::of_brep(x); + let identity = query.effective_identity(); + box_face_distances_are_exact(what, &face_distances(k, x, &identity, p)?); + let picked = super::offset::pick_faces(k, x, &on_top, TOL)?; + faces.push(picked.ok()); + } + assert!(faces[0].as_ref().is_some_and(|f| f.len() == 1), "the body: {faces:?}"); + assert_eq!(faces[0], faces[1], "the body and its copy pick the same face"); + // The maintainers' usage: the body itself, keyed by its naming scheme. + let body = BrepIdentity::of_brep(&b); + box_face_distances_are_exact("of_brep on the body", &face_distances(k, &mut b, &body, p)?); + // The copy under the arena's identities: no face's geometry owner resolves. + let arena = BrepIdentity::of_brep(&w); + match face_distances(k, &mut w, &arena, p) { + Err(SolidError::InvalidInput { .. }) => {} + other => panic!("the copy under the arena's identities: {other:?}"), + } + Ok(()) + }) + .unwrap(); +} + +/// A pick skips an entity whose query returns an SMLib status, as the capi skips any status +/// other than `SM_SUCCESS`; any other solidcore error fails the pick. +#[test] +fn a_solidcore_error_in_a_pick_is_an_error() { + use super::answer; + use super::blend::pick; + use solidcore::SolidError; + let all = [0usize, 1]; + let points = [[0.0; 3]]; + let status = pick(&all, &points, 1.0, 1e-6, |i, _| answer(if i == 0 { Err(SolidError::sm_err("q")) } else { Ok(0.5) })); + assert_eq!(status.unwrap().unwrap().0, vec![1], "a status skips the entity"); + let other = pick(&all, &points, 1.0, 1e-6, |i, _| answer(if i == 0 { Err(SolidError::invalid_input("q", "owner")) } else { Ok(0.5) })); + assert!(matches!(other, Err(SolidError::InvalidInput { .. })), "{other:?}"); + let unported = pick(&all, &points, 1.0, 1e-6, |i, _| answer(if i == 0 { Err(SolidError::unported("Sm::X", "u")) } else { Ok(0.5) })); + assert!(matches!(unported, Err(SolidError::Unported { .. })), "{unported:?}"); +} diff --git a/crates/smlib/src/core/sweep.rs b/crates/smlib/src/core/sweep.rs index 7cd124b60..63af1258a 100644 --- a/crates/smlib/src/core/sweep.rs +++ b/crates/smlib/src/core/sweep.rs @@ -61,7 +61,7 @@ use solidcore::topology::{Brep, FaceId}; use super::blend::status; use super::offset::{face_miss, pick_faces}; -use super::{Body, run, with_body}; +use super::{Body, answer, run, with_body}; use crate::sweeps::{Affine, Curve as Profile, DraftCorner, Ends, MAX_CURVES, MAX_STATION_CURVES, MAX_STATIONS, SweepFrame}; use crate::{Error, Result, ffi}; @@ -304,12 +304,12 @@ fn tangent(k: &Kernel, c: &Curve, t: f64, from_left: bool) -> solidcore::Result< } /// Whether the angle about `n` from `a` to `b` is a sharp corner (`sm_DraftHasCorner`: more than -/// `SM_EFF_ZERO_SQRT`); an angle that cannot be measured is none, as there. -fn sharp(n: Vec3, a: Option, b: Option) -> bool { - match (a, b) { - (Some(a), Some(b)) => n.ccw_angle_between(a, b).is_ok_and(|x| x.abs() > EFF_ZERO_SQRT), +/// `SM_EFF_ZERO_SQRT`); an angle whose measure returns a status is none, as there ([`answer`]). +fn sharp(n: Vec3, a: Option, b: Option) -> solidcore::Result { + Ok(match (a, b) { + (Some(a), Some(b)) => answer(n.ccw_angle_between(a, b))?.is_some_and(|x| x.abs() > EFF_ZERO_SQRT), _ => false, - } + }) } /// `sm_DraftHasCorner`, on the profile as given (one closed loop, in order): whether it has a @@ -320,14 +320,14 @@ fn has_corner(k: &Kernel, curves: &[Curve], n: Vec3) -> solidcore::Result for (i, b) in curves.iter().enumerate() { let Some(a) = curves.get((i + count - 1) % count) else { continue }; let (ia, ib) = (a.natural_interval(), b.natural_interval()); - if sharp(n, tangent(k, a, ia.max(), true)?, tangent(k, b, ib.min(), false)?) { + if sharp(n, tangent(k, a, ia.max(), true)?, tangent(k, b, ib.min(), false)?)? { return Ok(true); } if let CurveKind::BSpline(s) = b.kind() { let c = s.canonical()?; let inner = c.knots.iter().zip(&c.knot_multiplicities).skip(1).take(c.knots.len().saturating_sub(2)); for (&u, &m) in inner { - if m >= c.degree && sharp(n, tangent(k, b, u, true)?, tangent(k, b, u, false)?) { + if m >= c.degree && sharp(n, tangent(k, b, u, true)?, tangent(k, b, u, false)?)? { return Ok(true); } } diff --git a/crates/smlib/src/core/sweep_tests.rs b/crates/smlib/src/core/sweep_tests.rs index 88aa3f3eb..3caa2000a 100644 --- a/crates/smlib/src/core/sweep_tests.rs +++ b/crates/smlib/src/core/sweep_tests.rs @@ -464,7 +464,6 @@ fn the_cpp_kernel_places_the_profile_alike() { /// A diagonal 10 above a 10 x 10 x 10 box's top, projected down onto the top: the same diagonal /// at z = 10. #[test] -#[ignore = "solidcore#1440: the topology point solve misses faces, so SmApiFaceClosestPoint picks no face (solidcore#1440)"] fn project_a_line_onto_a_face() { let got = timed("project", || { let b = make_box([0.0; 3], [10.0; 3]).unwrap(); @@ -482,7 +481,6 @@ fn project_a_line_onto_a_face() { /// A face's planar section needs `SmBrep::CreatePlanarSectionCurves`: not supported, after the /// face pick. #[test] -#[ignore = "solidcore#1440: the topology point solve misses faces, so the face pick fails first (solidcore#1440); then no CreatePlanarSectionCurves (solidcore#1451)"] fn a_face_section_is_not_supported_yet() { let got = timed("section", || { let b = make_box([0.0; 3], [10.0; 3]).unwrap();