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

kicad_monkey_fab/
lib.rs

1//! Pure-Rust fabrication output engine for KiCad >= 7 PCBs.
2//!
3//! `kicad-monkey-fab` lowers a [`kicad_monkey_core::PcbView`] directly into a
4//! canonical whole-nanometre, `+Y`-up [`FabViewData`] model and writes
5//! manufacturing deliverables directly from that single semantic model:
6//!
7//! - Gerber X2 / X1 (`.GTL`, `.GBL`, `.G1`.., `.GTS`, `.GBS`, `.GTP`, `.GBP`, `.GTO`, `.GBO`, `.GM1`)
8//! - Excellon NC Drill (multi-span PTH/NPTH + `G85` routed oval slots)
9//! - Analytic composite and per-layer SVGs
10//! - IPC-2581 Rev B (`.cvg`)
11//! - Pick-and-Place (centroid) CSV and grouped BOM CSV
12//! - Pure-Rust ISO 10303-21 Micro-STEP board substrate
13//! - All 17 canonical virtual fabrication layers
14
15#![forbid(unsafe_code)]
16
17pub mod bake;
18pub mod bake_footprint;
19pub mod designator_fit;
20pub mod diodes;
21pub mod drill;
22pub mod geom;
23pub mod gerber;
24pub mod ipc2581;
25pub mod layer_map;
26pub mod micro_step;
27pub mod passives;
28pub mod pin1;
29pub mod pose;
30pub mod svg;
31pub mod tabular;
32pub mod view;
33pub mod virtual_layers;
34
35pub use bake::{
36    BakeLayerReport, BakeVirtualLayersOptions, BakeVirtualLayersReport, DEFAULT_VDOC_PCB_LAYERS,
37    PcbCleanOptions, PcbCleanReport, UserLayerCollision, VIRTUAL_GROUP_PREFIX, VdocLayerPreset,
38    bake_virtual_layers_source, bake_virtual_layers_with_view, clean_pcb_doc_layers_source,
39    clear_baked_virtual_layers, default_kicad_layer_for_virtual,
40    default_kicad_layer_for_virtual_preset, detect_user_layer_collisions,
41};
42pub use bake_footprint::{
43    BakeFootprintVirtualLayersOptions, BakeFootprintVirtualLayersReport,
44    DEFAULT_FOOTPRINT_VIRTUAL_LAYERS, FOOTPRINT_SUPPORTED_VIRTUAL_LAYERS,
45    bake_virtual_layers_to_footprint_source, build_footprint_fab_view, build_footprint_pad_outline,
46    clean_footprint_doc_layers_source, detect_footprint_layer_collisions, footprint_glob_match,
47    infer_synthetic_designator, resolve_footprint_virtual_layer_key,
48};
49pub use designator_fit::{
50    DEFAULT_OBLIQUE_MIN_ASPECT_RATIO, DesignatorFit, DesignatorFitSession,
51    normalize_designator_axis, pad_envelope, region_from_evenodd_layers, ring_polygon,
52    subtract_cutouts,
53};
54pub use diodes::{
55    DiodeColorMode, DiodeGlyph, DiodeGlyphStroke, DiodeOptions, DiodeOverride, DiodeStrokeKind,
56    DiodeType, DiodeVisibilityMode, ResolvedDiode, build_diode_glyphs, build_diodes_layer,
57    resolve_diodes,
58};
59pub use drill::{DrillOptions, write_nc_drill};
60pub use geom::{
61    AreaKind, AreaShape, ChamferCorners, CoordNm, DOT_NM, FabArea, FabComponent, FabDrillPair,
62    FabHole, FabLand, FabLayer, FabLayerItems, FabProfile, FabStackRow, FabStroke, LandKind,
63    LandRole, LayerRole, LayerSide, Placement2D, Ring2D, RingSeg, StrokeKind, StrokePath,
64};
65pub use gerber::{GerberOptions, render_virtual_gerber, write_gerbers};
66pub use ipc2581::write_ipc2581;
67pub use micro_step::{LayerStepOptions, LayerStepResult, write_layer_step, write_micro_step};
68pub use passives::{
69    CapacitorOptions, InductorOptions, ResolvedCapacitor, ResolvedInductor, build_capacitors_layer,
70    build_capacitors_layer_with_options, build_inductors_layer, build_inductors_layer_with_options,
71    build_resistors_layer, resolve_capacitor, resolve_inductor,
72};
73pub use pin1::{
74    PadLabelOrientation, Pin1Marker, Pin1Options, Pin1Override, Pin1Role, build_pin1_layer,
75    build_pin1_markers, is_grid_pad_designator,
76};
77pub use pose::{
78    BOARD_MODEL_Z_OFFSET_MM, FabBody3D, Matrix4, flatten_row_major, local_hlr_mm_to_board_nm,
79    local_pose_matrix, normalize_scale, turned_pose_matrix,
80};
81pub use svg::{SvgOptions, write_composite_svg, write_layer_svgs};
82pub use tabular::{write_bom_csv, write_pnp_csv};
83pub use view::FabViewData;
84pub use virtual_layers::{ALL_VIRTUAL_LAYERS, build_virtual_layer, resolve_virtual_layer_key};
85
86use kicad_monkey_core::pcb::PcbView;
87use serde::{Deserialize, Serialize};
88use std::fmt;
89use std::path::{Path, PathBuf};
90
91/// Minimum supported KiCad PCB major version.
92pub const MIN_SUPPORTED_PCB_KICAD_MAJOR: u32 = 7;
93
94/// Fabrication crate error.
95#[derive(Debug)]
96pub enum FabError {
97    Io(std::io::Error),
98    Parse(String),
99    UnknownVirtualLayer(String),
100}
101
102impl fmt::Display for FabError {
103    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104        match self {
105            Self::Io(err) => write!(f, "I/O error: {err}"),
106            Self::Parse(msg) => write!(f, "PCB parse error: {msg}"),
107            Self::UnknownVirtualLayer(name) => write!(f, "unknown virtual layer: {name}"),
108        }
109    }
110}
111
112impl std::error::Error for FabError {}
113
114impl From<std::io::Error> for FabError {
115    fn from(err: std::io::Error) -> Self {
116        Self::Io(err)
117    }
118}
119
120/// One generated manufacturing file held in memory before writing to disk.
121#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
122pub struct FabFile {
123    pub name: String,
124    pub data: Vec<u8>,
125    pub key: Option<String>,
126    pub role: String,
127    pub plated: Option<bool>,
128    pub span: Option<(String, String)>,
129}
130
131/// Result of a complete `write_all` fabrication run.
132#[derive(Clone, Debug, Default)]
133pub struct FabOutput {
134    pub files: Vec<PathBuf>,
135}
136
137/// Options controlling [`KiCadFab::write_all`].
138#[derive(Clone, Debug)]
139pub struct FabAllOptions {
140    pub stem: Option<String>,
141    pub gerbers: bool,
142    pub drill: bool,
143    pub ipc2581: bool,
144    pub svg: bool,
145    pub layer_svgs: bool,
146    pub pnp: bool,
147    pub bom: bool,
148    pub micro_step: bool,
149    pub virtual_layers: Vec<String>,
150    pub x2: bool,
151    pub use_aux_origin: bool,
152    pub include_silk: bool,
153}
154
155impl Default for FabAllOptions {
156    fn default() -> Self {
157        Self {
158            stem: None,
159            gerbers: true,
160            drill: true,
161            ipc2581: false,
162            svg: false,
163            layer_svgs: false,
164            pnp: false,
165            bom: false,
166            micro_step: false,
167            virtual_layers: Vec::new(),
168            x2: true,
169            use_aux_origin: false,
170            include_silk: true,
171        }
172    }
173}
174
175/// High-level facade for pure-Rust KiCad fabrication output generation.
176#[derive(Clone, Debug)]
177pub struct KiCadFab {
178    view: FabViewData,
179}
180
181impl KiCadFab {
182    /// Parse a `.kicad_pcb` file on disk into a `KiCadFab` engine.
183    pub fn from_pcb_file(path: impl AsRef<Path>) -> Result<Self, FabError> {
184        let path = path.as_ref();
185        let source = std::fs::read_to_string(path)?;
186        let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("board");
187        Self::from_pcb_source(&source, stem)
188    }
189
190    /// Parse `.kicad_pcb` source text into a `KiCadFab` engine.
191    pub fn from_pcb_source(source: &str, name: impl Into<String>) -> Result<Self, FabError> {
192        let view = FabViewData::from_pcb_source(source, name)?;
193        Ok(Self { view })
194    }
195
196    /// Build a `KiCadFab` engine from an already-parsed [`PcbView`].
197    pub fn from_pcb_view(view: &PcbView<'_>, name: impl Into<String>) -> Result<Self, FabError> {
198        let data = FabViewData::from_pcb_view(view, name)?;
199        Ok(Self { view: data })
200    }
201
202    /// Borrow the underlying canonical [`FabViewData`].
203    #[must_use]
204    pub fn view(&self) -> &FabViewData {
205        &self.view
206    }
207
208    /// Generate Gerber X2/X1 files in memory.
209    #[must_use]
210    pub fn to_gerbers(&self, opts: &GerberOptions) -> Vec<FabFile> {
211        write_gerbers(&self.view, opts)
212    }
213
214    /// Generate Excellon NC Drill files in memory.
215    #[must_use]
216    pub fn to_nc_drill(&self, opts: &DrillOptions) -> Vec<FabFile> {
217        write_nc_drill(&self.view, opts)
218    }
219
220    /// Generate an analytic composite board SVG.
221    #[must_use]
222    pub fn to_svg(&self, opts: &SvgOptions) -> String {
223        write_composite_svg(&self.view, opts)
224    }
225
226    /// Generate per-layer SVG files in memory.
227    #[must_use]
228    pub fn to_layer_svgs(&self, opts: &SvgOptions) -> Vec<FabFile> {
229        write_layer_svgs(&self.view, opts)
230    }
231
232    /// Generate an IPC-2581 Rev B `.cvg` XML document.
233    #[must_use]
234    pub fn to_ipc2581(&self) -> String {
235        write_ipc2581(&self.view)
236    }
237
238    /// Generate Pick-and-Place centroid CSV.
239    #[must_use]
240    pub fn to_pnp(&self, use_aux_origin: bool) -> String {
241        write_pnp_csv(&self.view, use_aux_origin)
242    }
243
244    /// Generate grouped BOM CSV.
245    #[must_use]
246    pub fn to_bom(&self) -> String {
247        write_bom_csv(&self.view)
248    }
249
250    /// Generate a pure-Rust ISO 10303-21 Micro-STEP substrate model.
251    #[must_use]
252    pub fn to_micro_step(&self) -> String {
253        write_micro_step(&self.view)
254    }
255
256    /// Synthesize one virtual fabrication layer by canonical name or alias.
257    pub fn virtual_layer(&self, name: &str) -> Result<FabLayerItems, FabError> {
258        let key = resolve_virtual_layer_key(name)
259            .ok_or_else(|| FabError::UnknownVirtualLayer(name.to_owned()))?;
260        Ok(build_virtual_layer(&self.view, key))
261    }
262
263    /// Generate all requested fabrication outputs and write them into `output_dir`.
264    pub fn write_all(
265        &self,
266        output_dir: impl AsRef<Path>,
267        opts: &FabAllOptions,
268    ) -> Result<FabOutput, FabError> {
269        let out_dir = output_dir.as_ref();
270        std::fs::create_dir_all(out_dir)?;
271        let stem = opts.stem.as_deref().unwrap_or(&self.view.name).to_owned();
272        let mut written = Vec::new();
273
274        if opts.gerbers {
275            let g_opts = GerberOptions {
276                stem: stem.clone(),
277                x2: opts.x2,
278                use_aux_origin: opts.use_aux_origin,
279                include_profile: true,
280                include_silk: opts.include_silk,
281            };
282            for file in self.to_gerbers(&g_opts) {
283                written.push(write_fab_file(out_dir, &file)?);
284            }
285        }
286        if opts.drill {
287            let d_opts = DrillOptions {
288                stem: stem.clone(),
289                use_aux_origin: opts.use_aux_origin,
290            };
291            for file in self.to_nc_drill(&d_opts) {
292                written.push(write_fab_file(out_dir, &file)?);
293            }
294        }
295        if opts.ipc2581 {
296            let p = out_dir.join(format!("{stem}.cvg"));
297            std::fs::write(&p, self.to_ipc2581())?;
298            written.push(p);
299        }
300        if opts.svg {
301            let s_opts = SvgOptions {
302                stem: stem.clone(),
303                bottom: false,
304                padding_mm: 2.0,
305                include_silk: opts.include_silk,
306            };
307            let p_top = out_dir.join(format!("{stem}-top.svg"));
308            std::fs::write(&p_top, self.to_svg(&s_opts))?;
309            written.push(p_top);
310            let p_bot = out_dir.join(format!("{stem}-bottom.svg"));
311            std::fs::write(
312                &p_bot,
313                self.to_svg(&SvgOptions {
314                    bottom: true,
315                    ..s_opts
316                }),
317            )?;
318            written.push(p_bot);
319        }
320        if opts.layer_svgs {
321            let s_opts = SvgOptions {
322                stem: stem.clone(),
323                bottom: false,
324                padding_mm: 2.0,
325                include_silk: opts.include_silk,
326            };
327            for file in self.to_layer_svgs(&s_opts) {
328                written.push(write_fab_file(out_dir, &file)?);
329            }
330        }
331        if opts.pnp {
332            let p = out_dir.join(format!("{stem}-pnp.csv"));
333            std::fs::write(&p, self.to_pnp(opts.use_aux_origin))?;
334            written.push(p);
335        }
336        if opts.bom {
337            let p = out_dir.join(format!("{stem}-bom.csv"));
338            std::fs::write(&p, self.to_bom())?;
339            written.push(p);
340        }
341        if opts.micro_step {
342            let p = out_dir.join(format!("{stem}.step"));
343            std::fs::write(&p, self.to_micro_step())?;
344            written.push(p);
345        }
346        let shift = if opts.use_aux_origin {
347            CoordNm::new(-self.view.aux_origin.x, -self.view.aux_origin.y)
348        } else {
349            CoordNm::new(0, 0)
350        };
351        for vname in &opts.virtual_layers {
352            let key = resolve_virtual_layer_key(vname)
353                .ok_or_else(|| FabError::UnknownVirtualLayer(vname.clone()))?;
354            let items = build_virtual_layer(&self.view, key);
355            let gbr = render_virtual_gerber(key, &items, shift, opts.x2);
356            let p = out_dir.join(format!("{stem}-{key}.gbr"));
357            std::fs::write(&p, gbr)?;
358            written.push(p);
359        }
360
361        Ok(FabOutput { files: written })
362    }
363}
364
365fn write_fab_file(out_dir: &Path, file: &FabFile) -> Result<PathBuf, FabError> {
366    let path = out_dir.join(&file.name);
367    std::fs::write(&path, &file.data)?;
368    Ok(path)
369}