aboutsummaryrefslogtreecommitdiff
path: root/tools/placer/src/geom.rs
blob: 3514340adf9db37e887c05eb3c0aa6d5696bd692 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
//! Axis-aligned rectangles, 90 degree turns, segment crossings and the MST.

pub type Pt = (f64, f64);

#[derive(Clone, Copy, Debug, Default)]
pub struct Rect {
    pub x0: f64,
    pub y0: f64,
    pub x1: f64,
    pub y1: f64,
}

impl Rect {
    pub fn new(x0: f64, y0: f64, x1: f64, y1: f64) -> Rect {
        Rect { x0: x0.min(x1), y0: y0.min(y1), x1: x0.max(x1), y1: y0.max(y1) }
    }
    pub fn around(c: Pt, hw: f64, hh: f64) -> Rect {
        Rect::new(c.0 - hw, c.1 - hh, c.0 + hw, c.1 + hh)
    }
    pub fn area(&self) -> f64 {
        (self.x1 - self.x0) * (self.y1 - self.y0)
    }
    /// Overlap area with `o`.
    pub fn inter(&self, o: &Rect) -> f64 {
        let w = self.x1.min(o.x1) - self.x0.max(o.x0);
        let h = self.y1.min(o.y1) - self.y0.max(o.y0);
        if w > 0.0 && h > 0.0 {
            w * h
        } else {
            0.0
        }
    }
    pub fn hits(&self, o: &Rect) -> bool {
        self.x0 < o.x1 && o.x0 < self.x1 && self.y0 < o.y1 && o.y0 < self.y1
    }
    /// Area of `self` that lies outside `b`.
    pub fn outside(&self, b: &Rect) -> f64 {
        self.area() - self.inter(b)
    }
    pub fn grow(&self, d: f64) -> Rect {
        Rect { x0: self.x0 - d, y0: self.y0 - d, x1: self.x1 + d, y1: self.y1 + d }
    }
    pub fn union(&self, o: &Rect) -> Rect {
        Rect { x0: self.x0.min(o.x0), y0: self.y0.min(o.y0), x1: self.x1.max(o.x1), y1: self.y1.max(o.y1) }
    }
    /// The rectangle of a footprint-local rectangle on a part at `at`, turned by `k` x 90 degrees.
    pub fn place(&self, at: Pt, k: u8) -> Rect {
        let a = turn((self.x0, self.y0), k);
        let b = turn((self.x1, self.y1), k);
        Rect::new(a.0 + at.0, a.1 + at.1, b.0 + at.0, b.1 + at.1)
    }
}

/// Turn a footprint-local vector by k x 90 degrees as KiCad does: positive angles turn
/// counter-clockwise on screen, where y points down.
pub fn turn(p: Pt, k: u8) -> Pt {
    match k & 3 {
        0 => p,
        1 => (p.1, -p.0),
        2 => (-p.0, -p.1),
        _ => (-p.1, p.0),
    }
}

pub fn dist(a: Pt, b: Pt) -> f64 {
    ((a.0 - b.0).powi(2) + (a.1 - b.1).powi(2)).sqrt()
}

/// Proper crossing of segments ab and cd; touching or shared ends do not count.
pub fn crosses(a: Pt, b: Pt, c: Pt, d: Pt) -> bool {
    fn orient(p: Pt, q: Pt, r: Pt) -> f64 {
        (q.0 - p.0) * (r.1 - p.1) - (q.1 - p.1) * (r.0 - p.0)
    }
    let (o1, o2) = (orient(a, b, c), orient(a, b, d));
    if o1 * o2 >= 0.0 {
        return false;
    }
    let (o3, o4) = (orient(c, d, a), orient(c, d, b));
    o3 * o4 < 0.0
}

/// Segment ab passes through rectangle r (Liang-Barsky clipping).
pub fn seg_hits(a: Pt, b: Pt, r: &Rect) -> bool {
    let (dx, dy) = (b.0 - a.0, b.1 - a.1);
    let (mut t0, mut t1) = (0.0f64, 1.0f64);
    for (p, q) in [(-dx, a.0 - r.x0), (dx, r.x1 - a.0), (-dy, a.1 - r.y0), (dy, r.y1 - a.1)] {
        if p.abs() < 1e-12 {
            if q < 0.0 {
                return false;
            }
        } else {
            let t = q / p;
            if p < 0.0 {
                t0 = t0.max(t);
            } else {
                t1 = t1.min(t);
            }
            if t0 > t1 {
                return false;
            }
        }
    }
    true
}

/// Prim's MST over the points: (i, j) pairs.
pub fn mst(pts: &[Pt]) -> Vec<(usize, usize)> {
    let n = pts.len();
    let mut out = Vec::with_capacity(n.saturating_sub(1));
    if n < 2 {
        return out;
    }
    let mut inside = vec![false; n];
    let mut best = vec![f64::INFINITY; n];
    let mut link = vec![usize::MAX; n];
    best[0] = 0.0;
    for _ in 0..n {
        let mut i = usize::MAX;
        for k in 0..n {
            if !inside[k] && (i == usize::MAX || best[k] < best[i]) {
                i = k;
            }
        }
        inside[i] = true;
        if link[i] != usize::MAX {
            out.push((link[i], i));
        }
        for k in 0..n {
            if !inside[k] {
                let d = dist(pts[i], pts[k]);
                if d < best[k] {
                    best[k] = d;
                    link[k] = i;
                }
            }
        }
    }
    out
}

/// Cover a polygon with rectangles: one horizontal slab per pair of vertex heights, each
/// cut into the x intervals that lie inside. Exact for rectilinear outlines, a slight
/// overestimate for slanted edges and arcs (each slab takes the wider of its two ends).
pub fn poly_rects(poly: &[[f64; 2]]) -> Vec<Rect> {
    let mut ys: Vec<f64> = poly.iter().map(|p| p[1]).collect();
    ys.sort_by(|a, b| a.partial_cmp(b).unwrap());
    ys.dedup_by(|a, b| (*a - *b).abs() < 1e-4);
    let xs_at = |y: f64| {
        let mut xs = Vec::new();
        for i in 0..poly.len() {
            let (a, b) = (poly[i], poly[(i + 1) % poly.len()]);
            if (a[1] <= y && b[1] > y) || (b[1] <= y && a[1] > y) {
                xs.push(a[0] + (y - a[1]) / (b[1] - a[1]) * (b[0] - a[0]));
            }
        }
        xs.sort_by(|a, b| a.partial_cmp(b).unwrap());
        xs
    };
    let mut out = Vec::new();
    for w in ys.windows(2) {
        let (y0, y1) = (w[0], w[1]);
        let eps = (y1 - y0) * 1e-3;
        let (lo, hi) = (xs_at(y0 + eps), xs_at(y1 - eps));
        if lo.len() != hi.len() {
            continue;
        }
        for k in (0..lo.len()).step_by(2) {
            if k + 1 < lo.len() {
                out.push(Rect::new(lo[k].min(hi[k]), y0, lo[k + 1].max(hi[k + 1]), y1));
            }
        }
    }
    out
}