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

kicad_monkey_core/pcb/
physical.rs

1//! Iterable physical facts derived directly from PCB source records.
2//!
3//! Footprint-local coordinates stay local and are paired with an explicit
4//! placement transform. Consumers therefore choose when and how to compose
5//! transforms without losing KiCad source semantics.
6
7use super::*;
8
9#[derive(Clone, Debug, PartialEq)]
10pub struct PcbPadDrill {
11    pub shape: PcbHoleShape,
12    pub width: f64,
13    pub height: Option<f64>,
14    pub offset: PcbPoint,
15}
16
17#[derive(Clone, Copy, Debug, Eq, PartialEq)]
18pub enum PcbHoleShape {
19    Round,
20    Oval,
21}
22
23impl PcbHoleShape {
24    pub const fn as_str(self) -> &'static str {
25        match self {
26            Self::Round => "round",
27            Self::Oval => "oval",
28        }
29    }
30}
31
32#[derive(Clone, Copy, Debug, Eq, PartialEq)]
33pub enum PcbHoleOwner {
34    Pad,
35    Via,
36}
37
38impl PcbHoleOwner {
39    pub const fn as_str(self) -> &'static str {
40        match self {
41            Self::Pad => "pad",
42            Self::Via => "via",
43        }
44    }
45}
46
47#[derive(Clone, Debug, PartialEq)]
48pub struct PcbHole {
49    pub owner: PcbHoleOwner,
50    pub owner_index: usize,
51    pub footprint_index: Option<usize>,
52    /// Board coordinates for vias; footprint-local coordinates for pads.
53    pub center: PcbPoint,
54    /// Drill offset in the pad's local coordinate system.
55    pub offset: PcbPoint,
56    pub shape: PcbHoleShape,
57    pub width: f64,
58    pub height: f64,
59    pub angle: f64,
60    pub plated: bool,
61    pub layers: Vec<String>,
62    pub uuid: Option<String>,
63    pub source_range: Range<usize>,
64}
65
66#[derive(Clone, Debug, PartialEq)]
67pub struct PcbFootprintTransform {
68    pub footprint_index: usize,
69    pub x: f64,
70    pub y: f64,
71    pub angle: f64,
72    pub layer: String,
73    pub locked: bool,
74    pub path: Option<String>,
75    pub sheet_name: Option<String>,
76    pub sheet_file: Option<String>,
77    pub uuid: Option<String>,
78    pub source_range: Range<usize>,
79}
80
81#[derive(Clone, Copy, Debug, Eq, PartialEq)]
82pub enum PcbProfileOwner {
83    Board,
84    Footprint { footprint_index: usize },
85}
86
87#[derive(Clone, Debug, PartialEq)]
88pub struct PcbProfilePrimitive {
89    pub owner: PcbProfileOwner,
90    pub graphic: PcbGraphic,
91}
92
93impl<'a> PcbView<'a> {
94    /// Iterate source-authored holes: footprint-local pad drills, then board vias.
95    pub fn holes(&self) -> impl Iterator<Item = Result<PcbHole, Error>> + '_ {
96        let pads = self
97            .pads
98            .iter()
99            .filter(move |_| self.selection.contains(PcbFamily::Holes))
100            .enumerate()
101            .filter_map(|(index, span)| {
102                match pad_hole_from_span(self.source, span, index, self.limits) {
103                    Ok(Some(hole)) => Some(Ok(hole)),
104                    Ok(None) => None,
105                    Err(error) => Some(Err(error)),
106                }
107            });
108        let vias = self
109            .vias
110            .iter()
111            .filter(move |_| self.selection.contains(PcbFamily::Holes))
112            .enumerate()
113            .filter_map(|(index, span)| {
114                match via_hole_from_span(self.source, span, index, self.limits) {
115                    Ok(Some(hole)) => Some(Ok(hole)),
116                    Ok(None) => None,
117                    Err(error) => Some(Err(error)),
118                }
119            });
120        pads.chain(vias)
121    }
122
123    /// Iterate explicit footprint-local to board placement facts in source order.
124    pub fn footprint_transforms(
125        &self,
126    ) -> impl Iterator<Item = Result<PcbFootprintTransform, Error>> + '_ {
127        self.footprints
128            .iter()
129            .filter(move |_| self.selection.contains(PcbFamily::FootprintTransforms))
130            .enumerate()
131            .map(|(index, span)| {
132                footprint_transform_from_span(self.source, span, index, self.limits)
133            })
134    }
135
136    /// Iterate top-level and footprint-local Edge.Cuts carriers.
137    pub fn profile_primitives(
138        &self,
139    ) -> impl Iterator<Item = Result<PcbProfilePrimitive, Error>> + '_ {
140        let board = self
141            .graphics
142            .iter()
143            .filter(move |_| self.selection.contains(PcbFamily::Profile))
144            .filter_map(|span| {
145                match profile_from_span(self.source, span, PcbProfileOwner::Board, self.limits) {
146                    Ok(Some(profile)) => Some(Ok(profile)),
147                    Ok(None) => None,
148                    Err(error) => Some(Err(error)),
149                }
150            });
151        let footprints = self
152            .footprint_graphics
153            .iter()
154            .filter(move |_| self.selection.contains(PcbFamily::Profile))
155            .filter_map(|indexed| {
156                let owner = PcbProfileOwner::Footprint {
157                    footprint_index: indexed.parent_index,
158                };
159                match profile_from_span(self.source, &indexed.span, owner, self.limits) {
160                    Ok(Some(profile)) => Some(Ok(profile)),
161                    Ok(None) => None,
162                    Err(error) => Some(Err(error)),
163                }
164            });
165        board.chain(footprints)
166    }
167}
168
169pub(super) fn is_footprint_profile_head(head: &str) -> bool {
170    matches!(
171        head,
172        "fp_line" | "fp_arc" | "fp_circle" | "fp_rect" | "fp_poly"
173    )
174}
175
176/// A pad's shape offset from its position, `(drill ... (offset x y))`. pcbnew
177/// reads it with or without a drill size: an SMD pad saved as
178/// `(drill (offset 1.7 0.85))` moves its copper, mask and paste by it
179/// (kicad-cli 10.0.5, JumperlessV5r7 TP18/TP28).
180pub(super) fn pad_offset_from_children(
181    source: &str,
182    children: &[FormSpan],
183    limits: PcbLimits,
184) -> Result<PcbPoint, Error> {
185    let Some(drill) = child(children, "drill") else {
186        return Ok(PcbPoint { x: 0.0, y: 0.0 });
187    };
188    let drill_children = direct_children(source, drill, 4, limits)?;
189    let [x, y] = optional_pair(source, &drill_children, "offset", [0.0, 0.0])?;
190    Ok(PcbPoint { x, y })
191}
192
193pub(super) fn pad_drill_from_children(
194    source: &str,
195    children: &[FormSpan],
196    limits: PcbLimits,
197) -> Result<Option<PcbPadDrill>, Error> {
198    let Some(drill) = child(children, "drill") else {
199        return Ok(None);
200    };
201    let values = bounded_scalar_values(source, drill, 3)?;
202    let oval = values
203        .first()
204        .is_some_and(|value| token_string(value) == "oval");
205    let width_index = usize::from(oval);
206    let Some(width) = optional_f64(values.get(width_index), drill)? else {
207        return Ok(None);
208    };
209    let height = oval
210        .then(|| optional_f64(values.get(width_index + 1), drill))
211        .transpose()?
212        .flatten();
213    let drill_children = direct_children(source, drill, 4, limits)?;
214    let offset = optional_pair(source, &drill_children, "offset", [0.0, 0.0])?;
215    Ok(Some(PcbPadDrill {
216        shape: if oval {
217            PcbHoleShape::Oval
218        } else {
219            PcbHoleShape::Round
220        },
221        width,
222        height,
223        offset: PcbPoint {
224            x: offset[0],
225            y: offset[1],
226        },
227    }))
228}
229
230fn pad_hole_from_span(
231    source: &str,
232    indexed: &IndexedNestedForm,
233    owner_index: usize,
234    limits: PcbLimits,
235) -> Result<Option<PcbHole>, Error> {
236    let children = direct_children(source, &indexed.span, limits.max_pad_children, limits)?;
237    let Some(drill) = pad_drill_from_children(source, &children, limits)? else {
238        return Ok(None);
239    };
240    if drill.width <= 0.0 || drill.height.is_some_and(|height| height <= 0.0) {
241        return Ok(None);
242    }
243    let at = optional_vector(
244        source,
245        &children,
246        "at",
247        [0.0, 0.0, 0.0],
248        limits.max_pad_header_scalars,
249    )?;
250    let header = bounded_scalar_values(source, &indexed.span, 3)?;
251    let kind = header.get(1).map(token_string).unwrap_or_default();
252    Ok(Some(PcbHole {
253        owner: PcbHoleOwner::Pad,
254        owner_index,
255        footprint_index: Some(indexed.parent_index),
256        center: PcbPoint { x: at[0], y: at[1] },
257        offset: drill.offset,
258        shape: drill.shape,
259        width: drill.width,
260        height: drill.height.unwrap_or(drill.width),
261        angle: at[2],
262        plated: kind != "np_thru_hole",
263        layers: child_strings(source, &children, "layers", limits.max_layers)?,
264        uuid: optional_uuid(source, &children)?,
265        source_range: indexed.span.range.clone(),
266    }))
267}
268
269fn via_hole_from_span(
270    source: &str,
271    span: &FormSpan,
272    owner_index: usize,
273    limits: PcbLimits,
274) -> Result<Option<PcbHole>, Error> {
275    let children = direct_children(source, span, limits.max_via_children, limits)?;
276    let Some(drill) = optional_child_f64(source, &children, "drill")?.filter(|drill| *drill > 0.0)
277    else {
278        return Ok(None);
279    };
280    let at = optional_coordinate_pair(source, &children, "at")?;
281    Ok(Some(PcbHole {
282        owner: PcbHoleOwner::Via,
283        owner_index,
284        footprint_index: None,
285        center: PcbPoint { x: at[0], y: at[1] },
286        offset: PcbPoint { x: 0.0, y: 0.0 },
287        shape: PcbHoleShape::Round,
288        width: drill,
289        height: drill,
290        angle: 0.0,
291        plated: true,
292        layers: child_strings(source, &children, "layers", limits.max_layers)?,
293        uuid: optional_uuid(source, &children)?,
294        source_range: span.range.clone(),
295    }))
296}
297
298fn footprint_transform_from_span(
299    source: &str,
300    indexed: &IndexedFootprint,
301    footprint_index: usize,
302    limits: PcbLimits,
303) -> Result<PcbFootprintTransform, Error> {
304    let children = direct_children(source, &indexed.span, limits.max_footprint_children, limits)?;
305    let at = optional_vector(
306        source,
307        &children,
308        "at",
309        [0.0, 0.0, 0.0],
310        limits.max_footprint_header_scalars,
311    )?;
312    Ok(PcbFootprintTransform {
313        footprint_index,
314        x: at[0],
315        y: at[1],
316        angle: at[2],
317        layer: optional_child_string(source, &children, "layer")?
318            .unwrap_or_else(|| "F.Cu".to_owned()),
319        locked: child_bool(source, &children, "locked")?,
320        path: optional_child_string(source, &children, "path")?.filter(|value| !value.is_empty()),
321        sheet_name: optional_child_string(source, &children, "sheetname")?
322            .filter(|value| !value.is_empty()),
323        sheet_file: optional_child_string(source, &children, "sheetfile")?
324            .filter(|value| !value.is_empty()),
325        uuid: optional_uuid(source, &children)?,
326        source_range: indexed.span.range.clone(),
327    })
328}
329
330fn profile_from_span(
331    source: &str,
332    span: &FormSpan,
333    owner: PcbProfileOwner,
334    limits: PcbLimits,
335) -> Result<Option<PcbProfilePrimitive>, Error> {
336    let children = direct_children(source, span, limits.max_object_children, limits)?;
337    if optional_child_string(source, &children, "layer")?.as_deref() != Some("Edge.Cuts") {
338        return Ok(None);
339    }
340    Ok(Some(PcbProfilePrimitive {
341        owner,
342        graphic: graphic_from_span(source, span, limits)?,
343    }))
344}