use crate::feature_pipeline::SceneMap;
use crate::{FaceRecord, NurbsCurve, PointClass, PolygonClass, Vec2, Vec3};
const STATIONS: [f64; 5] = [0.0, 0.25, 0.5, 0.75, 1.0];
const MIN_CORNER_SIN: f64 = 0.035;
#[derive(Clone, Debug)]
pub(super) struct JointFace {
pub name: String,
pub solid: String,
handle: u32,
face_id: u64,
normal: Vec3,
gap: Option<Vec3>,
}
impl JointFace {
pub(super) fn same(&self, other: &JointFace) -> bool {
same(self, other)
}
}
#[derive(Clone, Debug)]
pub(super) struct Fit {
pub faces: [JointFace; 2],
pub legs: [Vec3; 2],
pub root: Vec3,
pub skip: [f64; 2],
pub span: (f64, f64),
}
impl Fit {
pub(super) fn bridge(&self) -> [f64; 2] {
if self.skip[0] > 0.0 && self.skip[1] > 0.0 { self.skip } else { [0.0, 0.0] }
}
pub(super) fn carried(&self, seam: &Seam, fraction: f64) -> Fit {
let face = |face: &JointFace| JointFace {
normal: seam.carry(fraction, face.normal),
gap: face.gap.map(|gap| seam.carry(fraction, gap)),
..face.clone()
};
Fit {
faces: [face(&self.faces[0]), face(&self.faces[1])],
legs: [seam.carry(fraction, self.legs[0]), seam.carry(fraction, self.legs[1])],
root: seam.carry(fraction, self.root),
skip: self.skip,
span: self.span,
}
}
}
pub(super) type NoFit = String;
#[derive(Clone, Copy, Debug)]
pub(super) enum Run {
Line,
Arc { centre: Vec3, axis: Vec3, angle: f64 },
}
#[derive(Clone, Debug)]
pub(super) struct Seam {
pub start: Vec3,
pub tangent: Vec3,
pub length: f64,
pub run: Run,
pub owner: Option<String>,
}
fn rotate(v: Vec3, axis: Vec3, angle: f64) -> Vec3 {
let (sin, cos) = angle.sin_cos();
v.scale(cos).add(axis.cross(v).scale(sin)).add(axis.scale(axis.dot(v) * (1.0 - cos)))
}
impl Seam {
pub(super) fn line(start: Vec3, tangent: Vec3, length: f64, owner: Option<String>) -> Seam {
Seam { start, tangent, length, run: Run::Line, owner }
}
pub(super) fn from_curve(curve: &NurbsCurve, owner: Option<String>) -> Result<Option<Seam>, String> {
let [t0, t1] = curve.domain()?;
let start = curve.evaluate(t0)?;
let end = curve.evaluate(t1)?;
if curve.degree == 1 && curve.control_points.len() == 2 {
let delta = end.sub(start);
return Ok(Some(Seam::line(start, delta.normalized()?, delta.length(), owner)));
}
let scale = curve.control_points.iter()
.map(|pole| if pole.w.abs() > 1e-300 { Vec3::new(pole.x / pole.w, pole.y / pole.w, pole.z / pole.w) } else { Vec3::ZERO })
.map(|point| point.sub(start).length()).fold(1.0_f64, f64::max);
let Some(circle) = crate::recognize_circle(curve, t0, t1, 1e-9 * scale) else { return Ok(None) };
let radial = start.sub(circle.centre);
let tangent = curve.unit_tangent(t0, t0, t1)?;
let axis = if circle.axis.cross(radial).dot(tangent) >= 0.0 { circle.axis } else { circle.axis.scale(-1.0) };
let to = end.sub(circle.centre);
let mut angle = axis.dot(radial.cross(to)).atan2(radial.dot(to));
if angle <= 1e-12 {
angle += std::f64::consts::TAU;
}
let tangent = axis.cross(radial).normalized()?;
Ok(Some(Seam { start, tangent, length: circle.radius * angle, run: Run::Arc { centre: circle.centre, axis, angle }, owner }))
}
pub(super) fn at(&self, fraction: f64) -> Vec3 {
match self.run {
Run::Line => self.start.add(self.tangent.scale(self.length * fraction)),
Run::Arc { centre, axis, angle } => centre.add(rotate(self.start.sub(centre), axis, angle * fraction)),
}
}
pub(super) fn carry(&self, fraction: f64, direction: Vec3) -> Vec3 {
match self.run {
Run::Line => direction,
Run::Arc { axis, angle, .. } => rotate(direction, axis, angle * fraction),
}
}
pub(super) fn part(&self, from: f64, to: f64) -> Seam {
let run = match self.run {
Run::Line => Run::Line,
Run::Arc { centre, axis, angle } => Run::Arc { centre, axis, angle: angle * (to - from) },
};
Seam { start: self.at(from), tangent: self.carry(from, self.tangent), length: self.length * (to - from), run, owner: self.owner.clone() }
}
pub(super) fn end_tangent(&self) -> Vec3 {
self.carry(1.0, self.tangent)
}
pub(super) fn is_line(&self) -> bool {
matches!(self.run, Run::Line)
}
fn tolerance(&self) -> f64 {
1e-6_f64.max(self.length * 1e-12)
}
}
#[derive(Clone, Copy, Debug, Default)]
pub(super) struct Trim {
pub ends: [Option<(Vec3, Vec3, f64)>; 2],
}
pub(super) fn sweep(seam: &Seam, points: &[Vec3], trim: &Trim) -> Result<crate::BrepSolid, String> {
sweep_section(seam, points, None, trim)
}
pub(super) fn contour_arc(root: Vec3, a: Vec3, b: Vec3, height: f64) -> Result<(Vec3, f64, f64, Vec3), String> {
let chord = b.sub(a);
let half = chord.length() * 0.5;
let middle = a.add(chord.scale(0.5));
let toward = middle.sub(root);
let out = toward.sub(chord.scale(toward.dot(chord) / chord.dot(chord))).normalized()?;
let depth = height.abs();
let radius = (half * half + depth * depth) / (2.0 * depth);
let bulge = if height > 0.0 { out } else { out.scale(-1.0) };
let centre = middle.sub(bulge.scale(radius - depth));
let angle = 2.0 * half.atan2(radius - depth);
Ok((centre, radius, angle, middle.add(bulge.scale(depth))))
}
pub(super) fn section_reach(sections: &[[Vec3; 3]], contour: Option<f64>) -> Result<f64, String> {
let mut reach = 0.0_f64;
for [root, a, b] in sections {
reach = reach.max(root.length()).max(root.add(*a).length()).max(root.add(*b).length());
if let Some(height) = contour.filter(|height| *height > 0.0) {
let (centre, radius, _, _) = contour_arc(*root, root.add(*a), root.add(*b), height)?;
reach = reach.max(centre.length() + radius);
}
}
Ok(reach)
}
pub(super) fn sweep_section(seam: &Seam, points: &[Vec3], contour: Option<f64>, trim: &Trim) -> Result<crate::BrepSolid, String> {
let mut outline = Vec::with_capacity(points.len());
for i in 0..points.len() {
let (from, to) = (points[i], points[(i + 1) % points.len()]);
match contour {
Some(height) if i == 1 && points.len() == 3 => {
let (centre, _, _, apex) = contour_arc(points[0], from, to, height)?;
outline.push(Side::Arc { from, to, centre, through: apex });
}
_ => outline.push(Side::Line(from, to)),
}
}
sweep_outline(seam, &outline, trim)
}
fn sweep_bridged(seam: &Seam, root: Vec3, points: [Vec3; 4], contour: Option<f64>, trim: &Trim) -> Result<crate::BrepSolid, String> {
let mut outline = Vec::with_capacity(4);
for i in 0..4 {
let (from, to) = (points[i], points[(i + 1) % 4]);
match contour {
Some(height) if i == 1 => {
let (centre, _, _, apex) = contour_arc(root, from, to, height)?;
outline.push(Side::Arc { from, to, centre, through: apex });
}
_ => outline.push(Side::Line(from, to)),
}
}
sweep_outline(seam, &outline, trim)
}
#[derive(Clone, Copy, Debug)]
pub(super) enum Side {
Line(Vec3, Vec3),
Arc { from: Vec3, to: Vec3, centre: Vec3, through: Vec3 },
}
impl Side {
fn moved(self, shift: Vec3) -> Side {
match self {
Side::Line(a, b) => Side::Line(a.add(shift), b.add(shift)),
Side::Arc { from, to, centre, through } => Side::Arc { from: from.add(shift), to: to.add(shift), centre: centre.add(shift), through: through.add(shift) },
}
}
fn curve(self) -> Result<NurbsCurve, String> {
match self {
Side::Line(a, b) => crate::make_line(a, b),
Side::Arc { from, to, centre, through } => {
let radius = from.sub(centre).length();
let x_axis = from.sub(centre).normalized()?;
let mut normal = x_axis.cross(through.sub(centre));
let toward = to.sub(centre);
if normal.length() <= 1e-12 * radius {
return Err("an arc's middle point is opposite its start".into());
}
normal = normal.normalized()?;
let y_axis = normal.cross(x_axis);
let mut angle = toward.dot(y_axis).atan2(toward.dot(x_axis));
if angle <= 0.0 {
angle += std::f64::consts::TAU;
}
crate::make_arc(centre, x_axis, y_axis, radius, 0.0, angle)
}
}
}
}
pub(super) fn sweep_outline(seam: &Seam, sides: &[Side], trim: &Trim) -> Result<crate::BrepSolid, String> {
match seam.run {
Run::Line => {
let before = trim.ends[0].map_or(0.0, |(_, _, extend)| extend);
let after = trim.ends[1].map_or(0.0, |(_, _, extend)| extend);
let shift = seam.tangent.scale(-before);
let profile = sides.iter().map(|side| side.moved(shift).curve()).collect::<Result<Vec<_>, _>>()?;
let mut solid = crate::extrude_profile_brep(&profile, seam.tangent, seam.length + before + after)
.map_err(|error| error.to_string())?;
for (end, cut) in trim.ends.iter().enumerate() {
let Some((point, normal, _)) = cut else { continue };
let (below, above) = crate::split_solid_by_plane(&solid, *point, *normal)
.map_err(|error| format!("could not mitre the bead: {error}"))?;
solid = if end == 0 { above } else { below };
}
Ok(solid)
}
Run::Arc { centre, axis, angle } => {
if trim.ends.iter().any(Option::is_some) {
return Err("an arc is never mitred".into());
}
let profile = sides.iter().map(|side| side.curve()).collect::<Result<Vec<_>, _>>()?;
crate::revolve_profile_brep(&profile, centre, axis, angle)
}
}
}
fn with_face<T>(handle: u32, face_id: u64, f: impl FnOnce(&FaceRecord) -> Result<T, String>) -> Result<T, String> {
crate::with_registered_solid_str(handle, |solid| {
let face = solid.shells.iter().flat_map(|shell| &shell.faces).find(|face| face.id == face_id)
.ok_or_else(|| format!("face {face_id} is no longer resident"))?;
f(face)
})
}
pub(super) fn face_class(face: &FaceRecord, point: Vec3, tolerance: f64) -> Result<Option<PolygonClass>, String> {
let projection = crate::project_point_to_surface(&face.surface, point)?;
if projection.distance > tolerance {
return Ok(None);
}
crate::parameter_point_in_face(face, Vec2 { x: projection.u, y: projection.v }, tolerance).map(Some)
}
fn carries_seam(face: &FaceRecord, seam: &Seam) -> Result<Option<Vec3>, String> {
let tolerance = seam.tolerance();
let mut normal: Option<Vec3> = None;
for fraction in STATIONS {
let point = seam.at(fraction);
if !matches!(face_class(face, point, tolerance)?, Some(PolygonClass::Inside | PolygonClass::Boundary)) {
return Ok(None);
}
let (_, outward) = crate::fillet::face_plane_normal(face, point).map_err(|refusal| refusal.to_string())?;
match normal {
None => normal = Some(outward),
Some(first) => {
let carried = seam.carry(fraction, first);
if carried.cross(outward).length() > 1e-9 || carried.dot(outward) < 0.0 {
return Ok(None);
}
}
}
}
Ok(normal)
}
fn bounds(solid: &crate::BrepSolid) -> (Vec3, Vec3) {
let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
let edge_poles = solid.edges.iter().flat_map(|edge| edge.curve.control_points.iter());
let face_poles = solid.shells.iter().flat_map(|shell| &shell.faces)
.flat_map(|face| face.surface.control_points.iter().flatten());
for pole in edge_poles.chain(face_poles) {
let w = if pole.w.abs() > 1e-300 { pole.w } else { 1.0 };
let p = Vec3::new(pole.x / w, pole.y / w, pole.z / w);
low = Vec3::new(low.x.min(p.x), low.y.min(p.y), low.z.min(p.z));
high = Vec3::new(high.x.max(p.x), high.y.max(p.y), high.z.max(p.z));
}
(low, high)
}
fn solid_bounds_contain(solid: &crate::BrepSolid, points: &[Vec3], tolerance: f64) -> bool {
let (low, high) = bounds(solid);
points.iter().all(|p| {
p.x >= low.x - tolerance && p.y >= low.y - tolerance && p.z >= low.z - tolerance
&& p.x <= high.x + tolerance && p.y <= high.y + tolerance && p.z <= high.z + tolerance
})
}
fn is_weld_bead(solid: &crate::BrepSolid) -> bool {
solid.shells.iter().flat_map(|shell| &shell.faces)
.all(|face| face.name.as_deref().is_some_and(|name| name.contains(":BeadFace")))
}
pub(super) fn owned_by(name: &str, weld: &str) -> bool {
name == weld || name.strip_prefix(weld).is_some_and(|rest| rest.starts_with(":Bead"))
}
fn candidates(scene: &SceneMap, seam: &Seam, exclude: &str) -> Result<Vec<JointFace>, String> {
let ends = [seam.at(0.0), seam.at(1.0)];
let mut names: Vec<(&String, &u32)> = scene.solids.iter().filter(|(name, _)| !owned_by(name, exclude)).collect();
names.sort();
let mut found = Vec::new();
for (solid_name, &handle) in names {
let faces = crate::with_registered_solid_str(handle, |solid| {
if is_weld_bead(solid) || !solid_bounds_contain(solid, &ends, seam.tolerance()) {
return Ok(Vec::new());
}
let mut faces = Vec::new();
for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
if let Ok(Some(normal)) = carries_seam(face, seam) {
faces.push((face.id, face.name.clone(), normal));
}
}
Ok(faces)
})?;
for (face_id, name, normal) in faces {
let name = name.unwrap_or_else(|| format!("{solid_name} face {face_id}"));
found.push(JointFace { name, solid: solid_name.clone(), handle, face_id, normal, gap: None });
}
}
Ok(found)
}
fn across_gap(scene: &SceneMap, seam: &Seam, name: &str, widest: f64) -> Result<Option<JointFace>, String> {
if !seam.is_line() {
return Ok(None);
}
let tolerance = seam.tolerance();
for face in scene.resolve_face_group(name) {
let found = with_face(face.handle, face.face_id, |record| {
let mut first: Option<(Vec3, Vec3)> = None;
for fraction in STATIONS {
let point = seam.at(fraction);
let Ok((on, outward)) = crate::fillet::face_plane_normal(record, point) else { return Ok(None) };
let gap = point.sub(on).dot(outward);
if outward.dot(seam.tangent).abs() > 1e-9 || gap <= tolerance || gap >= widest {
return Ok(None);
}
let flat = record.surface.control_points.iter().flatten().all(|pole| {
let w = if pole.w.abs() > 1e-300 { pole.w } else { 1.0 };
Vec3::new(pole.x / w, pole.y / w, pole.z / w).sub(on).dot(outward).abs() <= tolerance
});
if !flat {
return Ok(None);
}
let offset = outward.scale(-gap);
match first {
None => first = Some((offset, outward)),
Some((offset0, outward0)) => {
if offset.sub(offset0).length() > tolerance || outward.cross(outward0).length() > 1e-9 {
return Ok(None);
}
}
}
}
Ok(first)
})?;
if let Some((offset, normal)) = found {
let solid = scene.solids.iter().filter(|(_, handle)| **handle == face.handle)
.map(|(name, _)| name.clone()).min().unwrap_or_default();
return Ok(Some(JointFace { name: name.to_string(), solid, handle: face.handle, face_id: face.face_id, normal, gap: Some(offset) }));
}
}
Ok(None)
}
fn gapped_faces(scene: &SceneMap, seam: &Seam, carriers: &[JointFace], widest: f64) -> Result<Vec<JointFace>, String> {
let mut handles: Vec<u32> = carriers.iter().map(|joint| joint.handle).collect();
handles.sort_unstable();
handles.dedup();
let mut found = Vec::new();
for handle in handles {
let names: Vec<String> = crate::with_registered_solid_str(handle, |solid| {
Ok(solid.shells.iter().flat_map(|shell| &shell.faces)
.filter(|face| !carriers.iter().any(|joint| joint.handle == handle && joint.face_id == face.id))
.filter_map(|face| face.name.clone()).collect())
})?;
for name in names {
if let Some(joint) = across_gap(scene, seam, &name, widest)? {
if joint.handle == handle {
found.push(joint);
}
}
}
}
Ok(found)
}
pub(super) fn bridges(scene: &SceneMap, seam: &Seam, name: &str, legs: [f64; 2]) -> Result<bool, String> {
Ok(across_gap(scene, seam, name, legs[0].max(legs[1]))?.is_some())
}
fn bridges_here(scene: &SceneMap, seam: &Seam, name: &str, legs: [f64; 2]) -> Result<bool, String> {
if !bridges(scene, seam, name, legs)? {
return Ok(false);
}
let widest = legs[0].max(legs[1]);
let tolerance = seam.tolerance();
let middle = seam.at(0.5);
for face in scene.resolve_face_group(name) {
let near = crate::with_registered_solid_str(face.handle, |body| {
let Some(record) = body.shells.iter().flat_map(|shell| &shell.faces).find(|f| f.id == face.face_id) else { return Ok(false) };
let Ok((on, normal)) = crate::fillet::face_plane_normal(record, middle) else { return Ok(false) };
let foot = middle.sub(normal.scale(middle.sub(on).dot(normal)));
if matches!(face_class(record, foot, tolerance)?, Some(PolygonClass::Inside | PolygonClass::Boundary)) {
return Ok(true);
}
for coedge in record.loops.iter().flat_map(|l| &l.coedges) {
let Some(edge) = body.edges.iter().find(|e| e.id == coedge.edge_id) else { continue };
for k in 0..=32 {
let point = edge.curve.evaluate(edge.t0 + (edge.t1 - edge.t0) * k as f64 / 32.0)?;
if point.sub(foot).length() <= widest {
return Ok(true);
}
}
}
Ok(false)
})?;
if near {
return Ok(true);
}
}
Ok(false)
}
fn root_of(pair: [&JointFace; 2], tangent: Vec3) -> Result<Option<(Vec3, [f64; 2])>, String> {
let (gapped, carrier) = match (pair[0].gap, pair[1].gap) {
(None, None) => return Ok(Some((Vec3::ZERO, [0.0, 0.0]))),
(Some(_), None) => (0, 1),
(None, Some(_)) => (1, 0),
(Some(_), Some(_)) => return Ok(None),
};
let offset = pair[gapped].gap.expect("the gapped face");
let normal = pair[gapped].normal;
let leg = leg_direction(pair[carrier], pair[gapped], tangent)?;
let across = leg.dot(normal);
if across.abs() < MIN_CORNER_SIN {
return Ok(None);
}
let shift = leg.scale(offset.dot(normal) / across);
if shift.dot(leg) >= 0.0 {
return Ok(None);
}
let mut skip = [0.0; 2];
skip[carrier] = shift.length();
Ok(Some((shift, skip)))
}
fn backed_root(pair: [&JointFace; 2], seam: &Seam, probe: f64, reach: f64) -> Result<Option<(Vec3, [f64; 2])>, String> {
let Some((root, mut skip)) = root_of(pair, seam.tangent)? else { return Ok(None) };
let Some(gapped) = pair.iter().position(|face| face.gap.is_some()) else { return Ok(Some((root, skip))) };
let tolerance = seam.tolerance();
let leg = seam.carry(0.5, leg_direction(pair[gapped], pair[1 - gapped], seam.tangent)?);
let middle = seam.at(0.5).add(seam.carry(0.5, root));
let on = |s: f64| runs_onto(pair[gapped], middle.add(leg.scale(s)), tolerance);
if on(0.0)? {
return Ok(Some((root, skip)));
}
const SAMPLES: usize = 64;
let mut off = 0.0;
for k in 1..=SAMPLES {
let s = reach * k as f64 / SAMPLES as f64;
if !on(s)? {
off = s;
continue;
}
let mut inside = s;
while inside - off > tolerance * 1e-2 {
let mid = 0.5 * (off + inside);
if on(mid)? { inside = mid } else { off = mid }
}
let edge = edge_along(pair[gapped], middle, leg, seam.tangent, inside, tolerance)?;
let Some(edge) = edge.filter(|edge| *edge > 10.0 * tolerance) else {
return Ok(on(probe)?.then_some((root, skip)));
};
if skip[1 - gapped] <= tolerance {
return Ok(None);
}
skip[gapped] = edge;
return Ok(Some((root, skip)));
}
Ok(None)
}
fn backed_span(seam: &Seam, faces: [&JointFace; 2], legs: [Vec3; 2], root: Vec3, skip: [f64; 2], sizes: [f64; 2]) -> Result<Option<(f64, f64)>, String> {
let tolerance = seam.tolerance();
let origin = seam.start.add(root);
let mut breaks: Vec<f64> = Vec::new();
for i in 0..2 {
let (leg, low, high) = (legs[i], skip[i] + 10.0 * tolerance, sizes[i] - 10.0 * tolerance);
let coords = |p: Vec3| { let d = p.sub(origin); (d.dot(seam.tangent), d.dot(leg)) };
let curves: Vec<NurbsCurve> = crate::with_registered_solid_str(faces[i].handle, |solid| {
let record = solid.shells.iter().flat_map(|shell| &shell.faces).find(|f| f.id == faces[i].face_id)
.ok_or_else(|| format!("face {} is no longer resident", faces[i].face_id))?;
let mut curves = Vec::new();
for coedge in record.loops.iter().flat_map(|l| &l.coedges) {
let Some(edge) = solid.edges.iter().find(|e| e.id == coedge.edge_id) else { continue };
if edge.degenerate { continue; }
curves.push(crate::feature_pipeline::features::common::trimmed_curve(&edge.curve, edge.t0, edge.t1)?);
}
Ok(curves)
})?;
for curve in &curves {
let [t0, t1] = curve.domain()?;
let at = |t: f64| -> Result<(f64, f64), String> { Ok(coords(curve.evaluate(t)?)) };
const SAMPLES: usize = 512;
let ts: Vec<f64> = (0..=SAMPLES).map(|k| t0 + (t1 - t0) * k as f64 / SAMPLES as f64).collect();
let points = ts.iter().map(|t| at(*t)).collect::<Result<Vec<_>, _>>()?;
let inside = |s: f64| s > low && s < high;
for k in 0..SAMPLES {
let ((f0, s0), (_, s1)) = (points[k], points[k + 1]);
for bound in [low, high] {
if (s0 - bound) * (s1 - bound) < 0.0 {
let (mut a, mut b) = (ts[k], ts[k + 1]);
for _ in 0..80 {
let m = 0.5 * (a + b);
if (at(m)?.1 - bound) * (s0 - bound) > 0.0 { a = m } else { b = m }
}
breaks.push(at(0.5 * (a + b))?.0);
}
}
if inside(s0) {
breaks.push(f0);
}
}
if inside(points[SAMPLES].1) {
breaks.push(points[SAMPLES].0);
}
for k in 1..SAMPLES {
let (prev, here, next) = (points[k - 1].0, points[k].0, points[k + 1].0);
let extreme = (here >= prev && here >= next) || (here <= prev && here <= next);
if !extreme || !inside(points[k].1) || (here - prev).abs() + (next - here).abs() <= 0.0 {
continue;
}
let maximum = here >= prev;
let (mut a, mut b) = (ts[k - 1], ts[k + 1]);
for _ in 0..100 {
let (m1, m2) = (a + (b - a) / 3.0, b - (b - a) / 3.0);
let (g1, g2) = (at(m1)?.0, at(m2)?.0);
if (g1 < g2) == maximum { a = m1 } else { b = m2 }
}
let (f, s) = at(0.5 * (a + b))?;
if inside(s) {
breaks.push(f);
}
}
}
}
breaks.push(0.0);
breaks.push(seam.length);
breaks.retain(|f| *f >= 0.0 && *f <= seam.length);
breaks.sort_by(f64::total_cmp);
let backed = |f: f64| -> Result<bool, String> {
for i in 0..2 {
for k in 0..=16 {
let s = skip[i] + (sizes[i] - skip[i]) * k as f64 / 16.0;
if !runs_onto(faces[i], origin.add(seam.tangent.scale(f)).add(legs[i].scale(s)), tolerance)? {
return Ok(false);
}
}
}
Ok(true)
};
let mut best: Option<(f64, f64)> = None;
for pair in breaks.windows(2) {
let (a, b) = (pair[0], pair[1]);
if b - a <= 100.0 * tolerance || best.is_some_and(|(x, y)| y - x >= b - a) {
continue;
}
if backed(0.5 * (a + b))? {
best = Some((a, b));
}
}
let Some((a, b)) = best else { return Ok(None) };
let near = 10.0 * tolerance;
Ok(Some((if a <= near { 0.0 } else { a }, if b >= seam.length - near { seam.length } else { b })))
}
fn edge_along(face: &JointFace, from: Vec3, leg: Vec3, tangent: Vec3, near: f64, tolerance: f64) -> Result<Option<f64>, String> {
crate::with_registered_solid_str(face.handle, |solid| {
let record = solid.shells.iter().flat_map(|shell| &shell.faces).find(|f| f.id == face.face_id)
.ok_or_else(|| format!("face {} is no longer resident", face.face_id))?;
let mut best: Option<f64> = None;
for coedge in record.loops.iter().flat_map(|l| &l.coedges) {
let Some(edge) = solid.edges.iter().find(|e| e.id == coedge.edge_id) else { continue };
let (a, b) = (edge.curve.evaluate(edge.t0)?, edge.curve.evaluate(edge.t1)?);
let Ok(along) = b.sub(a).normalized() else { continue };
let middle = edge.curve.evaluate(0.5 * (edge.t0 + edge.t1))?;
if along.cross(tangent).length() > 1e-9 || middle.sub(a).cross(along).length() > tolerance {
continue;
}
let d = a.sub(from);
let s = d.dot(leg);
let off = d.sub(leg.scale(s)).sub(along.scale(d.dot(along))).length();
if off <= 10.0 * tolerance && (s - near).abs() <= 10.0 * tolerance && best.is_none_or(|b| (s - near).abs() < (b - near).abs()) {
best = Some(s);
}
}
Ok(best)
})
}
fn leg_direction(face: &JointFace, other: &JointFace, tangent: Vec3) -> Result<Vec3, String> {
let direction = face.normal.cross(tangent).normalized()?;
Ok(if direction.dot(other.normal) < 0.0 { direction.scale(-1.0) } else { direction })
}
fn runs_onto(face: &JointFace, point: Vec3, tolerance: f64) -> Result<bool, String> {
with_face(face.handle, face.face_id, |record| {
Ok(matches!(face_class(record, point, tolerance)?, Some(PolygonClass::Inside | PolygonClass::Boundary)))
})
}
fn outside_solid(scene: &SceneMap, solid: &str, point: Vec3, tolerance: f64) -> Result<bool, String> {
let handle = scene.solids.get(solid).copied().ok_or_else(|| format!("solid '{solid}' is no longer resident"))?;
crate::with_registered_solid_str(handle, |body| {
Ok(crate::classify_point(point, body, tolerance)?.class == PointClass::Out)
})
}
fn corner(scene: &SceneMap, seam: &Seam, pair: [&JointFace; 2], solids: &[String], probe: f64, sizes: [f64; 2]) -> Result<Option<[Vec3; 2]>, String> {
let reach = sizes[0].max(sizes[1]);
if pair[0].normal.cross(pair[1].normal).length() < MIN_CORNER_SIN {
return Ok(None);
}
let legs = [leg_direction(pair[0], pair[1], seam.tangent)?, leg_direction(pair[1], pair[0], seam.tangent)?];
let Some((root, skip)) = backed_root(pair, seam, probe, reach)? else { return Ok(None) };
let tolerance = seam.tolerance();
let middle = seam.at(0.5).add(seam.carry(0.5, root));
let carried = [seam.carry(0.5, legs[0]), seam.carry(0.5, legs[1])];
for ((face, leg), skip) in pair.iter().zip(&carried).zip(skip) {
if !runs_onto(face, middle.add(leg.scale(skip + probe)), tolerance)? {
return Ok(None);
}
}
let wedge = middle.add(carried[0].add(carried[1]).scale(probe / 3.0));
let mut free = vec![wedge];
if skip[0] > 0.0 && skip[1] > 0.0 {
if skip[0].max(skip[1]) >= sizes[0].min(sizes[1]) - tolerance {
return Ok(None);
}
let opening = middle.add(carried[0].scale(skip[0])).add(middle.add(carried[1].scale(skip[1]))).scale(0.5);
free.push(opening.add(carried[0].add(carried[1]).scale(probe / 3.0)));
}
for point in free {
for solid in solids {
if !outside_solid(scene, solid, point, tolerance * 0.1)? {
return Ok(None);
}
}
}
Ok(Some(legs))
}
pub(super) fn fit(scene: &SceneMap, seam: &Seam, explicit: &[String], exclude: &str, legs: [f64; 2], previous: Option<&Fit>) -> Result<Result<Fit, NoFit>, String> {
if explicit.len() > 2 {
return Err("select at most two joint faces".into());
}
let all = candidates(scene, seam, exclude)?;
let mut chosen = Vec::new();
for name in explicit {
let group = scene.resolve_face_group(name);
if let Some(joint) = all.iter().find(|joint| group.iter().any(|face| joint.handle == face.handle && joint.face_id == face.face_id)) {
chosen.push(JointFace { name: name.clone(), ..joint.clone() });
continue;
}
if let Some(joint) = across_gap(scene, seam, name, legs[0].max(legs[1]))? {
chosen.push(joint);
continue;
}
return Ok(Err(format!("joint face '{name}' does not carry the seam along its whole length {}",
if seam.is_line() { "as a flat face" } else { "square to the arc's axis or coaxial with it" })));
}
let mut solids: Vec<String> = all.iter().chain(chosen.iter()).map(|joint| joint.solid.clone()).collect();
solids.sort();
solids.dedup();
let pool: Vec<JointFace> = all.iter().cloned().chain(chosen.iter().filter(|joint| joint.gap.is_some()).cloned()).collect();
let probe = (legs[0].min(legs[1]) * 0.05).min(seam.length * 0.05).max(seam.tolerance() * 10.0);
let mut pairs: Vec<([JointFace; 2], [Vec3; 2])> = Vec::new();
match chosen.as_slice() {
[first, second] => {
if let Some(legs) = corner(scene, seam, [first, second], &solids, probe, legs)? {
pairs.push(([first.clone(), second.clone()], legs));
}
}
_ => {
for (i, a) in pool.iter().enumerate() {
for b in &pool[i + 1..] {
if let [only] = chosen.as_slice() {
if !(same(only, a) || same(only, b)) {
continue;
}
}
if corner(scene, seam, [a, b], &solids, probe, legs)?.is_some() {
let [f0, f1] = order(seam, chosen.first(), [a, b]);
let legs = [leg_direction(&f0, &f1, seam.tangent)?, leg_direction(&f1, &f0, seam.tangent)?];
pairs.push(([f0, f1], legs));
}
}
}
}
}
if pairs.is_empty() && chosen.len() <= 1 && chosen.iter().all(|only| only.gap.is_none()) && seam.is_line() {
let widest = legs[0].max(legs[1]);
for gapped in gapped_faces(scene, seam, &all, widest)? {
for carrier in &all {
let bridged = backed_root([carrier, &gapped], seam, probe, widest)?
.is_some_and(|(_, skip)| skip[0] > 0.0 && skip[1] > 0.0);
let wanted = chosen.first().is_none_or(|only| same(only, carrier));
if wanted && bridged && corner(scene, seam, [carrier, &gapped], &solids, probe, legs)?.is_some() {
let [f0, f1] = order(seam, chosen.first(), [carrier, &gapped]);
let legs = [leg_direction(&f0, &f1, seam.tangent)?, leg_direction(&f1, &f0, seam.tangent)?];
pairs.push(([f0, f1], legs));
}
}
}
}
let ([mut first, mut second], mut legs_dir) = match pairs.len() {
0 if all.is_empty() => return Ok(Err(if seam.is_line() {
"no face carries the seam as a flat face".into()
} else {
"no face carries the arc square to its axis or coaxial with it".into()
})),
0 => return Ok(Err(format!(
"no concave corner along the seam between faces {}", list(&all)))),
1 => pairs.pop().expect("one pair"),
_ => return Ok(Err(format!(
"several corners meet at the seam ({}); select the two joint faces",
pairs.iter().map(|(faces, _)| format!("{} + {}", faces[0].name, faces[1].name)).collect::<Vec<_>>().join(", ")))),
};
if let Some(previous) = previous {
if first.same(&previous.faces[1]) || second.same(&previous.faces[0]) {
std::mem::swap(&mut first, &mut second);
legs_dir.swap(0, 1);
}
}
let tolerance = seam.tolerance();
let Some((root, skip)) = backed_root([&first, &second], seam, probe, legs[0].max(legs[1]))? else {
return Ok(Err(format!("no root across the gap between faces {} and {}", first.name, second.name)));
};
let span = if skip[0] > 0.0 && skip[1] > 0.0 && seam.is_line() {
let refused = || format!("faces {} and {} back no stretch of the seam together", first.name, second.name);
let Some((a, b)) = backed_span(seam, [&first, &second], legs_dir, root, skip, legs)? else { return Ok(Err(refused())) };
let base = 100.0 * crate::tolerance::WELD_FLOOR;
let mut found = None;
for k in 0..=8 {
let inset = |end: f64, own: f64| if k == 0 { if end == own { 0.0 } else { base } } else { base * f64::powi(2.0, k) };
let (from, to) = (a + inset(a, 0.0), b - inset(b, seam.length));
if to - from <= base {
break;
}
let span = (from / seam.length, to / seam.length);
let trial = Fit { faces: [first.clone(), second.clone()], legs: legs_dir, root, skip, span };
if supported(&seam.part(span.0, span.1), &trial, legs, &Trim { ends: [None, None] })?.is_ok() {
found = Some(if from == 0.0 && to == seam.length { (0.0, 1.0) } else { span });
break;
}
}
match found {
Some(span) => span,
None => return Ok(Err(refused())),
}
} else {
(0.0, 1.0)
};
let along = seam.part(span.0, span.1);
for (((face, leg), size), skip) in [&first, &second].iter().zip(&legs_dir).zip(legs).zip(skip) {
if size <= skip + tolerance {
return Ok(Err(format!("leg {size} does not reach across the {skip} root gap onto joint face {}", face.name)));
}
for fraction in STATIONS {
let toe = along.at(fraction).add(along.carry(fraction, root.add(leg.scale(size))));
if !runs_onto(face, toe, tolerance)? {
return Ok(Err(format!("leg {size} runs off joint face {}", face.name)));
}
}
}
Ok(Ok(Fit { faces: [first, second], legs: legs_dir, root, skip, span }))
}
#[derive(Clone, Debug)]
pub(super) struct FarRun {
pub seam: Seam,
member: usize,
far_id: u64,
}
pub(super) fn far_run(scene: &SceneMap, seam: &Seam, near: &Fit, legs: [f64; 2]) -> Result<Result<FarRun, NoFit>, String> {
let tolerance = seam.tolerance();
let mut found: Vec<FarRun> = Vec::new();
for member in 0..2 {
let face = &near.faces[member];
let through = &near.faces[1 - member];
if face.gap.is_some() {
continue;
}
let up = near.skip[member] + (legs[member] - near.skip[member]) * 0.5;
let point = seam.at(0.5).add(seam.carry(0.5, near.root.add(near.legs[member].scale(up))));
let inward = seam.carry(0.5, face.normal).scale(-1.0);
let far = crate::with_registered_solid_str(face.handle, |solid| {
let mut best: Option<(f64, u64)> = None;
for record in solid.shells.iter().flat_map(|shell| &shell.faces) {
if record.id == face.face_id {
continue;
}
let Ok((foot, outward)) = crate::fillet::face_plane_normal(record, point) else { continue };
let across = foot.sub(point);
let thickness = across.dot(inward);
if thickness <= tolerance || across.sub(inward.scale(thickness)).length() > tolerance
|| outward.dot(inward) < 1.0 - 1e-9 {
continue;
}
if !matches!(face_class(record, foot, tolerance)?, Some(PolygonClass::Inside | PolygonClass::Boundary)) {
continue;
}
if best.is_none_or(|(nearest, _)| thickness < nearest) {
best = Some((thickness, record.id));
}
}
Ok(best)
})?;
let Some((thickness, far_id)) = far else { continue };
let shift = face.normal.scale(-thickness);
let start = seam.start.add(shift);
let far_seam = match seam.run {
Run::Line => Seam::line(start, seam.tangent, seam.length, None),
Run::Arc { centre, axis, angle } => {
let radial = start.sub(centre);
let radius = radial.sub(axis.scale(radial.dot(axis))).length();
if radius <= tolerance {
continue;
}
Seam { start, tangent: seam.tangent, length: radius * angle, run: seam.run, owner: None }
}
};
let holds = if through.gap.is_some() {
across_gap(scene, &far_seam, &through.name, legs[0].max(legs[1]))?.is_some()
} else {
runs_onto(through, far_seam.at(0.5), tolerance)?
};
if holds {
found.push(FarRun { seam: far_seam, member, far_id });
}
}
Ok(match found.len() {
0 => Err("no far-side corner: neither joint face belongs to a member with a face straight across it on the other face".into()),
1 => Ok(found.pop().expect("one far side")),
_ => Err("both joint faces belong to members that continue past the joint; weld the far side's seam as its own weld".into()),
})
}
pub(super) fn fit_far(scene: &SceneMap, far: &FarRun, near: &Fit, exclude: &str, legs: [f64; 2]) -> Result<Result<Fit, NoFit>, String> {
let face = &near.faces[far.member];
let through = &near.faces[1 - far.member];
let joints = candidates(scene, &far.seam, exclude)?;
let Some(far_face) = joints.iter().find(|joint| joint.handle == face.handle && joint.face_id == far.far_id) else {
return Ok(Err("the member's far face does not carry the far side's seam".into()));
};
let through_name = if through.gap.is_some() {
through.name.clone()
} else {
let Some(through_face) = joints.iter().find(|joint| same(joint, through)) else {
return Ok(Err(format!("joint face {} does not carry the far side's seam", through.name)));
};
through_face.name.clone()
};
let picks = if far.member == 0 { [far_face.name.clone(), through_name] } else { [through_name, far_face.name.clone()] };
fit(scene, &far.seam, &picks, exclude, legs, None)
}
pub(super) fn carries(scene: &SceneMap, seam: &Seam, name: &str) -> Result<bool, String> {
for face in scene.resolve_face_group(name) {
if with_face(face.handle, face.face_id, |record| carries_any(record, seam))? {
return Ok(true);
}
}
Ok(false)
}
fn carries_any(face: &FaceRecord, seam: &Seam) -> Result<bool, String> {
let tolerance = seam.tolerance();
for fraction in STATIONS {
if !matches!(face_class(face, seam.at(fraction), tolerance)?, Some(PolygonClass::Inside | PolygonClass::Boundary)) {
return Ok(false);
}
}
Ok(true)
}
fn same(a: &JointFace, b: &JointFace) -> bool {
a.handle == b.handle && a.face_id == b.face_id
}
fn list(faces: &[JointFace]) -> String {
faces.iter().map(|face| face.name.as_str()).collect::<Vec<_>>().join(", ")
}
fn order(seam: &Seam, selected: Option<&JointFace>, pair: [&JointFace; 2]) -> [JointFace; 2] {
let first_wins = match selected {
Some(selected) => same(selected, pair[0]) || !same(selected, pair[1]),
None => {
let owned = |face: &JointFace| seam.owner.as_deref() == Some(face.solid.as_str());
match (owned(pair[0]), owned(pair[1])) {
(true, false) => true,
(false, true) => false,
_ => (&pair[0].name, &pair[0].solid) <= (&pair[1].name, &pair[1].solid),
}
}
};
if first_wins { [pair[0].clone(), pair[1].clone()] } else { [pair[1].clone(), pair[0].clone()] }
}
const TANGENT_JOIN: f64 = 1e-9;
const MITRE_FLOOR: f64 = 0.1;
pub(super) struct Chain {
pub runs: Vec<Seam>,
corners: Vec<(usize, usize, Option<(Vec3, Vec3)>)>,
}
impl Chain {
pub(super) fn new(runs: Vec<Seam>) -> Result<Chain, NoFit> {
let count = runs.len();
let tolerance = runs.iter().map(Seam::tolerance).fold(0.0, f64::max);
let closed = count > 1 && runs[count - 1].at(1.0).sub(runs[0].start).length() <= tolerance * 10.0;
let mut corners = Vec::new();
let joins: Vec<(usize, usize)> = (0..count.saturating_sub(1)).map(|k| (k, k + 1))
.chain(closed.then(|| (count - 1, 0))).collect();
let name = |k: usize| k + 1;
for (a, b) in joins {
let (out, into) = (runs[a].end_tangent(), runs[b].tangent);
if out.dot(into) >= 1.0 - TANGENT_JOIN {
corners.push((a, b, None));
continue;
}
if !(runs[a].is_line() && runs[b].is_line()) {
return Err(format!("segments {} and {} meet at a corner on an arc; a bead is mitred only between straight segments", name(a), name(b)));
}
let normal = out.add(into).normalized().map_err(|_| format!("the seam doubles back where segments {} and {} meet", name(a), name(b)))?;
if out.dot(normal) < MITRE_FLOOR {
return Err(format!("the seam turns back too sharply where segments {} and {} meet for a mitred bead", name(a), name(b)));
}
corners.push((a, b, Some((runs[b].start, normal))));
}
Ok(Chain { runs, corners })
}
pub(super) fn is_single_line(&self) -> bool {
self.runs.len() == 1 && self.runs[0].is_line()
}
fn label(&self, k: usize) -> String {
if self.runs.len() == 1 { String::new() } else { format!("segment {}: ", k + 1) }
}
pub(super) fn trims(&self, reach: f64) -> Result<Vec<Trim>, NoFit> {
let mut trims = vec![Trim::default(); self.runs.len()];
let mut taken = vec![0.0_f64; self.runs.len()];
for (a, b, corner) in &self.corners {
let Some((point, normal)) = corner else { continue };
let cos_half = self.runs[*b].tangent.dot(*normal);
let tan_half = (1.0 - cos_half * cos_half).max(0.0).sqrt() / cos_half;
let extend = reach * tan_half * 2.0 + reach * 0.01;
trims[*a].ends[1] = Some((*point, *normal, extend));
trims[*b].ends[0] = Some((*point, *normal, extend));
taken[*a] += reach * tan_half;
taken[*b] += reach * tan_half;
}
for (k, run) in self.runs.iter().enumerate() {
if taken[k] >= run.length {
return Err(format!("{}the segment is too short for the bead's mitred corners", self.label(k)));
}
}
Ok(trims)
}
pub(super) fn fit(&self, scene: &SceneMap, explicit: &[String], exclude: &str, legs: [f64; 2]) -> Result<Result<Vec<Fit>, NoFit>, String> {
let count = self.runs.len();
let mut picked: Vec<Vec<String>> = Vec::with_capacity(count);
for run in &self.runs {
if count == 1 {
picked.push(explicit.to_vec());
continue;
}
let mut names = Vec::new();
for name in explicit {
if carries(scene, run, name)? || bridges_here(scene, run, name, legs)? {
names.push(name.clone());
}
}
picked.push(names);
}
let start = explicit.first()
.and_then(|first| picked.iter().position(|names| names.first() == Some(first)))
.unwrap_or(0);
let order: Vec<(usize, Option<usize>)> = std::iter::once((start, None))
.chain((start + 1..count).map(|k| (k, Some(k - 1))))
.chain((0..start).rev().map(|k| (k, Some(k + 1))))
.collect();
let mut fitted: Vec<Option<Fit>> = vec![None; count];
for (k, neighbour) in order {
let next = neighbour.and_then(|n| fitted[n].as_ref());
match fit(scene, &self.runs[k], &picked[k], exclude, legs, next)? {
Ok(joint) => fitted[k] = Some(joint),
Err(reason) => return Ok(Err(format!("{}{reason}", self.label(k)))),
}
}
let fits: Vec<Fit> = fitted.into_iter().map(|fit| fit.expect("every run fitted")).collect();
if count > 1 && fits.iter().any(|fit| fit.span != (0.0, 1.0)) {
return Ok(Err("the joint faces back only part of a segment of a seam of several segments".into()));
}
for (a, b, corner) in &self.corners {
if corner.is_some() {
continue;
}
let tolerance = self.runs[*a].tolerance().max(self.runs[*b].tolerance()) * 10.0;
let roots = [self.runs[*a].carry(1.0, fits[*a].root), fits[*b].root];
if roots[0].sub(roots[1]).length() > tolerance {
return Ok(Err(format!("the joint changes where segments {} and {} meet", a + 1, b + 1)));
}
for (i, size) in legs.iter().enumerate() {
let end = self.runs[*a].carry(1.0, fits[*a].legs[i]).scale(*size);
let start = fits[*b].legs[i].scale(*size);
if end.sub(start).length() > tolerance {
return Ok(Err(format!("the joint changes where segments {} and {} meet", a + 1, b + 1)));
}
}
}
Ok(Ok(fits))
}
pub(super) fn rooted(&self, trims: &[Trim], roots: &[Vec3]) -> Result<Vec<Trim>, NoFit> {
let mut trims = trims.to_vec();
for (a, b, corner) in &self.corners {
let Some((point, normal)) = corner else { continue };
let (ra, rb) = (self.runs[*a].carry(1.0, roots[*a]), roots[*b]);
if ra.length() == 0.0 && rb.length() == 0.0 {
continue;
}
let tolerance = self.runs[*a].tolerance().max(self.runs[*b].tolerance()) * 10.0;
let Some(meet) = meet(point.add(ra), self.runs[*a].end_tangent(), point.add(rb), self.runs[*b].tangent, tolerance) else {
return Err(format!("the bead's root steps where segments {} and {} meet (a root gap on one of them only, or of different widths)", a + 1, b + 1));
};
let moved = meet.sub(*point).length();
for (run, end) in [(*a, 1), (*b, 0)] {
if let Some((_, _, extend)) = trims[run].ends[end] {
trims[run].ends[end] = Some((meet, *normal, extend + 2.0 * moved));
}
}
}
Ok(trims)
}
pub(super) fn far_side(&self, scene: &SceneMap, fits: &[Fit], exclude: &str, legs: [f64; 2]) -> Result<Result<(Chain, Vec<Fit>), NoFit>, String> {
let mut fars: Vec<FarRun> = Vec::new();
for (k, run) in self.runs.iter().enumerate() {
match far_run(scene, run, &fits[k], legs)? {
Ok(far) => fars.push(far),
Err(reason) => return Ok(Err(format!("{}{reason}", self.label(k)))),
}
}
let runs: Vec<Seam> = fars.iter().map(|far| far.seam.clone()).collect();
let runs = match self.rejoined(runs) {
Some(runs) => runs,
None => return Ok(Err("the far side's segments do not meet again at the member's corners".into())),
};
let mut far_fits = Vec::new();
for (k, (far, run)) in fars.iter_mut().zip(runs.iter()).enumerate() {
far.seam = run.clone();
match fit_far(scene, far, &fits[k], exclude, legs)? {
Ok(joint) => far_fits.push(joint),
Err(reason) => return Ok(Err(format!("{}no far-side corner: {reason}", self.label(k)))),
}
}
Ok(Chain::new(runs).map(|chain| (chain, far_fits)))
}
fn rejoined(&self, mut runs: Vec<Seam>) -> Option<Vec<Seam>> {
let count = runs.len();
let (mut starts, mut ends): (Vec<Option<Vec3>>, Vec<Option<Vec3>>) = (vec![None; count], vec![None; count]);
for (a, b, corner) in &self.corners {
let tolerance = runs[*a].tolerance().max(runs[*b].tolerance()) * 10.0;
match corner {
None => {
if runs[*a].at(1.0).sub(runs[*b].start).length() > tolerance {
return None;
}
}
Some(_) => {
let point = meet(runs[*a].start, runs[*a].tangent, runs[*b].start, runs[*b].tangent, tolerance)?;
ends[*a] = Some(point);
starts[*b] = Some(point);
}
}
}
for (k, run) in runs.iter_mut().enumerate() {
if starts[k].is_none() && ends[k].is_none() {
continue;
}
let start = starts[k].unwrap_or(run.start);
let end = ends[k].unwrap_or_else(|| run.at(1.0));
let length = end.sub(start).dot(run.tangent);
if length <= run.tolerance() * 10.0 {
return None;
}
*run = Seam::line(start, run.tangent, length, run.owner.clone());
}
Some(runs)
}
pub(super) fn offset(&self, normal: Vec3, distance: f64) -> Result<Option<Chain>, String> {
let mut runs = Vec::new();
for run in &self.runs {
let left = normal.cross(run.tangent).normalized()?.scale(distance);
let start = run.start.add(left);
runs.push(match run.run {
Run::Line => Seam::line(start, run.tangent, run.length, None),
Run::Arc { centre, axis, angle } => {
let radial = run.start.sub(centre);
let radial = radial.sub(axis.scale(radial.dot(axis)));
let radius = radial.length();
let moved = radius + left.dot(radial.scale(1.0 / radius));
if moved <= run.tolerance() {
return Ok(None);
}
Seam { start, tangent: run.tangent, length: moved * angle, run: run.run, owner: None }
}
});
}
let Some(runs) = self.rejoined(runs) else { return Ok(None) };
Ok(Chain::new(runs).ok())
}
pub(super) fn length(&self) -> f64 {
self.runs.iter().map(|run| run.length).sum()
}
pub(super) fn is_closed(&self) -> bool {
self.corners.iter().any(|(a, b, _)| *b == 0 && *a + 1 == self.runs.len() && self.runs.len() > 1)
}
pub(super) fn pieces(&self, sections: &[[Vec3; 3]], trims: &[Trim], from: f64, to: f64) -> Vec<Piece> {
let mut pieces = Vec::new();
let mut start = 0.0;
let total = self.length();
let last = self.runs.len().saturating_sub(1);
let closing = self.is_closed() && from <= self.runs[0].tolerance() && to >= total - self.runs[last].tolerance();
for (k, run) in self.runs.iter().enumerate() {
let end = start + run.length;
let (low, high) = (from.max(start), to.min(end));
let tolerance = run.tolerance();
if high - low > tolerance {
let f0 = if low - start <= tolerance { 0.0 } else { (low - start) / run.length };
let f1 = if end - high <= tolerance { 1.0 } else { (high - start) / run.length };
let [root, a, b] = sections[k];
let through_start = from < start - tolerance || (closing && k == 0);
let through_end = to > end + tolerance || (closing && k == last);
let trim = Trim { ends: [
if f0 == 0.0 && through_start { trims[k].ends[0] } else { None },
if f1 == 1.0 && through_end { trims[k].ends[1] } else { None },
] };
pieces.push(Piece {
bridge: [0.0, 0.0],
run: run.part(f0, f1),
section: [run.carry(f0, root), run.carry(f0, a), run.carry(f0, b)],
trim,
index: k,
from: f0,
});
}
start = end;
}
pieces
}
pub(super) fn verify_pieces(&self, scene: &SceneMap, fits: &[Fit], legs: [f64; 2], bead: &crate::BrepSolid, pieces: &[Piece], exclude: &str) -> Result<Result<(), NoFit>, String> {
let tolerance = self.runs.iter().map(Seam::tolerance).fold(0.0, f64::max);
if let Err(reason) = clear(scene, bead, exclude, tolerance)? {
return Ok(Err(reason));
}
for piece in pieces {
let joint = fits[piece.index].carried(&self.runs[piece.index], piece.from);
if let Err(reason) = supported(&piece.run, &joint, legs, &piece.trim)? {
return Ok(Err(format!("{}{reason}", self.label(piece.index))));
}
}
Ok(Ok(()))
}
}
fn meet(a: Vec3, da: Vec3, b: Vec3, db: Vec3, tolerance: f64) -> Option<Vec3> {
let cos = da.dot(db);
let denominator = 1.0 - cos * cos;
if denominator <= 1e-12 {
return (a.sub(b).cross(da).length() <= tolerance).then_some(b);
}
let w = a.sub(b);
let (d, e) = (da.dot(w), db.dot(w));
let s = (cos * e - d) / denominator;
let t = (e - cos * d) / denominator;
let (p, q) = (a.add(da.scale(s)), b.add(db.scale(t)));
(p.sub(q).length() <= tolerance).then(|| p.add(q).scale(0.5))
}
#[derive(Clone, Debug)]
pub(super) struct Piece {
pub run: Seam,
pub section: [Vec3; 3],
pub trim: Trim,
pub index: usize,
pub from: f64,
pub bridge: [f64; 2],
}
pub(super) fn build_bead(id: &str, pieces: &[Piece], contour: Option<f64>) -> Result<crate::BrepSolid, String> {
let mut bead: Option<crate::BrepSolid> = None;
for Piece { run, section: [root, a, b], trim, bridge, .. } in pieces {
let ((a, b), [skip_a, skip_b]) = if a.cross(*b).dot(run.tangent) >= 0.0 { ((*a, *b), *bridge) } else { ((*b, *a), [bridge[1], bridge[0]]) };
let start = run.start.add(*root);
let piece = if skip_a > 0.0 && skip_b > 0.0 {
let first = |leg: Vec3, skip: f64| start.add(leg.scale(skip / leg.length()));
sweep_bridged(run, start, [first(a, skip_a), start.add(a), start.add(b), first(b, skip_b)], contour, trim)?
} else {
sweep_section(run, &[start, start.add(a), start.add(b)], contour, trim)?
};
bead = Some(match bead {
None => piece,
Some(sum) => crate::boolean_operation(&sum, &piece, crate::BooleanOperation::Union, &crate::BooleanOptions::default())
.map_err(|refusal| format!("could not join the bead's segments: {refusal}"))?,
});
}
let mut bead = bead.ok_or("the seam is empty")?;
for (i, face) in bead.shells.iter_mut().flat_map(|shell| &mut shell.faces).enumerate() {
face.name = Some(format!("{id}:BeadFace{}", i + 1));
}
Ok(bead)
}
impl Chain {
pub(super) fn plane(&self) -> Option<Vec3> {
let mut up: Option<Vec3> = None;
for run in &self.runs {
if let Run::Arc { axis, .. } = run.run {
up.get_or_insert(axis);
}
}
if up.is_none() {
for pair in self.runs.windows(2) {
if let Ok(normal) = pair[0].tangent.cross(pair[1].tangent).normalized() {
up = Some(normal);
break;
}
}
}
let up = match up {
Some(up) => up,
None => self.runs[0].tangent.perpendicular().ok()?,
};
let origin = self.runs[0].start;
let flat = self.runs.iter().all(|run| {
let tolerance = run.tolerance() * 10.0;
let axis_ok = match run.run {
Run::Line => run.tangent.dot(up).abs() <= 1e-9,
Run::Arc { axis, .. } => axis.cross(up).length() <= 1e-9,
};
axis_ok && run.start.sub(origin).dot(up).abs() <= tolerance && run.at(1.0).sub(origin).dot(up).abs() <= tolerance
});
flat.then_some(up)
}
}
const LEFTOVER_VOLUME: f64 = 1e-9;
fn boolean(a: &crate::BrepSolid, b: &crate::BrepSolid, operation: crate::BooleanOperation) -> Result<crate::BrepSolid, crate::KernelRefusal> {
let options = crate::BooleanOptions { merge_coplanar_faces: false, ..Default::default() };
crate::boolean_operation(a, b, operation, &options)
}
fn empty(refusal: &crate::KernelRefusal) -> bool {
matches!(refusal.class, crate::RefusalClass::ConservativeEmptyOverlap)
}
pub(super) fn common_volume(a: &crate::BrepSolid, b: &crate::BrepSolid) -> Result<f64, NoFit> {
match boolean(a, b, crate::BooleanOperation::Intersect) {
Ok(common) => crate::solid_mass_properties(&common).map(|m| m.volume.abs())
.map_err(|error| format!("could not measure the common part: {error}")),
Err(refusal) if empty(&refusal) => Ok(0.0),
Err(refusal) => Err(format!("could not check the bead against the base metal: {refusal}")),
}
}
pub(super) fn clear(scene: &SceneMap, bead: &crate::BrepSolid, exclude: &str, tolerance: f64) -> Result<Result<(), NoFit>, String> {
let (low, high) = bounds(bead);
let mut names: Vec<(&String, &u32)> = scene.solids.iter().filter(|(name, _)| !owned_by(name, exclude)).collect();
names.sort();
for (name, &handle) in names {
let body = crate::registered_solid_clone(handle)?;
let (body_low, body_high) = bounds(&body);
let apart = body_low.x > high.x + tolerance || body_low.y > high.y + tolerance || body_low.z > high.z + tolerance
|| body_high.x < low.x - tolerance || body_high.y < low.y - tolerance || body_high.z < low.z - tolerance;
if apart {
continue;
}
match common_volume(bead, &body) {
Ok(shared) if shared > LEFTOVER_VOLUME => return Ok(Err(format!("the bead would overlap {name}"))),
Ok(_) => {}
Err(reason) => return Ok(Err(reason)),
}
}
Ok(Ok(()))
}
pub(super) fn clear_of(scene: &SceneMap, bead: &crate::BrepSolid, exclude: &str, replaced: &[(&str, &crate::BrepSolid)], tolerance: f64) -> Result<Result<(), NoFit>, String> {
let (low, high) = bounds(bead);
let mut names: Vec<(&String, &u32)> = scene.solids.iter().filter(|(name, _)| !owned_by(name, exclude)).collect();
names.sort();
for (name, &handle) in names {
let body = match replaced.iter().find(|(replaced, _)| *replaced == name.as_str()) {
Some((_, body)) => (*body).clone(),
None => crate::registered_solid_clone(handle)?,
};
let (body_low, body_high) = bounds(&body);
let apart = body_low.x > high.x + tolerance || body_low.y > high.y + tolerance || body_low.z > high.z + tolerance
|| body_high.x < low.x - tolerance || body_high.y < low.y - tolerance || body_high.z < low.z - tolerance;
if apart {
continue;
}
match common_volume(bead, &body) {
Ok(shared) if shared > LEFTOVER_VOLUME => return Ok(Err(format!("the bead would overlap {name}"))),
Ok(_) => {}
Err(reason) => return Ok(Err(reason)),
}
}
Ok(Ok(()))
}
pub(super) fn backed(slab: &crate::BrepSolid, body: &crate::BrepSolid) -> Result<Result<(), NoFit>, String> {
match boolean(slab, body, crate::BooleanOperation::Subtract) {
Err(refusal) if empty(&refusal) => Ok(Ok(())),
Ok(rest) => {
let left = crate::solid_mass_properties(&rest).map(|m| m.volume.abs()).unwrap_or(f64::INFINITY);
Ok(if left > LEFTOVER_VOLUME { Err(format!("{left} of the support slab lies outside the part")) } else { Ok(()) })
}
Err(refusal) => Ok(Err(format!("could not check the support: {refusal}"))),
}
}
pub(super) fn supported(seam: &Seam, joint: &Fit, legs: [f64; 2], trim: &Trim) -> Result<Result<(), NoFit>, String> {
for (i, (face, (direction, size))) in joint.faces.iter().zip(joint.legs.iter().zip(legs)).enumerate() {
let depth = support_depth(seam);
let start = seam.start.add(joint.root);
let toe = start.add(direction.scale(size));
let start = start.add(direction.scale(joint.skip[i]));
let inward = face.normal.scale(-depth);
let other = joint.faces[1 - i].normal;
let shift = (depth * face.normal.dot(other) / direction.dot(other)).max(0.0);
let slab = sweep(seam, &[start, toe, toe.add(inward), start.add(direction.scale(shift)).add(inward)], trim)?;
let body = crate::registered_solid_clone(face.handle)?;
match boolean(&slab, &body, crate::BooleanOperation::Subtract) {
Err(refusal) if empty(&refusal) => {}
Ok(rest) => {
let left = crate::solid_mass_properties(&rest).map(|m| m.volume.abs()).unwrap_or(f64::INFINITY);
if left > LEFTOVER_VOLUME {
return Ok(Err(format!("leg {size} is not supported along its whole length by joint face {}", face.name)));
}
}
Err(refusal) => return Ok(Err(format!("could not check the support under leg {size}: {refusal}"))),
}
}
Ok(Ok(()))
}
pub(super) fn support_depth(_seam: &Seam) -> f64 {
100.0 * crate::tolerance::WELD_FLOOR
}
pub(super) fn seam_between(scene: &SceneMap, faces: [&str; 2], exclude: &str, legs: [f64; 2]) -> Result<Result<String, String>, String> {
let mut found = edges_between(scene, faces, None)?;
if found.is_empty() {
let mut roots: Vec<(Vec3, Vec3)> = Vec::new();
for candidate in edges_between(scene, faces, Some(legs[0].max(legs[1])))? {
let seam = &candidate.4;
let picks = [faces[0].to_string(), faces[1].to_string()];
let Ok(joint) = fit(scene, seam, &picks, exclude, legs, None)? else { continue };
let (point, tolerance) = (seam.start.add(joint.root), seam.tolerance() * 10.0);
let shared = roots.iter().position(|(other, along)| along.cross(seam.tangent).length() <= 1e-9
&& point.sub(*other).cross(*along).length() <= tolerance);
match shared {
None => {
roots.push((point, seam.tangent));
found.push(candidate);
}
Some(k) if seam.length > found[k].4.length => found[k] = candidate,
Some(_) => {}
}
}
}
Ok(match found.as_slice() {
[(name, _, _, _, _)] => Ok(name.clone()),
[] => Err(format!("faces '{}' and '{}' do not meet along a straight or circular edge, nor stand a root gap narrower than the legs off one; select the seam edge", faces[0], faces[1])),
_ => Err(format!("faces '{}' and '{}' meet along several edges; select the seam edge", faces[0], faces[1])),
})
}
fn edges_between(scene: &SceneMap, faces: [&str; 2], gap: Option<f64>) -> Result<Vec<(String, Vec3, Vec3, Vec3, Seam)>, String> {
let mut found: Vec<(String, Vec3, Vec3, Vec3, Seam)> = Vec::new();
for (own, other) in [(faces[0], faces[1]), (faces[1], faces[0])] {
for face in scene.resolve_face_group(own) {
let runs: Vec<(u64, NurbsCurve)> = crate::with_registered_solid_str(face.handle, |solid| {
let record = solid.shells.iter().flat_map(|shell| &shell.faces).find(|f| f.id == face.face_id)
.ok_or_else(|| format!("face '{own}' is no longer resident"))?;
let mut runs = Vec::new();
for coedge in record.loops.iter().flat_map(|l| &l.coedges) {
let Some(edge) = solid.edges.iter().find(|e| e.id == coedge.edge_id) else { continue };
if edge.degenerate { continue; }
runs.push((edge.id, crate::feature_pipeline::features::common::trimmed_curve(&edge.curve, edge.t0, edge.t1)?));
}
Ok(runs)
})?;
for (edge_id, curve) in runs {
let Ok(Some(seam)) = Seam::from_curve(&curve, None) else { continue };
if seam.length <= seam.tolerance() { continue; }
let (start, end, middle) = (seam.at(0.0), seam.at(1.0), seam.at(0.5));
let meets = match gap {
None => carries(scene, &seam, other)?,
Some(widest) => across_gap(scene, &seam, other, widest)?.is_some(),
};
if !meets { continue; }
let mut names: Vec<&String> = scene.edges.iter()
.filter(|(_, edge)| edge.handle == face.handle && edge.edge_id == edge_id)
.map(|(name, _)| name).collect();
names.sort();
let Some(name) = names.first() else { continue };
let tolerance = seam.tolerance();
let same = |(_, a, b, m, _): &(String, Vec3, Vec3, Vec3, Seam)| m.sub(middle).length() < tolerance
&& ((a.sub(start).length() < tolerance && b.sub(end).length() < tolerance)
|| (a.sub(end).length() < tolerance && b.sub(start).length() < tolerance));
if !found.iter().any(same) {
found.push(((*name).clone(), start, end, middle, seam));
}
}
}
}
Ok(found)
}