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

kicad_monkey_fab/
drill.rs

1//! Excellon NC Drill writer supporting multi-span PTH, NPTH, and `G85` routed oval slots.
2
3use crate::geom::{CoordNm, FabHole};
4use crate::{FabFile, FabViewData};
5use std::collections::BTreeMap;
6use std::fmt::Write as _;
7
8/// NC drill writer options.
9#[derive(Clone, Debug)]
10pub struct DrillOptions {
11    pub stem: String,
12    pub use_aux_origin: bool,
13}
14
15impl Default for DrillOptions {
16    fn default() -> Self {
17        Self {
18            stem: "board".to_owned(),
19            use_aux_origin: false,
20        }
21    }
22}
23
24/// Emit Excellon `.DRL` files grouped by `(plated, drill_pair)`.
25#[must_use]
26pub fn write_nc_drill(view: &FabViewData, opts: &DrillOptions) -> Vec<FabFile> {
27    let shift = if opts.use_aux_origin {
28        CoordNm::new(-view.aux_origin.x, -view.aux_origin.y)
29    } else {
30        CoordNm::new(0, 0)
31    };
32
33    let mut groups: BTreeMap<(bool, String, String), Vec<&FabHole>> = BTreeMap::new();
34    for hole in &view.holes {
35        let pair = view.drill_pairs.iter().find(|p| p.id == hole.drill_pair);
36        let (start_k, end_k) = pair.map_or(("TOP", "BOTTOM"), |p| {
37            (p.start_key.as_str(), p.end_key.as_str())
38        });
39        groups
40            .entry((hole.plated, start_k.to_owned(), end_k.to_owned()))
41            .or_default()
42            .push(hole);
43    }
44
45    let mut files = Vec::new();
46    for ((plated, start_k, end_k), holes) in groups {
47        if holes.is_empty() {
48            continue;
49        }
50        let is_through = start_k == "TOP" && end_k == "BOTTOM";
51        let suffix = if !plated {
52            "-NPTH.drl".to_owned()
53        } else if is_through {
54            "-PTH.drl".to_owned()
55        } else {
56            format!("-{start_k}-{end_k}.drl")
57        };
58        let text = render_excellon_file(&holes, plated, shift);
59        files.push(FabFile {
60            name: format!("{}{suffix}", opts.stem),
61            data: text.into_bytes(),
62            key: None,
63            role: if plated { "drill_pth" } else { "drill_npth" }.to_owned(),
64            plated: Some(plated),
65            span: Some((start_k, end_k)),
66        });
67    }
68    files
69}
70
71fn render_excellon_file(holes: &[&FabHole], plated: bool, shift: CoordNm) -> String {
72    let mut by_tool: BTreeMap<i64, Vec<&FabHole>> = BTreeMap::new();
73    for &hole in holes {
74        by_tool.entry(hole.diameter.max(1)).or_default().push(hole);
75    }
76
77    let mut out = String::with_capacity(holes.len() * 28 + 256);
78    out.push_str("M48\n");
79    let _ = writeln!(
80        out,
81        "; DRILL file kicad-monkey-fab ({})",
82        if plated { "Plated" } else { "NonPlated" }
83    );
84    out.push_str("FMAT,2\nMETRIC,TZ\n");
85
86    let mut tool_ids: Vec<(usize, i64)> = Vec::with_capacity(by_tool.len());
87    for (idx, &diam) in by_tool.keys().enumerate() {
88        let tid = idx + 1;
89        let _ = writeln!(out, "T{tid}C{:.4}", diam as f64 / 1_000_000.0);
90        tool_ids.push((tid, diam));
91    }
92    out.push_str("%\nG90\nG05\n");
93
94    for (tid, diam) in tool_ids {
95        let _ = writeln!(out, "T{tid}");
96        if let Some(group) = by_tool.get(&diam) {
97            for hole in group {
98                if let Some((p0, p1)) = hole.slot_rout {
99                    let _ = writeln!(
100                        out,
101                        "X{:.4}Y{:.4}G85X{:.4}Y{:.4}",
102                        (p0.x + shift.x) as f64 / 1_000_000.0,
103                        (p0.y + shift.y) as f64 / 1_000_000.0,
104                        (p1.x + shift.x) as f64 / 1_000_000.0,
105                        (p1.y + shift.y) as f64 / 1_000_000.0,
106                    );
107                } else {
108                    let _ = writeln!(
109                        out,
110                        "X{:.4}Y{:.4}",
111                        (hole.center.x + shift.x) as f64 / 1_000_000.0,
112                        (hole.center.y + shift.y) as f64 / 1_000_000.0,
113                    );
114                }
115            }
116        }
117    }
118    out.push_str("M30\n");
119    out
120}