layouttk 0.4.1

GDSII and OASIS layout toolkit for layer extraction, verification, and window clipping
Documentation
//! Polygon operations on integer database coordinates. A region is a list of
//! implicitly closed contours, filled by the nonzero winding rule. Results have
//! counterclockwise outer boundaries and clockwise holes. Use [`fracture`] to
//! obtain independent filled polygons suitable for [`crate::Layout::add_element`].
//!
//! Clipping and sizing translate coordinates to a local frame with 256 working
//! units per DBU. The combined input extent may span up to 2^41 DBU along each
//! axis anywhere within the i64 domain. Intersections are snapped to integer
//! DBU, with exact half-grid ties going toward positive infinity. Sub-grid
//! slivers may collapse. Curve construction tolerances apply to chord error
//! before rounding vertices to the grid.
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,
};

pub type Ring = Vec<Point>;
pub type Region = Vec<Ring>;

/// A finer working grid protects one-DBU features from Clipper's tiny triangle
/// removal and improves rounding of intersections. Final points remain in DBU.
const SCALE: i64 = 256;
// Clipper documents decreasing intersection accuracy beyond 10^15. Recenter
// each operation so a tiny shape can still live at any signed 64-bit origin.
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)
    }
}

// Subtract an origin before multiplying, so large absolute positions do not
// cause loss of precision. Callers use a frame-bounded ring.
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)
}

/// Apply a nonzero-winding set operation and snap intersections to the DBU grid.
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)?)
}

/// Grow (positive) or shrink (negative) a filled region. Distance and circular
/// join chord tolerance are in DBU. The miter limit is a ratio to the distance.
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,
    ))
}

/// Split a region into strips along X or Y. Sorted cut positions may repeat.
/// The result has exactly one more entry than the number of cuts.
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)
}

/// Query a batch of points against the union. Boundary policy applies to both
/// exterior boundaries and hole boundaries.
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())
}

/// Preserve small simple boundaries and triangulate faces with holes or too
/// many vertices. The result consists of independent hole-free filled polygons.
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)
}