use crate::{NurbsCurve, Vec3};
const RELATIVE_TOLERANCE: f64 = 1e-6;
const PIECES_PER_SPAN: usize = 4;
const MAX_DEPTH: u32 = 12;
const VOTE_FRACTIONS: [f64; 5] = [0.13, 0.31, 0.5, 0.69, 0.87];
pub(crate) struct NestingLoop {
polygon: Vec<[f64; 2]>,
votes: Vec<[f64; 2]>,
slack: f64,
min: [f64; 2],
max: [f64; 2],
}
#[derive(Clone, Copy)]
pub(crate) struct PlaneFrame {
pub origin: Vec3,
pub x_axis: Vec3,
pub y_axis: Vec3,
}
impl PlaneFrame {
fn uv(&self, point: Vec3) -> [f64; 2] {
let delta = point.sub(self.origin);
[delta.dot(self.x_axis), delta.dot(self.y_axis)]
}
}
pub(crate) fn sample_loops(
loops: &[&[NurbsCurve]],
frame: PlaneFrame,
) -> Result<Vec<NestingLoop>, String> {
let mut lo = [f64::INFINITY; 2];
let mut hi = [f64::NEG_INFINITY; 2];
for curves in loops {
for curve in curves.iter() {
for control in &curve.control_points {
let uv = frame.uv(control.point()?);
for k in 0..2 {
lo[k] = lo[k].min(uv[k]);
hi[k] = hi[k].max(uv[k]);
}
}
}
}
let extent = (hi[0] - lo[0]).hypot(hi[1] - lo[1]);
let tolerance = (extent * RELATIVE_TOLERANCE).max(1e-12);
loops
.iter()
.map(|curves| sample_loop(curves, frame, tolerance))
.collect()
}
fn sample_loop(
curves: &[NurbsCurve],
frame: PlaneFrame,
tolerance: f64,
) -> Result<NestingLoop, String> {
let mut polygon = Vec::new();
let mut votes = Vec::new();
let mut slack: f64 = 0.0;
for curve in curves {
let [t0, t1] = curve.domain()?;
let at = |t: f64| -> Result<[f64; 2], String> { Ok(frame.uv(curve.evaluate(t)?)) };
let mut breaks = vec![t0];
for &knot in &curve.knots {
if knot > t0 && knot < t1 && knot > *breaks.last().unwrap() {
breaks.push(knot);
}
}
breaks.push(t1);
for span in breaks.windows(2) {
for piece in 0..PIECES_PER_SPAN {
let a = span[0] + (span[1] - span[0]) * (piece as f64 / PIECES_PER_SPAN as f64);
let b = span[0]
+ (span[1] - span[0]) * ((piece + 1) as f64 / PIECES_PER_SPAN as f64);
let (pa, pb) = (at(a)?, at(b)?);
refine(&at, a, pa, b, pb, tolerance, MAX_DEPTH, &mut polygon, &mut slack)?;
}
}
for fraction in VOTE_FRACTIONS {
votes.push(at(t0 + (t1 - t0) * fraction)?);
}
}
let mut min = [f64::INFINITY; 2];
let mut max = [f64::NEG_INFINITY; 2];
for point in &polygon {
for k in 0..2 {
min[k] = min[k].min(point[k]);
max[k] = max[k].max(point[k]);
}
}
Ok(NestingLoop {
polygon,
votes,
slack: slack.max(tolerance),
min,
max,
})
}
#[allow(clippy::too_many_arguments)]
fn refine(
at: &impl Fn(f64) -> Result<[f64; 2], String>,
a: f64,
pa: [f64; 2],
b: f64,
pb: [f64; 2],
tolerance: f64,
depth: u32,
polygon: &mut Vec<[f64; 2]>,
slack: &mut f64,
) -> Result<(), String> {
let m = 0.5 * (a + b);
let pm = at(m)?;
let deviation = distance_to_segment(pm, pa, pb);
if deviation <= tolerance || depth == 0 {
let q1 = distance_to_segment(at(0.5 * (a + m))?, pa, pb);
let q3 = distance_to_segment(at(0.5 * (m + b))?, pa, pb);
let worst = deviation.max(q1).max(q3);
if worst <= tolerance || depth == 0 {
*slack = slack.max(worst);
polygon.push(pa);
return Ok(());
}
}
refine(at, a, pa, m, pm, tolerance, depth - 1, polygon, slack)?;
refine(at, m, pm, b, pb, tolerance, depth - 1, polygon, slack)
}
pub(crate) fn containment(loops: &[NestingLoop]) -> Vec<Vec<bool>> {
let count = loops.len();
let mut contains = vec![vec![false; count]; count];
for i in 0..count {
for j in 0..count {
if i != j {
contains[i][j] = inside(&loops[i], &loops[j]);
}
}
}
contains
}
fn inside(inner: &NestingLoop, outer: &NestingLoop) -> bool {
if outer.polygon.len() < 3 {
return false;
}
let band = 2.0 * (outer.slack + inner.slack);
if inner.max[0] < outer.min[0] - band
|| inner.max[1] < outer.min[1] - band
|| inner.min[0] > outer.max[0] + band
|| inner.min[1] > outer.max[1] + band
{
return false;
}
let (mut ins, mut outs) = (0usize, 0usize);
for &point in &inner.votes {
if point[0] < outer.min[0] - band
|| point[1] < outer.min[1] - band
|| point[0] > outer.max[0] + band
|| point[1] > outer.max[1] + band
{
outs += 1;
continue;
}
let count = outer.polygon.len();
let on_boundary = (0..count).any(|k| {
distance_to_segment(point, outer.polygon[k], outer.polygon[(k + 1) % count]) <= band
});
if on_boundary {
continue;
}
if crate::polygon::parity_inside(point, count, |k| outer.polygon[k]) {
ins += 1;
} else {
outs += 1;
}
}
ins > outs
}
fn distance_to_segment(p: [f64; 2], a: [f64; 2], b: [f64; 2]) -> f64 {
let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
let length_squared = dx * dx + dy * dy;
let t = if length_squared > 0.0 {
(((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / length_squared).clamp(0.0, 1.0)
} else {
0.0
};
(p[0] - (a[0] + t * dx)).hypot(p[1] - (a[1] + t * dy))
}