mod construction;
use crate::{Error, Point, Result};
use clipper2_rust as cl;
pub use construction::{
Sampling, ellipse, elliptic_sector, fillet, fillet_radii, mirror_points, rectangle,
regular_polygon, scale_points, transform_points,
};
use num_bigint::BigInt;
use num_traits::Signed;
pub type Ring = Vec<Point>;
pub type Region = Vec<Ring>;
const SCALE: i64 = 256;
const WORK_LIMIT: i64 = 1 << 49;
#[derive(Debug, Copy, Clone)]
pub enum BooleanOp {
Union,
Intersection,
Difference,
Xor,
}
impl std::str::FromStr for BooleanOp {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
match s {
"union" | "or" => Ok(Self::Union),
"intersection" | "and" => Ok(Self::Intersection),
"difference" | "not" => Ok(Self::Difference),
"xor" => Ok(Self::Xor),
_ => Err(Error::invalid(
"operation must be union, intersection, difference or xor",
)),
}
}
}
impl From<BooleanOp> for cl::ClipType {
fn from(value: BooleanOp) -> Self {
match value {
BooleanOp::Union => Self::Union,
BooleanOp::Intersection => Self::Intersection,
BooleanOp::Difference => Self::Difference,
BooleanOp::Xor => Self::Xor,
}
}
}
#[derive(Debug, Copy, Clone)]
pub enum Join {
Miter,
Bevel,
Square,
Round,
}
#[derive(Debug, Copy, Clone)]
pub enum Axis {
X,
Y,
}
#[derive(Clone, Copy)]
struct Frame {
center: Point,
min: Point,
max: Point,
}
impl Frame {
fn new<'a>(points: impl Iterator<Item = &'a Point>) -> Result<Self> {
let mut min = Point {
x: i64::MAX,
y: i64::MAX,
};
let mut max = Point {
x: i64::MIN,
y: i64::MIN,
};
for p in points {
min.x = min.x.min(p.x);
min.y = min.y.min(p.y);
max.x = max.x.max(p.x);
max.y = max.y.max(p.y);
}
if min.x > max.x {
min = Point::default();
max = min;
}
let span = |lo: i64, hi: i64| i128::from(hi) - i128::from(lo);
if span(min.x, max.x).max(span(min.y, max.y)) > i128::from(WORK_LIMIT / SCALE) {
return Err(Error::invalid(
"geometry span exceeds the clipping kernel range (2^41 DBU)",
));
}
Ok(Self {
center: Point {
x: min.x.midpoint(max.x),
y: min.y.midpoint(max.y),
},
min,
max,
})
}
fn local(self, p: Point) -> cl::Point64 {
cl::Point64::new((p.x - self.center.x) * SCALE, (p.y - self.center.y) * SCALE)
}
fn paths(self, polygons: &[Ring]) -> Result<cl::Paths64> {
polygons
.iter()
.map(|ring| {
let mut path: cl::Path64 = ring.iter().map(|p| self.local(*p)).collect();
path.dedup();
if path.len() > 1 && path.first() == path.last() {
path.pop();
}
if path.len() < 3 {
return Err(Error::invalid(
"a contour needs at least three distinct vertices",
));
}
Ok(path)
})
.collect()
}
fn decode(self, paths: cl::Paths64) -> Result<Region> {
let mut rings = Vec::with_capacity(paths.len());
for path in paths {
let mut ring = Vec::with_capacity(path.len());
for p in path {
let coordinate = |value: i64, origin: i64| {
origin
.checked_add((value + SCALE / 2).div_euclid(SCALE))
.ok_or_else(|| Error::invalid("geometry result exceeds i64 DBU"))
};
ring.push(Point {
x: coordinate(p.x, self.center.x)?,
y: coordinate(p.y, self.center.y)?,
});
}
ring.dedup();
if ring.len() > 1 && ring.first() == ring.last() {
ring.pop();
}
if ring.len() >= 3 && signed_twice_area(&ring) != 0 {
rings.push(ring);
}
}
Ok(rings)
}
}
fn signed_twice_area(ring: &[Point]) -> i128 {
let o = ring[0];
ring[1..]
.windows(2)
.map(|p| {
let delta = |q: Point| {
(
i128::from(q.x) - i128::from(o.x),
i128::from(q.y) - i128::from(o.y),
)
};
let (ax, ay) = delta(p[0]);
let (bx, by) = delta(p[1]);
ax * by - ay * bx
})
.sum()
}
fn engine(subject: &cl::Paths64, clip: &cl::Paths64) -> cl::Clipper64 {
let mut c = cl::Clipper64::new();
c.set_preserve_collinear(false);
c.add_subject(subject);
c.add_clip(clip);
c
}
fn clip_paths(subject: &cl::Paths64, clip: &cl::Paths64, op: BooleanOp) -> Result<cl::Paths64> {
let mut out = Vec::new();
if !engine(subject, clip).execute(op.into(), cl::FillRule::NonZero, &mut out, None) {
return Err(Error::invalid("polygon clipping failed"));
}
Ok(out)
}
pub fn axis_aligned_rect(ring: &[Point]) -> Option<(Point, Point)> {
let [a, b, c, d] = ring else {
return None;
};
let ortho = (a.x == b.x && b.y == c.y && c.x == d.x && d.y == a.y)
|| (a.y == b.y && b.x == c.x && c.y == d.y && d.x == a.x);
if !ortho {
return None;
}
let lo = Point {
x: a.x.min(c.x),
y: a.y.min(c.y),
};
let hi = Point {
x: a.x.max(c.x),
y: a.y.max(c.y),
};
(lo.x < hi.x && lo.y < hi.y).then_some((lo, hi))
}
pub fn normalize_ring(mut ring: Ring) -> Result<Region> {
if let Some((lo, hi)) = axis_aligned_rect(&ring) {
return Ok(vec![rectangle(lo, hi)?]);
}
if ring.len() == 3 {
let area2 = signed_twice_area(&ring);
if area2 == 0 {
return Ok(Vec::new());
}
if area2 < 0 {
ring.reverse();
}
return Ok(vec![ring]);
}
boolean(&[ring], &[], BooleanOp::Union)
}
fn cross_sign(dx: i128, dy: i128, rx: i128, ry: i128) -> i8 {
if let Some(left) = dx.checked_mul(ry)
&& let Some(right) = dy.checked_mul(rx)
&& let Some(diff) = left.checked_sub(right)
{
return diff.signum() as i8;
}
let diff = BigInt::from(dx) * ry - BigInt::from(dy) * rx;
if diff.is_positive() {
1
} else if diff.is_negative() {
-1
} else {
0
}
}
pub fn hits_open_box(ring: &[Point], lower: Point, upper: Point) -> bool {
if ring.len() < 3 || lower.x >= upper.x || lower.y >= upper.y {
return false;
}
let (mut min_x, mut min_y, mut max_x, mut max_y) = (ring[0].x, ring[0].y, ring[0].x, ring[0].y);
for p in &ring[1..] {
min_x = min_x.min(p.x);
min_y = min_y.min(p.y);
max_x = max_x.max(p.x);
max_y = max_y.max(p.y);
}
if max_x <= lower.x || min_x >= upper.x || max_y <= lower.y || min_y >= upper.y {
return false;
}
if axis_aligned_rect(ring).is_some() {
return true;
}
let (x0, y0, x1, y1) = (
i128::from(lower.x),
i128::from(lower.y),
i128::from(upper.x),
i128::from(upper.y),
);
let cx2 = x0 + x1;
let cy2 = y0 + y1;
let mut winding: i64 = 0;
let mut prev = ring[ring.len() - 1];
for &curr in ring {
let (ax, ay) = (i128::from(prev.x), i128::from(prev.y));
let (bx, by) = (i128::from(curr.x), i128::from(curr.y));
let dx = bx - ax;
let dy = by - ay;
if ax.max(bx) > x0 && ax.min(bx) < x1 && ay.max(by) > y0 && ay.min(by) < y1 {
let mut has_neg = false;
let mut has_pos = false;
for x in [x0, x1] {
for y in [y0, y1] {
match cross_sign(dx, dy, x - ax, y - ay) {
-1 => has_neg = true,
1 => has_pos = true,
_ => {}
}
}
}
if has_neg && has_pos {
return true;
}
}
let ay2 = 2 * ay;
let by2 = 2 * by;
if ay2 <= cy2 && cy2 < by2 {
if cross_sign(dx, dy, cx2 - 2 * ax, cy2 - ay2) > 0 {
winding += 1;
}
} else if by2 <= cy2 && cy2 < ay2 && cross_sign(dx, dy, cx2 - 2 * ax, cy2 - ay2) < 0 {
winding -= 1;
}
prev = curr;
}
winding != 0
}
pub fn boolean(subject: &[Ring], clip: &[Ring], op: BooleanOp) -> Result<Region> {
let frame = Frame::new(subject.iter().chain(clip).flatten())?;
frame.decode(clip_paths(&frame.paths(subject)?, &frame.paths(clip)?, op)?)
}
pub fn offset(
polygons: &[Ring],
distance: f64,
join: Join,
miter_limit: f64,
tolerance: f64,
) -> Result<Region> {
if !distance.is_finite() || !miter_limit.is_finite() || miter_limit < 1.0 {
return Err(Error::invalid(
"offset needs a finite distance and finite miter limit >= 1",
));
}
construction::validate_tolerance(tolerance)?;
if distance.abs() * miter_limit.max(2.0) * SCALE as f64 > WORK_LIMIT as f64 {
return Err(Error::invalid("offset exceeds the clipping kernel range"));
}
if matches!(join, Join::Round) && distance != 0.0 {
construction::arc_steps(distance.abs(), std::f64::consts::TAU, tolerance)?;
}
let frame = Frame::new(polygons.iter().flatten())?;
let normalized = clip_paths(&frame.paths(polygons)?, &Vec::new(), BooleanOp::Union)?;
let jt = match join {
Join::Miter => cl::JoinType::Miter,
Join::Round => cl::JoinType::Round,
Join::Square => cl::JoinType::Square,
Join::Bevel => cl::JoinType::Bevel,
};
frame.decode(cl::inflate_paths_64(
&normalized,
distance * SCALE as f64,
jt,
cl::EndType::Polygon,
miter_limit,
tolerance.min(distance.abs()) * SCALE as f64,
))
}
pub fn slice(polygons: &[Ring], positions: &[i64], axis: Axis) -> Result<Vec<Region>> {
if !positions.is_sorted() {
return Err(Error::invalid("slice positions must be sorted"));
}
let frame = Frame::new(polygons.iter().flatten())?;
let subject = frame.paths(polygons)?;
let (min, max) = match axis {
Axis::X => (frame.min.x, frame.max.x),
Axis::Y => (frame.min.y, frame.max.y),
};
let mut low = min;
let mut bins = Vec::with_capacity(positions.len() + 1);
for high in positions
.iter()
.copied()
.chain(std::iter::once(max))
.map(|v| v.clamp(min, max))
{
if low == high || frame.min.x == frame.max.x || frame.min.y == frame.max.y {
bins.push(Vec::new());
} else {
let (a, b) = match axis {
Axis::X => (
Point {
x: low,
y: frame.min.y,
},
Point {
x: high,
y: frame.max.y,
},
),
Axis::Y => (
Point {
x: frame.min.x,
y: low,
},
Point {
x: frame.max.x,
y: high,
},
),
};
let clip = frame.paths(&[rectangle(a, b)?])?;
bins.push(frame.decode(clip_paths(&subject, &clip, BooleanOp::Intersection)?)?);
}
low = high;
}
Ok(bins)
}
pub fn inside(points: &[Point], polygons: &[Ring], include_boundary: bool) -> Result<Vec<bool>> {
let frame = Frame::new(polygons.iter().flatten())?;
let paths = clip_paths(&frame.paths(polygons)?, &Vec::new(), BooleanOp::Union)?;
Ok(points
.iter()
.map(|p| {
if p.x < frame.min.x || p.x > frame.max.x || p.y < frame.min.y || p.y > frame.max.y {
return false;
}
let q = frame.local(*p);
let mut filled = false;
for path in &paths {
match cl::point_in_polygon(q, path) {
cl::PointInPolygonResult::IsOn => return include_boundary,
cl::PointInPolygonResult::IsInside => filled = !filled,
cl::PointInPolygonResult::IsOutside => {}
}
}
filled
})
.collect())
}
pub fn fracture(polygons: &[Ring], max_points: usize) -> Result<Region> {
if max_points < 3 {
return Err(Error::invalid("max_points must be at least 3"));
}
let frame = Frame::new(polygons.iter().flatten())?;
let paths = frame.paths(polygons)?;
let mut tree = cl::PolyTree64::new();
if !engine(&paths, &Vec::new()).execute_tree(
cl::ClipType::Union,
cl::FillRule::NonZero,
&mut tree,
&mut Vec::new(),
) {
return Err(Error::invalid(
"could not identify polygon faces for fracture",
));
}
let mut pieces = Vec::new();
for face in cl::poly_tree_to_faces64(&tree) {
if face.outer.len() <= max_points && face.holes.is_empty() {
pieces.push(face.outer);
} else {
let mut paths = face.holes;
paths.insert(0, face.outer);
let mut triangles = Vec::new();
let status = cl::triangulate_64(&paths, &mut triangles, false);
if status != cl::TriangulateResult::Success {
return Err(Error::invalid(format!(
"polygon triangulation failed ({status:?})"
)));
}
pieces.extend(triangles);
}
}
frame.decode(pieces)
}