Skip to main content
← Back to kicad-monkey Rust Docs kicad-monkey Rust Crate API Reference

kicad_monkey_fab/view/
profile.rs

1//! Board profile (`Edge.Cuts`) loop chaining with a 200 um spatial grid index.
2
3use crate::geom::{
4    CoordNm, FabProfile, Ring2D, RingSeg, circle_from_3pts, fp_local_to_board_mm, pt_up,
5};
6use geo::{Contains, Coord, Intersects, LineString, Polygon as GeoPolygon};
7use kicad_monkey_core::pcb::{PcbFootprint, PcbFootprintGraphic, PcbGraphic, PcbGraphicKind};
8use std::collections::HashMap;
9
10const TOL_NM: i64 = 100_000;
11const CELL_NM: i64 = 200_000;
12
13#[derive(Clone, Copy)]
14struct OpenSeg {
15    p0: CoordNm,
16    p1: CoordNm,
17    center: Option<CoordNm>,
18    ccw: bool,
19}
20
21/// Build the board's closed outer boundary (CCW) and interior cutouts (CW) from `Edge.Cuts`.
22#[must_use]
23pub fn build_profile(
24    board_graphics: &[PcbGraphic],
25    fp_graphics: &[PcbFootprintGraphic],
26    footprints: &[PcbFootprint],
27) -> Option<FabProfile> {
28    let mut rings: Vec<Ring2D> = Vec::new();
29    let mut open_segs: Vec<OpenSeg> = Vec::new();
30
31    for g in board_graphics {
32        if is_edge_cuts(g) {
33            collect_edge_graphic(g, None, &mut rings, &mut open_segs);
34        }
35    }
36    for fpg in fp_graphics {
37        if is_edge_cuts(&fpg.graphic) {
38            let fp = footprints.get(fpg.footprint_index);
39            collect_edge_graphic(&fpg.graphic, fp, &mut rings, &mut open_segs);
40        }
41    }
42
43    chain_open_segments(&open_segs, &mut rings);
44    if rings.is_empty() {
45        return None;
46    }
47
48    let mut scored: Vec<(f64, GeoPolygon<f64>, Ring2D)> = Vec::new();
49    for ring in rings {
50        let area = ring.signed_area().abs();
51        if area <= 1.0 {
52            continue;
53        }
54        let poly = ring_to_geo_polygon(&ring);
55        scored.push((area, poly, ring));
56    }
57    if scored.is_empty() {
58        return None;
59    }
60    scored.sort_by(|a, b| b.0.total_cmp(&a.0));
61
62    let mut iter = scored.into_iter();
63    let (_, outer_poly, outer_ring) = iter.next()?;
64    let outer = outer_ring.ensure_orientation(true);
65    let mut cutouts = Vec::new();
66    for (_, poly, ring) in iter {
67        if outer_poly.contains(&poly) || outer_poly.intersects(&poly) {
68            cutouts.push(ring.ensure_orientation(false));
69        }
70    }
71    Some(FabProfile { outer, cutouts })
72}
73
74fn is_edge_cuts(g: &PcbGraphic) -> bool {
75    if g.layer.as_deref() == Some("Edge.Cuts") {
76        return true;
77    }
78    g.layers
79        .as_ref()
80        .is_some_and(|ls| ls.iter().any(|l| l == "Edge.Cuts"))
81}
82
83fn collect_edge_graphic(
84    g: &PcbGraphic,
85    fp: Option<&PcbFootprint>,
86    rings: &mut Vec<Ring2D>,
87    open_segs: &mut Vec<OpenSeg>,
88) {
89    let xf = |x: f64, y: f64| -> CoordNm {
90        match fp {
91            Some(owner) => {
92                let (bx, by) = fp_local_to_board_mm(
93                    owner.at_x.unwrap_or(0.0),
94                    owner.at_y.unwrap_or(0.0),
95                    owner.angle.unwrap_or(0.0),
96                    x,
97                    y,
98                );
99                pt_up(bx, by)
100            }
101            None => pt_up(x, y),
102        }
103    };
104    match g.kind {
105        PcbGraphicKind::Line => {
106            if let (Some(s), Some(e)) = (g.start, g.end) {
107                let p0 = xf(s.x, s.y);
108                let p1 = xf(e.x, e.y);
109                if p0 != p1 {
110                    open_segs.push(OpenSeg {
111                        p0,
112                        p1,
113                        center: None,
114                        ccw: false,
115                    });
116                }
117            }
118        }
119        PcbGraphicKind::Arc => {
120            if let (Some(s), Some(m), Some(e)) = (g.start, g.mid, g.end) {
121                let p0 = xf(s.x, s.y);
122                let pm = xf(m.x, m.y);
123                let p1 = xf(e.x, e.y);
124                if p0 != p1 {
125                    let circ = circle_from_3pts(
126                        (p0.x as f64, p0.y as f64),
127                        (pm.x as f64, pm.y as f64),
128                        (p1.x as f64, p1.y as f64),
129                    );
130                    let (center, ccw) = match circ {
131                        Some(((cx, cy), _, ccw)) => (
132                            Some(CoordNm::new(cx.round() as i64, cy.round() as i64)),
133                            ccw,
134                        ),
135                        None => (None, false),
136                    };
137                    open_segs.push(OpenSeg {
138                        p0,
139                        p1,
140                        center,
141                        ccw,
142                    });
143                }
144            }
145        }
146        PcbGraphicKind::Circle => {
147            if let (Some(c_mm), Some(e_mm)) = (g.center, g.end) {
148                let c = xf(c_mm.x, c_mm.y);
149                let e = xf(e_mm.x, e_mm.y);
150                let r = ((e.x - c.x) as f64).hypot((e.y - c.y) as f64).round() as i64;
151                if r > 0 {
152                    rings.push(Ring2D {
153                        points: vec![CoordNm::new(c.x + r, c.y), CoordNm::new(c.x - r, c.y)],
154                        segs: vec![
155                            RingSeg::Arc {
156                                center: c,
157                                ccw: true,
158                                major: false,
159                            },
160                            RingSeg::Arc {
161                                center: c,
162                                ccw: true,
163                                major: false,
164                            },
165                        ],
166                    });
167                }
168            }
169        }
170        PcbGraphicKind::Rect => {
171            if let (Some(s), Some(e)) = (g.start, g.end) {
172                let corners = [xf(s.x, s.y), xf(e.x, s.y), xf(e.x, e.y), xf(s.x, e.y)];
173                if let Some(ring) = Ring2D::from_points_oriented(&corners, true) {
174                    rings.push(ring);
175                }
176            }
177        }
178        PcbGraphicKind::Poly => {
179            let pts: Vec<CoordNm> = g.points.iter().map(|p| xf(p.x, p.y)).collect();
180            if let Some(ring) = Ring2D::from_points_oriented(&pts, true) {
181                rings.push(ring);
182            }
183        }
184        _ => {}
185    }
186}
187
188fn chain_open_segments(open_segs: &[OpenSeg], rings: &mut Vec<Ring2D>) {
189    if open_segs.len() < 2 {
190        return;
191    }
192    let mut grid: HashMap<(i64, i64), Vec<(usize, bool)>> = HashMap::new();
193    for (j, seg) in open_segs.iter().enumerate() {
194        grid.entry((seg.p0.x.div_euclid(CELL_NM), seg.p0.y.div_euclid(CELL_NM)))
195            .or_default()
196            .push((j, false));
197        grid.entry((seg.p1.x.div_euclid(CELL_NM), seg.p1.y.div_euclid(CELL_NM)))
198            .or_default()
199            .push((j, true));
200    }
201
202    let mut used = vec![false; open_segs.len()];
203    for start_idx in 0..open_segs.len() {
204        if used[start_idx] {
205            continue;
206        }
207        used[start_idx] = true;
208        let first = open_segs[start_idx];
209        let mut chain = vec![first];
210        let loop_start = first.p0;
211        let mut cur_end = first.p1;
212        let mut closed = false;
213
214        loop {
215            if chain.len() >= 2 && close_enough(cur_end, loop_start) {
216                closed = true;
217                break;
218            }
219            let Some((best_idx, best_rev)) = find_next_seg(cur_end, open_segs, &used, &grid) else {
220                break;
221            };
222            used[best_idx] = true;
223            let seg = open_segs[best_idx];
224            if best_rev {
225                chain.push(OpenSeg {
226                    p0: seg.p1,
227                    p1: seg.p0,
228                    center: seg.center,
229                    ccw: !seg.ccw,
230                });
231                cur_end = seg.p0;
232            } else {
233                chain.push(seg);
234                cur_end = seg.p1;
235            }
236        }
237
238        if closed && chain.len() >= 2 {
239            let points = chain.iter().map(|s| s.p0).collect();
240            let segs = chain
241                .iter()
242                .map(|s| match s.center {
243                    Some(center) => RingSeg::Arc {
244                        center,
245                        ccw: s.ccw,
246                        major: false,
247                    },
248                    None => RingSeg::Line,
249                })
250                .collect();
251            rings.push(Ring2D { points, segs });
252        }
253    }
254}
255
256fn find_next_seg(
257    cur_end: CoordNm,
258    open_segs: &[OpenSeg],
259    used: &[bool],
260    grid: &HashMap<(i64, i64), Vec<(usize, bool)>>,
261) -> Option<(usize, bool)> {
262    let gx = cur_end.x.div_euclid(CELL_NM);
263    let gy = cur_end.y.div_euclid(CELL_NM);
264    let mut best: Option<(usize, bool, i64)> = None;
265    for dx in -1..=1 {
266        for dy in -1..=1 {
267            let Some(bucket) = grid.get(&(gx + dx, gy + dy)) else {
268                continue;
269            };
270            for &(j, is_end) in bucket {
271                if used[j] {
272                    continue;
273                }
274                let pt = if is_end {
275                    open_segs[j].p1
276                } else {
277                    open_segs[j].p0
278                };
279                let dist = (cur_end.x - pt.x).abs().max((cur_end.y - pt.y).abs());
280                if dist <= TOL_NM && best.is_none_or(|(_, _, bd)| dist < bd) {
281                    best = Some((j, is_end, dist));
282                }
283            }
284        }
285    }
286    best.map(|(j, rev, _)| (j, rev))
287}
288
289fn close_enough(a: CoordNm, b: CoordNm) -> bool {
290    (a.x - b.x).abs() <= TOL_NM && (a.y - b.y).abs() <= TOL_NM
291}
292
293fn ring_to_geo_polygon(ring: &Ring2D) -> GeoPolygon<f64> {
294    let coords: Vec<Coord<f64>> = ring
295        .flatten_polygon(24)
296        .into_iter()
297        .map(|p| Coord {
298            x: p.x as f64,
299            y: p.y as f64,
300        })
301        .collect();
302    GeoPolygon::new(LineString::from(coords), Vec::new())
303}