From 6fcd6713f5c4ba1019e9a46041bbbc6a435dded8 Mon Sep 17 00:00:00 2001 From: jyviko <2501648+jyviko@users.noreply.github.com> Date: Mon, 26 Oct 2026 11:14:20 -0400 Subject: [PATCH] Wave 251/509: kernel: fillet_setback, constant-radius rounds with corners set back (and 3 more) 4 commits, squashed; the originals stay reachable from tag archive/merge-main-develop. - c2361c000 jyviko: smlib: Brep::blend_setback, blends with corner setbacks (smlib_blend_setback) - f85343879 jyviko: kernel: fillet_setback, constant-radius rounds with corners set back - c854239d1 jyviko: doc, engine: solid.fillet setbacks: [{vertex, distance}] - 9ffd2f783 jyviko: kernel-cases: ladder 07/013 corner setback graded by invariants Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ --- crates/doc/src/document.rs | 14 ++++ crates/doc/src/eval.rs | 17 +++++ crates/doc/src/tests.rs | 25 ++++++++ crates/engine/src/cmd/features.rs | 17 ++++- crates/io/src/lib.rs | 2 + crates/kernel/src/blend.rs | 13 ++++ crates/kernel/src/blend_smlib.rs | 42 ++++++++++++ crates/kernel/src/fillet_setback_tests.rs | 44 +++++++++++++ crates/kernel/src/lib.rs | 4 +- crates/smlib/src/ffi/ops.rs | 64 ++++++++++++++++++- crates/smlib/src/ops.rs | 25 ++++++++ .../013-corner-setback/expected.json | 25 +++++++- .../07-fillets/013-corner-setback/recipe.json | 37 ++++++++++- 13 files changed, 322 insertions(+), 7 deletions(-) create mode 100644 crates/kernel/src/fillet_setback_tests.rs diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index d45806f4a..f31400cc8 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -683,6 +683,10 @@ pub enum FeatureKind { /// (default) or a G2 patch repeating each blend up to the second order. #[serde(default, skip_serializing_if = "FilletCorner::is_rolling")] corner: FilletCorner, + /// Corners set back: each corner's patch starts its distance along every edge there + /// from the vertex instead of where the rounds meet (a constant-radius fillet only). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + setbacks: Vec, /// Round each picked edge's tangent chain with it (the default: edges continuing it /// smoothly at its ends, as far as they go), or only the picked edges. #[serde(default = "yes", skip_serializing_if = "is_yes")] @@ -1841,6 +1845,16 @@ pub enum FeatureKind { }, } +/// A fillet corner set back: the vertex at `vertex`, where every edge is rounded, has its corner +/// patch start `distance` along each of its edges from the vertex, the rounds running whole up to +/// their sections there. One distance for all of a corner's edges. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)] +pub struct CornerSetback { + pub vertex: Position, + #[walk(length = "Setback")] + pub distance: Expr, +} + /// What fills the corner where three blended edges meet. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index b91b63830..0c648c85f 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -3498,6 +3498,13 @@ fn blend_body( // The blended body, and the lineage of what the last blend started from. let (nb, from) = match &f.kind { FeatureKind::Fillet { corner: crate::FilletCorner::G2, .. } => (kernel::fillet_g2_corners(&mb.body, edges, r)?, input), + FeatureKind::Fillet { setbacks, .. } if !setbacks.is_empty() => { + let mut corners = Vec::with_capacity(setbacks.len()); + for c in setbacks { + corners.push((c.vertex.0, val(vals, &c.distance, Kind::Length)?)); + } + (kernel::fillet_setback(&mb.body, edges, r, &corners)?, input) + } FeatureKind::Fillet { style: crate::FilletStyle::Curvature, .. } => (kernel::fillet_g2(&mb.body, edges, r)?, input), FeatureKind::Fillet { style: crate::FilletStyle::Chord, .. } => (kernel::fillet_chord(&mb.body, edges, r)?, input), FeatureKind::Fillet { style: crate::FilletStyle::Variable { radius2, start, mid, smooth }, .. } => { @@ -6732,6 +6739,15 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: } // Each edge is found on its own body (picked over several bodies, the edges of each // are blended on it), all against the bodies as they were before this feature. + // Corner setbacks likewise: SMLib sets back the corners of constant-radius rounds. + if let FeatureKind::Fillet { setbacks, corner, style, fit, .. } = &f.kind + && !setbacks.is_empty() + && (!corner.is_rolling() || !matches!(style, crate::FilletStyle::Constant) || !matches!(fit, crate::FilletFit::Exact)) + { + return Err(DocError::Invalid( + "corner setbacks are built for a constant-radius fillet (type: constant, fit: exact, corner: rolling) only".into(), + )); + } let on = blend_bodies(st, f, body, &crate::plain(edges))?; let mut groups: Vec<(usize, Vec)> = Vec::new(); for (i, ti) in on.iter().enumerate() { @@ -7770,6 +7786,7 @@ mod chain_tests { style: crate::FilletStyle::Constant, fit: Default::default(), corner: Default::default(), + setbacks: Vec::new(), tangent_chain: true, }, None, diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 9d96ba557..339e78ac7 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -262,6 +262,7 @@ fn box_fillet_cut_timeline() { style: Default::default(), fit: Default::default(), corner: Default::default(), + setbacks: Vec::new(), tangent_chain: true, }, None, @@ -335,6 +336,7 @@ fn errors_are_reported_not_fatal() { style: Default::default(), fit: Default::default(), corner: Default::default(), + setbacks: Vec::new(), tangent_chain: true, }, None, @@ -747,3 +749,26 @@ fn a_join_splits_off_only_what_touches_along_an_edge() { assert!(rel(other.1, arm) < 1e-6 && other.2 == 1, "the arm: {bodies:?}"); assert_eq!(kept, Some(KeptSeparate::AlongEdge)); } + +/// A fillet saved before corner setbacks reads with none and writes no `setbacks`; one with a +/// setback keeps it through a save, its distance an expression. +#[test] +fn fillet_setbacks_default_to_none_and_round_trip() { + let old = serde_json::json!({"type": "fillet", "edges": [[30.0, 40.0, 20.0]], "radius": "5"}); + let kind: FeatureKind = serde_json::from_value(old).unwrap(); + let FeatureKind::Fillet { setbacks, .. } = &kind else { panic!("{kind:?}") }; + assert!(setbacks.is_empty()); + assert!(serde_json::to_value(&kind).unwrap().get("setbacks").is_none()); + let set = FeatureKind::Fillet { + edges: vec![Position(Vec3::new(30.0, 40.0, 20.0))], + radius: "5".into(), + body: None, + style: Default::default(), + fit: Default::default(), + corner: Default::default(), + setbacks: vec![CornerSetback { vertex: Position(Vec3::new(60.0, 40.0, 20.0)), distance: "8 mm".into() }], + tangent_chain: true, + }; + let back: FeatureKind = serde_json::from_value(serde_json::to_value(&set).unwrap()).unwrap(); + assert_eq!(back, set); +} diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index 280b63d8f..74fbd99a7 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -49,7 +49,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("SOLID", "MODIFY") .icon("fillet") .key("F") - .params("edges: [[x,y,z] point on edge | {body, index}] ; radius: expr; tangent_chain?: bool (default true: each picked edge's tangent chain is rounded with it; false: exactly the picked edges); body?; type?: constant|curvature (alias g2: curvature-continuous quintic between planar faces along straight edges, one planar end face at each end (including sloped ends); radius sets the equivalent circular setback, not constant curvature; exact fit only)|chord (radius is the width across)|variable (radius at the end nearest start, radius2 at the other; one end may be 0, where the round closes to the corner)|spline (the radius along the edge is a clamped B-spline from the end nearest start: radius is its first control radius, radii the rest, knots its knot vector from 0 to 1; one end may be 0); radius2?; start?: [x,y,z]; radii?: [expr, …]; knots?: [number, …]; mid?: [[position 0…1 from start, radius expr], …] (variable radii between the ends); smooth?: bool (smooth instead of straight between the radii); corner?: rolling|g2 (rolling, the default: the corners where three blended edges meet are pieces of the rolling ball's sphere, tangent to each blend; g2: a patch repeating each blend's surface up to the second order, constant-radius exact fillets only, refused where it cannot be built); fit?: exact|reduce|taper (exact, the default: a radius too large for the geometry around the edges is refused; reduce: where it doesn't fit it is reduced to the largest that does, one radius for edges sharing a face; the smallest used is returned as `radius_applied`, each edge's as `radii_applied: [{edge: [x,y,z], radius}]`, and noted in the feature's warning; taper: along each straight edge between planar faces where it doesn't fit, the radius follows the room there as a smooth spline, down to 0 where a face closes to a point, noted in the feature's warning)"), + .params("edges: [[x,y,z] point on edge | {body, index}] ; radius: expr; tangent_chain?: bool (default true: each picked edge's tangent chain is rounded with it; false: exactly the picked edges); body?; type?: constant|curvature (alias g2: curvature-continuous quintic between planar faces along straight edges, one planar end face at each end (including sloped ends); radius sets the equivalent circular setback, not constant curvature; exact fit only)|chord (radius is the width across)|variable (radius at the end nearest start, radius2 at the other; one end may be 0, where the round closes to the corner)|spline (the radius along the edge is a clamped B-spline from the end nearest start: radius is its first control radius, radii the rest, knots its knot vector from 0 to 1; one end may be 0); radius2?; start?: [x,y,z]; radii?: [expr, …]; knots?: [number, …]; mid?: [[position 0…1 from start, radius expr], …] (variable radii between the ends); smooth?: bool (smooth instead of straight between the radii); corner?: rolling|g2 (rolling, the default: the corners where three blended edges meet are pieces of the rolling ball's sphere, tangent to each blend; g2: a patch repeating each blend's surface up to the second order, constant-radius exact fillets only, refused where it cannot be built); setbacks?: [{vertex: [x,y,z], distance: expr}, …] (corner setbacks: the corner at the vertex nearest `vertex`, where every edge meeting it is rounded, starts its patch `distance` along each of those edges from the vertex, past where the rounds would meet (past the radius at a square corner), so the rounds blend through a larger patch; one distance for all of a corner's edges; constant-radius exact fillets with rolling corners only); fit?: exact|reduce|taper (exact, the default: a radius too large for the geometry around the edges is refused; reduce: where it doesn't fit it is reduced to the largest that does, one radius for edges sharing a face; the smallest used is returned as `radius_applied`, each edge's as `radii_applied: [{edge: [x,y,z], radius}]`, and noted in the feature's warning; taper: along each straight edge between planar faces where it doesn't fit, the radius follows the room there as a smooth spline, down to 0 where a face closes to a point, noted in the feature's warning)"), CommandSpec::new("solid.chamfer", "Chamfer", chamfer).at("SOLID", "MODIFY").icon("chamfer").params("edges: [[x,y,z] | {body, index}] ; distance: expr; tangent_chain?: bool (default true: each picked edge's tangent chain is cut with it; false: exactly the picked edges); distance2?: expr (along the second face) | angle?: expr (from the first face); flip?: bool (which face is first: by default the one facing up most); body?"), CommandSpec::new("solid.combine", "Combine", combine).at("SOLID", "MODIFY").icon("combine").params("target: body; tools: [body]; operation?: join|cut|intersect; touching?: separate|one_body (what a join makes of pieces that share no face: separate, the default, makes each piece that touches another only along an edge or at a point a body of its own and keeps pieces that touch nothing in one body; one_body keeps every piece in one body); keep_tools?: bool; new_component?: bool (the result goes into a new component; component_name?)"), CommandSpec::new("solid.pattern.rectangular", "Rectangular Pattern", pattern_rect) @@ -1654,6 +1654,20 @@ fn fillet(s: &mut Session, p: &Value) -> Result { if !corner.is_rolling() && (!style.is_constant() || !fit.is_exact()) { return Err(bad(cmd, "`corner: g2` is built for a constant-radius fillet (`type: constant`, `fit: exact`) only")); } + // Corner setbacks: each a vertex and the distance its patch starts along the edges there. + let mut setbacks = Vec::new(); + if let Some(list) = p.get("setbacks") { + let list = list.as_array().ok_or_else(|| bad(cmd, "`setbacks` is a list of {vertex: [x,y,z], distance: expr}"))?; + for item in list { + let vertex = item.get("vertex").and_then(vec3).ok_or_else(|| bad(cmd, "each setback needs `vertex`: [x,y,z] at the corner"))?; + let distance = expr(item, "distance").ok_or_else(|| bad(cmd, "each setback needs `distance`: a length"))?; + check_expr(s, &distance, Kind::Length, cmd, "setback distance")?; + setbacks.push(solidcraft_doc::CornerSetback { vertex: Position(vertex), distance }); + } + if !setbacks.is_empty() && (!style.is_constant() || !fit.is_exact() || !corner.is_rolling()) { + return Err(bad(cmd, "`setbacks` are built for a constant-radius fillet (`type: constant`, `fit: exact`, `corner: rolling`) only")); + } + } let mut out = add_feature( s, p, @@ -1664,6 +1678,7 @@ fn fillet(s: &mut Session, p: &Value) -> Result { style, fit, corner, + setbacks, tangent_chain: bool_(p, "tangent_chain").unwrap_or(true), }, )?; diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index ab9aadc8f..f4fafebae 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -1048,6 +1048,7 @@ mod tests { style: Default::default(), fit: Default::default(), corner: Default::default(), + setbacks: Vec::new(), tangent_chain: true, }, None, @@ -1134,6 +1135,7 @@ mod tests { style: Default::default(), fit: Default::default(), corner: Default::default(), + setbacks: Vec::new(), tangent_chain: true, }, None, diff --git a/crates/kernel/src/blend.rs b/crates/kernel/src/blend.rs index 67ff61f99..862695176 100644 --- a/crates/kernel/src/blend.rs +++ b/crates/kernel/src/blend.rs @@ -212,6 +212,19 @@ pub fn fillet(body: &Body, edges: &[Vec3], radius: f64) -> Result { crate::blend_smlib::fillet(body, edges, radius).and_then(|b| closed(body, b)) } +/// [`fillet`] with corner setbacks: each `(at, distance)` sets back the corner at the vertex +/// nearest `at`, a vertex where every edge is rounded, so its patch starts `distance` along +/// each of its edges from the vertex (one distance for all of a corner's edges: SMLib keeps one +/// per corner). The rounds run whole up to their sections there, and the patch between them +/// meets each face in a curve from one round's contact line to the next. The distance must reach +/// past where the rounds would meet without it (past the radius at a square corner); a corner +/// where some edge is not rounded is refused as not supported, a setback as long as an edge at +/// its corner as too large. +pub fn fillet_setback(body: &Body, edges: &[Vec3], radius: f64, setbacks: &[(Vec3, f64)]) -> Result { + body.require_brep("fillet")?; + crate::blend_smlib::fillet_setback(body, edges, radius, setbacks).and_then(|b| closed(body, b)) +} + /// [`fillet`] whose corners where three blended edges meet are G2 patches. SMLib's fillet /// corners are a sphere or a Coons patch that meets the rounds tangentially, so this is refused /// rather than quietly given those corners; [`fillet`] (the default) is unchanged. diff --git a/crates/kernel/src/blend_smlib.rs b/crates/kernel/src/blend_smlib.rs index aac1c4978..64096cfb7 100644 --- a/crates/kernel/src/blend_smlib.rs +++ b/crates/kernel/src/blend_smlib.rs @@ -37,6 +37,12 @@ pub(crate) fn fillet_each(body: &Body, edges: &[Vec3], radii: &[f64]) -> Result< imp::blend(body, "fillet", Kind::Round, edges, radii) } +/// A constant-radius round whose corners at `setbacks` (a point at each corner's vertex, and the +/// distance its patch starts along each edge there) are set back ([`crate::fillet_setback`]). +pub(crate) fn fillet_setback(body: &Body, edges: &[Vec3], radius: f64, setbacks: &[(Vec3, f64)]) -> Result { + imp::blend_setback(body, edges, &vec![radius; edges.len()], setbacks) +} + /// Curvature-continuous rounds with the setback of a round of `radius` ([`crate::fillet_g2`]). pub(crate) fn fillet_g2(body: &Body, edges: &[Vec3], radius: f64) -> Result { imp::blend(body, "G2 fillet", Kind::Curvature, edges, &vec![radius; edges.len()]) @@ -179,6 +185,42 @@ mod imp { run(body, what, &picked.edges, |b| b.blend(kind, &picked.points, sizes, tol)) } + /// Rounds with corner setbacks: each corner point picks the body's nearest vertex (within + /// the pick tolerance), handed to SMLib at that vertex's own position. + pub(super) fn blend_setback(body: &Body, edges: &[Vec3], sizes: &[f64], setbacks: &[(Vec3, f64)]) -> Result { + let what = "fillet with corner setbacks"; + body.require_brep(what)?; + sizes_ok(what, sizes)?; + if setbacks.is_empty() || setbacks.len() > solidcraft_smlib::MAX_POINTS { + return Err(KernelError::Invalid(format!("{what}: give 1…{} corners", solidcraft_smlib::MAX_POINTS))); + } + if setbacks.iter().any(|(p, d)| !p.is_finite() || !(d.is_finite() && *d > 1e-6 && *d < 1e6)) { + return Err(KernelError::Invalid(format!("{what}: each corner is a finite point with a positive, finite setback"))); + } + let picked = resolve(body, edges)?; + let corners = corner_vertices(body, setbacks.iter().map(|(p, _)| *p))?; + let distances: Vec = setbacks.iter().map(|(_, d)| *d).collect(); + let tol = pick_tolerance(body); + run(body, what, &picked.edges, |b| b.blend_setback(Blend::Round, &picked.points, sizes, &corners, &distances, tol)) + } + + /// The body's vertex nearest each point, within the pick tolerance: the ends of its edges. + fn corner_vertices(body: &Body, picks: impl Iterator) -> Result> { + let mesh = body.mesh(&crate::MeshTolerance::chord((body.size() * 2e-3).max(1e-3)))?; + let ends: Vec = mesh.edges.iter().flat_map(|l| l.first().into_iter().chain(l.last())).copied().collect(); + let reach = pick_tolerance(body); + picks + .map(|p| { + ends.iter() + .map(|v| (v.dist(p), *v)) + .filter(|(d, _)| *d <= reach) + .min_by(|a, b| a.0.total_cmp(&b.0)) + .map(|(_, v)| [v.x, v.y, v.z]) + .ok_or_else(|| KernelError::Invalid(format!("no corner near the setback point ({:.3}, {:.3}, {:.3})", p.x, p.y, p.z))) + }) + .collect() + } + pub(super) fn sides(body: &Body, edges: &[Vec3], d1: f64, side: crate::ChamferSide, flip: bool) -> Result { body.require_brep("chamfer")?; sizes_ok("chamfer", &vec![d1; edges.len()])?; diff --git a/crates/kernel/src/fillet_setback_tests.rs b/crates/kernel/src/fillet_setback_tests.rs new file mode 100644 index 000000000..d1e0a886c --- /dev/null +++ b/crates/kernel/src/fillet_setback_tests.rs @@ -0,0 +1,44 @@ +use solidcraft_geom::Vec3; + +use crate::*; + +/// The 60 x 40 x 20 box with r5 rounds on the three edges at (60, 40, 20). +fn corner_case(setback: Option) -> Result { + let b = box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(60.0, 40.0, 20.0)).unwrap(); + let edges = [Vec3::new(30.0, 40.0, 20.0), Vec3::new(60.0, 20.0, 20.0), Vec3::new(60.0, 40.0, 10.0)]; + match setback { + Some(s) => fillet_setback(&b, &edges, 5.0, &[(Vec3::new(60.0, 40.0, 20.0), s)]), + None => fillet(&b, &edges, 5.0), + } +} + +/// Set back 8 along each edge: outside the corner cube [52, 60] x [32, 40] x [12, 20] the body +/// is the sphere corner's, and inside it the convex body holds the hull of its points on the +/// cube's faces (299.0201) and lies within the three rounds' prisms (512 - 225 (1 - pi/4) - +/// 125 (sqrt 2 - 1)); see capi/tests/ops_kernel.cpp, corner_setback. The patch is SMLib's two +/// quadrilaterals per side: 15 faces, 36 edges, 23 vertices; the box stays the box. +#[test] +fn a_corner_set_back_8_blends_through_a_larger_patch() { + let pi = std::f64::consts::PI; + let sphere = measure(&corner_case(None).unwrap()).unwrap().volume; + let out = corner_case(Some(8.0)).unwrap(); + assert!(out.validity().is_empty(), "{:?}", out.validity()); + let m = measure(&out).unwrap(); + let in_c_sphere = 512.0 - 225.0 * (1.0 - pi / 4.0) - 125.0 * (1.0 - pi / 6.0); + let prisms = 512.0 - 225.0 * (1.0 - pi / 4.0) - 125.0 * (2f64.sqrt() - 1.0); + let outside = sphere - in_c_sphere; + assert!(m.volume > outside + 299.0201 && m.volume < outside + prisms, "{} not in [{}, {}]", m.volume, outside + 299.0201, outside + prisms); + assert_eq!((m.faces, m.edges, m.vertices), (15, 36, 23)); + assert!((m.bbox.min - Vec3::new(0.0, 0.0, 0.0)).len() < 1e-6 && (m.bbox.max - Vec3::new(60.0, 40.0, 20.0)).len() < 1e-6, "{:?}", m.bbox); +} + +/// A setback point at no vertex, at a corner where no edge is rounded, or as long as an edge +/// there, is refused. +#[test] +fn a_setback_off_the_rounded_corner_is_refused() { + let b = box_solid(Vec3::new(0.0, 0.0, 0.0), Vec3::new(60.0, 40.0, 20.0)).unwrap(); + let edges = [Vec3::new(30.0, 40.0, 20.0), Vec3::new(60.0, 20.0, 20.0), Vec3::new(60.0, 40.0, 10.0)]; + assert!(fillet_setback(&b, &edges, 5.0, &[(Vec3::new(30.0, 20.0, 10.0), 8.0)]).is_err()); + assert!(fillet_setback(&b, &edges, 5.0, &[(Vec3::new(0.0, 0.0, 0.0), 8.0)]).is_err()); + assert!(matches!(corner_case(Some(20.0)), Err(KernelError::TooLarge(_)))); +} diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index 65e1bcea8..ba77210cd 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -39,6 +39,8 @@ mod emboss; mod face_source_tests; mod fair; mod fill; +#[cfg(test)] +mod fillet_setback_tests; mod freeform; pub mod fuzz; mod heal; @@ -150,7 +152,7 @@ mod validity; pub mod watch; mod whole_face; -pub use blend::{ChamferSide, chamfer, chamfer_sides, fillet, fillet_each, fillet_g2, fillet_g2_corners, fillet_max, fillet_max_each, tangent_chain}; +pub use blend::{ChamferSide, chamfer, chamfer_sides, fillet, fillet_each, fillet_g2, fillet_g2_corners, fillet_max, fillet_max_each, fillet_setback, tangent_chain}; pub use blend_corner::fillet_radii; pub use blend_variable::{RadiusSpline, Taper, fillet_chord, fillet_tapered, fillet_variable, fillet_variable_points, fillet_variable_spline, taper}; pub use body::{Body, CapSignature, DISPLAY_ANGLE, DisplayShare, EdgeInfo, FaceInfo, FacePaint, FaceSource, MeshTolerance, Paint}; diff --git a/crates/smlib/src/ffi/ops.rs b/crates/smlib/src/ffi/ops.rs index 1e09aabe8..691319097 100644 --- a/crates/smlib/src/ffi/ops.rs +++ b/crates/smlib/src/ffi/ops.rs @@ -1,5 +1,5 @@ //! 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_chamfer`, `smlib_blend`, `smlib_blend_setback`, `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 //! [`crate::ops`]. @@ -81,6 +81,20 @@ unsafe extern "C" { out: *mut *mut RawBrep, out_failed_point: *mut i64, ) -> i32; + fn smlib_blend_setback( + brep: *const RawBrep, + kind: i32, + points: *const f64, + sizes: *const f64, + n_points: i64, + corners: *const f64, + setbacks: *const f64, + n_corners: i64, + tolerance: f64, + out: *mut *mut RawBrep, + out_failed_point: *mut i64, + out_failed_corner: *mut i64, + ) -> i32; fn smlib_fillet_variable( brep: *const RawBrep, point: *const f64, @@ -265,6 +279,54 @@ pub fn blend(kind: i32, b: &Handle, points: &[[f64; 3]], sizes: &[f64], toleranc }) } +/// `smlib_blend_setback`: `sizes` holds one size per point and `setbacks` one distance per +/// corner (the caller checks the lengths match). A failed pick names its point; a corner that +/// picks no vertex or several comes back with no index. +#[cfg(feature = "native")] +pub fn blend_setback( + kind: i32, + b: &Handle, + points: &[[f64; 3]], + sizes: &[f64], + corners: &[[f64; 3]], + setbacks: &[f64], + tolerance: f64, +) -> Result { + let n = i64::try_from(points.len()).map_err(|_| (ERR_ARG, None))?; + let nc = i64::try_from(corners.len()).map_err(|_| (ERR_ARG, None))?; + if sizes.len() != points.len() || setbacks.len() != corners.len() { + return Err((ERR_ARG, None)); + } + let flat = points.as_ptr().cast::(); + let flat_corners = corners.as_ptr().cast::(); + let (mut failed, mut failed_corner) = (-1i64, -1i64); + new_brep(|out| unsafe { + smlib_blend_setback( + b.raw(), + kind, + flat, + sizes.as_ptr(), + n, + flat_corners, + setbacks.as_ptr(), + nc, + tolerance, + out, + &mut failed, + &mut failed_corner, + ) + }) + .map_err(|s| { + let at = (s == ERR_PICK_NONE || s == ERR_PICK_AMBIGUOUS).then(|| usize::try_from(failed).ok()).flatten(); + (s, at) + }) +} + +#[cfg(not(feature = "native"))] +pub fn blend_setback(_: i32, _: &Handle, _: &[[f64; 3]], _: &[f64], _: &[[f64; 3]], _: &[f64], _: f64) -> Result { + Err((NOT_BUILT, None)) +} + /// `smlib_fillet_variable`. #[cfg(feature = "native")] pub fn fillet_variable( diff --git a/crates/smlib/src/ops.rs b/crates/smlib/src/ops.rs index f273409ac..dbe331c9a 100644 --- a/crates/smlib/src/ops.rs +++ b/crates/smlib/src/ops.rs @@ -150,6 +150,31 @@ impl Brep { ffi::ops::blend(kind, &self.0, edges, sizes, tolerance).map(Brep).map_err(pick_error) } + /// [`Brep::blend`] with corner setbacks: each of `corners` picks the vertex nearest it + /// (within `tolerance`), a corner where every edge is blended, and that corner's patch starts + /// `setbacks[j]` along each of its edges from the vertex (one distance per corner, as SMLib + /// keeps it). A corner SMLib builds no setback on (some edge there not blended, a chamfer) is + /// [`Error::Unsupported`]; a setback as long as an edge there, [`Error::NoRoom`]. + pub fn blend_setback(&self, kind: Blend, edges: &[[f64; 3]], sizes: &[f64], corners: &[[f64; 3]], setbacks: &[f64], tolerance: f64) -> Result { + init()?; + if edges.len() > MAX_POINTS + || edges.is_empty() + || sizes.len() != edges.len() + || corners.is_empty() + || corners.len() > MAX_POINTS + || setbacks.len() != corners.len() + { + return Err(Error::Argument); + } + let kind = match kind { + Blend::Round => ffi::ops::BLEND_ROUND, + Blend::Curvature => ffi::ops::BLEND_CURVATURE, + Blend::Chord => ffi::ops::BLEND_CHORD, + Blend::Chamfer => ffi::ops::BLEND_CHAMFER, + }; + ffi::ops::blend_setback(kind, &self.0, edges, sizes, corners, setbacks, tolerance).map(Brep).map_err(pick_error) + } + /// The one edge nearest to `edge` (within `tolerance`) rounded with a radius /// that varies along it: a clamped B-spline of `degree` (1 to 3) with `knots` and control /// `radii` over the position along the edge, 0 at its end nearest `start` and 1 at the other diff --git a/tests/kernel-cases/ladder/07-fillets/013-corner-setback/expected.json b/tests/kernel-cases/ladder/07-fillets/013-corner-setback/expected.json index 5b6f1ab57..d62cece2e 100644 --- a/tests/kernel-cases/ladder/07-fillets/013-corner-setback/expected.json +++ b/tests/kernel-cases/ladder/07-fillets/013-corner-setback/expected.json @@ -1,7 +1,26 @@ { "sources": [], - "what": "three r5 rounds at a corner with setbacks of 8 mm along each edge", + "what": "three r5 rounds at the corner (60,40,20) with setbacks of 8 mm along each edge", "source": "invariants", - "method": "the setback corner patch would be graded by invariants", - "missing": "solid.fillet has no corner setback distances" + "method": "outside the corner cube C = [52,60]x[32,40]x[12,20] the body is the sphere corner's (009: V0 = 47377.120025868, of which 512 - 225 (1-pi/4) - 125 (1-pi/6) lies in C); the body is convex, so in C it holds the hull of its points on C's faces (the rounds' sections at the setback planes x=52, y=32, z=12 and the cube's corners outside the patch: 299.0201 by a hull of the sections sampled, below the true hull) and lies within the planes tangent to it along those sections, the three rounds' prisms (512 - 225 (1-pi/4) - 125 (sqrt2-1): the corner cube of r keeps the cylinders' common octant (2-sqrt2) r^3). The volume is the middle of [47271.9757, 47384.8935] with that half width as its tolerance. The box is unchanged. SMLib's setback patch is two quadrilaterals per side meeting at its centre: 6 box faces, 3 rounds, 6 patch pieces; vertices: 4 untouched box corners, 2 at each round's far end, the 6 section ends (where the patch starts, 8 from the vertex along each edge), the 6 side middles and the centre (23); edges by Euler, 23 + 15 - 2", + "body_count": 1, + "volume_mm3": 47328.434587888, + "faces": 15, + "edges": 36, + "vertices": 23, + "bbox": { + "min": [ + 0, + 0, + 0 + ], + "max": [ + 60, + 40, + 20 + ] + }, + "tolerance": { + "rel": 0.001192 + } } diff --git a/tests/kernel-cases/ladder/07-fillets/013-corner-setback/recipe.json b/tests/kernel-cases/ladder/07-fillets/013-corner-setback/recipe.json index fe7861aa1..221a5361e 100644 --- a/tests/kernel-cases/ladder/07-fillets/013-corner-setback/recipe.json +++ b/tests/kernel-cases/ladder/07-fillets/013-corner-setback/recipe.json @@ -1,3 +1,38 @@ { - "commands": [] + "base": "../../01-primitives/001-box", + "commands": [ + { + "command": "solid.fillet", + "params": { + "edges": [ + [ + 30, + 40, + 20 + ], + [ + 60, + 20, + 20 + ], + [ + 60, + 40, + 10 + ] + ], + "radius": 5, + "setbacks": [ + { + "vertex": [ + 60, + 40, + 20 + ], + "distance": 8 + } + ] + } + } + ] }