use crate::geom::{Curve, Surface};
use crate::math::{Point3, Vec3};
use crate::tol;
pub(crate) type Pairs = Vec<(usize, usize)>;
pub(crate) struct Side<'a> {
pub surface: &'a Surface,
pub reversed: bool,
pub travel: Vec3,
}
pub(crate) fn length(c: &Curve, range: (f64, f64)) -> f64 {
let n = 16;
(0..n)
.map(|k| {
let at = |k: usize| c.eval(range.0 + (range.1 - range.0) * k as f64 / n as f64);
at(k).dist(at(k + 1))
})
.sum()
}
fn outward(s: &Side, p: Point3) -> Vec3 {
let uv = s.surface.project(p);
let n = s.surface.normal(uv.x, uv.y);
if s.reversed { -n } else { n }
}
pub(crate) fn round(m: Point3, t: Vec3, len: f64, sides: &[Side]) -> Option<(Pairs, Pairs)> {
let step = 1e-3 * len.clamp(1e3 * tol::LINEAR, 1.0);
let mut around: Vec<(f64, bool, usize)> = Vec::with_capacity(sides.len());
let mut axes: Option<(Vec3, Vec3)> = None;
for (i, s) in sides.iter().enumerate() {
let into = outward(s, m).cross(s.travel).unit()?;
let uv = s.surface.project(m + into * step);
let q = s.surface.eval(uv.x, uv.y);
let w = q - m;
let w = (w - t * w.dot(t)).unit()?;
let (a, b) = *axes.get_or_insert((w, t.cross(w)));
let angle = w.dot(b).atan2(w.dot(a));
let ahead = (-outward(s, q)).dot(t.cross(w)) > 0.0;
around.push((angle, ahead, i));
}
around.sort_by(|x, y| x.0.total_cmp(&y.0));
let k = around.len();
let level = |x: f64, y: f64| {
let d = (x - y).rem_euclid(std::f64::consts::TAU);
d.min(std::f64::consts::TAU - d) * step <= tol::LINEAR
};
for i in 0..k {
let (j, l) = ((i + 1) % k, (i + 2) % k);
if around[i].1 == around[j].1
&& around[j].1 != around[l].1
&& level(around[j].0, around[l].0)
{
around.swap(j, l);
}
}
let (mut partners, mut beside) = (Vec::new(), Vec::new());
for i in 0..k {
let j = (i + 1) % k;
if around[i].1 == around[j].1 {
return None;
}
if around[i].1 {
partners.push((around[i].2, around[j].2));
} else {
beside.push((around[i].2, around[j].2));
}
}
Some((partners, beside))
}