layouttk 0.5.0

GDSII and OASIS layout toolkit for layer extraction, verification, and window clipping
Documentation
//! Curves are constructed in continuous database units. Polygon vertices are
//! rounded once, to the nearest DBU (halfway values away from zero).
mod builder;
mod hobby;
mod stroke;

pub use builder::{Curve, PathBuilder, Track, parametric};
pub use hobby::{HobbyOptions, hobby_controls};
pub use stroke::{
    Cap, Join, Junction, StrokeSection, StrokeStyle, fillet, grid_outline, offset_spine,
    robust_outline, robust_stroke, robust_stroke_bounded, stroke, stroke_outline, stroke_with,
};

use crate::{Error, Point, Result};
use std::ops::{Add, Div, Mul, Sub};

#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Vec2 {
    pub x: f64,
    pub y: f64,
}

impl Vec2 {
    pub const fn new(x: f64, y: f64) -> Self {
        Self { x, y }
    }
    pub fn norm(self) -> f64 {
        self.x.hypot(self.y)
    }
    pub fn angle(self) -> f64 {
        self.y.atan2(self.x)
    }
    pub fn dot(self, other: Self) -> f64 {
        self.x * other.x + self.y * other.y
    }
    pub fn cross(self, other: Self) -> f64 {
        self.x * other.y - self.y * other.x
    }
    pub fn normal(self) -> Self {
        Self::new(-self.y, self.x)
    }
    pub fn polar(angle: f64) -> Self {
        Self::new(angle.cos(), angle.sin())
    }
    pub fn finite(self) -> bool {
        self.x.is_finite() && self.y.is_finite()
    }
    pub fn grid(self) -> Result<Point> {
        // Reject values beyond the integral precision of construction coordinates.
        const MAX: f64 = (1_u64 << 53) as f64 - 1.;
        if !self.finite() || self.x.abs() > MAX || self.y.abs() > MAX {
            return Err(Error::invalid(
                "path coordinate exceeds the exact f64 integer range",
            ));
        }
        Ok(Point {
            x: self.x.round() as i64,
            y: self.y.round() as i64,
        })
    }
}

impl Add for Vec2 {
    type Output = Self;
    fn add(self, r: Self) -> Self {
        Self::new(self.x + r.x, self.y + r.y)
    }
}
impl Sub for Vec2 {
    type Output = Self;
    fn sub(self, r: Self) -> Self {
        Self::new(self.x - r.x, self.y - r.y)
    }
}
impl Mul<f64> for Vec2 {
    type Output = Self;
    fn mul(self, r: f64) -> Self {
        Self::new(self.x * r, self.y * r)
    }
}
impl Div<f64> for Vec2 {
    type Output = Self;
    fn div(self, r: f64) -> Self {
        Self::new(self.x / r, self.y / r)
    }
}

pub const MAX_SAMPLES: usize = 1_000_000;
pub type Sample = (f64, Vec2);

fn tolerance_ok(tolerance: f64) -> Result<()> {
    if tolerance.is_finite() && tolerance > 0. {
        Ok(())
    } else {
        Err(Error::invalid("path tolerance must be positive and finite"))
    }
}

/// Subdivide a Bézier until its control hull lies within tolerance of the chord.
pub fn bezier(controls: &[Vec2], tolerance: f64) -> Result<Vec<Sample>> {
    tolerance_ok(tolerance)?;
    if controls.len() < 2 || controls.len() > 256 || !controls.iter().all(|p| p.finite()) {
        return Err(Error::invalid(
            "a Bezier needs 2 to 256 finite control points",
        ));
    }
    let mut result = vec![(0., controls[0])];
    let mut stack = vec![(0., 1., controls.to_vec(), 0)];
    while let Some((start, end, mut hull, depth)) = stack.pop() {
        let a = hull[0];
        let b = hull[hull.len() - 1];
        let chord = b - a;
        let norm = chord.norm();
        let unit = if norm > 0. {
            chord / norm
        } else {
            Vec2::default()
        };
        // Match the parameterization as well as the geometric locus. This
        // preserves width profiles on otherwise collinear non-uniform curves.
        let flat = hull.iter().enumerate().all(|(i, p)| {
            let linear = a + chord * (i as f64 / (hull.len() - 1) as f64);
            let projection = a + unit * (((*p - a).dot(unit)).clamp(0., norm));
            (*p - linear).norm() <= tolerance && (*p - projection).norm() <= tolerance
        });
        if flat {
            if result.len() >= MAX_SAMPLES {
                return Err(Error::invalid("Bezier sample budget exceeded"));
            }
            result.push((end, b));
            continue;
        }
        if depth >= 40 {
            return Err(Error::invalid(
                "Bezier tolerance exceeds numerical resolution",
            ));
        }
        let mut left = vec![a];
        let mut right = vec![b];
        while hull.len() > 1 {
            for i in 0..hull.len() - 1 {
                hull[i] = hull[i] * 0.5 + hull[i + 1] * 0.5;
            }
            hull.pop();
            left.push(hull[0]);
            right.push(hull[hull.len() - 1]);
        }
        right.reverse();
        let mid = (start + end) * 0.5;
        stack.push((mid, end, right, depth + 1));
        stack.push((start, mid, left, depth + 1));
    }
    Ok(result)
}

/// Sample an ellipse from its starting point. The two angles are polar
/// directions in the global frame, measured in radians.
pub fn arc(
    start: Vec2,
    radii: Vec2,
    initial: f64,
    final_angle: f64,
    rotation: f64,
    tolerance: f64,
) -> Result<Vec<Sample>> {
    tolerance_ok(tolerance)?;
    if !start.finite()
        || !radii.finite()
        || radii.x <= 0.
        || radii.y <= 0.
        || ![initial, final_angle, rotation]
            .iter()
            .all(|a| a.is_finite())
    {
        return Err(Error::invalid(
            "arc requires positive radii and finite angles and coordinates",
        ));
    }
    let parameter = |angle: f64| {
        let principal = angle.sin().atan2(angle.cos());
        let t = (radii.x * principal.sin()).atan2(radii.y * principal.cos());
        angle + (t - principal)
    };
    let a = parameter(initial - rotation);
    let b = parameter(final_angle - rotation);
    let span = b - a;
    let step = (4.
        * (0.5 * (tolerance / radii.x.max(radii.y)).min(1.))
            .sqrt()
            .asin())
    .min(std::f64::consts::FRAC_PI_2);
    let count = (span.abs() / step).ceil().max(1.);
    if !count.is_finite() || count >= MAX_SAMPLES as f64 {
        return Err(Error::invalid("arc sample budget exceeded"));
    }
    let ex = Vec2::polar(rotation);
    let point = |t: f64| ex * (radii.x * t.cos()) + ex.normal() * (radii.y * t.sin());
    let origin = point(a);
    Ok((0..=count as usize)
        .map(|i| {
            let t = i as f64 / count;
            (t, start + (point(a + t * span) - origin))
        })
        .collect())
}

/// Round an open vertex sequence to DBU, removing adjacent grid duplicates.
pub fn on_grid(points: &[Vec2]) -> Result<Vec<Point>> {
    let mut result = Vec::with_capacity(points.len());
    for p in points {
        let p = p.grid()?;
        if result.last() != Some(&p) {
            result.push(p);
        }
    }
    Ok(result)
}