1use crate::FabViewData;
4use crate::geom::{
5 AreaShape, CoordNm, FabLayer, FabLayerItems, FabProfile, LayerRole, LayerSide, Placement2D,
6 Ring2D, StrokePath,
7};
8use std::collections::BTreeMap;
9use std::fmt::Write as _;
10
11#[must_use]
13pub fn write_ipc2581(view: &FabViewData) -> String {
14 let mut out = String::with_capacity(16_384);
15 out.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
16 out.push_str("<IPC-2581 revision=\"B\" xmlns=\"http://webstds.ipc.org/2581\">\n");
17 write_content_section(&mut out, view);
18 write_logistic_and_history(&mut out, view);
19 write_bom_section(&mut out, view);
20 write_ecad_section(&mut out, view);
21 out.push_str("</IPC-2581>\n");
22 out
23}
24
25fn write_content_section(out: &mut String, view: &FabViewData) {
26 let name = xml_escape(&view.name);
27 let _ = writeln!(out, " <Content roleRef=\"Owner\">");
28 let _ = writeln!(out, " <FunctionMode mode=\"FULL\" level=\"1\"/>");
29 let _ = writeln!(out, " <StepRef name=\"{name}\"/>");
30 for layer in &view.layers {
31 let _ = writeln!(out, " <LayerRef name=\"{}\"/>", xml_escape(&layer.key));
32 }
33 let _ = writeln!(out, " <BomRef name=\"BOM\"/>");
34 out.push_str(" </Content>\n");
35}
36
37fn write_logistic_and_history(out: &mut String, view: &FabViewData) {
38 let name = xml_escape(&view.name);
39 out.push_str(" <LogisticHeader>\n");
40 out.push_str(" <Role id=\"Owner\" roleFunction=\"DESIGNER\"/>\n");
41 out.push_str(" <Enterprise id=\"ENT1\" code=\"WN\" name=\"KiCad Monkey\"/>\n");
42 out.push_str(
43 " <Person name=\"kicad-monkey-fab\" enterpriseRef=\"ENT1\" roleRef=\"Owner\"/>\n",
44 );
45 out.push_str(" </LogisticHeader>\n");
46 let _ = writeln!(
47 out,
48 " <HistoryRecord number=\"1\" origination=\"2026-01-01T00:00:00Z\" software=\"kicad-monkey-fab\" lastChange=\"2026-01-01T00:00:00Z\" comment=\"Generated for {name}\"/>"
49 );
50}
51
52fn write_bom_section(out: &mut String, view: &FabViewData) {
53 let mut grouped: BTreeMap<(String, String), Vec<(&str, &str)>> = BTreeMap::new();
54 for comp in &view.components {
55 if !comp.fitted || comp.exclude_from_bom || comp.board_only {
56 continue;
57 }
58 grouped
59 .entry((comp.value.clone(), comp.footprint.clone()))
60 .or_default()
61 .push((comp.designator.as_str(), comp.description.as_str()));
62 }
63 out.push_str(" <Bom name=\"BOM\">\n");
64 out.push_str(" <BomHeader assembly=\"MAIN\" revision=\"1\"/>\n");
65 for ((val, fp), refs) in grouped {
66 let oem = xml_escape(&format!("{val}::{fp}"));
67 let desc = xml_escape(refs.first().map_or("", |r| r.1));
68 let _ = writeln!(
69 out,
70 " <BomItem OEMDesignNumberRef=\"{oem}\" quantity=\"{}\" category=\"ELECTRICAL\" description=\"{desc}\">",
71 refs.len()
72 );
73 for (des, _) in refs {
74 let _ = writeln!(
75 out,
76 " <RefDes name=\"{}\" populate=\"true\"/>",
77 xml_escape(des)
78 );
79 }
80 out.push_str(" </BomItem>\n");
81 }
82 out.push_str(" </Bom>\n");
83}
84
85fn write_ecad_section(out: &mut String, view: &FabViewData) {
86 let step_name = xml_escape(&view.name);
87 out.push_str(" <Ecad name=\"ECAD\">\n");
88 out.push_str(" <CadHeader units=\"MILLIMETER\"/>\n");
89 out.push_str(" <CadData>\n");
90 for layer in &view.layers {
91 let (fn_name, side_name) = ipc_layer_attrs(layer);
92 let pol = if layer.positive {
93 "POSITIVE"
94 } else {
95 "NEGATIVE"
96 };
97 let _ = writeln!(
98 out,
99 " <Layer name=\"{}\" layerFunction=\"{fn_name}\" side=\"{side_name}\" polarity=\"{pol}\"/>",
100 xml_escape(&layer.key)
101 );
102 }
103 write_stackup(out, view);
104 let _ = writeln!(out, " <Step name=\"{step_name}\">");
105 if let Some(profile) = view.profile.as_ref() {
106 write_profile(out, profile);
107 }
108 write_components(out, view);
109 for layer in &view.layers {
110 if let Some(items) = view.layers_items.get(&layer.key)
111 && !items.is_empty()
112 {
113 write_layer_features(out, &layer.key, items);
114 }
115 }
116 write_drill_features(out, view);
117 out.push_str(" </Step>\n");
118 out.push_str(" </CadData>\n");
119 out.push_str(" </Ecad>\n");
120}
121
122fn write_stackup(out: &mut String, view: &FabViewData) {
123 let total_mm = view.thickness_nm as f64 / 1e6;
124 let _ = writeln!(
125 out,
126 " <Stackup name=\"PRIMARY\" overallThickness=\"{total_mm:.4}\" tolPlus=\"0.1\" tolMinus=\"0.1\" whereMeasured=\"METAL\">"
127 );
128 let _ = writeln!(
129 out,
130 " <StackupGroup name=\"GROUP1\" thickness=\"{total_mm:.4}\" tolPlus=\"0.1\" tolMinus=\"0.1\">"
131 );
132 for (idx, row) in view.stackup.iter().enumerate() {
133 let lref = row.layer_key.as_deref().unwrap_or(row.name.as_str());
134 let _ = writeln!(
135 out,
136 " <StackupLayer layerOrGroupRef=\"{}\" thickness=\"{:.4}\" sequence=\"{}\"/>",
137 xml_escape(lref),
138 row.thickness_nm as f64 / 1e6,
139 idx + 1
140 );
141 }
142 out.push_str(" </StackupGroup>\n");
143 out.push_str(" </Stackup>\n");
144}
145
146fn write_profile(out: &mut String, profile: &FabProfile) {
147 out.push_str(" <Profile>\n");
148 write_polygon_xml(out, " ", &profile.outer, Placement2D::identity());
149 for cutout in &profile.cutouts {
150 out.push_str(" <Cutout>\n");
151 write_polygon_xml(out, " ", cutout, Placement2D::identity());
152 out.push_str(" </Cutout>\n");
153 }
154 out.push_str(" </Profile>\n");
155}
156
157fn write_components(out: &mut String, view: &FabViewData) {
158 for comp in &view.components {
159 if comp.board_only {
160 continue;
161 }
162 let side = if comp.side == LayerSide::Bottom {
163 "BOTTOM"
164 } else {
165 "TOP"
166 };
167 let _ = writeln!(
168 out,
169 " <Component refDes=\"{}\" packageRef=\"{}\" part=\"{}\" layerRef=\"{side}\">",
170 xml_escape(&comp.designator),
171 xml_escape(&comp.footprint),
172 xml_escape(&comp.value),
173 );
174 let _ = writeln!(
175 out,
176 " <Xform rotation=\"{:.3}\"/>",
177 comp.rotation_deg
178 );
179 let _ = writeln!(
180 out,
181 " <Location x=\"{:.4}\" y=\"{:.4}\"/>",
182 comp.center.x as f64 / 1e6,
183 comp.center.y as f64 / 1e6
184 );
185 out.push_str(" </Component>\n");
186 }
187}
188
189fn write_layer_features(out: &mut String, key: &str, items: &FabLayerItems) {
190 let _ = writeln!(
191 out,
192 " <LayerFeature layerRef=\"{}\">",
193 xml_escape(key)
194 );
195 out.push_str(" <Set>\n");
196 for area in &items.areas {
197 match &area.shape {
198 AreaShape::Region { outer, .. } => {
199 out.push_str(" <Features>\n");
200 write_polygon_xml(out, " ", outer, area.placement);
201 out.push_str(" </Features>\n");
202 }
203 AreaShape::Disk { radius } if *radius > 0 => {
204 let _ = writeln!(
205 out,
206 " <Features><Location x=\"{:.4}\" y=\"{:.4}\"/><Circle diameter=\"{:.4}\"/></Features>",
207 area.placement.tx as f64 / 1e6,
208 area.placement.ty as f64 / 1e6,
209 (*radius as f64 * 2.0) / 1e6
210 );
211 }
212 _ => {}
213 }
214 }
215 for stroke in &items.strokes {
216 let w = (stroke.width.max(10_000) as f64) / 1e6;
217 match stroke.path {
218 StrokePath::Line { start, end } => {
219 let _ = writeln!(
220 out,
221 " <Features><Line startX=\"{:.4}\" startY=\"{:.4}\" endX=\"{:.4}\" endY=\"{:.4}\"><LineDesc lineEnd=\"ROUND\" lineWidth=\"{w:.4}\"/></Line></Features>",
222 start.x as f64 / 1e6,
223 start.y as f64 / 1e6,
224 end.x as f64 / 1e6,
225 end.y as f64 / 1e6
226 );
227 }
228 StrokePath::Arc {
229 start,
230 end,
231 center,
232 ccw,
233 ..
234 } => {
235 let cw = if ccw { "false" } else { "true" };
236 let _ = writeln!(
237 out,
238 " <Features><Arc startX=\"{:.4}\" startY=\"{:.4}\" endX=\"{:.4}\" endY=\"{:.4}\" centerX=\"{:.4}\" centerY=\"{:.4}\" clockwise=\"{cw}\"><LineDesc lineEnd=\"ROUND\" lineWidth=\"{w:.4}\"/></Arc></Features>",
239 start.x as f64 / 1e6,
240 start.y as f64 / 1e6,
241 end.x as f64 / 1e6,
242 end.y as f64 / 1e6,
243 center.x as f64 / 1e6,
244 center.y as f64 / 1e6
245 );
246 }
247 StrokePath::FullCircle { center, radius } => {
248 let _ = writeln!(
249 out,
250 " <Features><Circle diameter=\"{:.4}\"><LineDesc lineEnd=\"ROUND\" lineWidth=\"{w:.4}\"/><Location x=\"{:.4}\" y=\"{:.4}\"/></Circle></Features>",
251 (radius * 2) as f64 / 1e6,
252 center.x as f64 / 1e6,
253 center.y as f64 / 1e6
254 );
255 }
256 }
257 }
258 for land in &items.lands {
259 let _ = writeln!(
260 out,
261 " <Pad><Location x=\"{:.4}\" y=\"{:.4}\"/><Xform rotation=\"{:.3}\"/>{}</Pad>",
262 land.placement.tx as f64 / 1e6,
263 land.placement.ty as f64 / 1e6,
264 land.placement.angle_deg,
265 ipc_pad_primitive(&land.shape)
266 );
267 }
268 out.push_str(" </Set>\n");
269 out.push_str(" </LayerFeature>\n");
270}
271
272fn write_drill_features(out: &mut String, view: &FabViewData) {
273 if view.holes.is_empty() {
274 return;
275 }
276 out.push_str(" <LayerFeature layerRef=\"DRILL\">\n");
277 out.push_str(" <Set>\n");
278 for hole in &view.holes {
279 let status = if hole.plated { "PLATED" } else { "NONPLATED" };
280 let _ = writeln!(
281 out,
282 " <Hole name=\"{}\" diameter=\"{:.4}\" platingStatus=\"{status}\" plusTol=\"0.05\" minusTol=\"0.05\" x=\"{:.4}\" y=\"{:.4}\"/>",
283 xml_escape(&hole.id),
284 hole.diameter as f64 / 1e6,
285 hole.center.x as f64 / 1e6,
286 hole.center.y as f64 / 1e6
287 );
288 }
289 out.push_str(" </Set>\n");
290 out.push_str(" </LayerFeature>\n");
291}
292
293fn write_polygon_xml(out: &mut String, indent: &str, ring: &Ring2D, pl: Placement2D) {
294 let pts = ring.flatten_polygon(24);
295 let Some(first) = pts.first().copied() else {
296 return;
297 };
298 let f = pl.transform(first.x as f64, first.y as f64);
299 let _ = writeln!(out, "{indent}<Polygon>");
300 let _ = writeln!(
301 out,
302 "{indent} <PolyBegin x=\"{:.4}\" y=\"{:.4}\"/>",
303 f.x as f64 / 1e6,
304 f.y as f64 / 1e6
305 );
306 for &pt in pts.iter().skip(1) {
307 let p: CoordNm = pl.transform(pt.x as f64, pt.y as f64);
308 let _ = writeln!(
309 out,
310 "{indent} <PolyStepSegment x=\"{:.4}\" y=\"{:.4}\"/>",
311 p.x as f64 / 1e6,
312 p.y as f64 / 1e6
313 );
314 }
315 let _ = writeln!(
316 out,
317 "{indent} <PolyStepSegment x=\"{:.4}\" y=\"{:.4}\"/>",
318 f.x as f64 / 1e6,
319 f.y as f64 / 1e6
320 );
321 let _ = writeln!(out, "{indent}</Polygon>");
322}
323
324fn ipc_pad_primitive(shape: &AreaShape) -> String {
325 match shape {
326 AreaShape::Disk { radius } => {
327 format!("<Circle diameter=\"{:.4}\"/>", (*radius * 2) as f64 / 1e6)
328 }
329 AreaShape::Rect { width, height } | AreaShape::Trapezoid { width, height, .. } => {
330 format!(
331 "<RectCenter width=\"{:.4}\" height=\"{:.4}\"/>",
332 *width as f64 / 1e6,
333 *height as f64 / 1e6
334 )
335 }
336 AreaShape::Capsule { length, width } => {
337 format!(
338 "<Oval width=\"{:.4}\" height=\"{:.4}\"/>",
339 *length as f64 / 1e6,
340 *width as f64 / 1e6
341 )
342 }
343 AreaShape::RoundedRect {
344 width,
345 height,
346 radius,
347 } => {
348 format!(
349 "<RectRound width=\"{:.4}\" height=\"{:.4}\" radius=\"{:.4}\"/>",
350 *width as f64 / 1e6,
351 *height as f64 / 1e6,
352 *radius as f64 / 1e6
353 )
354 }
355 AreaShape::ChamferedRect {
356 width,
357 height,
358 chamfer,
359 ..
360 } => {
361 format!(
362 "<RectCham width=\"{:.4}\" height=\"{:.4}\" chamfer=\"{:.4}\"/>",
363 *width as f64 / 1e6,
364 *height as f64 / 1e6,
365 *chamfer as f64 / 1e6
366 )
367 }
368 AreaShape::Region { .. } => "<Circle diameter=\"0.2000\"/>".to_owned(),
369 }
370}
371
372fn ipc_layer_attrs(layer: &FabLayer) -> (&'static str, &'static str) {
373 let fn_name = match layer.role {
374 LayerRole::Conductor => "CONDUCTOR",
375 LayerRole::SolderMask => "SOLDERMASK",
376 LayerRole::Paste => "SOLDERPASTE",
377 LayerRole::Silkscreen => "SILKSCREEN",
378 LayerRole::Profile => "BOARD_OUTLINE",
379 LayerRole::Mechanical | LayerRole::Virtual => "DOCUMENT",
380 };
381 let side = match layer.side {
382 LayerSide::Top => "TOP",
383 LayerSide::Bottom => "BOTTOM",
384 LayerSide::Internal => "INTERNAL",
385 LayerSide::None => "NONE",
386 };
387 (fn_name, side)
388}
389
390fn xml_escape(input: &str) -> String {
391 let mut out = String::with_capacity(input.len());
392 for ch in input.chars() {
393 match ch {
394 '&' => out.push_str("&"),
395 '<' => out.push_str("<"),
396 '>' => out.push_str(">"),
397 '"' => out.push_str("""),
398 '\'' => out.push_str("'"),
399 _ => out.push(ch),
400 }
401 }
402 out
403}