Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

11.0 KB
Raw Blame
//! Face and edge history out of SMLib operations, in [`solidcore_record::brep::history`]'s terms.
//!
//! SMLib carries identity through its own edits: every split, merge, copy and coincidence an
//! operation makes passes the attributes of what it changes on to what it makes. So each operand
//! is tagged ([`Brep::tagged`]: face i and edge i become operand k's face i and edge i), the
//! operation runs on the tagged copies, and the result's tags say where each face and edge came
//! from ([`Brep::history`]). Nothing is sampled or guessed.
//!
//! Indices here are SMLib's own: positions in a body's face and edge lists, which a copy keeps.
//! [`Raw::history`] renumbers them into canonical order (docs/native-brep.md) with the
//! [`Order`] the export gives each body.

use std::collections::BTreeSet;

use solidcore_record::brep::history::{Change, EdgeOrigin, EdgeProv, FaceOrigin, FaceProv, Failed, History, Side};

use crate::{Brep, Result, core};

/// A result face as SMLib reports it: how it relates to its origins, and the (operand, face)
/// pairs it came from, sorted.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RawFace {
    pub change: Change,
    pub origins: Vec<(usize, usize)>,
}

/// A result edge as SMLib reports it: the result faces it bounds (ascending) and the (operand,
/// edge) pairs it came from, sorted; none where it is new (where its faces meet).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RawEdge {
    pub faces: Vec<usize>,
    pub origins: Vec<(usize, usize)>,
}

/// A result's history in SMLib's own face and edge order.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Raw {
    pub faces: Vec<RawFace>,
    pub edges: Vec<RawEdge>,
}

/// Where one body's faces and edges go in canonical order: `faces[i]` is the canonical index of
/// SMLib's face i, likewise for edges. Empty means SMLib's order is the canonical one.
///
/// An SMLib edge solids touch along (non-manifold) becomes one record edge per solid:
/// `edges[i]` is the first of them, and `pieces` lists every piece of such an edge, the first
/// too, with the canonical faces it bounds.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Order {
    pub faces: Vec<usize>,
    pub edges: Vec<usize>,
    pub pieces: Vec<Piece>,
}

/// One record edge of an SMLib edge split where solids touch along it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Piece {
    /// The SMLib edge.
    pub edge: usize,
    /// The record edge.
    pub canonical: usize,
    /// The canonical faces it bounds, ascending.
    pub faces: Vec<usize>,
}

impl Brep {
    /// A copy whose face i and edge i are tagged as face i and edge i of operand `operand` (in
    /// SMLib's order, which the copy keeps). Run an operation on tagged copies, then read its
    /// result's [`Brep::history`].
    pub fn tagged(&self, operand: usize) -> Result<Brep> {
        let r = core::history::tag(self.core(), operand).map(Brep::made_core);
        crate::trace::made("tagged", &[self], &r, || serde_json::json!({"operand": operand}));
        r
    }

    /// The history of this body, made by an operation from tagged operands: each face's and
    /// edge's origins among them. Faces and edges no tag reached have none.
    pub fn history(&self) -> Result<Raw> {
        core::history::read(self.core())
    }
}

