use super::{Frame, Ring, signed_twice_area};
use crate::{Error, Point, Result, Transform};
use std::f64::consts::{FRAC_PI_2, PI, TAU};
const MAX_VERTICES: usize = 1_000_000;
const FLOAT_LIMIT: f64 = (1_u64 << 51) as f64;
pub(super) fn validate_tolerance(tolerance: f64) -> Result<()> {
if tolerance.is_finite() && tolerance > 0.0 {
Ok(())
} else {
Err(Error::invalid("tolerance must be positive and finite"))
}
}
pub(super) fn arc_steps(radius: f64, sweep: f64, tolerance: f64) -> Result<usize> {
validate_tolerance(tolerance)?;
let step = (4.0 * (tolerance / (2.0 * radius)).min(1.0).sqrt().asin()).min(FRAC_PI_2);
let count = (sweep.abs() / step).ceil().max(1.0);
if count > MAX_VERTICES as f64 {
return Err(Error::invalid(
"curve needs over one million vertices at the requested tolerance",
));
}
Ok(count as usize)
}
fn rounded(value: f64) -> Result<i128> {
if !value.is_finite() || value.abs() > FLOAT_LIMIT {
return Err(Error::invalid(
"floating-point construction exceeds its local DBU precision range",
));
}
Ok(value.round() as i128)
}
fn point_i128(x: i128, y: i128) -> Result<Point> {
let coordinate =
|v| i64::try_from(v).map_err(|_| Error::invalid("geometry result exceeds i64 DBU"));
Ok(Point {
x: coordinate(x)?,
y: coordinate(y)?,
})
}
fn relative_point(origin: Point, x: f64, y: f64) -> Result<Point> {
point_i128(
i128::from(origin.x) + rounded(x)?,
i128::from(origin.y) + rounded(y)?,
)
}
fn finished(mut ring: Ring) -> Result<Ring> {
ring.dedup();
if ring.len() > 1 && ring.first() == ring.last() {
ring.pop();
}
if ring.len() < 3 {
return Err(Error::invalid("polygon collapses on the integer DBU grid"));
}
Frame::new(ring.iter())?;
if signed_twice_area(&ring) == 0 {
return Err(Error::invalid(
"polygon has zero signed area on the integer DBU grid",
));
}
Ok(ring)
}
pub fn rectangle(a: Point, b: Point) -> Result<Ring> {
let (x0, x1) = (a.x.min(b.x), a.x.max(b.x));
let (y0, y1) = (a.y.min(b.y), a.y.max(b.y));
if x0 == x1 || y0 == y1 {
return Err(Error::invalid(
"rectangle must have positive width and height",
));
}
Ok(vec![
Point { x: x0, y: y0 },
Point { x: x1, y: y0 },
Point { x: x1, y: y1 },
Point { x: x0, y: y1 },
])
}
fn check_radius(radius: f64) -> Result<()> {
if radius > 0.0 && radius.is_finite() && radius <= FLOAT_LIMIT {
Ok(())
} else {
Err(Error::invalid(
"radius must be positive, finite and within the local DBU precision range",
))
}
}
pub fn ellipse(center: Point, radius_x: f64, radius_y: f64, tolerance: f64) -> Result<Ring> {
check_radius(radius_x)?;
check_radius(radius_y)?;
let quarter = arc_steps(radius_x.max(radius_y), FRAC_PI_2, tolerance)?;
let count = 4 * quarter;
if count > MAX_VERTICES {
return Err(Error::invalid("ellipse exceeds one million vertices"));
}
let mut ring = Ring::with_capacity(count);
for i in 0..count {
let (s, c) = (TAU * i as f64 / count as f64).sin_cos();
ring.push(relative_point(center, radius_x * c, radius_y * s)?);
}
finished(ring)
}
pub fn regular_polygon(center: Point, radius: f64, sides: usize, angle_deg: f64) -> Result<Ring> {
check_radius(radius)?;
if !(3..=MAX_VERTICES).contains(&sides) || !angle_deg.is_finite() {
return Err(Error::invalid(
"regular polygon needs 3..=1000000 sides and a finite angle",
));
}
let start = angle_deg.rem_euclid(360.0).to_radians();
let mut ring = Ring::with_capacity(sides);
for i in 0..sides {
let (s, c) = (start + TAU * i as f64 / sides as f64).sin_cos();
ring.push(relative_point(center, radius * c, radius * s)?);
}
finished(ring)
}
pub fn transform_points(
points: &[Point],
origin: Point,
translation: Point,
transform: Transform,
) -> Result<Ring> {
if !transform.angle_deg.is_finite()
|| !transform.magnification.is_finite()
|| transform.magnification <= 0.0
{
return Err(Error::invalid(
"transform needs a finite angle and positive finite magnification",
));
}
let angle = transform.angle_deg.rem_euclid(360.0);
let quarter_turn = angle % 90.0 == 0.0;
let (sin, cos) = angle.to_radians().sin_cos();
let ox = i128::from(origin.x) + i128::from(translation.x);
let oy = i128::from(origin.y) + i128::from(translation.y);
points
.iter()
.map(|p| {
let dx = i128::from(p.x) - i128::from(origin.x);
let dy = i128::from(p.y) - i128::from(origin.y);
let dy = if transform.reflect_x { -dy } else { dy };
let (x, y) = if quarter_turn {
match (angle / 90.0) as u8 {
0 => (dx, dy),
1 => (-dy, dx),
2 => (-dx, -dy),
_ => (dy, -dx),
}
} else {
(dx, dy)
};
if quarter_turn && transform.magnification == 1.0 {
return point_i128(ox + x, oy + y);
}
if x.unsigned_abs().max(y.unsigned_abs()) > FLOAT_LIMIT as u128 {
return Err(Error::invalid(
"transform exceeds its local DBU precision range",
));
}
let (x, y) = (x as f64, y as f64);
let (x, y) = if quarter_turn {
(x, y)
} else {
(x * cos - y * sin, x * sin + y * cos)
};
point_i128(
ox + rounded(x * transform.magnification)?,
oy + rounded(y * transform.magnification)?,
)
})
.collect()
}
pub fn fillet(points: &[Point], radius: f64, tolerance: f64) -> Result<Ring> {
fillet_radii(points, &[radius], tolerance)
}
pub fn fillet_radii(points: &[Point], radii: &[f64], tolerance: f64) -> Result<Ring> {
validate_tolerance(tolerance)?;
let ring = finished(points.to_vec())?;
if radii.len() != 1 && (radii.len() != ring.len() || ring.len() != points.len()) {
return Err(Error::invalid(
"provide a scalar radius or one radius per distinct contour vertex",
));
}
if radii.iter().any(|r| !r.is_finite() || *r < 0.0) {
return Err(Error::invalid(
"fillet radii must be nonnegative and finite",
));
}
let mut out = Vec::new();
for (i, &vertex) in ring.iter().enumerate() {
let radius = if radii.len() == 1 { radii[0] } else { radii[i] };
if radius == 0.0 {
out.push(vertex);
continue;
}
let previous = ring[(i + ring.len() - 1) % ring.len()];
let next = ring[(i + 1) % ring.len()];
let (dx, dy) = (
(vertex.x - previous.x) as f64,
(vertex.y - previous.y) as f64,
);
let (ex, ey) = ((next.x - vertex.x) as f64, (next.y - vertex.y) as f64);
let (incoming, outgoing) = (dx.hypot(dy), ex.hypot(ey));
let (ux, uy, vx, vy) = (dx / incoming, dy / incoming, ex / outgoing, ey / outgoing);
let turn = (ux * vy - uy * vx).atan2(ux * vx + uy * vy);
if (PI - turn.abs()).abs() <= f64::EPSILON {
return Err(Error::invalid("cannot fillet a reversing edge"));
}
if turn.abs() <= f64::EPSILON {
out.push(vertex);
continue;
}
let tangent = (turn.abs() / 2.0).tan();
let trim = (radius * tangent).min(incoming.min(outgoing) / 2.0);
let r = trim / tangent;
let signed_r = turn.signum() * r;
let (cx, cy) = (-ux * trim - uy * signed_r, -uy * trim + ux * signed_r);
let (rx, ry) = (uy * signed_r, -ux * signed_r);
let count = arc_steps(r, turn, tolerance)?;
if out.len() + count + 1 > MAX_VERTICES {
return Err(Error::invalid("fillet exceeds one million vertices"));
}
out.push(relative_point(vertex, -ux * trim, -uy * trim)?);
for j in 1..count {
let (s, c) = (turn * j as f64 / count as f64).sin_cos();
out.push(relative_point(
vertex,
cx + c * rx - s * ry,
cy + s * rx + c * ry,
)?);
}
out.push(relative_point(vertex, vx * trim, vy * trim)?);
}
finished(out)
}
pub fn scale_points(points: &[Point], origin: Point, sx: f64, sy: f64) -> Result<Ring> {
if !sx.is_finite() || !sy.is_finite() {
return Err(Error::invalid("scale factors must be finite"));
}
fn scale(v: i64, origin: i64, factor: f64) -> Result<i64> {
let delta = i128::from(v) - i128::from(origin);
let offset = if factor == 1.0 {
delta
} else if factor == -1.0 {
-delta
} else if factor == 0.0 {
0
} else {
if delta.unsigned_abs() > FLOAT_LIMIT as u128 {
return Err(Error::invalid("scale exceeds local DBU precision"));
}
rounded(delta as f64 * factor)?
};
i64::try_from(i128::from(origin) + offset)
.map_err(|_| Error::invalid("scaled coordinate exceeds i64 DBU"))
}
points
.iter()
.map(|p| {
Ok(Point {
x: scale(p.x, origin.x, sx)?,
y: scale(p.y, origin.y, sy)?,
})
})
.collect()
}
pub fn mirror_points(points: &[Point], a: Point, b: Point) -> Result<Ring> {
let dx = i128::from(b.x) - i128::from(a.x);
let dy = i128::from(b.y) - i128::from(a.y);
if dx == 0 && dy == 0 {
return Err(Error::invalid("a mirror axis needs two distinct points"));
}
if dx == 0 {
return scale_points(points, a, -1.0, 1.0);
}
if dy == 0 {
return scale_points(points, a, 1.0, -1.0);
}
let angle = if dx == dy {
90.0
} else if dx == -dy {
270.0
} else {
2.0 * (dy as f64).atan2(dx as f64).to_degrees()
};
transform_points(
points,
a,
Point::default(),
Transform {
angle_deg: angle,
magnification: 1.0,
reflect_x: true,
},
)
}
#[derive(Clone, Copy, Debug)]
pub enum Sampling {
Tolerance(f64),
Vertices(usize),
}
pub fn elliptic_sector(
center: Point,
outer: (f64, f64),
inner: Option<(f64, f64)>,
start_deg: f64,
sweep_deg: f64,
sampling: Sampling,
) -> Result<Vec<Ring>> {
check_radius(outer.0)?;
check_radius(outer.1)?;
if let Sampling::Tolerance(tolerance) = sampling {
validate_tolerance(tolerance)?;
}
if !start_deg.is_finite()
|| !sweep_deg.is_finite()
|| sweep_deg == 0.0
|| sweep_deg.abs() > 360.0
{
return Err(Error::invalid(
"sector needs a finite start angle and a nonzero sweep of at most 360 degrees",
));
}
if let Some((rx, ry)) = inner {
check_radius(rx)?;
check_radius(ry)?;
if rx > outer.0 || ry > outer.1 || (rx, ry) == outer {
return Err(Error::invalid(
"inner ellipse must fit inside the outer ellipse",
));
}
}
let full = sweep_deg.abs() == 360.0;
let begin = if sweep_deg < 0.0 {
start_deg.rem_euclid(360.0) + sweep_deg
} else {
start_deg.rem_euclid(360.0)
};
let begin = begin.to_radians();
let end = begin + sweep_deg.abs().to_radians();
let (outer_count, inner_count) = match sampling {
Sampling::Tolerance(_) => (None, None),
Sampling::Vertices(n) => {
if n > MAX_VERTICES {
return Err(Error::invalid("sector exceeds one million vertices"));
}
let split = if inner.is_some() {
n / 2
} else {
usize::from(!full)
};
let count = n.saturating_sub(split);
let min = if full { 3 } else { 2 };
if count < min || (inner.is_some() && split < min) {
return Err(Error::invalid("too few vertices for the requested sector"));
}
(Some(count), Some(split))
}
};
let arc = |(rx, ry): (f64, f64), exact: Option<usize>| -> Result<Ring> {
let param = |a: f64| (rx * a.sin()).atan2(ry * a.cos());
let start = param(begin);
let sweep = if full {
TAU
} else {
(param(end) - start).rem_euclid(TAU)
};
let edges = match (exact, sampling) {
(Some(n), _) => n - usize::from(!full),
(_, Sampling::Tolerance(tol)) => arc_steps(rx.max(ry), sweep, tol)?,
_ => unreachable!(),
};
let count = edges + usize::from(!full);
(0..count)
.map(|i| {
let (s, c) = (start + sweep * (i as f64) / (edges as f64)).sin_cos();
relative_point(center, rx * c, ry * s)
})
.collect()
};
let finish = |ring: Ring| -> Result<Ring> {
let count = ring.len();
let result = finished(ring)?;
if matches!(sampling, Sampling::Vertices(_)) && result.len() != count {
return Err(Error::invalid(
"chosen grid cannot resolve the requested vertex count",
));
}
Ok(result)
};
let mut outer_ring = arc(outer, outer_count)?;
let mut result = Vec::new();
if let Some(radii) = inner {
let mut hole = arc(radii, inner_count)?;
hole.reverse();
if full {
result.push(finish(outer_ring)?);
result.push(finish(hole)?);
return Ok(result);
}
outer_ring.extend(hole);
} else if !full {
outer_ring.push(center);
}
result.push(finish(outer_ring)?);
Ok(result)
}