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

kicad_monkey_fab/
svg.rs

1//! Analytic composite and per-layer SVG writers over canonical `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::{FabFile, FabViewData};
8use std::fmt::Write as _;
9
10/// SVG export options.
11#[derive(Clone, Debug)]
12pub struct SvgOptions {
13    pub stem: String,
14    pub bottom: bool,
15    pub padding_mm: f64,
16    pub include_silk: bool,
17}
18
19impl Default for SvgOptions {
20    fn default() -> Self {
21        Self {
22            stem: "board".to_owned(),
23            bottom: false,
24            padding_mm: 2.0,
25            include_silk: true,
26        }
27    }
28}
29
30/// Render a composite board SVG (substrate, copper, mask tint, silk, drills).
31#[must_use]
32pub fn write_composite_svg(view: &FabViewData, opts: &SvgOptions) -> String {
33    let bounds = view.bounds_nm().unwrap_or([0, 0, 10_000_000, 10_000_000]);
34    let pad = (opts.padding_mm * 1_000_000.0).round() as i64;
35    let vx = (bounds[0] - pad) as f64 / 1_000_000.0;
36    let vy = (-(bounds[3] + pad)) as f64 / 1_000_000.0;
37    let vw = ((bounds[2] - bounds[0]) + 2 * pad).max(1_000_000) as f64 / 1_000_000.0;
38    let vh = ((bounds[3] - bounds[1]) + 2 * pad).max(1_000_000) as f64 / 1_000_000.0;
39
40    let (cu_key, mask_key, silk_key) = if opts.bottom {
41        ("BOTTOM", "BOTTOMSOLDER", "BOTTOMOVERLAY")
42    } else {
43        ("TOP", "TOPSOLDER", "TOPOVERLAY")
44    };
45
46    let mut out = String::with_capacity(8192);
47    let _ = writeln!(
48        out,
49        "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"{vx:.4} {vy:.4} {vw:.4} {vh:.4}\" width=\"{vw:.3}mm\" height=\"{vh:.3}mm\">"
50    );
51    let _ = writeln!(
52        out,
53        "  <rect x=\"{vx:.4}\" y=\"{vy:.4}\" width=\"{vw:.4}\" height=\"{vh:.4}\" fill=\"#11151a\"/>"
54    );
55
56    if let Some(profile) = view.profile.as_ref() {
57        let d = profile_path_d(profile);
58        let _ = writeln!(
59            out,
60            "  <g id=\"substrate\"><path d=\"{d}\" fill=\"#1a4d2e\" fill-rule=\"evenodd\" stroke=\"#c9d1d9\" stroke-width=\"0.12\"/></g>"
61        );
62    }
63
64    if let Some(items) = view.layers_items.get(cu_key) {
65        let _ = writeln!(out, "  <g id=\"copper-{cu_key}\">");
66        write_layer_items_svg(&mut out, items, "#c89d42");
67        out.push_str("  </g>\n");
68    }
69
70    if let Some(items) = view.layers_items.get(mask_key) {
71        let _ = writeln!(out, "  <g id=\"mask-{mask_key}\" opacity=\"0.85\">");
72        write_layer_items_svg(&mut out, items, "#e5c158");
73        out.push_str("  </g>\n");
74    }
75
76    if opts.include_silk
77        && let Some(items) = view.layers_items.get(silk_key)
78    {
79        let _ = writeln!(out, "  <g id=\"silk-{silk_key}\">");
80        write_layer_items_svg(&mut out, items, "#f0f3f6");
81        out.push_str("  </g>\n");
82    }
83
84    if !view.holes.is_empty() {
85        out.push_str("  <g id=\"drills\">\n");
86        for hole in &view.holes {
87            if let Some((p0, p1)) = hole.slot_rout {
88                let _ = writeln!(
89                    out,
90                    "    <line x1=\"{:.4}\" y1=\"{:.4}\" x2=\"{:.4}\" y2=\"{:.4}\" stroke=\"#11151a\" stroke-width=\"{:.4}\" stroke-linecap=\"round\"/>",
91                    p0.x as f64 / 1e6,
92                    -(p0.y as f64) / 1e6,
93                    p1.x as f64 / 1e6,
94                    -(p1.y as f64) / 1e6,
95                    hole.diameter as f64 / 1e6
96                );
97            } else {
98                let _ = writeln!(
99                    out,
100                    "    <circle cx=\"{:.4}\" cy=\"{:.4}\" r=\"{:.4}\" fill=\"#11151a\"/>",
101                    hole.center.x as f64 / 1e6,
102                    -(hole.center.y as f64) / 1e6,
103                    (hole.diameter as f64 / 2.0) / 1e6
104                );
105            }
106        }
107        out.push_str("  </g>\n");
108    }
109
110    out.push_str("</svg>\n");
111    out
112}
113
114/// Render individual per-layer SVG files for all non-empty manufacturing layers.
115#[must_use]
116pub fn write_layer_svgs(view: &FabViewData, opts: &SvgOptions) -> Vec<FabFile> {
117    let bounds = view.bounds_nm().unwrap_or([0, 0, 10_000_000, 10_000_000]);
118    let pad = (opts.padding_mm * 1_000_000.0).round() as i64;
119    let vx = (bounds[0] - pad) as f64 / 1_000_000.0;
120    let vy = (-(bounds[3] + pad)) as f64 / 1_000_000.0;
121    let vw = ((bounds[2] - bounds[0]) + 2 * pad).max(1_000_000) as f64 / 1_000_000.0;
122    let vh = ((bounds[3] - bounds[1]) + 2 * pad).max(1_000_000) as f64 / 1_000_000.0;
123
124    let mut files = Vec::new();
125    for layer in &view.layers {
126        if layer.role == LayerRole::Profile {
127            if let Some(profile) = view.profile.as_ref() {
128                let svg = format!(
129                    "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"{vx:.4} {vy:.4} {vw:.4} {vh:.4}\" width=\"{vw:.3}mm\" height=\"{vh:.3}mm\">\n  <path d=\"{}\" fill=\"none\" stroke=\"#eab308\" stroke-width=\"0.15\"/>\n</svg>\n",
130                    profile_path_d(profile)
131                );
132                files.push(FabFile {
133                    name: format!("{}-{}.svg", opts.stem, layer.key),
134                    data: svg.into_bytes(),
135                    key: Some(layer.key.clone()),
136                    role: "svg_layer".to_owned(),
137                    plated: None,
138                    span: None,
139                });
140            }
141            continue;
142        }
143        let Some(items) = view.layers_items.get(&layer.key) else {
144            continue;
145        };
146        if items.is_empty() {
147            continue;
148        }
149        let color = layer_color(layer);
150        let mut svg = String::with_capacity(4096);
151        let _ = writeln!(
152            svg,
153            "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"{vx:.4} {vy:.4} {vw:.4} {vh:.4}\" width=\"{vw:.3}mm\" height=\"{vh:.3}mm\">"
154        );
155        let _ = writeln!(
156            svg,
157            "  <rect x=\"{vx:.4}\" y=\"{vy:.4}\" width=\"{vw:.4}\" height=\"{vh:.4}\" fill=\"#0d1117\"/>"
158        );
159        write_layer_items_svg(&mut svg, items, color);
160        svg.push_str("</svg>\n");
161        files.push(FabFile {
162            name: format!("{}-{}.svg", opts.stem, layer.key),
163            data: svg.into_bytes(),
164            key: Some(layer.key.clone()),
165            role: "svg_layer".to_owned(),
166            plated: None,
167            span: None,
168        });
169    }
170    files
171}
172
173fn layer_color(layer: &FabLayer) -> &'static str {
174    match (layer.role, layer.side) {
175        (LayerRole::Conductor, LayerSide::Top) => "#ef4444",
176        (LayerRole::Conductor, LayerSide::Bottom) => "#3b82f6",
177        (LayerRole::Conductor, _) => "#f59e0b",
178        (LayerRole::SolderMask, _) => "#a855f7",
179        (LayerRole::Paste, _) => "#94a3b8",
180        (LayerRole::Silkscreen, _) => "#f8fafc",
181        _ => "#22c55e",
182    }
183}
184
185fn write_layer_items_svg(out: &mut String, items: &FabLayerItems, color: &str) {
186    for area in &items.areas {
187        write_area_svg(out, area, color);
188    }
189    for stroke in &items.strokes {
190        write_stroke_svg(out, stroke, color);
191    }
192    for land in &items.lands {
193        write_land_svg(out, land, color);
194    }
195}
196
197fn write_land_svg(out: &mut String, land: &FabLand, color: &str) {
198    write_shape_svg(out, &land.shape, land.placement, color);
199}
200
201fn write_area_svg(out: &mut String, area: &FabArea, color: &str) {
202    write_shape_svg(out, &area.shape, area.placement, color);
203}
204
205fn write_shape_svg(out: &mut String, shape: &AreaShape, pl: Placement2D, color: &str) {
206    match shape {
207        AreaShape::Disk { radius } => {
208            let _ = writeln!(
209                out,
210                "    <circle cx=\"{:.4}\" cy=\"{:.4}\" r=\"{:.4}\" fill=\"{color}\"/>",
211                pl.tx as f64 / 1e6,
212                -(pl.ty as f64) / 1e6,
213                *radius as f64 / 1e6
214            );
215        }
216        AreaShape::Rect { width, height } => {
217            let w = *width as f64 / 1e6;
218            let h = *height as f64 / 1e6;
219            let tf = svg_transform(pl);
220            let _ = writeln!(
221                out,
222                "    <rect x=\"{:.4}\" y=\"{:.4}\" width=\"{w:.4}\" height=\"{h:.4}\" fill=\"{color}\"{tf}/>",
223                -w / 2.0,
224                -h / 2.0
225            );
226        }
227        AreaShape::Capsule { length, width } => {
228            let w = *length as f64 / 1e6;
229            let h = *width as f64 / 1e6;
230            let r = (w.min(h)) / 2.0;
231            let tf = svg_transform(pl);
232            let _ = writeln!(
233                out,
234                "    <rect x=\"{:.4}\" y=\"{:.4}\" width=\"{w:.4}\" height=\"{h:.4}\" rx=\"{r:.4}\" ry=\"{r:.4}\" fill=\"{color}\"{tf}/>",
235                -w / 2.0,
236                -h / 2.0
237            );
238        }
239        AreaShape::RoundedRect {
240            width,
241            height,
242            radius,
243        } => {
244            let w = *width as f64 / 1e6;
245            let h = *height as f64 / 1e6;
246            let r = (*radius as f64 / 1e6).min(w.min(h) / 2.0);
247            let tf = svg_transform(pl);
248            let _ = writeln!(
249                out,
250                "    <rect x=\"{:.4}\" y=\"{:.4}\" width=\"{w:.4}\" height=\"{h:.4}\" rx=\"{r:.4}\" ry=\"{r:.4}\" fill=\"{color}\"{tf}/>",
251                -w / 2.0,
252                -h / 2.0
253            );
254        }
255        AreaShape::ChamferedRect {
256            width,
257            height,
258            chamfer,
259            corners,
260        } => {
261            let pts = chamfered_rect_points(*width, *height, *chamfer, *corners, pl);
262            write_polygon_svg(out, &pts, color);
263        }
264        AreaShape::Trapezoid {
265            width,
266            height,
267            delta_x,
268            delta_y,
269        } => {
270            let hw = *width as f64 / 2.0;
271            let hh = *height as f64 / 2.0;
272            let dx = *delta_x as f64 / 2.0;
273            let dy = *delta_y as f64 / 2.0;
274            let pts = [
275                pl.transform(-hw - dy, -hh - dx),
276                pl.transform(hw + dy, -hh + dx),
277                pl.transform(hw - dy, hh - dx),
278                pl.transform(-hw + dy, hh + dx),
279            ];
280            write_polygon_svg(out, &pts, color);
281        }
282        AreaShape::Region { outer, holes } => {
283            let mut d = ring_path_d(outer, pl);
284            for h in holes {
285                d.push(' ');
286                d.push_str(&ring_path_d(h, pl));
287            }
288            let _ = writeln!(
289                out,
290                "    <path d=\"{d}\" fill=\"{color}\" fill-rule=\"evenodd\"/>"
291            );
292        }
293    }
294}
295
296fn write_stroke_svg(out: &mut String, stroke: &FabStroke, color: &str) {
297    let w = (stroke.width.max(10_000) as f64) / 1e6;
298    match stroke.path {
299        StrokePath::Line { start, end } => {
300            let _ = writeln!(
301                out,
302                "    <line x1=\"{:.4}\" y1=\"{:.4}\" x2=\"{:.4}\" y2=\"{:.4}\" stroke=\"{color}\" stroke-width=\"{w:.4}\" stroke-linecap=\"round\"/>",
303                start.x as f64 / 1e6,
304                -(start.y as f64) / 1e6,
305                end.x as f64 / 1e6,
306                -(end.y as f64) / 1e6
307            );
308        }
309        StrokePath::Arc {
310            start,
311            end,
312            center,
313            ccw,
314            major,
315        } => {
316            let r = ((start.x - center.x) as f64).hypot((start.y - center.y) as f64) / 1e6;
317            // In SVG (+Y down), CCW in +Y-up corresponds to sweep=0.
318            let sweep = if ccw { 0 } else { 1 };
319            let large = i32::from(major);
320            let _ = writeln!(
321                out,
322                "    <path d=\"M{:.4},{:.4} A{r:.4},{r:.4} 0 {large},{sweep} {:.4},{:.4}\" fill=\"none\" stroke=\"{color}\" stroke-width=\"{w:.4}\" stroke-linecap=\"round\"/>",
323                start.x as f64 / 1e6,
324                -(start.y as f64) / 1e6,
325                end.x as f64 / 1e6,
326                -(end.y as f64) / 1e6
327            );
328        }
329        StrokePath::FullCircle { center, radius } => {
330            let _ = writeln!(
331                out,
332                "    <circle cx=\"{:.4}\" cy=\"{:.4}\" r=\"{:.4}\" fill=\"none\" stroke=\"{color}\" stroke-width=\"{w:.4}\"/>",
333                center.x as f64 / 1e6,
334                -(center.y as f64) / 1e6,
335                radius as f64 / 1e6
336            );
337        }
338    }
339}
340
341fn svg_transform(pl: Placement2D) -> String {
342    let tx = pl.tx as f64 / 1e6;
343    let ty = -(pl.ty as f64) / 1e6;
344    if pl.angle_deg.abs() < 1e-6 {
345        format!(" transform=\"translate({tx:.4},{ty:.4})\"")
346    } else {
347        format!(
348            " transform=\"translate({tx:.4},{ty:.4}) rotate({:.4})\"",
349            -pl.angle_deg
350        )
351    }
352}
353
354fn write_polygon_svg(out: &mut String, pts: &[CoordNm], color: &str) {
355    if pts.len() < 3 {
356        return;
357    }
358    let mut s = String::with_capacity(pts.len() * 18);
359    for (i, pt) in pts.iter().enumerate() {
360        if i > 0 {
361            s.push(' ');
362        }
363        let _ = write!(s, "{:.4},{:.4}", pt.x as f64 / 1e6, -(pt.y as f64) / 1e6);
364    }
365    let _ = writeln!(out, "    <polygon points=\"{s}\" fill=\"{color}\"/>");
366}
367
368fn profile_path_d(profile: &FabProfile) -> String {
369    let mut d = ring_path_d(&profile.outer, Placement2D::identity());
370    for cutout in &profile.cutouts {
371        d.push(' ');
372        d.push_str(&ring_path_d(cutout, Placement2D::identity()));
373    }
374    d
375}
376
377fn ring_path_d(ring: &Ring2D, pl: Placement2D) -> String {
378    let n = ring.points.len();
379    if n < 2 {
380        return String::new();
381    }
382    let xf = |p: CoordNm| -> CoordNm { pl.transform(p.x as f64, p.y as f64) };
383    let first = xf(ring.points[0]);
384    let mut d = format!(
385        "M{:.4},{:.4}",
386        first.x as f64 / 1e6,
387        -(first.y as f64) / 1e6
388    );
389    for i in 0..n {
390        let p0 = xf(ring.points[i]);
391        let p1 = xf(ring.points[(i + 1) % n]);
392        match ring.segs.get(i).copied().unwrap_or(RingSeg::Line) {
393            RingSeg::Line => {
394                let _ = write!(d, " L{:.4},{:.4}", p1.x as f64 / 1e6, -(p1.y as f64) / 1e6);
395            }
396            RingSeg::Arc { center, ccw, major } => {
397                let c = xf(center);
398                let r = ((p0.x - c.x) as f64).hypot((p0.y - c.y) as f64) / 1e6;
399                let sweep = if ccw { 0 } else { 1 };
400                let large = i32::from(major);
401                let _ = write!(
402                    d,
403                    " A{r:.4},{r:.4} 0 {large},{sweep} {:.4},{:.4}",
404                    p1.x as f64 / 1e6,
405                    -(p1.y as f64) / 1e6
406                );
407            }
408        }
409    }
410    d.push('Z');
411    d
412}
413
414fn chamfered_rect_points(
415    width: i64,
416    height: i64,
417    chamfer: i64,
418    corners: ChamferCorners,
419    pl: Placement2D,
420) -> Vec<CoordNm> {
421    let hw = width as f64 / 2.0;
422    let hh = height as f64 / 2.0;
423    let c = (chamfer as f64).min(hw).min(hh).max(0.0);
424    let mut local = Vec::with_capacity(8);
425    if corners.lower_left && c > 0.0 {
426        local.push((-hw, -hh + c));
427        local.push((-hw + c, -hh));
428    } else {
429        local.push((-hw, -hh));
430    }
431    if corners.lower_right && c > 0.0 {
432        local.push((hw - c, -hh));
433        local.push((hw, -hh + c));
434    } else {
435        local.push((hw, -hh));
436    }
437    if corners.upper_right && c > 0.0 {
438        local.push((hw, hh - c));
439        local.push((hw - c, hh));
440    } else {
441        local.push((hw, hh));
442    }
443    if corners.upper_left && c > 0.0 {
444        local.push((-hw + c, hh));
445        local.push((-hw, hh - c));
446    } else {
447        local.push((-hw, hh));
448    }
449    local.into_iter().map(|(x, y)| pl.transform(x, y)).collect()
450}