BREP_kernel 0.33.0

Rust B-rep CAD kernel (next.BREP.io): a boundary representation (B-rep) geometry kernel for building CAD applications, native and WebAssembly.
Documentation
use super::*;
use super::chain::weld_chain;
use super::geometry::{Loop, Segment};

/// Move segments into their planned closed loops (each index claimed at most
/// once across the plans; open-chain segments stay behind — their geometry is
/// already emitted as the path or is a secondary open chain, exactly the established
/// `openChains` that never join the profile).
pub(super) fn assemble_loops(segments: Vec<Segment>, plans: Vec<Vec<(usize, bool)>>) -> Vec<Loop> {
    let mut slots: Vec<Option<Segment>> = segments.into_iter().map(Some).collect();
    let mut loops = Vec::with_capacity(plans.len());
    for plan in plans {
        let mut entries = Vec::with_capacity(plan.len());
        for (index, reversed) in plan {
            let segment = slots[index]
                .take()
                .expect("each segment is claimed by exactly one loop");
            entries.push((segment, reversed));
        }
        // `loop_id` is resolved over the whole assembled set once, downstream
        // (`loop_ids::resolve`) — assembly itself decides no identity.
        loops.push(Loop {
            entries,
            loop_id: None,
        });
    }
    loops
}

/// Group the EMITTED closed loops into disjoint REGIONS by even-odd containment
/// depth: a depth-EVEN loop is a region's OUTER boundary; a depth-ODD loop is a
/// hole of the region whose outer directly contains it (so an island inside a
/// hole becomes its own region — the even-odd material rule). Containment is
/// decided on the emitted curves themselves — the geometry the solid is built
/// from — by the shared predicate in [`crate::feature_pipeline::loop_nesting`]
/// (adaptive exact sampling, a vote of interior points, boundary points
/// abstain). Regions come back in original loop order, each `[outer, holes…]`
/// (holes in loop order too).
pub(super) fn classify_regions(
    loops: Vec<ProfileLoop>,
    frame: &Frame,
) -> Result<Vec<Vec<ProfileLoop>>, String> {
    use crate::feature_pipeline::loop_nesting::{containment, sample_loops, PlaneFrame};
    let count = loops.len();
    if count == 1 {
        return Ok(vec![loops]);
    }
    let curves: Vec<&[NurbsCurve]> = loops.iter().map(|l| l.curves.as_slice()).collect();
    let sampled = sample_loops(
        &curves,
        PlaneFrame {
            origin: frame.origin,
            x_axis: frame.x_axis,
            y_axis: frame.y_axis,
        },
    )?;
    // contains[i][j]: loop i lies inside loop j.
    let contains = containment(&sampled);
    let depth: Vec<usize> = (0..count)
        .map(|i| contains[i].iter().filter(|inside| **inside).count())
        .collect();
    // Plan the regions on indices: each depth-even loop opens a region; each
    // depth-odd loop joins the region of its DIRECT parent (the containing
    // loop exactly one level up — unique when the loops properly nest).
    let mut plans: Vec<(usize, Vec<usize>)> = (0..count)
        .filter(|&i| depth[i] % 2 == 0)
        .map(|i| (i, Vec::new()))
        .collect();
    for hole in 0..count {
        if depth[hole] % 2 == 0 {
            continue;
        }
        let parent = (0..count)
            .find(|&j| contains[hole][j] && depth[j] + 1 == depth[hole])
            .ok_or("sketch: loop containment is inconsistent (crossing loops?)")?;
        plans
            .iter_mut()
            .find(|(outer, _)| *outer == parent)
            .expect("a hole's direct parent is depth-even, so it opened a region")
            .1
            .push(hole);
    }
    // Move the loops into their planned regions.
    let mut slots: Vec<Option<ProfileLoop>> = loops.into_iter().map(Some).collect();
    let mut regions = Vec::with_capacity(plans.len());
    for (outer, holes) in plans {
        let mut region = Vec::with_capacity(holes.len() + 1);
        region.push(slots[outer].take().expect("each loop lands in one region"));
        for hole in holes {
            region.push(slots[hole].take().expect("each loop lands in one region"));
        }
        regions.push(region);
    }
    Ok(regions)
}

/// Emit a loop's curves in the plane frame, head-to-tail and welded exactly
/// closed ([`weld_chain`]), with the parallel per-curve source edge names.
pub(super) fn emit_loop(loop_data: &Loop, frame: &Frame) -> Result<ProfileLoop, String> {
    let mut curves = Vec::with_capacity(loop_data.entries.len());
    let mut edge_names = Vec::with_capacity(loop_data.entries.len());
    for (segment, reversed) in &loop_data.entries {
        curves.push(segment.to_curve(frame, *reversed)?);
        edge_names.push(segment.name.clone());
    }
    weld_chain(&mut curves, true);
    // A single closed Bézier is a valid sketch loop, but profile consumers
    // require at least two boundary curves (as for circles and ellipses).
    // Split exactly by knot insertion, preserving both source edge and loop
    // identity. Keep the path/per-geometry publications as one source curve.
    if curves.len() == 1 {
        let [start, end] = curves[0].domain()?;
        let (first, second) = curves[0].split((start + end) * 0.5)?;
        curves = vec![first, second];
        edge_names.push(edge_names[0].clone());
    }
    Ok(ProfileLoop {
        curves,
        edge_names,
        loop_id: loop_data.loop_id,
    })
}