Skip to main content

brep_offset/offset/offset_shell/
solid.rs

1//! Whole-solid offset (D3).
2//!
3//! `offset_solid` runs the shell pipeline in its WHOLE-BODY mode
4//! (`Body::Whole`): every face is retained, there is no opening and no wall,
5//! the source's own faces are not assembled, and the body is the offset
6//! carriers alone, closed at every sharp junction by the extend-and-intersect
7//! the pipeline already does for a shell's retained faces.
8//!
9//! The sign is the natural one: a positive distance grows the body along its
10//! outward normals, a negative one shrinks it. `offset_shell` takes the
11//! opposite sign (positive = inward wall), so the pipeline is asked for
12//! `-distance`.
13//!
14//! `OffsetCorners::Rounded` (D3) is the true parallel body, the Minkowski sum
15//! with a ball of radius `|d|`: the sharp body with every convex edge image
16//! (outward) or concave edge image (inward) rolled by the blend network at
17//! radius `|d|`, which is what puts the exact cylinder or torus cap on each
18//! straight or circular edge and the corner ball at each vertex. The blend's
19//! constructions are reused through `fillet_edges`, never rebuilt here.
20use super::debug_enabled;
21use super::pipeline::{offset_body, Body};
22use super::{OffsetFaceRole, OffsetShellFaceImageRecord, OffsetShellResultRecord};
23use crate::classification::PolygonClass;
24use crate::topology::{BrepSolid, EdgeRecord, FaceRecord};
25use crate::{
26    boolean_operation, fillet_edges, project_point_to_surface, BooleanOperation, BooleanOptions,
27    KernelRefusal, KernelStage, OrRefuse, RefusalClass, Vec2, Vec3,
28};
29use rustc_hash::FxHashMap as HashMap;
30use serde::{Deserialize, Serialize};
31
32/// How the offset body closes the joins between offset faces.
33#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
34#[serde(rename_all = "lowercase")]
35pub enum OffsetCorners {
36    #[default]
37    Sharp,
38    /// The exact parallel body: convex joins (outward) or concave joins
39    /// (inward) carry the rolling ball's cylinder, torus or sphere.
40    Rounded,
41}
42
43/// Offset every face of `source` by `distance` (positive grows) and join the
44/// offset faces into a closed body.
45pub fn offset_solid(
46    source: &BrepSolid,
47    distance: f64,
48    corners: OffsetCorners,
49) -> Result<OffsetShellResultRecord, KernelRefusal> {
50    if let Some(scaled) = crate::rescale::ScaledOffset::of(source, distance, "offset_solid")? {
51        let mut record = offset_solid(&scaled.source, scaled.distance, corners).map_err(|error| scaled.refusal(error))?;
52        record.solid = scaled.back(&record.solid, "offset_solid")?;
53        return Ok(record);
54    }
55    let built = offset_solid_unread(source, distance, corners)?;
56    if corners == OffsetCorners::Rounded {
57        if let Some(refusal) = super::rim_witness::rim_witness_refusal(source, &built.solid, distance) {
58            return Err(refusal);
59        }
60    }
61    Ok(built)
62}
63
64/// [`offset_solid`] before its result is read back ([`super::rim_witness`]).
65fn offset_solid_unread(
66    source: &BrepSolid,
67    distance: f64,
68    corners: OffsetCorners,
69) -> Result<OffsetShellResultRecord, KernelRefusal> {
70    let grown = offset_solid_joined(source, distance, corners)?;
71    if corners == OffsetCorners::Rounded && distance > 0.0 {
72        if let Some(carved) = super::bore_dimples::carve_bore_dimples(source, &grown.solid, distance) {
73            let operands = grown
74                .solid
75                .shells
76                .iter()
77                .flat_map(|shell| &shell.faces)
78                .zip(&grown.face_images)
79                .map(|(face, image)| (face, image.clone()))
80                .collect::<Vec<_>>();
81            let cap = OffsetShellFaceImageRecord { role: OffsetFaceRole::Offset, source_face_id: 0 };
82            if let Ok(face_images) = provenance_by_surface(&carved, &operands, Some(&cap)) {
83                return Ok(OffsetShellResultRecord { solid: carved, face_images });
84            }
85        }
86    }
87    Ok(grown)
88}
89
90/// [`offset_solid`] before the bore dimples ([`super::bore_dimples`]): the
91/// sharp body, or its rounding, or a decomposition's.
92fn offset_solid_joined(
93    source: &BrepSolid,
94    distance: f64,
95    corners: OffsetCorners,
96) -> Result<OffsetShellResultRecord, KernelRefusal> {
97    if corners == OffsetCorners::Rounded && distance > 0.0 {
98        if let Some(grown) = grown_across_reflex_edges(source, distance) {
99            return Ok(grown);
100        }
101    }
102    let widened_before = super::outward_side_widen::widened_count();
103    let sharp = match offset_body(source, &[], -distance, Body::Whole, "offset_solid") {
104        // A rounded growth whose sharp body was assembled only because a
105        // curved face's side was widened (`outward_side_widen`) used to be
106        // refused there and built by the revolved-parallel lane, which is
107        // exact; a solid of revolution keeps that lane, and any other body
108        // (the lane declines it) rounds the sharp body.
109        Ok(_) if corners == OffsetCorners::Rounded
110            && distance > 0.0
111            && super::outward_side_widen::widened_count() != widened_before
112            && super::revolved_parallel::revolved_parallel(source, distance).is_some() =>
113        {
114            return Ok(super::revolved_parallel::revolved_parallel(source, distance).unwrap());
115        }
116        Ok(sharp) => sharp,
117        Err(error) => {
118            if corners == OffsetCorners::Rounded {
119                if let Some(grown) = grown_by_pieces(source, distance) {
120                    return Ok(grown);
121                }
122                if let Some(grown) = super::revolved_parallel::revolved_parallel(source, distance) {
123                    return Ok(grown);
124                }
125                if let Some(grown) = super::pipe_parallel::pipe_parallel(source, distance) {
126                    return Ok(grown);
127                }
128            }
129            return Err(error);
130        }
131    };
132    match corners {
133        OffsetCorners::Sharp => Ok(sharp),
134        OffsetCorners::Rounded => match round_offset_joins(sharp, distance) {
135            Ok(rounded) => Ok(rounded),
136            // A mitred body cannot carry the ball over a vertex of degree four
137            // or more; a convex polyhedron's parallel body is built directly.
138            Err(error) => match crate::blend::convex_parallel::convex_polyhedron_parallel(source, distance) {
139                Ok(Some((solid, images))) if solid.validate().is_empty() => {
140                    let face_images = images
141                        .into_iter()
142                        .map(|image| OffsetShellFaceImageRecord { role: OffsetFaceRole::Offset, source_face_id: image.unwrap_or(0) })
143                        .collect();
144                    Ok(OffsetShellResultRecord { solid, face_images })
145                }
146                _ => super::revolved_parallel::revolved_parallel(source, distance)
147                    .or_else(|| super::pipe_parallel::pipe_parallel(source, distance))
148                    .ok_or(error),
149            },
150        },
151    }
152}
153
154/// `BREP_OFFSET_GROW_BY_PIECES` (default on; `=0` restores): [`grown_by_pieces`].
155fn grow_by_pieces_enabled() -> bool {
156    switch!("BREP_OFFSET_GROW_BY_PIECES", true)
157}
158
159
160/// The ROUNDED growth of a body whose own offset body the pipeline could not
161/// assemble, as the union of its pieces' growths: the parallel body of a
162/// union is the union of the parallel bodies, `(A ∪ B) ⊕ D = (A ⊕ D) ∪
163/// (B ⊕ D)`, for any pieces whose union is the body.
164///
165/// Cause (a drum with a groove 1.6 wide grown by 1, brep-bench
166/// offset/grooved-drum-grown): the groove's walls offset across each other,
167/// "a skin partly shadowed that way is not yet assembled", and even assembled
168/// the sharp body would have no groove left to round, while the case's notch
169/// is the two tori about the groove's outer rims. Cut at the planes of its
170/// planar faces the drum is three cylinders; each grows by the pipeline's own
171/// rounded offset, and their union carries the notch where the two rim tori
172/// cross.
173///
174/// The cuts are chosen by [`thin_pair_planes`] (the planes parallel to a pair
175/// of planar faces whose offsets cross), each kept only where it divides a
176/// piece (`split_solid_by_plane`). A SHRINK runs the same construction on the
177/// body's complement in a frame box ([`shrunk_by_pieces`]). Every piece must
178/// grow and the union must validate; anything else declines and the
179/// pipeline's own refusal stands. The faces are all `Offset` images with
180/// `source_face_id` 0, as the rounded caps are: a face of the union may carry
181/// the growth of several source faces' pieces.
182fn grown_by_pieces(source: &BrepSolid, distance: f64) -> Option<OffsetShellResultRecord> {
183    if !grow_by_pieces_enabled() {
184        return None;
185    }
186    match grown_by_pieces_impl(source, distance) {
187        Ok(result) => result,
188        Err(error) => {
189            os_debug!("grow by pieces declined: {error}");
190            None
191        }
192    }
193}
194
195fn grown_by_pieces_impl(source: &BrepSolid, distance: f64) -> Result<Option<OffsetShellResultRecord>, KernelRefusal> {
196    if distance < 0.0 {
197        return shrunk_by_pieces(source, -distance);
198    }
199    let Some(sets) = thin_pair_planes(source, distance, true)? else {
200        return Ok(None);
201    };
202    let mut answer = None;
203    for planes in &sets {
204        match grown_union(source, planes, distance) {
205            Ok(Some(solid)) => {
206                answer = Some(solid);
207                break;
208            }
209            Ok(None) => {}
210            Err(error) => os_debug!("grow by pieces: {} plane(s) declined: {error}", planes.len()),
211        }
212    }
213    let Some(solid) = answer else {
214        return Ok(None);
215    };
216    let face_images = solid
217        .shells
218        .iter()
219        .flat_map(|shell| &shell.faces)
220        .map(|_| OffsetShellFaceImageRecord { role: OffsetFaceRole::Offset, source_face_id: 0 })
221        .collect();
222    Ok(Some(OffsetShellResultRecord { solid, face_images }))
223}
224
225/// Roll the sharp body's joins that the ball of radius `|distance|` rounds:
226/// the convex edges of an outward offset, the concave edges of an inward one.
227/// A body with no such edge is already the parallel body and is returned as
228/// it is. Provenance: a face still on a sharp-body surface keeps that face's
229/// image; a cap (a cylinder, torus or corner ball the blend built, which lies
230/// on no offset face) is an `Offset` image with `source_face_id` 0, because it
231/// rounds a JOIN between source faces and has no single source face.
232fn round_offset_joins(
233    sharp: OffsetShellResultRecord,
234    distance: f64,
235) -> Result<OffsetShellResultRecord, KernelRefusal> {
236    let wanted_convex = distance > 0.0;
237    let midpoints = sharp_join_midpoints(&sharp.solid, wanted_convex)?;
238    if midpoints.is_empty() {
239        return Ok(sharp);
240    }
241    let solid = fillet_edges(&sharp.solid, &midpoints, None, distance.abs(), false, None)
242        .map_err(|error| {
243            error.with_message(|message| {
244                format!(
245                    "offset_solid: the rounded joins of the offset body could not be built \
246                     ({} edge(s) at radius {:.6}): {message}",
247                    midpoints.len(),
248                    distance.abs()
249                )
250            })
251        })?;
252    let operands = sharp
253        .solid
254        .shells
255        .iter()
256        .flat_map(|shell| &shell.faces)
257        .zip(&sharp.face_images)
258        .map(|(face, image)| (face, image.clone()))
259        .collect::<Vec<_>>();
260    let cap = OffsetShellFaceImageRecord {
261        role: OffsetFaceRole::Offset,
262        source_face_id: 0,
263    };
264    let face_images = provenance_by_surface(&solid, &operands, Some(&cap))?;
265    Ok(OffsetShellResultRecord { solid, face_images })
266}
267
268/// Per-face provenance of a body whose faces lie on its operands' surfaces (a
269/// boolean result, a blend's untouched faces): each result face takes the
270/// image of the FIRST operand face whose surface carries an interior point of
271/// it and whose trim contains that point's foot. Operands are matched in the
272/// order given, so a coincident pair (a held face and the opening it copies)
273/// resolves to whichever is listed first. A face on no operand surface takes
274/// `unmatched`, or refuses by name when there is none.
275pub(super) fn provenance_by_surface(
276    result: &BrepSolid,
277    operands: &[(&FaceRecord, OffsetShellFaceImageRecord)],
278    unmatched: Option<&OffsetShellFaceImageRecord>,
279) -> Result<Vec<OffsetShellFaceImageRecord>, KernelRefusal> {
280    let band = 1e-6 * crate::solid_scale(result).max(1.0);
281    let mut images = Vec::new();
282    for face in result.shells.iter().flat_map(|shell| &shell.faces) {
283        let seeds = super::source_seeds(result, face.id)?;
284        let seed = seeds[0];
285        let point = face.surface.evaluate(seed.x, seed.y).or_refuse(KernelStage::Sew, "evaluate")?;
286        let mut found = None;
287        for (operand, image) in operands {
288            let Ok(foot) = project_point_to_surface(&operand.surface, point) else { continue };
289            if foot.distance > band {
290                continue;
291            }
292            let inside = super::parameter_point_in_face(operand, Vec2 { x: foot.u, y: foot.v }, 1e-8)
293                .is_ok_and(|class| class != PolygonClass::Outside);
294            if inside {
295                found = Some(image.clone());
296                break;
297            }
298        }
299        match found.or_else(|| unmatched.cloned()) {
300            Some(image) => images.push(image),
301            None => {
302                return Err(KernelRefusal::internal(
303                    KernelStage::Sew,
304                    "offset_shell_provenance_lost",
305                    format!(
306                        "offset_shell: result face {} at ({:.4}, {:.4}, {:.4}) lies on no operand face",
307                        face.id, point.x, point.y, point.z
308                    ),
309                ))
310            }
311        }
312    }
313    Ok(images)
314}
315
316/// Midpoints of the SHARP edges of `solid` whose convexity is `convex`: an
317/// edge bordering two different faces whose outward normals differ there, read
318/// at the edge midpoint. Tangent junctions (a blend face meeting its support)
319/// and face-local seams are not joins and are skipped.
320fn sharp_join_midpoints(solid: &BrepSolid, convex: bool) -> Result<Vec<Vec3>, KernelRefusal> {
321    // Cosine of the dihedral angle above which two faces read as tangent.
322    const TANGENT_COSINE: f64 = 1.0 - 1e-6;
323    let faces = solid
324        .shells
325        .iter()
326        .flat_map(|shell| &shell.faces)
327        .collect::<Vec<_>>();
328    let mut uses = HashMap::<u64, Vec<(&FaceRecord, bool)>>::default();
329    for face in &faces {
330        for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
331            uses.entry(coedge.edge_id).or_default().push((face, coedge.forward));
332        }
333    }
334    let mut midpoints = Vec::new();
335    for edge in &solid.edges {
336        if edge.degenerate {
337            continue;
338        }
339        let Some(pair) = uses.get(&edge.id) else { continue };
340        if pair.len() != 2 || pair[0].0.id == pair[1].0.id {
341            continue;
342        }
343        if edge_is_convex_join(edge, pair[0], pair[1].0, TANGENT_COSINE)? == Some(convex) {
344            midpoints.push(edge.curve.evaluate(0.5 * (edge.t0 + edge.t1)).or_refuse(KernelStage::Classify, "evaluate")?);
345        }
346    }
347    Ok(midpoints)
348}
349
350/// `Some(true)` for a convex join, `Some(false)` for a concave one, `None` for
351/// a tangent junction. With `t` the direction the first face's coedge runs
352/// along the edge and `n_a` that face's outward normal, `n_a × t` points into
353/// the first face; the join is convex when the second face's outward normal
354/// points away from there.
355fn edge_is_convex_join(
356    edge: &EdgeRecord,
357    (first, first_forward): (&FaceRecord, bool),
358    second: &FaceRecord,
359    tangent_cosine: f64,
360) -> Result<Option<bool>, KernelRefusal> {
361    let t = 0.5 * (edge.t0 + edge.t1);
362    let derivatives = edge.curve.derivatives(t, 1).or_refuse(KernelStage::Classify, "derivatives")?;
363    let point = derivatives[0];
364    let mut tangent = derivatives[1].normalized().or_refuse(KernelStage::Classify, "normalized")?;
365    if !first_forward {
366        tangent = tangent.scale(-1.0);
367    }
368    let normal_a = outward_normal_at(first, point)?;
369    let normal_b = outward_normal_at(second, point)?;
370    if normal_a.dot(normal_b) >= tangent_cosine {
371        return Ok(None);
372    }
373    Ok(Some(normal_b.dot(normal_a.cross(tangent)) < 0.0))
374}
375
376fn outward_normal_at(face: &FaceRecord, point: Vec3) -> Result<Vec3, KernelRefusal> {
377    let foot = project_point_to_surface(&face.surface, point).or_refuse(KernelStage::Classify, "project_point_to_surface")?;
378    super::face_normal(face, foot.u, foot.v)
379}
380
381// ---------------------------------------------------------------------------
382// Shell as a boolean
383// ---------------------------------------------------------------------------
384
385/// The textbook shell: the offset body with the opening faces HELD (copied at
386/// distance zero, so they cancel in the difference), then `source − body` for
387/// an inward shell and `body − source` for an outward one. The walls at the
388/// openings come out of the boolean. `distance` carries `offset_shell`'s sign
389/// (positive inward).
390///
391/// This is the lane `offset_shell` falls back to when its direct construction
392/// refuses by one of its own names (`direct_refusal_takes_the_boolean_lane`);
393/// it is public so the two can be compared on any fixture. The result's
394/// `face_images` are read back from the operands by surface
395/// (`provenance_by_surface`): `Offset` for a face of the body's skins,
396/// `Wall` for a held opening face, `Source` for a face of the source.
397pub fn offset_shell_by_boolean(
398    source: &BrepSolid,
399    opening_face_ids: &[u64],
400    distance: f64,
401) -> Result<OffsetShellResultRecord, KernelRefusal> {
402    if let Some(scaled) = crate::rescale::ScaledOffset::of(source, distance, "offset_shell")? {
403        let mut record = offset_shell_by_boolean(&scaled.source, opening_face_ids, scaled.distance)
404            .map_err(|error| scaled.refusal(error))?;
405        record.solid = scaled.back(&record.solid, "offset_shell")?;
406        return Ok(record);
407    }
408    if opening_face_ids.is_empty() {
409        return Err(KernelRefusal::input(
410            KernelStage::Collect,
411            "offset_shell_no_opening",
412            "offset_shell: at least one opening face is required",
413        ));
414    }
415    let body = offset_body(source, opening_face_ids, distance, Body::Whole, "offset_shell_by_boolean")
416        .or_else(|error| {
417            if !direct_refusal_takes_the_boolean_lane(&error) {
418                return Err(error);
419            }
420            let result = super::joint_offset::build(source, opening_face_ids, distance);
421            if let Err(reason) = &result {
422                os_debug!("joint offset refused: {reason}");
423            }
424            result.map_err(|_| error)
425        })?;
426    let (kept, removed) = if distance > 0.0 { (source, &body.solid) } else { (&body.solid, source) };
427    let solid = boolean_operation(kept, removed, BooleanOperation::Subtract, &BooleanOptions::default())
428        .map_err(|error| {
429            error.with_message(|message| {
430                format!("offset_shell: the boolean lane's difference could not be built: {message}")
431            })
432        })?;
433    // The body's faces first, so the ring on a held face's plane reads as
434    // that face's `Wall` rather than as the coincident source opening.
435    let mut operands = body
436        .solid
437        .shells
438        .iter()
439        .flat_map(|shell| &shell.faces)
440        .zip(&body.face_images)
441        .map(|(face, image)| (face, image.clone()))
442        .collect::<Vec<_>>();
443    operands.extend(source.shells.iter().flat_map(|shell| &shell.faces).map(|face| {
444        (
445            face,
446            OffsetShellFaceImageRecord {
447                role: OffsetFaceRole::Source,
448                source_face_id: face.id,
449            },
450        )
451    }));
452    let face_images = provenance_by_surface(&solid, &operands, None)?;
453    Ok(OffsetShellResultRecord { solid, face_images })
454}
455
456/// Lane O row 34: the CLOSED hollow, a shell with no openings. The offset
457/// body, the whole source grown or shrunk with sharp joins, against the
458/// source: `source − body` inward and `body − source` outward, so the result
459/// is the outer shell and the inner void's shell, with the walls of the band
460/// between them. `distance` carries `offset_shell`'s sign (positive inward).
461/// `face_images` are read back from the operands by surface as in
462/// [`offset_shell_by_boolean`]: `Offset` for the body's faces, `Source` for
463/// the source's.
464///
465/// The construction checks itself: the result is exactly two shells and its
466/// volume is the difference of the operands' volumes.
467pub fn offset_shell_closed(source: &BrepSolid, distance: f64) -> Result<OffsetShellResultRecord, KernelRefusal> {
468    if let Some(scaled) = crate::rescale::ScaledOffset::of(source, distance, "offset_shell_closed")? {
469        let mut record = offset_shell_closed(&scaled.source, scaled.distance).map_err(|error| scaled.refusal(error))?;
470        record.solid = scaled.back(&record.solid, "offset_shell_closed")?;
471        return Ok(record);
472    }
473    let body = offset_body(source, &[], distance, Body::Whole, "offset_shell_closed")?;
474    let (kept, removed) = if distance > 0.0 { (source, &body.solid) } else { (&body.solid, source) };
475    let solid = boolean_operation(kept, removed, BooleanOperation::Subtract, &BooleanOptions::default())
476        .map_err(|error| {
477            error.with_message(|message| format!("offset_shell: the closed hollow's difference could not be built: {message}"))
478        })?;
479    let volume = |solid: &BrepSolid| {
480        crate::solid_mass_properties(solid)
481            .map(|properties| properties.volume)
482            .or_refuse(KernelStage::Validate, "solid_mass_properties")
483    };
484    let expected = volume(kept)? - volume(removed)?;
485    let measured = volume(&solid)?;
486    if solid.shells.len() != 2 || !(expected > 0.0) || !((measured - expected).abs() <= 1e-9 * expected) {
487        return Err(KernelRefusal::internal(
488            KernelStage::Validate,
489            "offset_shell_closed_hollow",
490            format!(
491                "offset_shell: the closed hollow is not the band between its operands ({} shells, volume {measured} against {expected})",
492                solid.shells.len()
493            ),
494        ));
495    }
496    let mut operands = body
497        .solid
498        .shells
499        .iter()
500        .flat_map(|shell| &shell.faces)
501        .zip(&body.face_images)
502        .map(|(face, image)| (face, image.clone()))
503        .collect::<Vec<_>>();
504    operands.extend(source.shells.iter().flat_map(|shell| &shell.faces).map(|face| {
505        (face, OffsetShellFaceImageRecord { role: OffsetFaceRole::Source, source_face_id: face.id })
506    }));
507    let face_images = provenance_by_surface(&solid, &operands, None)?;
508    Ok(OffsetShellResultRecord { solid, face_images })
509}
510
511/// Whether a refusal of the direct pipeline is one of its OWN named
512/// inabilities, the ones the boolean recipe can answer differently: an
513/// `offset_shell_*` unsupported-geometry or internal refusal, or the
514/// assembler's typed non-integral-genus and degenerate-arrangement refusals
515/// that `cause_in_front` carries a shell cause through. Input refusals
516/// (distance, foreign opening, no retained face) and soundness refusals are
517/// not: the first name a caller's mistake, the second a body that must not be
518/// shipped by any route.
519pub fn direct_refusal_takes_the_boolean_lane(refusal: &KernelRefusal) -> bool {
520    match &refusal.class {
521        RefusalClass::UnsupportedGeometry { what } | RefusalClass::Internal { what } => {
522            what.starts_with("offset_shell_")
523        }
524        RefusalClass::NonIntegralGenus { .. } => {
525            refusal.message.starts_with("offset_shell")
526                || (bare_genus_takes_the_boolean_lane() && refusal.message.starts_with("boolean assembly:"))
527        }
528        RefusalClass::DegenerateArrangement { .. } => refusal.message.starts_with("offset_shell"),
529        _ => false,
530    }
531}
532
533/// `BREP_OFFSET_BARE_GENUS_BOOLEAN_LANE` (default on; `=0` restores): the
534/// direct pipeline's assembly refusing a non-integral genus takes the boolean
535/// lane even with no shell cause put in front of it. Which sentence a refusal
536/// carries says nothing about whether the lane can answer:
537/// `inbox_20261017_negative_shell` only reached the lane through the note of
538/// an omission, and the omission was a misread fillet's true skin; reading
539/// that skin correctly (`BREP_OFFSET_TANGENT_EDGE_EUCLID`) left the same
540/// failed assembly with no note, and the shell was refused.
541fn bare_genus_takes_the_boolean_lane() -> bool {
542    crate::switch!("BREP_OFFSET_BARE_GENUS_BOOLEAN_LANE", true)
543}
544
545/// The cut planes: every planar face's plane parallel to a THIN PAIR, two
546/// planar faces with opposite outward normals closer than `2·amount` that face
547/// each other across void (`grow`) or across material (shrink) — the pair
548/// whose offsets cross. Deduplicated. Two sets are offered in turn: every
549/// planar face's plane parallel to a thin pair, then the thin pairs' own
550/// planes alone (when fewer), because the boolean that unions the grown
551/// pieces can fail on where one set's pieces meet and not the other's (the
552/// dumbbell's complement cut at all four y planes left sliver edges where the
553/// neck-mouth rounds of adjacent pieces cross). `None` when there is no thin
554/// pair or every set has more than eight planes.
555fn thin_pair_planes(solid: &BrepSolid, amount: f64, grow: bool) -> Result<Option<Vec<Vec<(Vec3, Vec3)>>>, KernelRefusal> {
556    let band = 1e-9 * crate::solid_scale(solid).max(1.0);
557    // Each planar face's plane, its OUTWARD normal.
558    let mut faces: Vec<(Vec3, Vec3)> = Vec::new();
559    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
560        let Some((point, normal)) = super::rim_welds::planar_surface_frame(&face.surface, band)? else {
561            continue;
562        };
563        let [u0, u1] = face.surface.domain_u().or_refuse(KernelStage::Refine, "domain_u")?;
564        let [v0, v1] = face.surface.domain_v().or_refuse(KernelStage::Refine, "domain_v")?;
565        let Ok(outward) = super::face_normal(face, 0.5 * (u0 + u1), 0.5 * (v0 + v1)) else {
566            continue;
567        };
568        faces.push((point, if outward.dot(normal) < 0.0 { normal.scale(-1.0) } else { normal }));
569    }
570    let mut directions: Vec<Vec3> = Vec::new();
571    let mut pairs: Vec<(usize, usize)> = Vec::new();
572    for (index, (point, normal)) in faces.iter().enumerate() {
573        for (offset, (other, other_normal)) in faces[index + 1..].iter().enumerate() {
574            if normal.dot(*other_normal) > -1.0 + 1e-12 {
575                continue;
576            }
577            // Signed gap from this face's plane to the other's, along this
578            // face's outward normal: positive across void, negative across
579            // material.
580            let gap = other.sub(*point).dot(*normal);
581            let thin = if grow { gap > band && gap < 2.0 * amount } else { gap < -band && -gap < 2.0 * amount };
582            if thin {
583                pairs.push((index, index + 1 + offset));
584                if !directions.iter().any(|axis| axis.dot(*normal).abs() >= 1.0 - 1e-12) {
585                    directions.push(*normal);
586                }
587            }
588        }
589    }
590    if directions.is_empty() {
591        return Ok(None);
592    }
593    let push = |planes: &mut Vec<(Vec3, Vec3)>, point: Vec3, normal: Vec3| {
594        let seen = planes
595            .iter()
596            .any(|(other, axis)| axis.dot(normal).abs() >= 1.0 - 1e-12 && point.sub(*other).dot(*axis).abs() <= band);
597        if !seen {
598            planes.push((point, normal));
599        }
600    };
601    let mut parallel: Vec<(Vec3, Vec3)> = Vec::new();
602    for (point, normal) in &faces {
603        if directions.iter().any(|axis| axis.dot(*normal).abs() >= 1.0 - 1e-12) {
604            push(&mut parallel, *point, *normal);
605        }
606    }
607    let mut paired: Vec<(Vec3, Vec3)> = Vec::new();
608    for (first, second) in &pairs {
609        push(&mut paired, faces[*first].0, faces[*first].1);
610        push(&mut paired, faces[*second].0, faces[*second].1);
611    }
612    let mut sets = Vec::new();
613    if parallel.len() <= 8 {
614        sets.push(parallel.clone());
615    }
616    if paired.len() <= 8 && paired.len() < parallel.len() {
617        sets.push(paired);
618    }
619    Ok((!sets.is_empty()).then_some(sets))
620}
621
622/// `solid` cut by every plane that divides a piece of it.
623fn cut_by_planes(solid: &BrepSolid, planes: &[(Vec3, Vec3)]) -> Vec<BrepSolid> {
624    let mut pieces = vec![solid.clone()];
625    for (point, normal) in planes {
626        let mut next = Vec::with_capacity(pieces.len() * 2);
627        for piece in pieces {
628            match crate::split_solid_by_plane(&piece, *point, *normal) {
629                Ok((below, above)) => {
630                    next.push(below);
631                    next.push(above);
632                }
633                Err(_) => next.push(piece),
634            }
635        }
636        pieces = next;
637    }
638    pieces
639}
640
641/// The SHRINK by `amount` through the complement: `S ⊖ D = S − ((F − S) ⊕ D)`
642/// for a frame box `F` reaching past `S` by more than `amount`, where the
643/// complement's growth is the union of its pieces' growths, the pieces cut at
644/// the planes of `S`'s planar faces.
645///
646/// Cause (a drum with a flange 1.6 thick shrunk by 1, brep-bench
647/// offset/flanged-drum-shrunk): the flange's two faces offset across each
648/// other ("a skin partly shadowed that way is not yet assembled"), and the
649/// low ridge the case reads is the two concave tori about the flange's inner
650/// rims, which the complement's pieces carry as the rounds of their own
651/// convex rims.
652fn shrunk_by_pieces(source: &BrepSolid, amount: f64) -> Result<Option<OffsetShellResultRecord>, KernelRefusal> {
653    let Some(sets) = thin_pair_planes(source, amount, false)? else {
654        return Ok(None);
655    };
656    let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
657    let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
658    for face in source.shells.iter().flat_map(|shell| &shell.faces) {
659        for control in face.surface.control_points.iter().flatten() {
660            let Ok(point) = control.point() else { return Ok(None) };
661            low = Vec3::new(low.x.min(point.x), low.y.min(point.y), low.z.min(point.z));
662            high = Vec3::new(high.x.max(point.x), high.y.max(point.y), high.z.max(point.z));
663        }
664    }
665    let margin = 3.0 * amount;
666    let corner = low.sub(Vec3::new(margin, margin, margin));
667    let size = high.sub(low).add(Vec3::new(2.0 * margin, 2.0 * margin, 2.0 * margin));
668    let frame = crate::make_box_brep(corner, size.x, size.y, size.z).or_refuse(KernelStage::Refine, "make_box_brep")?;
669    let options = BooleanOptions::default();
670    let outside = boolean_operation(&frame, source, BooleanOperation::Subtract, &options)?;
671    let mut answer = None;
672    for planes in &sets {
673        let attempt = grown_union(&outside, planes, amount).and_then(|reach| match reach {
674            Some(reach) => boolean_operation(source, &reach, BooleanOperation::Subtract, &options).map(Some),
675            None => Ok(None),
676        });
677        match attempt {
678            Ok(Some(solid)) if solid.validate().is_empty() => {
679                answer = Some(solid);
680                break;
681            }
682            Ok(_) => {}
683            Err(error) => os_debug!("shrink by pieces: {} plane(s) declined: {error}", planes.len()),
684        }
685    }
686    if answer.is_none() && shrink_by_subtraction_enabled() {
687        for planes in &sets {
688            match subtracted_one_by_one(source, &outside, planes, amount) {
689                Ok(Some(solid)) => {
690                    answer = Some(solid);
691                    break;
692                }
693                Ok(None) => {}
694                Err(error) => os_debug!("shrink by subtraction: {} plane(s) declined: {error}", planes.len()),
695            }
696        }
697    }
698    let Some(solid) = answer else {
699        return Ok(None);
700    };
701    let face_images = solid
702        .shells
703        .iter()
704        .flat_map(|shell| &shell.faces)
705        .map(|_| OffsetShellFaceImageRecord { role: OffsetFaceRole::Offset, source_face_id: 0 })
706        .collect();
707    Ok(Some(OffsetShellResultRecord { solid, face_images }))
708}
709
710/// `solid` cut at `planes`, each piece grown by `amount` with rounded joins,
711/// and the growths' union; `None` when the planes leave one piece or the
712/// union does not validate.
713fn grown_union(solid: &BrepSolid, planes: &[(Vec3, Vec3)], amount: f64) -> Result<Option<BrepSolid>, KernelRefusal> {
714    let Some(grown) = grown_pieces(solid, planes, amount)? else {
715        return Ok(None);
716    };
717    let union = crate::boolean_operation_nary(&grown, BooleanOperation::Union)?;
718    Ok(union.validate().is_empty().then_some(union))
719}
720
721/// `solid` cut at `planes`, each piece grown by `amount` with rounded joins;
722/// `None` when the planes leave one piece.
723fn grown_pieces(solid: &BrepSolid, planes: &[(Vec3, Vec3)], amount: f64) -> Result<Option<Vec<BrepSolid>>, KernelRefusal> {
724    let pieces = cut_by_planes(solid, planes);
725    if pieces.len() < 2 {
726        return Ok(None);
727    }
728    os_debug!("by pieces: {} plane(s) cut the body into {} piece(s)", planes.len(), pieces.len());
729    let mut grown = Vec::with_capacity(pieces.len());
730    for (index, piece) in pieces.iter().enumerate() {
731        let sharp = offset_body(piece, &[], -amount, Body::Whole, "offset_solid_piece")
732            .map_err(|error| error.with_message(|message| format!("piece {index}: {message}")))?;
733        grown.push(round_offset_joins(sharp, amount)?.solid);
734    }
735    Ok(Some(grown))
736}
737
738/// `BREP_OFFSET_SHRINK_BY_SUBTRACTION` (default on; `=0` restores): where the union of a
739/// shrink's grown complement pieces cannot be assembled, the pieces are
740/// subtracted from the body one at a time instead.
741///
742/// Cause (the dumbbell plate shrunk by 1.5, brep-bench
743/// shell/dumbbell-neck-filled): the grown pieces' concave rounds about the
744/// neck mouths cross at y = 5, and their n-ary union failed ("boolean assembly
745/// produced invalid topology (S=3 genus=2)", one-use edges ~3e-5 long near
746/// (8.882, 5, 1.5)) for every plane set. `S − (A ∪ B) = (S − A) − B`.
747fn shrink_by_subtraction_enabled() -> bool {
748    switch!("BREP_OFFSET_SHRINK_BY_SUBTRACTION", true)
749}
750
751
752fn subtracted_one_by_one(source: &BrepSolid, outside: &BrepSolid, planes: &[(Vec3, Vec3)], amount: f64) -> Result<Option<BrepSolid>, KernelRefusal> {
753    let Some(grown) = grown_pieces(outside, planes, amount)? else {
754        return Ok(None);
755    };
756    let options = BooleanOptions::default();
757    let mut body = source.clone();
758    for (index, piece) in grown.iter().enumerate() {
759        body = boolean_operation(&body, piece, BooleanOperation::Subtract, &options)
760            .map_err(|error| error.with_message(|message| format!("subtracting grown piece {index}: {message}")))?;
761    }
762    Ok(body.validate().is_empty().then_some(body))
763}
764
765/// `BREP_OFFSET_REFLEX_BY_PIECES` (default on; `=0` restores): [`grown_across_reflex_edges`].
766fn reflex_by_pieces_enabled() -> bool {
767    switch!("BREP_OFFSET_REFLEX_BY_PIECES", true)
768}
769
770
771/// The ROUNDED growth of a body with CONCAVE (reflex) edges between planar
772/// faces, as the union of its pieces' growths, the pieces cut at those
773/// faces' planes; `None` (and the ordinary sharp body + rounds) where the body
774/// has none, or a piece or the union fails.
775///
776/// Cause (an L-shaped plate grown by 1, brep-bench offset/l-block-grown, read
777/// volume +0.041 and area −0.061 against the closed form): the sharp body is
778/// right, but where its reflex edge meets the top and bottom, the rounds of
779/// the two convex edges beside it must meet in a sharp concave crease, and
780/// `fillet_edges` blends that corner instead. Cut at x = 5 the plate is two
781/// boxes; each grows to a rounded box exactly, and their union carries the
782/// crease as the two rounds' own intersection.
783fn grown_across_reflex_edges(source: &BrepSolid, distance: f64) -> Option<OffsetShellResultRecord> {
784    if !reflex_by_pieces_enabled() {
785        return None;
786    }
787    let attempt = || -> Result<Option<OffsetShellResultRecord>, KernelRefusal> {
788        let band = 1e-9 * crate::solid_scale(source).max(1.0);
789        let faces = source.shells.iter().flat_map(|shell| &shell.faces).collect::<Vec<_>>();
790        let mut uses = HashMap::<u64, Vec<(&FaceRecord, bool)>>::default();
791        for face in &faces {
792            for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
793                uses.entry(coedge.edge_id).or_default().push((face, coedge.forward));
794            }
795        }
796        let mut planes: Vec<(Vec3, Vec3)> = Vec::new();
797        for edge in &source.edges {
798            if edge.degenerate {
799                continue;
800            }
801            let Some(pair) = uses.get(&edge.id) else { continue };
802            if pair.len() != 2 || pair[0].0.id == pair[1].0.id {
803                continue;
804            }
805            if edge_is_convex_join(edge, pair[0], pair[1].0, 1.0 - 1e-6)? != Some(false) {
806                continue;
807            }
808            for (face, _) in pair {
809                let Some((point, normal)) = super::rim_welds::planar_surface_frame(&face.surface, band)? else {
810                    continue;
811                };
812                let seen = planes
813                    .iter()
814                    .any(|(other, axis)| axis.dot(normal).abs() >= 1.0 - 1e-12 && point.sub(*other).dot(*axis).abs() <= band);
815                if !seen {
816                    planes.push((point, normal));
817                }
818            }
819        }
820        if planes.is_empty() || planes.len() > 8 {
821            return Ok(None);
822        }
823        // One plane per reflex edge is enough, and fewer pieces meet in fewer
824        // places: try each plane alone first, then all of them.
825        let mut sets = planes.iter().map(|plane| vec![*plane]).collect::<Vec<_>>();
826        if planes.len() > 1 {
827            sets.push(planes.clone());
828        }
829        for set in &sets {
830            match grown_union(source, set, distance) {
831                Ok(Some(solid)) => {
832                    os_debug!("reflex by pieces: {} plane(s)", set.len());
833                    let face_images = solid
834                        .shells
835                        .iter()
836                        .flat_map(|shell| &shell.faces)
837                        .map(|_| OffsetShellFaceImageRecord { role: OffsetFaceRole::Offset, source_face_id: 0 })
838                        .collect();
839                    return Ok(Some(OffsetShellResultRecord { solid, face_images }));
840                }
841                Ok(None) => {}
842                Err(error) => os_debug!("reflex by pieces: {} plane(s) declined: {error}", set.len()),
843            }
844        }
845        Ok(None)
846    };
847    match attempt() {
848        Ok(result) => result,
849        Err(error) => {
850            os_debug!("reflex by pieces declined: {error}");
851            None
852        }
853    }
854}