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

kicad_monkey_fab/
gerber.rs

1//! High-speed Gerber X2/X1 writer over canonical whole-nm `+Y`-up `FabViewData`.
2
3use crate::geom::{
4    AreaShape, ChamferCorners, CoordNm, FabArea, FabLand, FabLayer, FabLayerItems, FabProfile,
5    FabStroke, LayerRole, LayerSide, Placement2D, Ring2D, RingSeg, StrokePath,
6};
7use crate::layer_map::PROFILE_KEY;
8use crate::{FabFile, FabViewData};
9use std::collections::HashMap;
10use std::fmt::Write as _;
11
12/// Gerber generation options.
13#[derive(Clone, Debug)]
14pub struct GerberOptions {
15    pub stem: String,
16    pub x2: bool,
17    pub use_aux_origin: bool,
18    pub include_profile: bool,
19    pub include_silk: bool,
20}
21
22impl Default for GerberOptions {
23    fn default() -> Self {
24        Self {
25            stem: "board".to_owned(),
26            x2: true,
27            use_aux_origin: false,
28            include_profile: true,
29            include_silk: true,
30        }
31    }
32}
33
34/// Emit Gerber X2/X1 files for all standard manufacturing layers of `view`.
35#[must_use]
36pub fn write_gerbers(view: &FabViewData, opts: &GerberOptions) -> Vec<FabFile> {
37    let shift = if opts.use_aux_origin {
38        CoordNm::new(-view.aux_origin.x, -view.aux_origin.y)
39    } else {
40        CoordNm::new(0, 0)
41    };
42    let mut files = Vec::new();
43    for layer in &view.layers {
44        if layer.role == LayerRole::Profile {
45            if opts.include_profile
46                && let Some(profile) = view.profile.as_ref()
47            {
48                let text = render_profile_gerber(profile, shift, opts.x2);
49                files.push(FabFile {
50                    name: format!("{}.GM1", opts.stem),
51                    data: text.into_bytes(),
52                    key: Some(PROFILE_KEY.to_owned()),
53                    role: "profile".to_owned(),
54                    plated: None,
55                    span: None,
56                });
57            }
58            continue;
59        }
60        if layer.role == LayerRole::Silkscreen && !opts.include_silk {
61            continue;
62        }
63        if !matches!(
64            layer.role,
65            LayerRole::Conductor | LayerRole::SolderMask | LayerRole::Paste | LayerRole::Silkscreen
66        ) {
67            continue;
68        }
69        let items = view.layers_items.get(&layer.key);
70        let empty = FabLayerItems::default();
71        let items = items.unwrap_or(&empty);
72        if items.is_empty() {
73            continue;
74        }
75        let text = render_layer_gerber(layer, view.copper_count, items, shift, opts.x2);
76        let ext = protel_extension(layer);
77        files.push(FabFile {
78            name: format!("{}.{ext}", opts.stem),
79            data: text.into_bytes(),
80            key: Some(layer.key.clone()),
81            role: role_name(layer.role).to_owned(),
82            plated: None,
83            span: None,
84        });
85    }
86    files
87}
88
89/// Render a single virtual layer's items as a Gerber X2/X1 file.
90#[must_use]
91pub fn render_virtual_gerber(key: &str, items: &FabLayerItems, shift: CoordNm, x2: bool) -> String {
92    let layer = FabLayer {
93        key: key.to_owned(),
94        kicad_name: key.to_owned(),
95        role: LayerRole::Virtual,
96        side: LayerSide::None,
97        positive: true,
98        copper_index: None,
99    };
100    render_layer_gerber(&layer, 2, items, shift, x2)
101}
102
103#[derive(Clone, Debug, Eq, Hash, PartialEq)]
104enum ApertureKey {
105    Circle(i64),
106    Rect(i64, i64),
107    Obround(i64, i64),
108}
109
110struct ApertureTable {
111    map: HashMap<ApertureKey, usize>,
112    ordered: Vec<(usize, ApertureKey)>,
113}
114
115impl ApertureTable {
116    fn new() -> Self {
117        Self {
118            map: HashMap::new(),
119            ordered: Vec::new(),
120        }
121    }
122
123    fn intern(&mut self, key: ApertureKey) -> usize {
124        if let Some(&code) = self.map.get(&key) {
125            return code;
126        }
127        let code = 10 + self.ordered.len();
128        self.map.insert(key.clone(), code);
129        self.ordered.push((code, key));
130        code
131    }
132
133    fn write_defs(&self, out: &mut String) {
134        for (code, key) in &self.ordered {
135            match *key {
136                ApertureKey::Circle(d) => {
137                    let _ = writeln!(out, "%ADD{code}C,{:.6}*%", nm_to_mm(d.max(1)));
138                }
139                ApertureKey::Rect(w, h) => {
140                    let _ = writeln!(
141                        out,
142                        "%ADD{code}R,{:.6}X{:.6}*%",
143                        nm_to_mm(w.max(1)),
144                        nm_to_mm(h.max(1))
145                    );
146                }
147                ApertureKey::Obround(w, h) => {
148                    let _ = writeln!(
149                        out,
150                        "%ADD{code}O,{:.6}X{:.6}*%",
151                        nm_to_mm(w.max(1)),
152                        nm_to_mm(h.max(1))
153                    );
154                }
155            }
156        }
157    }
158}
159
160fn render_layer_gerber(
161    layer: &FabLayer,
162    copper_count: usize,
163    items: &FabLayerItems,
164    shift: CoordNm,
165    x2: bool,
166) -> String {
167    let mut apertures = ApertureTable::new();
168    let mut body = String::with_capacity(4096);
169    let mut cur_d: Option<usize> = None;
170
171    // 1. Filled areas (zones, custom pad polygons, text outlines)
172    for area in &items.areas {
173        write_area(&mut body, area, shift, &mut apertures, &mut cur_d);
174    }
175
176    // 2. Flashed lands (pads and vias)
177    for land in &items.lands {
178        write_land(&mut body, land, shift, &mut apertures, &mut cur_d);
179    }
180
181    // 3. Swept strokes (tracks, graphics, text strokes)
182    for stroke in &items.strokes {
183        write_stroke(&mut body, stroke, shift, &mut apertures, &mut cur_d);
184    }
185
186    let mut out = String::with_capacity(body.len() + 512);
187    write_header(&mut out, layer, copper_count, x2);
188    apertures.write_defs(&mut out);
189    out.push_str(&body);
190    out.push_str("M02*\n");
191    out
192}
193
194fn render_profile_gerber(profile: &FabProfile, shift: CoordNm, x2: bool) -> String {
195    let mut out = String::with_capacity(1024);
196    if x2 {
197        out.push_str(concat!(
198            "%TF.GenerationSoftware,Wavenumber,kicad-monkey-fab,",
199            env!("CARGO_PKG_VERSION"),
200            "*%\n"
201        ));
202        out.push_str("%TF.FileFunction,Profile,NP*%\n");
203        out.push_str("%TF.FilePolarity,Positive*%\n");
204    }
205    out.push_str("%FSLAX46Y46*%\n%MOMM*%\n%LPD*%\n%ADD10C,0.100000*%\nD10*\nG75*\n");
206    write_ring_outline_stroke(&mut out, &profile.outer, shift);
207    for cutout in &profile.cutouts {
208        write_ring_outline_stroke(&mut out, cutout, shift);
209    }
210    out.push_str("M02*\n");
211    out
212}
213
214fn write_header(out: &mut String, layer: &FabLayer, copper_count: usize, x2: bool) {
215    if x2 {
216        out.push_str(concat!(
217            "%TF.GenerationSoftware,Wavenumber,kicad-monkey-fab,",
218            env!("CARGO_PKG_VERSION"),
219            "*%\n"
220        ));
221        let func = file_function(layer, copper_count);
222        let _ = writeln!(out, "%TF.FileFunction,{func}*%");
223        let pol = if layer.role == LayerRole::SolderMask || !layer.positive {
224            "Negative"
225        } else {
226            "Positive"
227        };
228        let _ = writeln!(out, "%TF.FilePolarity,{pol}*%");
229    }
230    out.push_str("%FSLAX46Y46*%\n%MOMM*%\n%LPD*%\nG75*\n");
231}
232
233fn file_function(layer: &FabLayer, copper_count: usize) -> String {
234    match layer.role {
235        LayerRole::Conductor => {
236            let idx = layer.copper_index.unwrap_or(1);
237            let side = match layer.side {
238                LayerSide::Top => "Top",
239                LayerSide::Bottom => "Bot",
240                LayerSide::Internal | LayerSide::None => "Inr",
241            };
242            format!("Copper,L{idx},{side}")
243        }
244        LayerRole::SolderMask => match layer.side {
245            LayerSide::Bottom => "Soldermask,Bot".to_owned(),
246            _ => "Soldermask,Top".to_owned(),
247        },
248        LayerRole::Paste => match layer.side {
249            LayerSide::Bottom => "Paste,Bot".to_owned(),
250            _ => "Paste,Top".to_owned(),
251        },
252        LayerRole::Silkscreen => match layer.side {
253            LayerSide::Bottom => "Legend,Bot".to_owned(),
254            _ => "Legend,Top".to_owned(),
255        },
256        LayerRole::Profile => format!("Profile,NP,L{copper_count}"),
257        LayerRole::Mechanical | LayerRole::Virtual => format!("Other,{}", layer.key),
258    }
259}
260
261fn select_aperture(body: &mut String, cur_d: &mut Option<usize>, d: usize) {
262    if *cur_d != Some(d) {
263        let _ = writeln!(body, "D{d}*");
264        *cur_d = Some(d);
265    }
266}
267
268fn write_land(
269    body: &mut String,
270    land: &FabLand,
271    shift: CoordNm,
272    apertures: &mut ApertureTable,
273    cur_d: &mut Option<usize>,
274) {
275    let p = land.placement;
276    let angle_norm = p.angle_deg.rem_euclid(360.0);
277    let is_0_180 = angle_norm.abs() < 1e-4
278        || (angle_norm - 180.0).abs() < 1e-4
279        || (angle_norm - 360.0).abs() < 1e-4;
280    let is_90_270 = (angle_norm - 90.0).abs() < 1e-4 || (angle_norm - 270.0).abs() < 1e-4;
281
282    match &land.shape {
283        AreaShape::Disk { radius } => {
284            let d = apertures.intern(ApertureKey::Circle((radius * 2).max(1)));
285            select_aperture(body, cur_d, d);
286            let _ = writeln!(body, "X{}Y{}D03*", p.tx + shift.x, p.ty + shift.y);
287        }
288        AreaShape::Rect { width, height } if is_0_180 || is_90_270 => {
289            let (w, h) = if is_90_270 {
290                (*height, *width)
291            } else {
292                (*width, *height)
293            };
294            let d = apertures.intern(ApertureKey::Rect(w, h));
295            select_aperture(body, cur_d, d);
296            let _ = writeln!(body, "X{}Y{}D03*", p.tx + shift.x, p.ty + shift.y);
297        }
298        AreaShape::Capsule { length, width } if is_0_180 || is_90_270 => {
299            let (w, h) = if is_90_270 {
300                (*width, *length)
301            } else {
302                (*length, *width)
303            };
304            let d = apertures.intern(ApertureKey::Obround(w, h));
305            select_aperture(body, cur_d, d);
306            let _ = writeln!(body, "X{}Y{}D03*", p.tx + shift.x, p.ty + shift.y);
307        }
308        other => {
309            let poly = shape_to_board_polygon(other, p);
310            if poly.len() >= 3 {
311                write_polygon_region(body, &poly, shift);
312            }
313        }
314    }
315}
316
317fn write_area(
318    body: &mut String,
319    area: &FabArea,
320    shift: CoordNm,
321    apertures: &mut ApertureTable,
322    cur_d: &mut Option<usize>,
323) {
324    match &area.shape {
325        AreaShape::Disk { radius } => {
326            let d = apertures.intern(ApertureKey::Circle((radius * 2).max(1)));
327            select_aperture(body, cur_d, d);
328            let _ = writeln!(
329                body,
330                "X{}Y{}D03*",
331                area.placement.tx + shift.x,
332                area.placement.ty + shift.y
333            );
334        }
335        AreaShape::Region { outer, .. } => {
336            let poly = outer.flatten_polygon(24);
337            if poly.len() >= 3 {
338                write_polygon_region(body, &poly, shift);
339            }
340        }
341        other => {
342            let poly = shape_to_board_polygon(other, area.placement);
343            if poly.len() >= 3 {
344                write_polygon_region(body, &poly, shift);
345            }
346        }
347    }
348}
349
350fn write_stroke(
351    body: &mut String,
352    stroke: &FabStroke,
353    shift: CoordNm,
354    apertures: &mut ApertureTable,
355    cur_d: &mut Option<usize>,
356) {
357    let d = apertures.intern(ApertureKey::Circle(stroke.width.max(1)));
358    select_aperture(body, cur_d, d);
359    match stroke.path {
360        StrokePath::Line { start, end } => {
361            let _ = writeln!(
362                body,
363                "G01*\nX{}Y{}D02*\nX{}Y{}D01*",
364                start.x + shift.x,
365                start.y + shift.y,
366                end.x + shift.x,
367                end.y + shift.y
368            );
369        }
370        StrokePath::Arc {
371            start,
372            end,
373            center,
374            ccw,
375            ..
376        } => {
377            let cmd = if ccw { "G03" } else { "G02" };
378            let i = center.x - start.x;
379            let j = center.y - start.y;
380            let _ = writeln!(
381                body,
382                "X{}Y{}D02*\n{cmd}*X{}Y{}I{i}J{j}D01*\nG01*",
383                start.x + shift.x,
384                start.y + shift.y,
385                end.x + shift.x,
386                end.y + shift.y
387            );
388        }
389        StrokePath::FullCircle { center, radius } => {
390            let sx = center.x + radius + shift.x;
391            let sy = center.y + shift.y;
392            let _ = writeln!(
393                body,
394                "X{sx}Y{sy}D02*\nG03*X{sx}Y{sy}I{}J0D01*\nG01*",
395                -radius
396            );
397        }
398    }
399}
400
401fn write_polygon_region(body: &mut String, pts: &[CoordNm], shift: CoordNm) {
402    if pts.len() < 3 {
403        return;
404    }
405    body.push_str("G36*\nG01*\n");
406    let first = pts[0];
407    let _ = writeln!(body, "X{}Y{}D02*", first.x + shift.x, first.y + shift.y);
408    for pt in pts.iter().skip(1) {
409        let _ = writeln!(body, "X{}Y{}D01*", pt.x + shift.x, pt.y + shift.y);
410    }
411    let _ = writeln!(
412        body,
413        "X{}Y{}D01*\nG37*",
414        first.x + shift.x,
415        first.y + shift.y
416    );
417}
418
419fn write_ring_outline_stroke(out: &mut String, ring: &Ring2D, shift: CoordNm) {
420    let n = ring.points.len();
421    if n < 2 {
422        return;
423    }
424    let first = ring.points[0];
425    let _ = writeln!(
426        out,
427        "G01*\nX{}Y{}D02*",
428        first.x + shift.x,
429        first.y + shift.y
430    );
431    for i in 0..n {
432        let p0 = ring.points[i];
433        let p1 = ring.points[(i + 1) % n];
434        match ring.segs.get(i).copied().unwrap_or(RingSeg::Line) {
435            RingSeg::Line => {
436                let _ = writeln!(out, "G01*X{}Y{}D01*", p1.x + shift.x, p1.y + shift.y);
437            }
438            RingSeg::Arc { center, ccw, .. } => {
439                let cmd = if ccw { "G03" } else { "G02" };
440                let dx = center.x - p0.x;
441                let dy = center.y - p0.y;
442                let _ = writeln!(
443                    out,
444                    "{cmd}*X{}Y{}I{dx}J{dy}D01*",
445                    p1.x + shift.x,
446                    p1.y + shift.y
447                );
448            }
449        }
450    }
451}
452
453/// Tessellate any local `AreaShape` into board-space polygon vertices (`+Y` up, whole nm).
454#[must_use]
455pub fn shape_to_board_polygon(shape: &AreaShape, placement: Placement2D) -> Vec<CoordNm> {
456    let local: Vec<(f64, f64)> = match shape {
457        AreaShape::Disk { radius } => {
458            let r = *radius as f64;
459            (0..32)
460                .map(|i| {
461                    let a = std::f64::consts::TAU * (i as f64 / 32.0);
462                    let (s, c) = a.sin_cos();
463                    (r * c, r * s)
464                })
465                .collect()
466        }
467        AreaShape::Rect { width, height } => {
468            let hw = *width as f64 * 0.5;
469            let hh = *height as f64 * 0.5;
470            vec![(-hw, -hh), (hw, -hh), (hw, hh), (-hw, hh)]
471        }
472        AreaShape::Capsule { length, width } => capsule_local_pts(*length as f64, *width as f64),
473        AreaShape::RoundedRect {
474            width,
475            height,
476            radius,
477        } => roundrect_local_pts(*width as f64, *height as f64, *radius as f64),
478        AreaShape::ChamferedRect {
479            width,
480            height,
481            chamfer,
482            corners,
483        } => chamfered_local_pts(*width as f64, *height as f64, *chamfer as f64, *corners),
484        AreaShape::Trapezoid {
485            width,
486            height,
487            delta_x,
488            delta_y,
489        } => trapezoid_local_pts(
490            *width as f64,
491            *height as f64,
492            *delta_x as f64,
493            *delta_y as f64,
494        ),
495        AreaShape::Region { outer, .. } => return outer.flatten_polygon(24),
496    };
497    local
498        .into_iter()
499        .map(|(lx, ly)| placement.transform(lx, ly))
500        .collect()
501}
502
503fn capsule_local_pts(length: f64, width: f64) -> Vec<(f64, f64)> {
504    let r = width * 0.5;
505    let half_flat = ((length - width) * 0.5).max(0.0);
506    let mut pts = Vec::with_capacity(32);
507    let steps = 12;
508    for i in 0..=steps {
509        let a = -std::f64::consts::FRAC_PI_2 + std::f64::consts::PI * (i as f64 / steps as f64);
510        let (s, c) = a.sin_cos();
511        pts.push((half_flat + r * c, r * s));
512    }
513    for i in 0..=steps {
514        let a = std::f64::consts::FRAC_PI_2 + std::f64::consts::PI * (i as f64 / steps as f64);
515        let (s, c) = a.sin_cos();
516        pts.push((-half_flat + r * c, r * s));
517    }
518    pts
519}
520
521fn roundrect_local_pts(width: f64, height: f64, radius: f64) -> Vec<(f64, f64)> {
522    let r = radius.min(width * 0.5).min(height * 0.5);
523    let ix = width * 0.5 - r;
524    let iy = height * 0.5 - r;
525    let corners = [
526        (ix, -iy, -std::f64::consts::FRAC_PI_2),
527        (ix, iy, 0.0),
528        (-ix, iy, std::f64::consts::FRAC_PI_2),
529        (-ix, -iy, std::f64::consts::PI),
530    ];
531    let steps = 6;
532    let mut pts = Vec::with_capacity(4 * (steps + 1));
533    for (cx, cy, a0) in corners {
534        for i in 0..=steps {
535            let a = a0 + std::f64::consts::FRAC_PI_2 * (i as f64 / steps as f64);
536            let (s, c) = a.sin_cos();
537            pts.push((cx + r * c, cy + r * s));
538        }
539    }
540    pts
541}
542
543fn chamfered_local_pts(
544    width: f64,
545    height: f64,
546    chamfer: f64,
547    corners: ChamferCorners,
548) -> Vec<(f64, f64)> {
549    let hw = width * 0.5;
550    let hh = height * 0.5;
551    let c = chamfer.min(hw).min(hh);
552    let mut pts = Vec::with_capacity(8);
553    if corners.lower_left {
554        pts.push((-hw, -hh + c));
555        pts.push((-hw + c, -hh));
556    } else {
557        pts.push((-hw, -hh));
558    }
559    if corners.lower_right {
560        pts.push((hw - c, -hh));
561        pts.push((hw, -hh + c));
562    } else {
563        pts.push((hw, -hh));
564    }
565    if corners.upper_right {
566        pts.push((hw, hh - c));
567        pts.push((hw - c, hh));
568    } else {
569        pts.push((hw, hh));
570    }
571    if corners.upper_left {
572        pts.push((-hw + c, hh));
573        pts.push((-hw, hh - c));
574    } else {
575        pts.push((-hw, hh));
576    }
577    pts
578}
579
580fn trapezoid_local_pts(width: f64, height: f64, dx: f64, dy: f64) -> Vec<(f64, f64)> {
581    let hw = width * 0.5;
582    let hh = height * 0.5;
583    let hdx = dx * 0.5;
584    let hdy = dy * 0.5;
585    vec![
586        (-hw - hdy, -hh + hdx),
587        (hw + hdy, -hh - hdx),
588        (hw - hdy, hh + hdx),
589        (-hw + hdy, hh - hdx),
590    ]
591}
592
593fn protel_extension(layer: &FabLayer) -> String {
594    match layer.key.as_str() {
595        "TOP" => "GTL".to_owned(),
596        "BOTTOM" => "GBL".to_owned(),
597        "TOPSOLDER" => "GTS".to_owned(),
598        "BOTTOMSOLDER" => "GBS".to_owned(),
599        "TOPPASTE" => "GTP".to_owned(),
600        "BOTTOMPASTE" => "GBP".to_owned(),
601        "TOPOVERLAY" => "GTO".to_owned(),
602        "BOTTOMOVERLAY" => "GBO".to_owned(),
603        PROFILE_KEY => "GM1".to_owned(),
604        other if other.starts_with("MID") => format!("G{}", other.trim_start_matches("MID")),
605        other => format!("{other}.gbr"),
606    }
607}
608
609fn role_name(role: LayerRole) -> &'static str {
610    match role {
611        LayerRole::Conductor => "conductor",
612        LayerRole::SolderMask => "solder_mask",
613        LayerRole::Paste => "paste",
614        LayerRole::Silkscreen => "silkscreen",
615        LayerRole::Profile => "profile",
616        LayerRole::Mechanical => "mechanical",
617        LayerRole::Virtual => "virtual",
618    }
619}
620
621fn nm_to_mm(nm: i64) -> f64 {
622    nm as f64 / 1_000_000.0
623}