//! Extend (Surface › Extend): boundary edges of a surface body pushed outward across their
//! face, by a distance, up to a plane or a face, or (natural only) back to the surface's own
//! bounds. Three ways to continue past an edge, each SMLib's extension of the surface
//! (`smlib_extend_sheet`, `SmBSplineSurface::CreateExtendedSurface`):
//!
//! - natural: the surface itself continued (a B-spline's end spans as their own polynomials,
//! which keeps a plane, a cylinder or any conic section on itself);
//! - tangent: continued tangent to the surface across the edge (G1);
//! - curvature: continued keeping the surface's curvature across the edge too (G2).
//!
//! The face is extended where it is its surface's whole parameter box and the edge is a whole
//! side of it: the box grows past that side, the sides next to it continue along the surface's
//! parameter lines, and the face stays one face on the extended surface. Edges picked on two
//! sides grow the box on both, meeting at the box's corner.
//!
//! A body of several faces grows face by face, each extended alone as above and the faces sewn
//! back together. A side that lengthens is shared with the face next to it: that face grows too,
//! past its edge continuing the picked one, when the two meet tangent along the side (the faces
//! of one smooth surface, a spline's spans extruded, grow as one); across a crease it grows only
//! when that edge is picked as well, and otherwise the extension is refused (it would run past
//! the face beside it). The lengthened sides must meet again: faces whose extensions part are
//! refused. Up to a target, the face is extended
//! past it and trimmed back where the target meets it ([`crate::trim_keep`]: SMLib's exact
//! intersection). Back to the bounds is the face untrimmed to its surface's box
//! ([`crate::untrim`]). A plane's straight edges pushed out with their neighbours lengthened
//! keep the exact planar extension ([`crate::surfaces::extend`]).
//!
//! Refused rather than built: edges between two faces, edges of holes, and (not supported yet)
//! an edge that is not a whole side of its surface's box (a trimmed edge, whose extension is no
//! curve SMLib holds exactly).
use std::collections::{BTreeMap, BTreeSet};
use solidcraft_geom::Vec3;
use solidcraft_geom::brep::{self, eval::CurveEval};
use solidcraft_smlib::trim::Continuation;
use crate::body::Body;
use crate::history::{Change, FaceOrigin};
use crate::native::{body_from_smlib_ordered, smlib_body_ordered};
use crate::surface_trim::TrimKeep;
use crate::surfaces::Parts;
use crate::{KernelError, Result, SplitTool, record};
/// Most edge picks.
const MAX_PICKS: usize = 10_000;
/// How far past its edge, in body sizes, an extension up to a target runs before it is trimmed
/// back to the target: a target farther than that is not reached.
const REACH: f64 = 50.0;
/// Samples along an edge that find the edge nearest a pick.
const PICK_SAMPLES: usize = 32;
/// How a surface continues past its edge.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ExtendMode {
/// The surface itself, continued.
#[default]
Natural,
/// Continued tangent to the surface across the edge (G1).
Tangent,
/// Continued keeping the surface's curvature across the edge (G2).
Curvature,
}
/// How far an extension goes.
#[derive(Clone, Copy, Debug)]
pub enum ExtendLimit<'a> {
/// This far from the edge, measured across the surface.
Distance(f64),
/// To where it meets a plane, or the surface of a face (extended).
UpTo(&'a SplitTool<'a>),
/// Back to the surface's own bounds (natural only), undoing a trim: a free-form surface's
/// parameter box, an analytic surface's the box of the face's own span.
Bounds,
}
/// What [`extend_surface`] does.
#[derive(Clone, Copy, Debug)]
pub struct ExtendOptions<'a> {
pub mode: ExtendMode,
pub limit: ExtendLimit<'a>,
/// Lengthen the edges next to an extended edge to meet the extension. On a face that is its
/// surface's whole box those edges are parameter lines, which the extension continues.
pub neighbours: bool,
}
/// The boundary edges of `body` picked by points on them, extended as `opts` says. The result is
/// a surface body whose history is over `[body]`: an extended face is the face it was (bounded
/// differently) and its edges the edges they continue.
pub fn extend_surface(body: &Body, at: &[Vec3], opts: &ExtendOptions) -> Result
{
body.require_brep("extend")?;
if at.is_empty() {
return Err(KernelError::Invalid("pick the edges to extend".into()));
}
if at.len() > MAX_PICKS {
return Err(KernelError::Invalid("too many edges picked".into()));
}
if at.iter().any(|p| !p.is_finite()) {
return Err(KernelError::Invalid("an edge point is not finite".into()));
}
match opts.limit {
ExtendLimit::Distance(d) if !(d.is_finite() && d > 0.0 && d <= 1e6) => {
return Err(KernelError::Invalid("the extension distance must be positive".into()));
}
ExtendLimit::Bounds if opts.mode != ExtendMode::Natural => {
return Err(KernelError::Invalid("only a natural extension goes back to the surface's bounds".into()));
}
_ => {}
}
let record = crate::native::brep_record(body)?;
// A plane's straight edges pushed out with their neighbours lengthened: the exact planar
// extension (what designs saved before the other modes build).
if let (ExtendMode::Natural, ExtendLimit::Distance(d), true) = (opts.mode, opts.limit, opts.neighbours)
&& plain_planar(&record)
{
return crate::surfaces::extend(body, at, d);
}
let picked = picked_edges(&record, body.size(), at)?;
match opts.limit {
ExtendLimit::Bounds => {
let faces: BTreeSet = picked.iter().map(|(_, f)| *f).collect();
back_to_bounds(body, &faces.into_iter().collect::>())
}
ExtendLimit::Distance(d) => continued(body, at, &picked, d, opts.mode).map(|(out, _)| out),
ExtendLimit::UpTo(tool) => up_to(body, at, &picked, tool, opts.mode),
}
}
/// One planar face, one loop of straight edges: what [`crate::surfaces::extend`] takes.
fn plain_planar(record: &brep::Brep) -> bool {
let [face] = record.faces.as_slice() else { return false };
let [brep::Loop::Edges { edges }] = face.loops.as_slice() else { return false };
matches!(face.surface, brep::Surface::Plane { .. } | brep::Surface::PlaneThrough { .. })
&& edges.iter().all(|u| record.edges.get(u.edge as usize).is_some_and(|e| matches!(e.curve, brep::Curve::Line { .. })))
}
/// The boundary edges the points pick, each with its face: for each point, the record edge
/// nearest it (by samples along each edge), within a twentieth of the body's size. An edge two
/// faces share, or one of a hole, is refused.
fn picked_edges(record: &brep::Brep, size: f64, at: &[Vec3]) -> Result> {
let curves: Vec = record
.edges
.iter()
.enumerate()
.map(|(i, e)| CurveEval::new(e.parameters()).map_err(|err| KernelError::Failed(format!("extend: edge {i}'s curve: {err}"))))
.collect::>()?;
let reach = size * 0.05 + 1e-6;
let mut picked = Vec::with_capacity(at.len());
for p in at {
let mut best: Option<(f64, usize)> = None;
for (i, (e, c)) in record.edges.iter().zip(&curves).enumerate() {
let [t0, t1] = e.interval;
for k in 0..=PICK_SAMPLES {
let Some(q) = c.point(t0 + (t1 - t0) * k as f64 / PICK_SAMPLES as f64) else { continue };
let d = q.dist(*p);
if best.is_none_or(|(b, _)| d < b) {
best = Some((d, i));
}
}
}
let (index, edge) = match best {
Some((d, i)) if d <= reach => record.edges.get(i).map(|e| (i, e)),
_ => None,
}
.ok_or_else(|| KernelError::Invalid(format!("no edge at {p:?}")))?;
let [only] = edge.uses.as_slice() else {
return Err(KernelError::Invalid("an edge between two faces can't be extended: pick edges on the surface's boundary".into()));
};
// A face's first loop is its outer one (as SMLib keeps them).
if only.r#loop != 0 {
return Err(KernelError::Invalid("not supported yet: extending an edge of a hole (Untrim takes holes away)".into()));
}
picked.push((index, only.face as usize));
}
Ok(picked)
}
/// The faces of `body` continued `distance` past the picked edges (`at`, which `picked` names
/// with their faces), as `mode` says, and the faces that grew. One face is extended by SMLib
/// ([`one_face`]); a body of several grows face by face ([`grown`] says which past which edges),
/// each face extended alone and the faces sewn back together, each the face it was. Faces whose
/// lengthened sides part (no longer one edge) are refused.
fn continued(body: &Body, at: &[Vec3], picked: &[(usize, usize)], distance: f64, mode: ExtendMode) -> Result<(Body, Vec)> {
if body.face_count() == 1 {
return Ok((one_face(body, at, distance, mode)?, vec![0]));
}
let r = body.record();
let grow = grown(r, picked)?;
let mut pieces = Vec::with_capacity(grow.len() + 1);
for (&f, edges) in &grow {
let alone = crate::surfaces::taken(body, r, &[(f, false)])?;
let points = edges.iter().map(|e| edge_middle(r, *e)).collect::>>()?;
let longer = one_face(&alone, &points, distance, mode)?;
pieces.push((longer.record().clone(), vec![record::from_face(0, f, Change::Modified)]));
}
let rest: Vec<(usize, bool)> = (0..r.faces.len()).filter(|f| !grow.contains_key(f)).map(|f| (f, false)).collect();
if !rest.is_empty() {
let c = Parts::of(r, &rest)?.canonical()?;
let kept = c
.faces
.iter()
.map(|p| rest.get(*p).map(|(f, _)| record::from_face(0, *f, Change::Kept)))
.collect::