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

kicad_monkey_fab/
passives.rs

1//! Full-parity passive orientation/symbol virtual layers:
2//! `CAPACITORS_TOP/BOTTOM`, `INDUCTORS_TOP/BOTTOM`, `RESISTORS_TOP/BOTTOM`.
3//!
4//! Mirrors Python `kicad_monkey/fab/virtual/{_capacitors,_inductors,_resistors}.py`.
5
6use crate::FabViewData;
7use crate::geom::{
8    AreaKind, AreaShape, CoordNm, FabArea, FabComponent, FabLand, FabLayerItems, FabStroke,
9    LayerSide, Placement2D, StrokeKind, StrokePath, mm_to_nm,
10};
11use std::collections::HashMap;
12use std::f64::consts::PI;
13
14const MIN_LINE_WIDTH_NM: i64 = 35_000;
15const MAX_LINE_WIDTH_NM: i64 = 180_000;
16
17/// Exact 6-peak IEEE resistor zig-zag normalized to `u in [-0.5, +0.5]`, `v in [-0.12, +0.12]`.
18const ZIGZAG_POINTS: [(f64, f64); 10] = [
19    (-0.50, 0.00),
20    (-0.30, 0.00),
21    (-0.25, -0.12),
22    (-0.15, 0.12),
23    (-0.05, -0.12),
24    (0.05, 0.12),
25    (0.15, -0.12),
26    (0.25, 0.12),
27    (0.30, 0.00),
28    (0.50, 0.00),
29];
30
31const MLCC_GUARD_TOKENS: [&str; 12] = [
32    "mlcc", "ceramic", "cer", "x7r", "x5r", "x7s", "x6s", "c0g", "np0", "npo", "film", "mica",
33];
34
35const POLARIZED_CAP_KEYWORDS: [&str; 25] = [
36    "tantalum",
37    "tant",
38    "electrolytic",
39    "elec",
40    "polymer",
41    "supercap",
42    "niobium",
43    "polarized",
44    "polarised",
45    "alum",
46    "aluminum",
47    "aluminium",
48    "cpol",
49    "cap_pol",
50    "oscon",
51    "poscap",
52    "eia-a",
53    "eia-b",
54    "eia-c",
55    "eia-d",
56    "eia-e",
57    "case_a",
58    "case_b",
59    "case_c",
60    "case_d",
61];
62
63/// Options for `CAPACITORS_TOP` / `CAPACITORS_BOTTOM` (matches Python `CapacitorLayerOptions`).
64#[derive(Clone, Copy, Debug, Default)]
65pub struct CapacitorOptions {
66    /// When `false` (default), skip non-polarized MLCC/ceramic capacitors.
67    pub include_non_polarized: bool,
68}
69
70/// Options for `INDUCTORS_TOP` / `INDUCTORS_BOTTOM` (matches Python `InductorLayerOptions`).
71#[derive(Clone, Copy, Debug, Default)]
72pub struct InductorOptions {
73    /// When `false` (default), skip non-polarized inductors / ferrite beads.
74    pub include_non_polarized: bool,
75}
76
77/// Classified capacitor polarity & pin split (reused by `PIN1_*` and `CAPACITORS_*`).
78#[derive(Clone, Debug)]
79pub struct ResolvedCapacitor {
80    pub component_id: String,
81    pub designator: String,
82    pub positive_pins: Vec<String>,
83    pub negative_pins: Vec<String>,
84    pub polarized: bool,
85}
86
87/// Classified inductor polarity & pin split (reused by `PIN1_*` and `INDUCTORS_*`).
88#[derive(Clone, Debug)]
89pub struct ResolvedInductor {
90    pub component_id: String,
91    pub designator: String,
92    pub polarity_pins: Vec<String>,
93    pub other_pins: Vec<String>,
94    pub polarized: bool,
95}
96
97struct InterPadFrame {
98    mid: (f64, f64),
99    ux: f64,
100    uy: f64,
101    vx: f64,
102    vy: f64,
103    span: f64,
104}
105
106impl InterPadFrame {
107    fn pt(&self, u: f64, v: f64) -> CoordNm {
108        let x = self.mid.0 + (u * self.ux + v * self.vx) * self.span;
109        let y = self.mid.1 + (u * self.uy + v * self.vy) * self.span;
110        CoordNm::new(x.round() as i64, y.round() as i64)
111    }
112
113    fn stroke_width(&self) -> i64 {
114        ((self.span * 0.055).round() as i64).clamp(MIN_LINE_WIDTH_NM, MAX_LINE_WIDTH_NM)
115    }
116}
117
118/// Classify a component as a capacitor and infer whether it is polarized.
119#[must_use]
120pub fn resolve_capacitor(comp: &FabComponent) -> Option<ResolvedCapacitor> {
121    if !comp.fitted || comp.board_only {
122        return None;
123    }
124    let prefix = designator_prefix(&comp.designator);
125    let type_param = param_ci(comp, "CAPACITOR_TYPE");
126    if let Some(tp) = type_param
127        && is_suppress_token(tp)
128    {
129        return None;
130    }
131    if prefix != "C" && type_param.is_none() {
132        return None;
133    }
134    if comp.pins.len() < 2 {
135        return None;
136    }
137    let blob = text_blob(comp);
138    let pos_param = param_ci(comp, "POSITIVE_PAD").filter(|p| !is_suppress_token(p));
139    let neg_param = param_ci(comp, "NEGATIVE_PAD").filter(|p| !is_suppress_token(p));
140
141    let explicit_polarized = type_param.and_then(parse_polarized_token);
142    let has_pos_neg_param = pos_param.is_some() || neg_param.is_some();
143    let has_pos_pin_tok = comp.pins.iter().any(|p| is_pos_pin_token(p));
144    let has_neg_pin_tok = comp.pins.iter().any(|p| is_neg_pin_token(p));
145    let has_mlcc_guard = MLCC_GUARD_TOKENS.iter().any(|t| has_word(&blob, t));
146    let has_pol_kw = POLARIZED_CAP_KEYWORDS.iter().any(|t| has_word(&blob, t));
147
148    let polarized = if let Some(pol) = explicit_polarized {
149        pol
150    } else if has_pos_neg_param || (has_pos_pin_tok && has_neg_pin_tok) {
151        true
152    } else if has_mlcc_guard {
153        false
154    } else {
155        has_pol_kw
156    };
157
158    let (positive_pins, negative_pins) = split_polarity_pins(comp, pos_param, neg_param, "1");
159    if positive_pins.is_empty() || negative_pins.is_empty() {
160        return None;
161    }
162    Some(ResolvedCapacitor {
163        component_id: comp.id.clone(),
164        designator: comp.designator.clone(),
165        positive_pins,
166        negative_pins,
167        polarized,
168    })
169}
170
171/// Classify a component as an inductor and infer whether it has a declared polarity/start pad.
172#[must_use]
173pub fn resolve_inductor(comp: &FabComponent) -> Option<ResolvedInductor> {
174    if !comp.fitted || comp.board_only || comp.pins.len() < 2 {
175        return None;
176    }
177    let prefix = designator_prefix(&comp.designator);
178    let type_param = param_ci(comp, "INDUCTOR_TYPE");
179    if let Some(tp) = type_param
180        && is_suppress_token(tp)
181    {
182        return None;
183    }
184    if !matches!(prefix.as_str(), "L" | "FB" | "IND") && type_param.is_none() {
185        return None;
186    }
187    let raw_pol = param_ci(comp, "INDUCTOR_POLARITY_PAD").or_else(|| param_ci(comp, "PIN1_PAD"));
188    let suppressed_pol = raw_pol.is_some_and(is_suppress_token);
189    let pol_param = raw_pol.filter(|p| !is_suppress_token(p));
190    let polarized = if suppressed_pol {
191        false
192    } else {
193        type_param
194            .and_then(parse_polarized_token)
195            .unwrap_or_else(|| pol_param.is_some())
196    };
197    let start_pin = pol_param.unwrap_or("1");
198    let (polarity_pins, other_pins) = split_polarity_pins(comp, Some(start_pin), None, "1");
199    if polarity_pins.is_empty() || other_pins.is_empty() {
200        return None;
201    }
202    Some(ResolvedInductor {
203        component_id: comp.id.clone(),
204        designator: comp.designator.clone(),
205        polarity_pins,
206        other_pins,
207        polarized,
208    })
209}
210
211/// Synthesize `CAPACITORS_TOP` or `CAPACITORS_BOTTOM` schematic symbols (polarized-only default).
212#[must_use]
213pub fn build_capacitors_layer(view: &FabViewData, side: LayerSide) -> FabLayerItems {
214    build_capacitors_layer_with_options(view, side, CapacitorOptions::default())
215}
216
217/// Synthesize `CAPACITORS_TOP` or `CAPACITORS_BOTTOM` with explicit options.
218#[must_use]
219pub fn build_capacitors_layer_with_options(
220    view: &FabViewData,
221    side: LayerSide,
222    opts: CapacitorOptions,
223) -> FabLayerItems {
224    let mut out = FabLayerItems::default();
225    let pads = pad_centers_by_comp(view, side);
226    for comp in &view.components {
227        if comp.side != side {
228            continue;
229        }
230        let Some(cap) = resolve_capacitor(comp) else {
231            continue;
232        };
233        if !opts.include_non_polarized && !cap.polarized {
234            continue;
235        }
236        let Some(frame) = frame_for_groups(&pads, &comp.id, &cap.positive_pins, &cap.negative_pins)
237        else {
238            continue;
239        };
240        let w = frame.stroke_width();
241        // Leads from pad centers to plates
242        push_line(
243            &mut out,
244            frame.pt(-0.50, 0.0),
245            frame.pt(-0.08, 0.0),
246            w,
247            &comp.id,
248        );
249        push_line(
250            &mut out,
251            frame.pt(0.08, 0.0),
252            frame.pt(0.50, 0.0),
253            w,
254            &comp.id,
255        );
256        // Flat anode plate
257        push_line(
258            &mut out,
259            frame.pt(-0.08, -0.22),
260            frame.pt(-0.08, 0.22),
261            w,
262            &comp.id,
263        );
264        if cap.polarized {
265            // Curved +/-29 deg cathode plate + off-axis '+' sign
266            let steps = 8;
267            let mut prev = None;
268            for i in 0..=steps {
269                let t = -1.0 + 2.0 * (i as f64 / steps as f64);
270                let ang = t * (29.0_f64.to_radians());
271                let u = 0.08 + 0.06 * (1.0 - ang.cos()) / (1.0 - 29.0_f64.to_radians().cos());
272                let v = 0.22 * (ang.sin() / 29.0_f64.to_radians().sin());
273                let pt = frame.pt(u, v);
274                if let Some(p0) = prev {
275                    push_line(&mut out, p0, pt, w, &comp.id);
276                }
277                prev = Some(pt);
278            }
279            push_line(
280                &mut out,
281                frame.pt(-0.26, 0.14),
282                frame.pt(-0.14, 0.14),
283                w,
284                &comp.id,
285            );
286            push_line(
287                &mut out,
288                frame.pt(-0.20, 0.08),
289                frame.pt(-0.20, 0.20),
290                w,
291                &comp.id,
292            );
293        } else {
294            push_line(
295                &mut out,
296                frame.pt(0.08, -0.22),
297                frame.pt(0.08, 0.22),
298                w,
299                &comp.id,
300            );
301        }
302    }
303    out
304}
305
306/// Synthesize `INDUCTORS_TOP` or `INDUCTORS_BOTTOM` schematic coil symbols (polarized-only default).
307#[must_use]
308pub fn build_inductors_layer(view: &FabViewData, side: LayerSide) -> FabLayerItems {
309    build_inductors_layer_with_options(view, side, InductorOptions::default())
310}
311
312/// Synthesize `INDUCTORS_TOP` or `INDUCTORS_BOTTOM` with explicit options.
313#[must_use]
314pub fn build_inductors_layer_with_options(
315    view: &FabViewData,
316    side: LayerSide,
317    opts: InductorOptions,
318) -> FabLayerItems {
319    let mut out = FabLayerItems::default();
320    let pads = pad_centers_by_comp(view, side);
321    for comp in &view.components {
322        if comp.side != side {
323            continue;
324        }
325        let Some(ind) = resolve_inductor(comp) else {
326            continue;
327        };
328        if !opts.include_non_polarized && !ind.polarized {
329            continue;
330        }
331        let Some(frame) = frame_for_groups(&pads, &comp.id, &ind.polarity_pins, &ind.other_pins)
332        else {
333            continue;
334        };
335        let w = frame.stroke_width();
336        let bulge = inductor_bulge_sign(&frame, side);
337        push_line(
338            &mut out,
339            frame.pt(-0.50, 0.0),
340            frame.pt(-0.32, 0.0),
341            w,
342            &comp.id,
343        );
344        push_line(
345            &mut out,
346            frame.pt(0.32, 0.0),
347            frame.pt(0.50, 0.0),
348            w,
349            &comp.id,
350        );
351        // 4 semicircular coil humps across u in [-0.32, +0.32]
352        let humps = 4;
353        let r = 0.64 / (2.0 * humps as f64);
354        let segs = 6;
355        for h in 0..humps {
356            let cu = -0.32 + (2.0 * h as f64 + 1.0) * r;
357            let mut prev = None;
358            for s in 0..=segs {
359                let ang = PI * (1.0 - s as f64 / segs as f64);
360                let pt = frame.pt(cu + r * ang.cos(), bulge * r * ang.sin());
361                if let Some(p0) = prev {
362                    push_line(&mut out, p0, pt, w, &comp.id);
363                }
364                prev = Some(pt);
365            }
366        }
367        if ind.polarized {
368            let dot_r = ((frame.span * 0.055).round() as i64).clamp(mm_to_nm(0.06), mm_to_nm(0.25));
369            let dot_pt = frame.pt(-0.32, bulge * r * 1.45);
370            out.areas.push(FabArea {
371                kind: AreaKind::Virtual,
372                shape: AreaShape::Disk { radius: dot_r },
373                placement: Placement2D::translate(dot_pt.x, dot_pt.y),
374                net: None,
375                component: Some(comp.id.clone()),
376                source: None,
377            });
378        }
379    }
380    out
381}
382
383/// Choose coil hump bulge sign matching Python `_inductors.py::_inductor_bulge_normal`.
384fn inductor_bulge_sign(frame: &InterPadFrame, side: LayerSide) -> f64 {
385    let mut sign = if frame.vy < -1.0e-6 || (frame.vy.abs() <= 1.0e-6 && frame.vx < 0.0) {
386        -1.0
387    } else {
388        1.0
389    };
390    if side == LayerSide::Bottom && frame.vy.abs() <= 1.0e-6 {
391        sign = -sign;
392    }
393    sign
394}
395
396/// Synthesize `RESISTORS_TOP` or `RESISTORS_BOTTOM` IEEE zig-zag (or IEC box) schematic symbols.
397#[must_use]
398pub fn build_resistors_layer(view: &FabViewData, side: LayerSide) -> FabLayerItems {
399    let mut out = FabLayerItems::default();
400    let pads = pad_centers_by_comp(view, side);
401    for comp in &view.components {
402        if comp.side != side || !comp.fitted || comp.board_only || comp.pins.len() != 2 {
403            continue;
404        }
405        let style_param = param_ci(comp, "RESISTOR_STYLE");
406        if let Some(st) = style_param
407            && is_suppress_token(st)
408        {
409            continue;
410        }
411        if designator_prefix(&comp.designator) != "R" && style_param.is_none() {
412            continue;
413        }
414        let p0 = [comp.pins[0].clone()];
415        let p1 = [comp.pins[1].clone()];
416        let Some(frame) = frame_for_groups(&pads, &comp.id, &p0, &p1) else {
417            continue;
418        };
419        let w = frame.stroke_width();
420        if style_param
421            .is_some_and(|s| s.eq_ignore_ascii_case("box") || s.eq_ignore_ascii_case("iec"))
422        {
423            push_line(
424                &mut out,
425                frame.pt(-0.50, 0.0),
426                frame.pt(-0.30, 0.0),
427                w,
428                &comp.id,
429            );
430            push_line(
431                &mut out,
432                frame.pt(0.30, 0.0),
433                frame.pt(0.50, 0.0),
434                w,
435                &comp.id,
436            );
437            let rect = [
438                frame.pt(-0.30, -0.11),
439                frame.pt(0.30, -0.11),
440                frame.pt(0.30, 0.11),
441                frame.pt(-0.30, 0.11),
442                frame.pt(-0.30, -0.11),
443            ];
444            for pair in rect.windows(2) {
445                push_line(&mut out, pair[0], pair[1], w, &comp.id);
446            }
447        } else {
448            let pts: Vec<CoordNm> = ZIGZAG_POINTS.iter().map(|&(u, v)| frame.pt(u, v)).collect();
449            for pair in pts.windows(2) {
450                push_line(&mut out, pair[0], pair[1], w, &comp.id);
451            }
452        }
453    }
454    out
455}
456
457fn push_line(out: &mut FabLayerItems, start: CoordNm, end: CoordNm, width: i64, comp_id: &str) {
458    if start == end {
459        return;
460    }
461    out.strokes.push(FabStroke {
462        kind: StrokeKind::Virtual,
463        path: StrokePath::Line { start, end },
464        width,
465        net: None,
466        component: Some(comp_id.to_owned()),
467        source: None,
468    });
469}
470
471fn pad_centers_by_comp(
472    view: &FabViewData,
473    side: LayerSide,
474) -> HashMap<&str, HashMap<String, Vec<CoordNm>>> {
475    let layer_key = if side == LayerSide::Bottom {
476        "BOTTOM"
477    } else {
478        "TOP"
479    };
480    let mut map: HashMap<&str, HashMap<String, Vec<CoordNm>>> = HashMap::new();
481    if let Some(items) = view.layers_items.get(layer_key) {
482        for land in &items.lands {
483            let (Some(cid), Some(pin)) = (land.component.as_deref(), land.pin.as_deref()) else {
484                continue;
485            };
486            map.entry(cid)
487                .or_default()
488                .entry(pin.trim().to_ascii_uppercase())
489                .or_default()
490                .push(CoordNm::new(land.placement.tx, land.placement.ty));
491        }
492    }
493    map
494}
495
496fn frame_for_groups(
497    pads: &HashMap<&str, HashMap<String, Vec<CoordNm>>>,
498    comp_id: &str,
499    group_a: &[String],
500    group_b: &[String],
501) -> Option<InterPadFrame> {
502    let by_pin = pads.get(comp_id)?;
503    let ca = group_centroid(by_pin, group_a)?;
504    let cb = group_centroid(by_pin, group_b)?;
505    let dx = cb.0 - ca.0;
506    let dy = cb.1 - ca.1;
507    let span = dx.hypot(dy);
508    if span < 50_000.0 {
509        return None;
510    }
511    let ux = dx / span;
512    let uy = dy / span;
513    Some(InterPadFrame {
514        mid: (0.5 * (ca.0 + cb.0), 0.5 * (ca.1 + cb.1)),
515        ux,
516        uy,
517        vx: -uy,
518        vy: ux,
519        span,
520    })
521}
522
523fn group_centroid(by_pin: &HashMap<String, Vec<CoordNm>>, pins: &[String]) -> Option<(f64, f64)> {
524    let mut sx = 0.0;
525    let mut sy = 0.0;
526    let mut n = 0usize;
527    for pin in pins {
528        if let Some(pts) = by_pin.get(&pin.trim().to_ascii_uppercase()) {
529            for pt in pts {
530                sx += pt.x as f64;
531                sy += pt.y as f64;
532                n += 1;
533            }
534        }
535    }
536    (n > 0).then(|| (sx / n as f64, sy / n as f64))
537}
538
539pub(crate) fn match_pin_list_ci(pins: &[String], raw_list: &str) -> Vec<String> {
540    let targets: Vec<&str> = raw_list
541        .split(',')
542        .map(str::trim)
543        .filter(|s| !s.is_empty())
544        .collect();
545    pins.iter()
546        .filter(|p| targets.iter().any(|t| p.eq_ignore_ascii_case(t)))
547        .cloned()
548        .collect()
549}
550
551fn exclude_pins_ci(pins: &[String], excluded: &[String]) -> Vec<String> {
552    pins.iter()
553        .filter(|p| !excluded.iter().any(|e| e.eq_ignore_ascii_case(p)))
554        .cloned()
555        .collect()
556}
557
558fn split_polarity_pins(
559    comp: &FabComponent,
560    pos_param: Option<&str>,
561    neg_param: Option<&str>,
562    default_pos: &str,
563) -> (Vec<String>, Vec<String>) {
564    let mut pos = pos_param
565        .map(|pp| match_pin_list_ci(&comp.pins, pp))
566        .unwrap_or_default();
567    let mut neg = neg_param
568        .map(|np| match_pin_list_ci(&comp.pins, np))
569        .unwrap_or_default();
570    if pos.is_empty() && neg.is_empty() {
571        pos = comp
572            .pins
573            .iter()
574            .filter(|p| is_pos_pin_token(p))
575            .cloned()
576            .collect();
577        neg = comp
578            .pins
579            .iter()
580            .filter(|p| is_neg_pin_token(p))
581            .cloned()
582            .collect();
583    }
584    let unique_count = {
585        let mut uniq: Vec<String> = comp
586            .pins
587            .iter()
588            .map(|p| p.trim().to_ascii_uppercase())
589            .filter(|p| !p.is_empty())
590            .collect();
591        uniq.sort();
592        uniq.dedup();
593        uniq.len()
594    };
595    if pos.is_empty() && neg.is_empty() {
596        pos = match_pin_list_ci(&comp.pins, default_pos);
597        neg = exclude_pins_ci(&comp.pins, &pos);
598    } else if pos.is_empty() && unique_count == 2 {
599        pos = exclude_pins_ci(&comp.pins, &neg);
600    } else if neg.is_empty() && unique_count == 2 {
601        neg = exclude_pins_ci(&comp.pins, &pos);
602    }
603    (pos, neg)
604}
605
606pub(crate) fn designator_prefix(designator: &str) -> String {
607    designator
608        .trim()
609        .chars()
610        .take_while(char::is_ascii_alphabetic)
611        .collect::<String>()
612        .to_ascii_uppercase()
613}
614
615pub(crate) fn param_ci<'a>(comp: &'a FabComponent, key: &str) -> Option<&'a str> {
616    comp.parameters
617        .iter()
618        .find(|(k, v)| k.eq_ignore_ascii_case(key) && !v.trim().is_empty())
619        .map(|(_, v)| v.trim())
620}
621
622fn text_blob(comp: &FabComponent) -> String {
623    format!("{} {} {}", comp.value, comp.footprint, comp.description).to_ascii_lowercase()
624}
625
626fn has_word(blob: &str, token: &str) -> bool {
627    blob.split(|c: char| !c.is_ascii_alphanumeric())
628        .any(|w| w == token)
629}
630
631fn parse_polarized_token(raw: &str) -> Option<bool> {
632    let tok = raw.trim().to_ascii_lowercase();
633    if matches!(
634        tok.as_str(),
635        "polarized"
636            | "polarised"
637            | "pol"
638            | "tantalum"
639            | "tant"
640            | "electrolytic"
641            | "elec"
642            | "polymer"
643            | "supercap"
644            | "niobium"
645            | "coupled"
646            | "dot"
647            | "start"
648    ) {
649        Some(true)
650    } else if matches!(
651        tok.as_str(),
652        "non_polarized"
653            | "non-polarized"
654            | "nonpolarized"
655            | "unpolarized"
656            | "np"
657            | "bipolar"
658            | "mlcc"
659            | "ceramic"
660            | "film"
661            | "mica"
662            | "standard"
663            | "normal"
664    ) {
665        Some(false)
666    } else {
667        None
668    }
669}
670
671fn is_pos_pin_token(pin: &str) -> bool {
672    matches!(
673        pin.trim().to_ascii_uppercase().as_str(),
674        "+" | "POS" | "POSITIVE" | "A" | "ANODE"
675    )
676}
677
678fn is_neg_pin_token(pin: &str) -> bool {
679    matches!(
680        pin.trim().to_ascii_uppercase().as_str(),
681        "-" | "NEG" | "NEGATIVE" | "K" | "CATHODE"
682    )
683}
684
685pub(crate) fn is_suppress_token(raw: &str) -> bool {
686    matches!(
687        raw.trim().to_ascii_lowercase().as_str(),
688        "none" | "false" | "off" | "no" | "0" | "disable" | "disabled"
689    )
690}
691
692pub(crate) fn pad_min_dim_nm(land: &FabLand) -> i64 {
693    match &land.shape {
694        AreaShape::Disk { radius } => radius * 2,
695        AreaShape::Rect { width, height }
696        | AreaShape::RoundedRect { width, height, .. }
697        | AreaShape::ChamferedRect { width, height, .. }
698        | AreaShape::Trapezoid { width, height, .. } => (*width).min(*height),
699        AreaShape::Capsule { width, .. } => *width,
700        AreaShape::Region { outer, .. } => outer
701            .bounds()
702            .map_or(600_000, |b| (b[2] - b[0]).min(b[3] - b[1])),
703    }
704}
705
706#[cfg(test)]
707mod tests {
708    use super::*;
709
710    #[test]
711    fn non_polarized_caps_and_inductors_are_skipped_by_default() {
712        let pcb = r#"(kicad_pcb (version 20240108) (generator pcbnew)
713          (layers (0 "F.Cu" signal) (31 "B.Cu" signal) (44 "Edge.Cuts" user))
714          (gr_rect (start 0 0) (end 20 20) (stroke (width 0.1)) (layer "Edge.Cuts"))
715          (footprint "Capacitor_SMD:C_0603" (layer "F.Cu") (at 5 10)
716            (property "Reference" "C1" (at 0 0) (layer "F.SilkS"))
717            (property "Value" "100nF X7R" (at 0 0) (layer "F.Fab"))
718            (pad "1" smd rect (at -0.8 0) (size 0.8 0.8) (layers "F.Cu"))
719            (pad "2" smd rect (at 0.8 0) (size 0.8 0.8) (layers "F.Cu")))
720          (footprint "Inductor_SMD:L_0603" (layer "F.Cu") (at 12 10)
721            (property "Reference" "L1" (at 0 0) (layer "F.SilkS"))
722            (property "Value" "1uH" (at 0 0) (layer "F.Fab"))
723            (pad "1" smd rect (at -0.8 0) (size 0.8 0.8) (layers "F.Cu"))
724            (pad "2" smd rect (at 0.8 0) (size 0.8 0.8) (layers "F.Cu"))))"#;
725        let view = FabViewData::from_pcb_source(pcb, "passives_demo").unwrap();
726        assert!(build_capacitors_layer(&view, LayerSide::Top).is_empty());
727        assert!(build_inductors_layer(&view, LayerSide::Top).is_empty());
728        assert!(
729            !build_capacitors_layer_with_options(
730                &view,
731                LayerSide::Top,
732                CapacitorOptions {
733                    include_non_polarized: true,
734                },
735            )
736            .is_empty()
737        );
738        assert!(
739            !build_inductors_layer_with_options(
740                &view,
741                LayerSide::Top,
742                InductorOptions {
743                    include_non_polarized: true,
744                },
745            )
746            .is_empty()
747        );
748    }
749}