Skip to main content

brep_kernel/
solid_face_calls.rs

1//! Public one-call operations on a solid's faces named by points.
2
3use crate::{thicken_sheet_faces, BrepSolid, KernelRefusal, KernelStage, OffsetCorners, Vec3};
4use std::collections::BTreeSet;
5
6/// The solid the faces of `solid` that `face_points` lie on sweep moving from 0
7/// to `thickness` along their outward normals (inward where it is negative);
8/// `solid` itself is not part of it. The faces are taken as one sheet, with the
9/// edges they share, and thickened by [`thicken_sheet_faces`] with sharp joins.
10pub fn thicken_faces(solid: &BrepSolid, face_points: &[Vec3], thickness: f64) -> Result<BrepSolid, KernelRefusal> {
11    if face_points.is_empty() {
12        return Err(KernelRefusal::input(KernelStage::Collect, "thicken_faces_points", "thicken_faces: no face named".to_string()));
13    }
14    let mut faces = BTreeSet::new();
15    for &point in face_points {
16        faces.insert(crate::resolve_face_by_point(solid, point)?);
17    }
18    let sheet = crate::feature_pipeline::features::sew_to_solid::extract(solid, &faces);
19    let thickened = thicken_sheet_faces(&[sheet], thickness, OffsetCorners::Sharp);
20    // Every face of the solid named: the sheet is the solid's whole closed
21    // boundary, which may be one face closed in both directions (a torus) with
22    // no edge for the sheet's walls to stand on. What its faces sweep moving
23    // out to `thickness` is the hollow between the boundary and the body grown
24    // (or shrunk) by `thickness` with sharp joins, as the closed shell builds
25    // it; that is answered where the sheet's own construction refuses.
26    let whole = solid.shells.iter().flat_map(|shell| &shell.faces).all(|face| faces.contains(&face.id));
27    match thickened {
28        Err(refusal) if whole => crate::offset_shell_closed(solid, -thickness).map(|hollow| hollow.solid).map_err(|_| refusal),
29        thickened => thickened,
30    }
31}
32
33/// How two solids meet, as they stand: the volume they share and the gap
34/// between them.
35#[derive(Clone, Copy, Debug, PartialEq)]
36pub struct Interference {
37    /// The volume of their intersection: above 0 where they overlap.
38    pub volume: f64,
39    /// The least distance from a point of one to a point of the other: 0
40    /// where they overlap or touch.
41    pub gap: f64,
42}
43
44/// How `a` and `b` meet: the volume of their intersection (the exact boolean's,
45/// 0 when their least boxes lie apart) and, when they share none, the least
46/// distance between their boundaries on their exact geometry
47/// ([`crate::solid_gap`]; 0 where they touch). `tolerance` (mm) is the band a
48/// point may stand past a face's trim and still count as on it.
49pub fn solid_interference(a: &BrepSolid, b: &BrepSolid, tolerance: f64) -> Result<Interference, KernelRefusal> {
50    let [la, ha] = crate::solid_least_box(a, tolerance)?;
51    let [lb, hb] = crate::solid_least_box(b, tolerance)?;
52    let apart = la.x > hb.x || lb.x > ha.x || la.y > hb.y || lb.y > ha.y || la.z > hb.z || lb.z > ha.z;
53    if apart {
54        return Ok(Interference { volume: 0.0, gap: crate::solid_gap(a, b, tolerance)? });
55    }
56    let scale = crate::solid_model_scale(a).max(crate::solid_model_scale(b)).max(1.0);
57    // Boundaries that stand apart leave each shell of one wholly inside or
58    // wholly outside the other, which one point of the shell tells; solids
59    // apart need no boolean (whose faces may lie too near one another for it
60    // to cut).
61    let gap = crate::solid_gap(a, b, tolerance)?;
62    let meet = gap <= tolerance.max(1e-9 * scale);
63    if !meet && !any_shell_inside(a, b, tolerance)? && !any_shell_inside(b, a, tolerance)? {
64        return Ok(Interference { volume: 0.0, gap });
65    }
66    let common = crate::boolean_operation(a, b, crate::BooleanOperation::Intersect, &crate::BooleanOptions::default())?;
67    let volume = if common.shells.iter().all(|shell| shell.faces.is_empty()) {
68        0.0
69    } else {
70        crate::solid_signed_volume(&common)
71            .map_err(|e| KernelRefusal::internal(KernelStage::Validate, "interference_volume", format!("interference: {e}")))?
72            .max(0.0)
73    };
74    // Where the boundaries meet, a shared volume no more than the smaller
75    // part's broadest side times the round-off of its coordinates is faces in
76    // contact, not an overlap; a part inside the other shares what it shares.
77    let side = |l: Vec3, h: Vec3| {
78        let mut e = [h.x - l.x, h.y - l.y, h.z - l.z];
79        e.sort_by(f64::total_cmp);
80        e[1] * e[2]
81    };
82    if volume > 0.0 && (!meet || volume > 1e-10 * scale * side(la, ha).min(side(lb, hb))) {
83        return Ok(Interference { volume, gap: 0.0 });
84    }
85    Ok(Interference { volume: 0.0, gap })
86}
87
88/// Whether a point of any shell of `inner` (where its first face's first trim
89/// begins, or its surface's middle for a face with no trim) lies inside `outer`.
90fn any_shell_inside(inner: &BrepSolid, outer: &BrepSolid, tolerance: f64) -> Result<bool, KernelRefusal> {
91    for shell in &inner.shells {
92        let Some(face) = shell.faces.first() else { continue };
93        let uv = match face.loops.iter().flat_map(|l| &l.coedges).next() {
94            Some(coedge) => coedge.pcurve.domain().and_then(|[t, _]| coedge.pcurve.evaluate(t)).map(|p| [p.x, p.y]),
95            None => face.surface.domain_u().and_then(|[u0, u1]| face.surface.domain_v().map(|[v0, v1]| [0.5 * (u0 + u1), 0.5 * (v0 + v1)])),
96        };
97        let point = uv.and_then(|[u, v]| face.surface.evaluate(u, v));
98        let point = point.map_err(|e| KernelRefusal::internal(KernelStage::Classify, "interference_inside", format!("interference: {e}")))?;
99        let class = crate::classify_point(point, outer, tolerance)
100            .map_err(|e| KernelRefusal::internal(KernelStage::Classify, "interference_inside", format!("interference: {e}")))?;
101        if class.class != crate::PointClass::Out {
102            return Ok(true);
103        }
104    }
105    Ok(false)
106}
107
108/// The faces of `solid` the points name, deduplicated in order: each point
109/// must lie inside one face's trim (within 1e-6 of the model's scale), not on
110/// an edge between faces, nor off them (a point in a hole's mouth names no
111/// face, though the cap's carrier runs through it).
112fn faces_named(solid: &BrepSolid, face_points: &[Vec3], what: &str) -> Result<Vec<u64>, KernelRefusal> {
113    if face_points.is_empty() {
114        return Err(KernelRefusal::input(KernelStage::Collect, format!("{what}_points"), format!("{what}: no face named")));
115    }
116    let tolerance = (crate::solid_model_scale(solid) * 1e-6).max(1e-9);
117    let mut seen = BTreeSet::new();
118    let mut faces = Vec::new();
119    for &point in face_points {
120        let foot = crate::nearest_boundary_point(solid, point, tolerance)?;
121        let face = match foot {
122            // Off the body first, whatever its nearest boundary point is.
123            Some(crate::BoundaryFoot { distance, .. }) if !(distance <= tolerance) => {
124                return Err(KernelRefusal::input(KernelStage::Collect, "point_off_faces", format!("{what}: the point {point:?} is {distance:e} from the boundary, off every face")));
125            }
126            Some(crate::BoundaryFoot { place: crate::BoundaryPlace::Face { face, .. }, .. }) => face,
127            // On an edge or vertex: it names a face only where every face
128            // round it is that one (a seam).
129            Some(foot) => {
130                let edges: Vec<u64> = match foot.place {
131                    crate::BoundaryPlace::Edge { edge, .. } => vec![edge],
132                    crate::BoundaryPlace::Vertex { vertex } => solid.edges.iter().filter(|e| e.start_vertex_id == vertex || e.end_vertex_id == vertex).map(|e| e.id).collect(),
133                    crate::BoundaryPlace::Face { face, .. } => vec![face],
134                };
135                let round: BTreeSet<u64> = solid
136                    .shells
137                    .iter()
138                    .flat_map(|shell| &shell.faces)
139                    .filter(|face| face.loops.iter().flat_map(|lp| &lp.coedges).any(|coedge| edges.contains(&coedge.edge_id)))
140                    .map(|face| face.id)
141                    .collect();
142                match (round.len(), round.iter().next()) {
143                    (1, Some(&face)) => face,
144                    _ => {
145                        return Err(KernelRefusal::input(KernelStage::Collect, "point_on_edge", format!("{what}: the point {point:?} lies on an edge or vertex between faces, naming none")));
146                    }
147                }
148            }
149            None => return Err(KernelRefusal::input(KernelStage::Collect, "no_faces", format!("{what}: the solid has no faces"))),
150        };
151        if seen.insert(face) {
152            faces.push(face);
153        }
154    }
155    Ok(faces)
156}
157
158/// `solid` with the faces `face_points` lie on each moved `distance` along
159/// its outward normal onto its offset surface (inward where it is negative),
160/// the faces round them extended or trimmed to meet them: Push Face's push
161/// (a plane translated, a cylinder, cone, sphere or torus offset exactly, a
162/// general revolution or free-form carrier within a bounded residual), then
163/// its acceptance. A plane landed exactly on a neighbour (two tops merged, a
164/// slot closed) is the boolean the push defines; a plane carried past one (an
165/// edge between them turned over) is refused as ill-posed. Exact to the push's tolerance, max(1e-7 of the model's
166/// scale, 1e-9); a nonzero distance below it is refused by name.
167pub fn offset_faces(solid: &BrepSolid, face_points: &[Vec3], distance: f64) -> Result<BrepSolid, KernelRefusal> {
168    if !distance.is_finite() {
169        return Err(KernelRefusal::input(KernelStage::Collect, "offset_faces_distance", "offset_faces: the distance must be finite"));
170    }
171    let faces = faces_named(solid, face_points, "offset_faces")?;
172    if distance == 0.0 {
173        return Ok(solid.clone());
174    }
175    // A distance the push's tolerance cannot tell from rest is refused by
176    // name, never returned as the body unmoved.
177    let resolution = (crate::solid_model_scale(solid) * 1e-7).max(1e-9);
178    if distance.abs() < resolution {
179        return Err(KernelRefusal::input(
180            KernelStage::Collect,
181            "motion_below_tolerance",
182            format!("offset_faces: the distance {distance:e} is below the {resolution:e} the push reads points to"),
183        ));
184    }
185    let mut notes = Vec::new();
186    crate::feature_pipeline::features::push_face::push_faces(solid.clone(), &faces, distance, &mut notes, false).map_err(|refusal| match refusal {
187        crate::feature_pipeline::FeatureRefusal::Typed(refusal) => refusal,
188        crate::feature_pipeline::FeatureRefusal::Text(message) => KernelRefusal::unsupported(KernelStage::Collect, "offset_faces", message),
189    })
190}
191
192/// The turn a rotation matrix makes: its unit axis and angle in (0, π], or
193/// None for the identity. Read from the skew part where the angle is clear of
194/// π, and from the symmetric part (its largest diagonal) near π, where the
195/// skew part vanishes.
196fn rotation_turn(r: &[[f64; 3]; 3]) -> Option<(Vec3, f64)> {
197    let trace = r[0][0] + r[1][1] + r[2][2];
198    let skew = Vec3::new(r[2][1] - r[1][2], r[0][2] - r[2][0], r[1][0] - r[0][1]);
199    // Its length scaled first, so a tiny turn's skew part does not square to zero.
200    let big = skew.x.abs().max(skew.y.abs()).max(skew.z.abs());
201    let skew_length = if big > 0.0 { big * Vec3::new(skew.x / big, skew.y / big, skew.z / big).length() } else { 0.0 };
202    let sine = 0.5 * skew_length;
203    let cosine = (0.5 * (trace - 1.0)).clamp(-1.0, 1.0);
204    let angle = sine.atan2(cosine);
205    if !(angle > 0.0) {
206        return None;
207    }
208    if cosine > -0.5 {
209        return Some((Vec3::new(skew.x / big, skew.y / big, skew.z / big).normalized().ok()?, angle));
210    }
211    // Near π: R + Rᵀ = 2 cos θ I + 2 (1 − cos θ) a aᵀ.
212    let k = 1.0 - cosine;
213    let column = (0..3).max_by(|&i, &j| r[i][i].total_cmp(&r[j][j])).unwrap_or(0);
214    let mut a = [0.0; 3];
215    a[column] = ((r[column][column] - cosine) / k).max(0.0).sqrt();
216    for i in 0..3 {
217        if i != column {
218            a[i] = (r[i][column] + r[column][i]) / (2.0 * k * a[column]);
219        }
220    }
221    let mut axis = Vec3::new(a[0], a[1], a[2]).normalized().ok()?;
222    // The skew part fixes the sign where it reads at all.
223    if axis.dot(skew) < 0.0 {
224        axis = axis.scale(-1.0);
225    }
226    Some((axis, angle))
227}
228
229/// `solid` with the faces `face_points` lie on moved rigidly by the rows
230/// `[R | t]` (a point x to R·x + t), the faces round them extended or trimmed
231/// to meet them: Transform Face's motion road (the turn and the slide solved
232/// in one re-intersection, its acceptance, and the re-cut and re-drill roads
233/// past a refusal). R must be a rotation (orthonormal, determinant +1).
234///
235/// The result is exact to the re-solve's tolerance, max(1e-7 of the model's
236/// scale, 1e-9): a part of the motion below it (a lift of 5e-10 riding on a
237/// slide along the face) may be read as rest. Within its envelope a whole
238/// motion below that tolerance, or a slide whose 1e-9 passes it, is refused
239/// by name; only R exactly the identity with no slide returns the body as it
240/// is.
241pub fn transform_faces(solid: &BrepSolid, face_points: &[Vec3], matrix: [[f64; 4]; 3]) -> Result<BrepSolid, KernelRefusal> {
242    if !matrix.iter().flatten().all(|x| x.is_finite()) {
243        return Err(KernelRefusal::input(KernelStage::Collect, "transform_faces_matrix", "transform_faces: the matrix must be finite"));
244    }
245    let r = [[matrix[0][0], matrix[0][1], matrix[0][2]], [matrix[1][0], matrix[1][1], matrix[1][2]], [matrix[2][0], matrix[2][1], matrix[2][2]]];
246    let t = Vec3::new(matrix[0][3], matrix[1][3], matrix[2][3]);
247    let mut off = 0.0f64;
248    for i in 0..3 {
249        for j in 0..3 {
250            let dot: f64 = (0..3).map(|k| r[k][i] * r[k][j]).sum();
251            off = off.max((dot - if i == j { 1.0 } else { 0.0 }).abs());
252        }
253    }
254    let det = r[0][0] * (r[1][1] * r[2][2] - r[1][2] * r[2][1]) - r[0][1] * (r[1][0] * r[2][2] - r[1][2] * r[2][0]) + r[0][2] * (r[1][0] * r[2][1] - r[1][1] * r[2][0]);
255    if !(off <= 1e-9 && det > 0.0) {
256        return Err(KernelRefusal::input(
257            KernelStage::Collect,
258            "transform_faces_rigid",
259            format!("transform_faces: the matrix's R is not a rotation (off orthonormal by {off:e}, determinant {det}): a face transform is a rigid motion"),
260        ));
261    }
262    let faces = faces_named(solid, face_points, "transform_faces")?;
263    // The turn about the selection's centre p (conditioning only: the motion
264    // is the same), the slide what is left: R(x − p) + p + s = R·x + t, so
265    // s = t + R·p − p carries all of a turn's displacement at p however small
266    // its angle. The turn itself is dropped only where it moves no corner of
267    // the body by more than 1e-12 of the model's scale.
268    let pivot = crate::feature_pipeline::features::transform_face::selection_centre(solid, &faces).unwrap_or(Vec3::new(0.0, 0.0, 0.0));
269    let turned = Vec3::new(
270        r[0][0] * pivot.x + r[0][1] * pivot.y + r[0][2] * pivot.z,
271        r[1][0] * pivot.x + r[1][1] * pivot.y + r[1][2] * pivot.z,
272        r[2][0] * pivot.x + r[2][1] * pivot.y + r[2][2] * pivot.z,
273    );
274    let slide = t.add(turned.sub(pivot));
275    // How far the body reaches from the pivot: its vertices and its faces'
276    // control points (a body without vertices, a whole torus, still turns).
277    let reach = solid
278        .vertices
279        .iter()
280        .map(|v| v.point)
281        .chain(solid.shells.iter().flat_map(|shell| &shell.faces).flat_map(|face| face.surface.control_points.iter().flatten()).filter_map(|p| p.point().ok()))
282        .map(|p| p.sub(pivot).length())
283        .fold(0.0f64, f64::max);
284    let scale = crate::solid_model_scale(solid).max(1e-300);
285    let read = rotation_turn(&r);
286    let swing = read.map_or(0.0, |(_, angle)| angle * reach);
287    let turn = read.filter(|_| swing > 1e-12 * scale).map(|(axis, angle)| (pivot, axis, angle));
288    // Exactly, by components (a length would square a tiny slide to zero).
289    let translates = slide.x != 0.0 || slide.y != 0.0 || slide.z != 0.0;
290    // Only the motion that moves nothing (R exactly the identity, element by
291    // element, and no slide) returns the body as it is; any other the turn's
292    // read cannot resolve falls to the refusal below.
293    let rest = (0..3).all(|i| (0..3).all(|j| r[i][j] == if i == j { 1.0 } else { 0.0 })) && t.x == 0.0 && t.y == 0.0 && t.z == 0.0;
294    if rest {
295        return Ok(solid.clone());
296    }
297    // A motion the re-solve's tolerance cannot tell from rest (it reads
298    // points to max(1e-7 of the scale, 1e-9)) is refused by name, never
299    // returned as the body unmoved.
300    let resolution = (scale * 1e-7).max(1e-9);
301    // The envelope: the re-solve reads a motion to 1e-9 of its length, so a
302    // slide whose 1e-9 passes the model's resolution could have a resolvable
303    // part read as rest; it is refused by name.
304    if slide.length() * 1e-9 > resolution {
305        return Err(KernelRefusal::input(
306            KernelStage::Collect,
307            "motion_out_of_envelope",
308            format!("transform_faces: the motion slides the faces {:e}, past what the re-solve reads to the model's resolution {resolution:e}", slide.length()),
309        ));
310    }
311    if turn.is_none() && slide.length() + swing < resolution {
312        return Err(KernelRefusal::input(
313            KernelStage::Collect,
314            "motion_below_tolerance",
315            format!("transform_faces: the motion moves the faces {:e}, below the {resolution:e} the re-solve reads points to", slide.length() + swing),
316        ));
317    }
318    // A motion every road refused for carrying a face past its neighbour (an
319    // edge between them turned over: the face pushed through the part) is the
320    // input's fault, not a shape the kernel lacks: refused as ill-posed, its
321    // message kept. A face landed exactly on a neighbour is answered above.
322    crate::feature_pipeline::features::transform_face::move_faces_road(solid, &faces, turn, translates, slide)
323        .map(|(body, _notes)| body)
324        .map_err(|(refusal, _step)| past_a_neighbour_is_ill_posed(refusal))
325}
326
327/// A refusal that a face was carried past its neighbour (a straight or curved
328/// edge turned over), in the ill-posed class; any other refusal as it is.
329fn past_a_neighbour_is_ill_posed(mut refusal: KernelRefusal) -> KernelRefusal {
330    use crate::face_refusal_slugs::{CURVED_EDGE_INVERSION, EDGE_INVERSION};
331    if matches!(&refusal.class, crate::RefusalClass::UnsupportedGeometry { what } if what == EDGE_INVERSION || what == CURVED_EDGE_INVERSION) {
332        refusal.class = crate::RefusalClass::IllPosed { what: "moved_past_a_neighbour".into() };
333    }
334    refusal
335}
336