1use crate::FabViewData;
4use crate::designator_fit::{DesignatorFitSession, pad_envelope, ring_polygon, subtract_cutouts};
5use crate::geom::{
6 AreaShape, CoordNm, FabComponent, FabLand, FabLayerItems, FabStroke, LayerSide, RingSeg,
7 StrokeKind, StrokePath, mm_to_nm,
8};
9use crate::view::text::realize_stroke_label;
10use geo::{ConvexHull, MultiPolygon, Polygon};
11use std::collections::HashMap;
12
13pub const ALL_VIRTUAL_LAYERS: [&str; 17] = [
15 "CUTOUTS",
16 "PIN1_TOP",
17 "PIN1_BOTTOM",
18 "DIODES_TOP",
19 "DIODES_BOTTOM",
20 "CAPACITORS_TOP",
21 "CAPACITORS_BOTTOM",
22 "INDUCTORS_TOP",
23 "INDUCTORS_BOTTOM",
24 "RESISTORS_TOP",
25 "RESISTORS_BOTTOM",
26 "ASSEMBLY_OUTLINES_TOP",
27 "ASSEMBLY_OUTLINES_BOTTOM",
28 "ASSEMBLY_DESIGNATORS_TOP",
29 "ASSEMBLY_DESIGNATORS_BOTTOM",
30 "PAD_LABELS_TOP",
31 "PAD_LABELS_BOTTOM",
32];
33
34#[must_use]
36pub fn resolve_virtual_layer_key(name: &str) -> Option<&'static str> {
37 let norm: String = name.trim().to_ascii_uppercase().replace(['-', ' '], "_");
38 match norm.as_str() {
39 "CUTOUTS" | "BOARD_CUTOUTS" => Some("CUTOUTS"),
40 "PIN1_TOP" | "PIN_1_TOP" => Some("PIN1_TOP"),
41 "PIN1_BOTTOM" | "PIN_1_BOTTOM" => Some("PIN1_BOTTOM"),
42 "DIODES_TOP" => Some("DIODES_TOP"),
43 "DIODES_BOTTOM" => Some("DIODES_BOTTOM"),
44 "CAPACITORS_TOP" | "CAPS_TOP" => Some("CAPACITORS_TOP"),
45 "CAPACITORS_BOTTOM" | "CAPS_BOTTOM" => Some("CAPACITORS_BOTTOM"),
46 "INDUCTORS_TOP" => Some("INDUCTORS_TOP"),
47 "INDUCTORS_BOTTOM" => Some("INDUCTORS_BOTTOM"),
48 "RESISTORS_TOP" => Some("RESISTORS_TOP"),
49 "RESISTORS_BOTTOM" => Some("RESISTORS_BOTTOM"),
50 "ASSEMBLY_OUTLINES_TOP" | "ASSY_OUTLINES_TOP" => Some("ASSEMBLY_OUTLINES_TOP"),
51 "ASSEMBLY_OUTLINES_BOTTOM" | "ASSY_OUTLINES_BOTTOM" => Some("ASSEMBLY_OUTLINES_BOTTOM"),
52 "ASSEMBLY_DESIGNATORS_TOP" | "ASSY_DESIGNATORS_TOP" => Some("ASSEMBLY_DESIGNATORS_TOP"),
53 "ASSEMBLY_DESIGNATORS_BOTTOM" | "ASSY_DESIGNATORS_BOTTOM" => {
54 Some("ASSEMBLY_DESIGNATORS_BOTTOM")
55 }
56 "PAD_LABELS_TOP" => Some("PAD_LABELS_TOP"),
57 "PAD_LABELS_BOTTOM" => Some("PAD_LABELS_BOTTOM"),
58 _ => None,
59 }
60}
61
62#[must_use]
64pub fn build_virtual_layer(view: &FabViewData, canonical_key: &str) -> FabLayerItems {
65 match canonical_key {
66 "CUTOUTS" => build_cutouts(view),
67 "PIN1_TOP" => crate::pin1::build_pin1_layer(
68 view,
69 LayerSide::Top,
70 &crate::pin1::Pin1Options::default(),
71 ),
72 "PIN1_BOTTOM" => crate::pin1::build_pin1_layer(
73 view,
74 LayerSide::Bottom,
75 &crate::pin1::Pin1Options::default(),
76 ),
77 "DIODES_TOP" => crate::diodes::build_diodes_layer(
78 view,
79 LayerSide::Top,
80 &crate::diodes::DiodeOptions::default(),
81 ),
82 "DIODES_BOTTOM" => crate::diodes::build_diodes_layer(
83 view,
84 LayerSide::Bottom,
85 &crate::diodes::DiodeOptions::default(),
86 ),
87 "CAPACITORS_TOP" => crate::passives::build_capacitors_layer(view, LayerSide::Top),
88 "CAPACITORS_BOTTOM" => crate::passives::build_capacitors_layer(view, LayerSide::Bottom),
89 "INDUCTORS_TOP" => crate::passives::build_inductors_layer(view, LayerSide::Top),
90 "INDUCTORS_BOTTOM" => crate::passives::build_inductors_layer(view, LayerSide::Bottom),
91 "RESISTORS_TOP" => crate::passives::build_resistors_layer(view, LayerSide::Top),
92 "RESISTORS_BOTTOM" => crate::passives::build_resistors_layer(view, LayerSide::Bottom),
93 "ASSEMBLY_OUTLINES_TOP" => build_assembly_outlines(view, LayerSide::Top),
94 "ASSEMBLY_OUTLINES_BOTTOM" => build_assembly_outlines(view, LayerSide::Bottom),
95 "ASSEMBLY_DESIGNATORS_TOP" => build_assembly_designators(view, LayerSide::Top),
96 "ASSEMBLY_DESIGNATORS_BOTTOM" => build_assembly_designators(view, LayerSide::Bottom),
97 "PAD_LABELS_TOP" => build_pad_labels(view, LayerSide::Top),
98 "PAD_LABELS_BOTTOM" => build_pad_labels(view, LayerSide::Bottom),
99 _ => FabLayerItems::default(),
100 }
101}
102
103fn build_cutouts(view: &FabViewData) -> FabLayerItems {
104 let mut out = FabLayerItems::default();
105 let Some(profile) = view.profile.as_ref() else {
106 return out;
107 };
108 for cutout in &profile.cutouts {
109 let n = cutout.points.len();
110 for i in 0..n {
111 let p0 = cutout.points[i];
112 let p1 = cutout.points[(i + 1) % n];
113 let path = match cutout.segs.get(i).copied().unwrap_or(RingSeg::Line) {
114 RingSeg::Line => StrokePath::Line { start: p0, end: p1 },
115 RingSeg::Arc { center, ccw, major } => StrokePath::Arc {
116 start: p0,
117 end: p1,
118 center,
119 ccw,
120 major,
121 },
122 };
123 out.strokes.push(FabStroke {
124 kind: StrokeKind::Virtual,
125 path,
126 width: 150_000,
127 net: None,
128 component: None,
129 source: None,
130 });
131 }
132 }
133 out
134}
135
136fn build_assembly_outlines(view: &FabViewData, side: LayerSide) -> FabLayerItems {
137 let fab_mech = if side == LayerSide::Bottom {
138 "MECHANICAL2"
139 } else {
140 "MECHANICAL1"
141 };
142 if let Some(items) = view.layers_items.get(fab_mech)
143 && !items.is_empty()
144 {
145 return items.clone();
146 }
147 let mut out = FabLayerItems::default();
148 let pads_by_comp = component_pad_bounds(view, side);
149 for comp in &view.components {
150 if comp.side != side || comp.board_only {
151 continue;
152 }
153 if let Some(bbox) = pads_by_comp.get(comp.id.as_str()).copied() {
154 push_rect_outline(&mut out, bbox, 100_000, Some(&comp.id));
155 }
156 }
157 out
158}
159
160fn build_assembly_designators(view: &FabViewData, side: LayerSide) -> FabLayerItems {
161 let mut out = FabLayerItems::default();
162 let mirrored = side == LayerSide::Bottom;
163 let cutouts = profile_cutouts_mm(view);
164 let outline_polys = component_outline_regions_mm(view, side);
165 let pad_polys = component_pad_polygons_mm(view, side);
166 let mut session = DesignatorFitSession::default();
167
168 for comp in &view.components {
169 if comp.side != side || !is_fitted(comp) || comp.designator.is_empty() {
170 continue;
171 }
172 let region = outline_polys.get(comp.id.as_str()).cloned().or_else(|| {
173 pad_polys
174 .get(comp.id.as_str())
175 .and_then(|ps| pad_envelope(ps))
176 });
177 let Some(region) = region.and_then(|r| subtract_cutouts(&r, &cutouts)) else {
178 continue;
179 };
180 let Some(fit) = session.fit(
181 &comp.designator,
182 ®ion,
183 0.78,
184 2.4,
185 comp.rotation_deg,
186 None,
187 ) else {
188 continue;
189 };
190 if fit.font_size_mm < 0.08 {
191 continue;
192 }
193 let center = CoordNm::new(mm_to_nm(fit.center_mm[0]), mm_to_nm(fit.center_mm[1]));
194 let angle_deg = if !mirrored && (fit.rotation_degrees + 90.0).abs() <= 1.0e-6 {
198 90.0
199 } else {
200 fit.rotation_degrees
201 };
202 push_stroke_label_angled(
203 &mut out,
204 &comp.designator,
205 center,
206 fit.font_size_mm,
207 angle_deg,
208 mirrored,
209 Some(&comp.id),
210 );
211 }
212 out
213}
214
215fn build_pad_labels(view: &FabViewData, side: LayerSide) -> FabLayerItems {
216 let mut out = FabLayerItems::default();
217 let layer_key = if side == LayerSide::Bottom {
218 "BOTTOM"
219 } else {
220 "TOP"
221 };
222 let Some(items) = view.layers_items.get(layer_key) else {
223 return out;
224 };
225 let mirrored = side == LayerSide::Bottom;
226 for land in &items.lands {
227 let Some(pin) = land.pin.as_deref() else {
228 continue;
229 };
230 if pin.is_empty() {
231 continue;
232 }
233 let h_mm = pad_label_height_mm(land);
234 push_stroke_label(
235 &mut out,
236 pin,
237 CoordNm::new(land.placement.tx, land.placement.ty),
238 h_mm,
239 mirrored,
240 land.component.as_deref(),
241 );
242 }
243 out
244}
245
246fn pad_label_height_mm(land: &FabLand) -> f64 {
247 let span_nm = match land.shape {
248 AreaShape::Disk { radius } => radius * 2,
249 AreaShape::Rect { width, height }
250 | AreaShape::RoundedRect { width, height, .. }
251 | AreaShape::ChamferedRect { width, height, .. }
252 | AreaShape::Trapezoid { width, height, .. } => width.min(height),
253 AreaShape::Capsule { width, .. } => width,
254 AreaShape::Region { .. } => 800_000,
255 };
256 ((span_nm as f64 / 1e6) * 0.45).clamp(0.25, 0.9)
257}
258
259fn push_stroke_label(
260 out: &mut FabLayerItems,
261 text: &str,
262 center: CoordNm,
263 height_mm: f64,
264 mirrored: bool,
265 comp_id: Option<&str>,
266) {
267 push_stroke_label_angled(out, text, center, height_mm, 0.0, mirrored, comp_id);
268}
269
270fn push_stroke_label_angled(
271 out: &mut FabLayerItems,
272 text: &str,
273 center: CoordNm,
274 height_mm: f64,
275 angle_deg: f64,
276 mirrored: bool,
277 comp_id: Option<&str>,
278) {
279 let (polylines, width) =
280 realize_stroke_label(text, center, height_mm, angle_deg, mirrored, None);
281 for pl in polylines {
282 for pair in pl.windows(2) {
283 out.strokes.push(FabStroke {
284 kind: StrokeKind::Virtual,
285 path: StrokePath::Line {
286 start: pair[0],
287 end: pair[1],
288 },
289 width,
290 net: None,
291 component: comp_id.map(str::to_owned),
292 source: None,
293 });
294 }
295 }
296}
297
298fn profile_cutouts_mm(view: &FabViewData) -> MultiPolygon<f64> {
299 let Some(profile) = view.profile.as_ref() else {
300 return MultiPolygon::new(Vec::new());
301 };
302 let polys: Vec<Polygon<f64>> = profile
303 .cutouts
304 .iter()
305 .filter_map(|ring| {
306 let pts: Vec<[f64; 2]> = ring
307 .flatten_polygon(16)
308 .into_iter()
309 .map(|p| [p.x as f64 / 1e6, p.y as f64 / 1e6])
310 .collect();
311 ring_polygon(&pts)
312 })
313 .collect();
314 MultiPolygon::new(polys)
315}
316
317fn component_outline_regions_mm(
318 view: &FabViewData,
319 side: LayerSide,
320) -> HashMap<&str, MultiPolygon<f64>> {
321 let fab_mech = if side == LayerSide::Bottom {
322 "MECHANICAL2"
323 } else {
324 "MECHANICAL1"
325 };
326 let mut pts_by_comp: HashMap<&str, Vec<[f64; 2]>> = HashMap::new();
327 if let Some(items) = view.layers_items.get(fab_mech) {
328 for stroke in &items.strokes {
329 let Some(cid) = stroke.component.as_deref() else {
330 continue;
331 };
332 let entry = pts_by_comp.entry(cid).or_default();
333 match stroke.path {
334 StrokePath::Line { start, end } | StrokePath::Arc { start, end, .. } => {
335 entry.push([start.x as f64 / 1e6, start.y as f64 / 1e6]);
336 entry.push([end.x as f64 / 1e6, end.y as f64 / 1e6]);
337 }
338 StrokePath::FullCircle { center, radius } => {
339 let cx = center.x as f64 / 1e6;
340 let cy = center.y as f64 / 1e6;
341 let r = radius as f64 / 1e6;
342 entry.push([cx - r, cy - r]);
343 entry.push([cx + r, cy - r]);
344 entry.push([cx + r, cy + r]);
345 entry.push([cx - r, cy + r]);
346 }
347 }
348 }
349 }
350 pts_by_comp
351 .into_iter()
352 .filter_map(|(cid, pts)| {
353 let mp = geo::MultiPoint::from(pts);
354 let hull = mp.convex_hull();
355 (hull.exterior().0.len() >= 4).then_some((cid, MultiPolygon::new(vec![hull])))
356 })
357 .collect()
358}
359
360fn component_pad_polygons_mm(
361 view: &FabViewData,
362 side: LayerSide,
363) -> HashMap<&str, Vec<Polygon<f64>>> {
364 let layer_key = if side == LayerSide::Bottom {
365 "BOTTOM"
366 } else {
367 "TOP"
368 };
369 let mut map: HashMap<&str, Vec<Polygon<f64>>> = HashMap::new();
370 let Some(items) = view.layers_items.get(layer_key) else {
371 return map;
372 };
373 for land in &items.lands {
374 let Some(cid) = land.component.as_deref() else {
375 continue;
376 };
377 if let Some(poly) = land_polygon_mm(land) {
378 map.entry(cid).or_default().push(poly);
379 }
380 }
381 map
382}
383
384fn land_polygon_mm(land: &FabLand) -> Option<Polygon<f64>> {
385 let (hw, hh) = match &land.shape {
386 AreaShape::Disk { radius } => (*radius as f64 / 1e6, *radius as f64 / 1e6),
387 AreaShape::Rect { width, height }
388 | AreaShape::RoundedRect { width, height, .. }
389 | AreaShape::ChamferedRect { width, height, .. }
390 | AreaShape::Trapezoid { width, height, .. } => (*width as f64 / 2e6, *height as f64 / 2e6),
391 AreaShape::Capsule { length, width } => (*length as f64 / 2e6, *width as f64 / 2e6),
392 AreaShape::Region { outer, .. } => {
393 let pts: Vec<[f64; 2]> = outer
394 .flatten_polygon(12)
395 .into_iter()
396 .map(|p| {
397 let wp = land.placement.transform(p.x as f64, p.y as f64);
398 [wp.x as f64 / 1e6, wp.y as f64 / 1e6]
399 })
400 .collect();
401 return ring_polygon(&pts);
402 }
403 };
404 if hw <= 0.0 || hh <= 0.0 {
405 return None;
406 }
407 let corners = [[-hw, -hh], [hw, -hh], [hw, hh], [-hw, hh]].map(|[lx, ly]| {
408 let wp = land.placement.transform(lx * 1e6, ly * 1e6);
409 [wp.x as f64 / 1e6, wp.y as f64 / 1e6]
410 });
411 ring_polygon(&corners)
412}
413
414fn component_pad_bounds(view: &FabViewData, side: LayerSide) -> HashMap<&str, [i64; 4]> {
415 let layer_key = if side == LayerSide::Bottom {
416 "BOTTOM"
417 } else {
418 "TOP"
419 };
420 let mut map: HashMap<&str, [i64; 4]> = HashMap::new();
421 let Some(items) = view.layers_items.get(layer_key) else {
422 return map;
423 };
424 for land in &items.lands {
425 let Some(cid) = land.component.as_deref() else {
426 continue;
427 };
428 let x = land.placement.tx;
429 let y = land.placement.ty;
430 map.entry(cid)
431 .and_modify(|b| {
432 b[0] = b[0].min(x);
433 b[1] = b[1].min(y);
434 b[2] = b[2].max(x);
435 b[3] = b[3].max(y);
436 })
437 .or_insert([x, y, x, y]);
438 }
439 map
440}
441
442fn push_rect_outline(out: &mut FabLayerItems, b: [i64; 4], width: i64, comp_id: Option<&str>) {
443 let pts = [
444 CoordNm::new(b[0], b[1]),
445 CoordNm::new(b[2], b[1]),
446 CoordNm::new(b[2], b[3]),
447 CoordNm::new(b[0], b[3]),
448 ];
449 for i in 0..4 {
450 out.strokes.push(FabStroke {
451 kind: StrokeKind::Virtual,
452 path: StrokePath::Line {
453 start: pts[i],
454 end: pts[(i + 1) % 4],
455 },
456 width,
457 net: None,
458 component: comp_id.map(str::to_owned),
459 source: None,
460 });
461 }
462}
463
464fn is_fitted(comp: &FabComponent) -> bool {
465 comp.fitted && !comp.board_only
466}