impl Raw {
    /// As a [`History`] over `operands.len()` operands, every index renumbered into canonical
    /// order: operand k's through `operands[k]`, the result's through `result`. An edge with no
    /// origin is where its two faces meet; one bounding other than two faces, or a face new to
    /// the operation, has no origin at all.
    pub fn history(&self, operands: &[Order], result: &Order) -> std::result::Result<History, Failed> {
        let bad = |what: &'static str| Failed(what);
        let map = |order: &[usize], i: usize| -> std::result::Result<usize, Failed> {
            if order.is_empty() { Ok(i) } else { order.get(i).copied().ok_or(bad("an index lies outside its body's order")) }
        };
        let operand = |k: usize| operands.get(k).ok_or(bad("an origin lies on no operand"));
        let face_origin = |(k, f): (usize, usize)| -> std::result::Result<FaceOrigin, Failed> {
            let o = operand(k)?;
            Ok(FaceOrigin::Face { operand: k, face: map(&o.faces, f)? })
        };
        // The result's faces and edges, each at its canonical place.
        let place = |order: &[usize], n: usize| -> std::result::Result<Vec<usize>, Failed> {
            let at: Vec<usize> = (0..n).map(|i| map(order, i)).collect::<std::result::Result<_, _>>()?;
            let distinct: BTreeSet<usize> = at.iter().copied().collect();
            if distinct.len() != n || at.iter().any(|c| *c >= n) {
                return Err(bad("the result's order is no permutation"));
            }
            Ok(at)
        };
        let fat = place(&result.faces, self.faces.len())?;
        // Each raw edge's record edges with the faces each bounds where it is split (`None`: as
        // SMLib has them); together a permutation of the result's edges.
        let n_edges = self.edges.len() + result.pieces.len() - result.pieces.iter().map(|p| p.edge).collect::<BTreeSet<_>>().len();
        let mut targets: Vec<(usize, usize, Option<&[usize]>)> = Vec::with_capacity(n_edges);
        for i in 0..self.edges.len() {
            let mut split = result.pieces.iter().filter(|p| p.edge == i).peekable();
            if split.peek().is_none() {
                targets.push((i, map(&result.edges, i)?, None));
            } else {
                targets.extend(split.map(|p| (i, p.canonical, Some(p.faces.as_slice()))));
            }
        }
        let distinct: BTreeSet<usize> = targets.iter().map(|t| t.1).collect();
        if targets.len() != n_edges || distinct.len() != n_edges || targets.iter().any(|t| t.1 >= n_edges) {
            return Err(bad("the result's order is no permutation"));
        }

        let mut faces: Vec<Option<FaceProv>> = vec![None; self.faces.len()];
        for (f, at) in self.faces.iter().zip(&fat) {
            let origins: BTreeSet<FaceOrigin> = f.origins.iter().map(|o| face_origin(*o)).collect::<std::result::Result<_, _>>()?;
            faces[*at] = Some(FaceProv { origins: origins.into_iter().collect(), change: f.change });
        }
        let faces: Vec<FaceProv> = faces.into_iter().collect::<Option<_>>().ok_or(bad("the result's order is no permutation"))?;

        let mut edges: Vec<Option<EdgeProv>> = vec![None; n_edges];
        for &(i, at, split) in &targets {
            let e = self.edges.get(i).ok_or(bad("an edge lies outside the result"))?;
            let bounds: Vec<usize> = match split {
                Some(faces) => faces.to_vec(),
                None => {
                    let bounds: BTreeSet<usize> = e
                        .faces
                        .iter()
                        .map(|f| fat.get(*f).copied().ok_or(bad("an edge lies on a face outside the result")))
                        .collect::<std::result::Result<_, _>>()?;
                    bounds.into_iter().collect()
                }
            };
            let origins = if e.origins.is_empty() {
                // New: where its two faces meet, each side what that face came from. Between two
                // pieces of one face (a split line) nothing met: it comes from nothing.
                let side = |f: usize| faces.get(f).and_then(|p| Side::new(p.origins.iter().copied()));
                match bounds.as_slice() {
                    [a, b] => side(*a).zip(side(*b)).filter(|(a, b)| a != b).map(|(a, b)| EdgeOrigin::meet(a, b)).into_iter().collect(),
                    _ => Vec::new(),
                }
            } else {
                let set: BTreeSet<EdgeOrigin> = e
                    .origins
                    .iter()
                    .map(|(k, i)| {
                        let o = operand(*k)?;
                        Ok(EdgeOrigin::Edge { operand: *k, edge: map(&o.edges, *i)? })
                    })
                    .collect::<std::result::Result<_, Failed>>()?;
                set.into_iter().collect()
            };
            *edges.get_mut(at).ok_or(bad("the result's order is no permutation"))? = Some(EdgeProv { faces: bounds, origins });
        }
        let edges: Vec<EdgeProv> = edges.into_iter().collect::<Option<_>>().ok_or(bad("the result's order is no permutation"))?;
        Ok(History { operands: operands.len(), faces, edges })
    }
}

/// A blend's faces (fillet, chamfer) in `h`, the history of a blend of edges `picked` of its
/// one operand (operand 0), whose own edges `operand` lists (the faces each bounds, as in the
/// operand's identity history), which also took up edges `taken_up` (no result edge comes from
/// them: a corner's short edge, or an edge the blend ran over): SMLib makes a blend face with no
/// tag, so each Generated face is given [`FaceOrigin::Edge`] for every picked edge whose two
/// faces both lie under faces next to it and no longer meet each other directly, and only where
/// no picked edge is such, every taken-up edge that is. A chamfer running up past the end of the
/// face beside it takes up that face's side edge and lies between its faces too: it is made from
/// the picked edge alone. A corner patch between several blends matches none of them and stays
/// without origin.
pub fn blends(h: &mut History, operand: &[EdgeProv], picked: &[usize], taken_up: &[usize]) {
    let mut next_to: Vec<BTreeSet<FaceOrigin>> = vec![BTreeSet::new(); h.faces.len()];
    for e in &h.edges {
        for f in &e.faces {
            for g in &e.faces {
                if let (Some(set), Some(p)) = (next_to.get_mut(*f), h.faces.get(*g))
                    && f != g
                {
                    set.extend(p.origins.iter().copied());
                }
            }
        }
    }
    // Pairs of operand faces whose result faces still meet along an edge.
    let mut meeting: BTreeSet<(FaceOrigin, FaceOrigin)> = BTreeSet::new();
    for e in &h.edges {
        if let [a, b] = e.faces.as_slice()
            && let (Some(a), Some(b)) = (h.faces.get(*a), h.faces.get(*b))
        {
            for x in &a.origins {
                for y in &b.origins {
                    meeting.insert((*x.min(y), *x.max(y)));
                }
            }
        }
    }
    for (f, around) in h.faces.iter_mut().zip(&next_to) {
        if f.change != Change::Generated || !f.origins.is_empty() {
            continue;
        }
        let under = |e: &&usize| {
            operand.get(**e).is_some_and(|p| {
                let [a, b] = p.faces.as_slice() else { return false };
                let (a, b) = (FaceOrigin::Face { operand: 0, face: *a }, FaceOrigin::Face { operand: 0, face: *b });
                around.contains(&a) && around.contains(&b) && !meeting.contains(&(a.min(b), a.max(b)))
            })
        };
        let mut edges: Vec<usize> = picked.iter().filter(under).copied().collect();
        if edges.is_empty() {
            edges = taken_up.iter().filter(under).copied().collect();
        }
        f.origins = edges.into_iter().map(|e| FaceOrigin::Edge { operand: 0, edge: e }).collect();
    }
}

#[cfg(test)]
mod tests;