1use super::{Board, CopperItem, CopperRef, Connectivity, Shape, polygon_contains, point_segment_distance};
65use crate::{Document, Netlist, Point, Uuid};
66use serde::{Deserialize, Serialize};
67use std::collections::{BTreeMap, BTreeSet, HashMap};
68
69pub const DEFAULT_THERMAL_GAP: i32 = 500;
71pub const DEFAULT_SPOKE_WIDTH: i32 = 500;
73pub const DEFAULT_MIN_WIDTH: i32 = 250;
75pub const PITCH: i32 = 50;
77pub const SIMPLIFY: f64 = 2.;
79const MAX_SAMPLES: usize = 12_000_000;
81
82fn default_thermal_gap() -> i32 {
83 DEFAULT_THERMAL_GAP
84}
85fn default_spoke_width() -> i32 {
86 DEFAULT_SPOKE_WIDTH
87}
88fn default_min_width() -> i32 {
89 DEFAULT_MIN_WIDTH
90}
91
92#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
95pub struct Zone {
96 pub id: Uuid,
97 pub net: String,
99 pub layer: u8,
100 pub outline: Vec<Point>,
102 #[serde(default = "default_thermal_gap")]
104 pub thermal_gap: i32,
105 #[serde(default = "default_spoke_width")]
106 pub spoke_width: i32,
107 #[serde(default = "default_min_width")]
109 pub min_width: i32,
110 #[serde(default, skip_serializing_if = "Vec::is_empty")]
112 pub fill: Vec<FillPiece>,
113}
114impl Zone {
115 pub fn new(net: &str, layer: u8, outline: Vec<Point>) -> Self {
116 Self {
117 id: Uuid::new_v4(),
118 net: net.to_owned(),
119 layer,
120 outline,
121 thermal_gap: DEFAULT_THERMAL_GAP,
122 spoke_width: DEFAULT_SPOKE_WIDTH,
123 min_width: DEFAULT_MIN_WIDTH,
124 fill: vec![],
125 }
126 }
127 pub fn fill_area(&self) -> f64 {
129 self.fill.iter().map(FillPiece::area).sum::<f64>() + 0.
131 }
132 pub(super) fn validate(&self, layer_count: u8) -> Result<(), String> {
133 let valid = |p: &Point| p.x.abs_diff(0) <= 100_000_000 && p.y.abs_diff(0) <= 100_000_000;
134 if self.layer >= layer_count {
135 return Err("A zone is on a copper layer the board does not have".into());
136 }
137 if self.net.trim().is_empty() {
138 return Err("A zone needs a net".into());
139 }
140 if self.outline.len() < 3 || !self.outline.iter().all(valid) || ring_area(&self.outline) == 0. {
141 return Err("A zone's outline needs at least three points enclosing an area".into());
142 }
143 let size = |v: i32| (1..=100_000_000).contains(&v);
144 if !size(self.thermal_gap) || !size(self.spoke_width) || !size(self.min_width) {
145 return Err("A zone's thermal gap, spoke width and minimum width must be positive".into());
146 }
147 let rings = self.fill.iter().flat_map(|p| std::iter::once(&p.outer).chain(&p.holes));
148 for ring in rings {
149 if ring.len() < 3 || !ring.iter().all(valid) {
150 return Err("A zone's fill has a ring of fewer than three valid points".into());
151 }
152 }
153 Ok(())
154 }
155}
156
157#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
159pub struct FillPiece {
160 pub outer: Vec<Point>,
161 #[serde(default, skip_serializing_if = "Vec::is_empty")]
162 pub holes: Vec<Vec<Point>>,
163}
164impl FillPiece {
165 pub fn contains(&self, p: Point) -> bool {
167 polygon_contains(&self.outer, p) && !self.holes.iter().any(|h| polygon_contains(h, p))
168 }
169 pub fn edges(&self) -> impl Iterator<Item = (Point, Point)> + '_ {
171 std::iter::once(&self.outer)
172 .chain(&self.holes)
173 .flat_map(|ring| (0..ring.len()).map(move |i| (ring[i], ring[(i + 1) % ring.len()])))
174 }
175 pub fn area(&self) -> f64 {
177 ring_area(&self.outer).abs() - self.holes.iter().map(|h| ring_area(h).abs()).sum::<f64>()
178 }
179 pub fn bounds(&self) -> (Point, Point) {
180 super::bounds_of(&self.outer).unwrap_or_default()
181 }
182 pub fn distance(&self, shape: &Shape) -> f64 {
184 if self.contains(shape.center()) {
185 return 0.;
186 }
187 self.edges()
188 .map(|(a, b)| Shape::segment(a, b, 0).distance(shape))
189 .fold(f64::INFINITY, f64::min)
190 }
191 pub fn touches(&self, shape: &Shape) -> bool {
196 let (lo, hi) = shape.bounds();
197 let near = |a: Point, b: Point| {
198 a.x.min(b.x) <= hi.x + 1 && a.x.max(b.x) >= lo.x - 1 && a.y.min(b.y) <= hi.y + 1 && a.y.max(b.y) >= lo.y - 1
199 };
200 self.edges()
201 .any(|(a, b)| near(a, b) && Shape::segment(a, b, 0).distance(shape) <= 0.5)
202 || self.contains(shape.center())
203 }
204 pub fn distance_to_piece(&self, other: &FillPiece) -> f64 {
206 if other.outer.first().is_some_and(|p| self.contains(*p))
207 || self.outer.first().is_some_and(|p| other.contains(*p))
208 {
209 return 0.;
210 }
211 let (min, max) = other.bounds();
212 let mut best = f64::INFINITY;
213 for (a, b) in self.edges() {
214 let edge = Shape::segment(a, b, 0);
215 let (e0, e1) = edge.bounds();
216 let far = f64::from((min.x - e1.x).max(e0.x - max.x).max(min.y - e1.y).max(e0.y - max.y));
217 if far >= best {
218 continue;
219 }
220 for (c, d) in other.edges() {
221 best = best.min(edge.distance(&Shape::segment(c, d, 0)));
222 }
223 }
224 best
225 }
226}
227
228pub fn ring_area(ring: &[Point]) -> f64 {
231 let mut sum = 0i128;
232 for i in 0..ring.len() {
233 let (a, b) = (ring[i], ring[(i + 1) % ring.len()]);
234 sum += i128::from(a.x) * i128::from(b.y) - i128::from(b.x) * i128::from(a.y);
235 }
236 sum as f64 / 2.
237}
238
239#[derive(Clone, Debug, PartialEq)]
241pub struct Thermal {
242 pub owner: CopperRef,
243 pub at: Point,
244 pub spokes: u8,
246}
247
248#[derive(Clone, Debug, PartialEq)]
250pub struct ZoneReport {
251 pub zone: Uuid,
252 pub pieces: usize,
253 pub area: f64,
255 pub islands_removed: usize,
257 pub thermals: Vec<Thermal>,
258 pub pitch: i32,
260 pub empty_because: Option<String>,
262 pub unstitched: Vec<(Point, Vec<String>)>,
265}
266
267#[derive(Clone, Debug, PartialEq)]
270pub struct ContestedVia {
271 pub via: usize,
273 pub at: Point,
274 pub nets: Vec<String>,
276 pub zones: Vec<usize>,
278}
279
280struct Stitching {
285 net: HashMap<usize, String>,
287 contested: BTreeMap<usize, BTreeSet<String>>,
289}
290fn holds(zone: &Zone, item: &CopperItem) -> bool {
291 item.layers.0 <= zone.layer && zone.layer <= item.layers.1 && polygon_contains(&zone.outline, item.shape.center())
292}
293fn stitching(board: &Board, conn: &Connectivity) -> Stitching {
294 let mut claims: BTreeMap<usize, BTreeSet<String>> = BTreeMap::new();
295 for (i, item) in conn.items.iter().enumerate() {
296 let island = conn.islands[i];
297 if !matches!(item.owner, CopperRef::Via(_)) || !conn.island_nets[island].is_empty() {
298 continue;
299 }
300 for zone in board.zones.iter().filter(|z| holds(z, item)) {
301 claims.entry(island).or_default().insert(zone.net.clone());
302 }
303 }
304 let mut out = Stitching { net: HashMap::new(), contested: BTreeMap::new() };
305 for (island, nets) in claims {
306 if nets.len() == 1 {
307 out.net.insert(island, nets.into_iter().next().unwrap());
308 } else {
309 out.contested.insert(island, nets);
310 }
311 }
312 out
313}
314
315impl Document {
316 pub fn fill_zones(&mut self) -> Vec<ZoneReport> {
318 let netlist = self.netlist();
319 self.board.fill_zones(&netlist)
320 }
321}
322
323impl Board {
324 pub fn fill_zones(&mut self, netlist: &Netlist) -> Vec<ZoneReport> {
326 let conn = self.connectivity_of(netlist, false);
327 let stitch = stitching(self, &conn);
328 let mut reports = Vec::with_capacity(self.zones.len());
329 for index in 0..self.zones.len() {
330 let (fill, report) = fill_zone(self, &conn, &stitch, index);
331 self.zones[index].fill = fill;
332 reports.push(report);
333 }
334 reports
335 }
336 pub fn zones_stale(&self, netlist: &Netlist) -> bool {
338 if self.zones.is_empty() {
339 return false;
340 }
341 let mut fresh = self.clone();
342 fresh.fill_zones(netlist);
343 fresh.zones != self.zones
344 }
345 pub fn contested_vias(&self, netlist: &Netlist) -> Vec<ContestedVia> {
348 if self.zones.is_empty() {
349 return vec![];
350 }
351 let conn = self.connectivity_of(netlist, false);
352 let stitch = stitching(self, &conn);
353 let mut out = vec![];
354 for (i, item) in conn.items.iter().enumerate() {
355 let CopperRef::Via(via) = item.owner else { continue };
356 let Some(nets) = stitch.contested.get(&conn.islands[i]) else { continue };
357 let zones: Vec<usize> = (0..self.zones.len()).filter(|&z| holds(&self.zones[z], item)).collect();
358 if !zones.is_empty() {
359 out.push(ContestedVia { via, at: item.shape.center(), nets: nets.iter().cloned().collect(), zones });
360 }
361 }
362 out
363 }
364 pub(super) fn stitching_findings(&self, netlist: &Netlist) -> Vec<super::Violation> {
367 self.contested_vias(netlist)
368 .into_iter()
369 .map(|c| {
370 let zones: Vec<String> = c.zones.iter().map(|&z| describe(&self.zones[z], self.layer_count)).collect();
371 let own: BTreeSet<&str> = c.zones.iter().map(|&z| self.zones[z].net.as_str()).collect();
372 let others: Vec<&str> = c.nets.iter().map(String::as_str).filter(|n| !own.contains(n)).collect();
373 let place = if others.is_empty() {
376 format!("is in both the {}", zones.join(" and the "))
377 } else {
378 format!(
379 "is in the {}, and copper joins it to a via in a {} zone",
380 zones.join(" and the "),
381 others.join(" and ")
382 )
383 };
384 super::Violation {
385 kind: super::ViolationKind::Stitching,
386 message: format!(
387 "Via at {:.2}, {:.2} mm has no net and {place}: it is stitched to none of them, \
388 because that would short {}. Give it a net, or keep it in one net's zones",
389 f64::from(c.at.x) / 1000.,
390 f64::from(c.at.y) / 1000.,
391 c.nets.join(" to ")
392 ),
393 at: c.at,
394 }
395 })
396 .collect()
397 }
398}
399
400enum Obstacle {
403 Keep(Shape, f64),
405 Zone(Vec<Point>, f64),
407}
408
409fn polygon_depth(polygon: &[Point], p: Point) -> f64 {
411 let n = polygon.len();
412 let d = (0..n)
413 .map(|i| point_segment_distance(p, polygon[i], polygon[(i + 1) % n]))
414 .fold(f64::INFINITY, f64::min);
415 if polygon_contains(polygon, p) { d } else { -d }
416}
417
418struct Grid {
420 x0: i32,
421 y0: i32,
422 h: i32,
423 nx: usize,
424 ny: usize,
425 v: Vec<f32>,
426}
427impl Grid {
428 fn at(&self, i: usize, j: usize) -> Point {
429 Point::new(self.x0 + i as i32 * self.h, self.y0 + j as i32 * self.h)
430 }
431 fn get(&self, i: usize, j: usize) -> f32 {
432 self.v[j * self.nx + i]
433 }
434 fn sample(&self, p: Point) -> f32 {
436 let fx = f64::from(p.x - self.x0) / f64::from(self.h);
437 let fy = f64::from(p.y - self.y0) / f64::from(self.h);
438 if fx < 0. || fy < 0. || fx >= (self.nx - 1) as f64 || fy >= (self.ny - 1) as f64 {
439 return f32::NEG_INFINITY;
440 }
441 let (i, j) = (fx as usize, fy as usize);
442 let (tx, ty) = ((fx - i as f64) as f32, (fy - j as f64) as f32);
443 let top = self.get(i, j) * (1. - tx) + self.get(i + 1, j) * tx;
444 let bottom = self.get(i, j + 1) * (1. - tx) + self.get(i + 1, j + 1) * tx;
445 top * (1. - ty) + bottom * ty
446 }
447}
448
449struct Buckets {
451 x0: i32,
452 y0: i32,
453 size: i32,
454 nx: usize,
455 ny: usize,
456 cells: Vec<Vec<u32>>,
457}
458impl Buckets {
459 fn new(min: Point, max: Point, size: i32) -> Self {
460 let nx = ((max.x - min.x) / size + 1).max(1) as usize;
461 let ny = ((max.y - min.y) / size + 1).max(1) as usize;
462 Self { x0: min.x, y0: min.y, size, nx, ny, cells: vec![vec![]; nx * ny] }
463 }
464 fn cell(&self, x: i32, y: i32) -> (usize, usize) {
465 let i = ((x - self.x0).div_euclid(self.size)).clamp(0, self.nx as i32 - 1) as usize;
466 let j = ((y - self.y0).div_euclid(self.size)).clamp(0, self.ny as i32 - 1) as usize;
467 (i, j)
468 }
469 fn insert(&mut self, index: u32, min: Point, max: Point) {
470 let (i0, j0) = self.cell(min.x, min.y);
471 let (i1, j1) = self.cell(max.x, max.y);
472 for j in j0..=j1 {
473 for i in i0..=i1 {
474 self.cells[j * self.nx + i].push(index);
475 }
476 }
477 }
478 fn near(&self, p: Point) -> &[u32] {
479 let (i, j) = self.cell(p.x, p.y);
480 &self.cells[j * self.nx + i]
481 }
482}
483
484fn item_net<'a>(conn: &'a Connectivity, i: usize) -> Option<&'a str> {
486 conn.island_net(conn.islands[i])
487}
488
489fn fill_zone(board: &Board, conn: &Connectivity, stitch: &Stitching, index: usize) -> (Vec<FillPiece>, ZoneReport) {
492 let zone = &board.zones[index];
493 let mut report = ZoneReport {
494 zone: zone.id,
495 pieces: 0,
496 area: 0.,
497 islands_removed: 0,
498 thermals: vec![],
499 pitch: PITCH,
500 empty_because: None,
501 unstitched: vec![],
502 };
503 let rules = &board.rules;
504 let own = rules.class_of(Some(zone.net.as_str())).clearance.max(0);
508 let clearance_to = |nets: &BTreeSet<String>| {
509 f64::from(rules.clearance_between_nets([zone.net.as_str()], nets.iter().map(String::as_str)).0)
510 };
511 let gap = f64::from(zone.thermal_gap.max(own));
512 let half_width = f64::from(zone.min_width) / 2.;
513 let spoke_half = f64::from(zone.spoke_width) / 2.;
514 let layer = zone.layer;
515 let on_layer = |item: &CopperItem| item.layers.0 <= layer && layer <= item.layers.1;
516
517 let (Some((zmin, zmax)), (omin, omax)) = (super::bounds_of(&zone.outline), board.outline_bounds()) else {
519 report.empty_because = Some("the zone has no outline".into());
520 return (vec![], report);
521 };
522 let min = Point::new(zmin.x.max(omin.x), zmin.y.max(omin.y));
523 let max = Point::new(zmax.x.min(omax.x), zmax.y.min(omax.y));
524 if min.x >= max.x || min.y >= max.y {
525 report.empty_because = Some("the zone is outside the board".into());
526 return (vec![], report);
527 }
528 let mut h = PITCH.min((own / 2).max(10));
531 let area = |h: i32| (((max.x - min.x) / h + 3) as usize) * (((max.y - min.y) / h + 3) as usize);
532 while area(h) > MAX_SAMPLES {
533 h *= 2;
534 }
535 report.pitch = h;
536 let radius = f64::from(own.max(h));
540 let margin = (2. * f64::from(h * h) / (8. * radius) + SIMPLIFY + 1. + 1.) as f32;
541
542 let x0 = min.x - h;
545 let y0 = min.y - h;
546 let nx = ((max.x - min.x) / h + 3) as usize;
547 let ny = ((max.y - min.y) / h + 3) as usize;
548
549 let mut obstacles: Vec<Obstacle> = vec![];
551 let mut thermal_pads: Vec<(CopperRef, Shape)> = vec![];
552 let mut same_net: Vec<usize> = vec![];
553 for (i, item) in conn.items.iter().enumerate() {
554 if !on_layer(item) {
555 continue;
556 }
557 let net = item_net(conn, i);
558 let island = conn.islands[i];
562 let held = matches!(item.owner, CopperRef::Via(_)) && holds(zone, item);
563 let stitched = held && stitch.net.get(&island) == Some(&zone.net);
564 if held && let Some(nets) = stitch.contested.get(&island) {
565 let others = nets.iter().filter(|n| **n != zone.net).cloned().collect();
566 report.unstitched.push((item.shape.center(), others));
567 }
568 if net == Some(zone.net.as_str()) || stitched {
569 same_net.push(i);
570 if let CopperRef::Pad { placement, pad } = item.owner
571 && board.placements[placement].footprint.pads[pad].drill.is_some()
572 {
573 thermal_pads.push((item.owner, item.shape.clone()));
574 }
575 } else {
576 obstacles.push(Obstacle::Keep(item.shape.clone(), clearance_to(&conn.island_nets[island])));
577 }
578 }
579 for earlier in &board.zones[..index] {
580 if earlier.layer == layer && earlier.net != zone.net && earlier.outline.len() >= 3 {
581 let clearance = f64::from(rules.clearance_between(Some(zone.net.as_str()), Some(earlier.net.as_str())).0);
582 obstacles.push(Obstacle::Zone(earlier.outline.clone(), clearance));
583 }
584 }
585 for cutout in &board.cutouts {
588 obstacles.push(Obstacle::Zone(cutout.points.clone(), f64::from(rules.edge_clearance)));
589 }
590 let clearance = obstacles
591 .iter()
592 .map(|o| match o {
593 Obstacle::Keep(_, c) | Obstacle::Zone(_, c) => *c,
594 })
595 .fold(f64::from(own), f64::max);
596 let cap = (half_width + 4. * f64::from(h)) as f32;
599 let reach = (clearance.max(gap) + f64::from(cap)) as i32 + h;
600 let mut buckets = Buckets::new(Point::new(x0, y0), Point::new(x0 + nx as i32 * h, y0 + ny as i32 * h), 1000);
601 for (k, obstacle) in obstacles.iter().enumerate() {
602 let (lo, hi) = match obstacle {
603 Obstacle::Keep(shape, _) => shape.bounds(),
604 Obstacle::Zone(outline, _) => super::bounds_of(outline).unwrap_or_default(),
605 };
606 buckets.insert(k as u32, Point::new(lo.x - reach, lo.y - reach), Point::new(hi.x + reach, hi.y + reach));
607 }
608 let mut relief = Buckets::new(Point::new(x0, y0), Point::new(x0 + nx as i32 * h, y0 + ny as i32 * h), 1000);
609 for (k, (_, shape)) in thermal_pads.iter().enumerate() {
610 let (lo, hi) = shape.bounds();
611 relief.insert(k as u32, Point::new(lo.x - reach, lo.y - reach), Point::new(hi.x + reach, hi.y + reach));
612 }
613
614 let edge_clearance = f64::from(rules.edge_clearance);
617 let keep = |p: Point| -> f32 {
618 let mut v = polygon_depth(&zone.outline, p).min(polygon_depth(&board.outline, p) - edge_clearance) as f32;
619 for &k in buckets.near(p) {
620 let d = match &obstacles[k as usize] {
621 Obstacle::Keep(shape, c) => shape.distance_to_point(p) - c,
622 Obstacle::Zone(outline, c) => -polygon_depth(outline, p) - c,
623 };
624 v = v.min(d as f32);
625 }
626 v.min(cap)
627 };
628 let mut base = Grid { x0, y0, h, nx, ny, v: vec![f32::NEG_INFINITY; nx * ny] };
629 let mut clear = vec![f32::NEG_INFINITY; nx * ny];
630 for j in 1..ny - 1 {
631 for i in 1..nx - 1 {
632 let p = base.at(i, j);
633 let k = keep(p);
634 let mut v = k;
635 for &t in relief.near(p) {
636 v = v.min((thermal_pads[t as usize].1.distance_to_point(p) - gap) as f32);
637 }
638 clear[j * nx + i] = k - margin;
639 base.v[j * nx + i] = v - margin;
640 }
641 }
642
643 let window = ((half_width + 2. * f64::from(h)) / f64::from(h)).ceil() as isize;
648 let mut opened = base.v.clone();
649 let deep = |v: f32| f64::from(v) >= half_width;
650 for j in 1..ny - 1 {
651 for i in 1..nx - 1 {
652 let v = base.v[j * nx + i];
653 if v < 0. || deep(v) {
654 continue;
655 }
656 let mut best = f64::INFINITY;
657 for dj in -window..=window {
658 for di in -window..=window {
659 let (a, b) = (i as isize + di, j as isize + dj);
660 if a < 0 || b < 0 || a >= nx as isize || b >= ny as isize {
661 continue;
662 }
663 let q = base.v[b as usize * nx + a as usize];
664 if !deep(q) {
665 continue;
666 }
667 let dist = f64::from(h) * ((di * di + dj * dj) as f64).sqrt();
668 best = best.min(dist - (f64::from(q) - half_width));
669 }
670 }
671 let reach = (half_width - best + 1.) as f32;
673 opened[j * nx + i] = v.min(reach);
674 }
675 }
676 let mut field = Grid { v: opened, ..base };
677
678 for (owner, shape) in &thermal_pads {
681 let (lo, hi) = shape.bounds();
682 let centre = shape.center();
683 let half = [(hi.x - lo.x) / 2, (hi.y - lo.y) / 2];
684 let mut spokes = 0u8;
685 for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)] {
686 let extent = f64::from(if dx != 0 { half[0] } else { half[1] });
687 let meet = extent + gap + spoke_half.max(f64::from(h));
688 let probe = Point::new(centre.x + (dx as f64 * meet) as i32, centre.y + (dy as f64 * meet) as i32);
689 if field.sample(probe) <= 0. {
690 continue;
691 }
692 let length = extent + gap + 2. * spoke_half;
693 let end = Point::new(centre.x + (dx as f64 * length) as i32, centre.y + (dy as f64 * length) as i32);
694 let spoke = Shape::segment(centre, end, zone.spoke_width);
695 let (s0, s1) = spoke.bounds();
696 let i0 = ((s0.x - x0) / h - 1).max(1) as usize;
697 let j0 = ((s0.y - y0) / h - 1).max(1) as usize;
698 let i1 = (((s1.x - x0) / h + 2) as usize).min(nx - 2);
699 let j1 = (((s1.y - y0) / h + 2) as usize).min(ny - 2);
700 for j in j0..=j1 {
701 for i in i0..=i1 {
702 let p = field.at(i, j);
703 let s = (spoke_half - point_segment_distance(p, centre, end)) as f32;
704 let v = s.min(clear[j * nx + i] + margin) - margin;
705 let cell = &mut field.v[j * nx + i];
706 *cell = cell.max(v);
707 }
708 }
709 spokes += 1;
710 }
711 report.thermals.push(Thermal { owner: *owner, at: centre, spokes });
712 }
713
714 let rings = contour(&field);
716 let mut outers: Vec<Vec<Point>> = vec![];
717 let mut holes: Vec<Vec<Point>> = vec![];
718 for ring in rings {
719 let ring = simplify_ring(&ring, SIMPLIFY);
720 if ring.len() < 3 {
721 continue;
722 }
723 let ring: Vec<Point> = ring
724 .iter()
725 .map(|&(x, y)| Point::new(x.round() as i32, y.round() as i32))
726 .collect();
727 let ring = super::simplify_path(ring);
728 let area = ring_area(&ring);
729 if area > 0. {
730 outers.push(ring);
731 } else if area < 0. {
732 holes.push(ring);
733 }
734 }
735 let mut pieces: Vec<FillPiece> = outers
736 .into_iter()
737 .map(|outer| FillPiece { outer, holes: vec![] })
738 .collect();
739 for hole in holes {
741 let probe = hole[0];
742 let owner = pieces
743 .iter()
744 .enumerate()
745 .filter(|(_, p)| polygon_contains(&p.outer, probe))
746 .min_by(|a, b| ring_area(&a.1.outer).total_cmp(&ring_area(&b.1.outer)))
747 .map(|(k, _)| k);
748 if let Some(k) = owner {
749 pieces[k].holes.push(hole);
750 }
751 }
752 let before = pieces.len();
753 pieces.retain(|piece| {
754 let (pmin, pmax) = piece.bounds();
755 same_net.iter().any(|&i| {
756 let (lo, hi) = conn.items[i].shape.bounds();
757 lo.x <= pmax.x && hi.x >= pmin.x && lo.y <= pmax.y && hi.y >= pmin.y
758 && piece.touches(&conn.items[i].shape)
759 })
760 });
761 report.islands_removed = before - pieces.len();
762 pieces.sort_by(|a, b| b.area().total_cmp(&a.area()));
764 report.pieces = pieces.len();
765 report.area = pieces.iter().map(FillPiece::area).sum::<f64>() + 0.;
766 if pieces.is_empty() {
767 report.empty_because = Some(if before > 0 {
768 format!(
769 "no piece of it reaches any {0} copper (a pad, track or via of {0}), and a piece that joins nothing is an island, which is removed",
770 zone.net
771 )
772 } else {
773 "nothing is left of it once the clearances to other copper and to the board edge are kept".into()
774 });
775 }
776 (pieces, report)
777}
778
779fn contour(grid: &Grid) -> Vec<Vec<(f64, f64)>> {
784 let (nx, ny) = (grid.nx, grid.ny);
785 let value = |i: usize, j: usize| {
786 let v = grid.get(i, j);
787 if v == 0. { -1e-6 } else { v }
788 };
789 let horizontal = |i: usize, j: usize| 2 * (j * nx + i);
792 let vertical = |i: usize, j: usize| 2 * (j * nx + i) + 1;
793 let point = |edge: usize| -> (f64, f64) {
794 let cell = edge / 2;
795 let (i, j) = (cell % nx, cell / nx);
796 let (i2, j2) = if edge % 2 == 0 { (i + 1, j) } else { (i, j + 1) };
797 let (va, vb) = (f64::from(value(i, j)), f64::from(value(i2, j2)));
798 let t = va / (va - vb);
799 let (a, b) = (grid.at(i, j), grid.at(i2, j2));
800 (
801 f64::from(a.x) + t * f64::from(b.x - a.x),
802 f64::from(a.y) + t * f64::from(b.y - a.y),
803 )
804 };
805 let mut next: HashMap<usize, usize> = HashMap::new();
806 for j in 0..ny - 1 {
807 for i in 0..nx - 1 {
808 let c = [value(i, j), value(i + 1, j), value(i + 1, j + 1), value(i, j + 1)];
809 let inside = c.map(|v| v > 0.);
810 let case = inside.iter().enumerate().fold(0, |acc, (k, &b)| acc | (usize::from(b) << k));
811 if case == 0 || case == 15 {
812 continue;
813 }
814 let edges = [horizontal(i, j), vertical(i + 1, j), horizontal(i, j + 1), vertical(i, j)];
815 let exits: Vec<usize> = (0..4).filter(|&k| inside[k] && !inside[(k + 1) % 4]).collect();
818 if exits.len() == 1 {
819 let entry = (0..4).find(|&k| !inside[k] && inside[(k + 1) % 4]).unwrap();
820 next.insert(edges[exits[0]], edges[entry]);
821 } else {
822 let joined = c.iter().map(|&v| f64::from(v)).sum::<f64>() > 0.;
823 for &k in &exits {
824 let entry = if joined { (k + 1) % 4 } else { (k + 3) % 4 };
825 next.insert(edges[k], edges[entry]);
826 }
827 }
828 }
829 }
830 let mut starts: Vec<usize> = next.keys().copied().collect();
831 starts.sort_unstable();
832 let mut seen = std::collections::HashSet::new();
833 let mut rings = vec![];
834 for start in starts {
835 if seen.contains(&start) {
836 continue;
837 }
838 let mut ring = vec![];
839 let mut edge = start;
840 loop {
841 if !seen.insert(edge) {
842 break;
843 }
844 ring.push(point(edge));
845 match next.get(&edge) {
846 Some(&n) => edge = n,
847 None => break,
848 }
849 }
850 if ring.len() >= 3 {
851 rings.push(ring);
852 }
853 }
854 rings
855}
856
857fn simplify_ring(ring: &[(f64, f64)], tolerance: f64) -> Vec<(f64, f64)> {
860 if ring.len() < 4 {
861 return ring.to_vec();
862 }
863 let d2 = |a: (f64, f64), b: (f64, f64)| (a.0 - b.0).powi(2) + (a.1 - b.1).powi(2);
864 let far = (1..ring.len())
865 .max_by(|&a, &b| d2(ring[0], ring[a]).total_cmp(&d2(ring[0], ring[b])))
866 .unwrap();
867 let mut keep = vec![false; ring.len()];
868 keep[0] = true;
869 keep[far] = true;
870 let closed: Vec<(f64, f64)> = ring.iter().copied().chain(std::iter::once(ring[0])).collect();
871 let mut stack = vec![(0, far), (far, ring.len())];
872 while let Some((a, b)) = stack.pop() {
873 if b <= a + 1 {
874 continue;
875 }
876 let (pa, pb) = (closed[a], closed[b]);
877 let (dx, dy) = (pb.0 - pa.0, pb.1 - pa.1);
878 let len = dx.hypot(dy);
879 let mut worst = (0., a);
880 for (k, &p) in closed.iter().enumerate().take(b).skip(a + 1) {
881 let d = if len < 1e-9 {
882 (p.0 - pa.0).hypot(p.1 - pa.1)
883 } else {
884 ((p.0 - pa.0) * dy - (p.1 - pa.1) * dx).abs() / len
885 };
886 if d > worst.0 {
887 worst = (d, k);
888 }
889 }
890 if worst.0 > tolerance {
891 keep[worst.1] = true;
892 stack.push((a, worst.1));
893 stack.push((worst.1, b));
894 }
895 }
896 ring.iter().zip(keep).filter(|(_, k)| *k).map(|(p, _)| *p).collect()
897}
898
899pub fn fill_triangles(rings: &[&[Point]]) -> Vec<[(f64, f64); 3]> {
912 type Edge = ((f64, f64), (f64, f64));
913 let mut edges: Vec<Edge> = vec![];
914 let mut ys: Vec<i32> = vec![];
915 for ring in rings {
916 for i in 0..ring.len() {
917 let (a, b) = (ring[i], ring[(i + 1) % ring.len()]);
918 ys.push(a.y);
919 if a.y != b.y {
920 let (a, b) = if a.y < b.y { (a, b) } else { (b, a) };
921 edges.push(((f64::from(a.x), f64::from(a.y)), (f64::from(b.x), f64::from(b.y))));
922 }
923 }
924 }
925 ys.sort_unstable();
926 ys.dedup();
927 edges.sort_by(|a, b| a.0.1.total_cmp(&b.0.1));
928 let x_at = |e: &Edge, y: f64| {
931 if y == e.0.1 {
932 e.0.0
933 } else if y == e.1.1 {
934 e.1.0
935 } else {
936 e.0.0 + (e.1.0 - e.0.0) * (y - e.0.1) / (e.1.1 - e.0.1)
937 }
938 };
939 let mut strips: Vec<Vec<[f64; 4]>> = Vec::with_capacity(ys.len());
941 let mut active: Vec<usize> = vec![];
942 let mut next_edge = 0;
943 for w in ys.windows(2) {
944 let (top, bottom) = (f64::from(w[0]), f64::from(w[1]));
945 while next_edge < edges.len() && edges[next_edge].0.1 <= top {
946 active.push(next_edge);
947 next_edge += 1;
948 }
949 active.retain(|&e| edges[e].1.1 > top);
950 let mid = (top + bottom) / 2.;
951 let mut crossing: Vec<(f64, usize)> = active
952 .iter()
953 .filter(|&&e| edges[e].0.1 <= top && edges[e].1.1 >= bottom)
954 .map(|&e| (x_at(&edges[e], mid), e))
955 .collect();
956 crossing.sort_by(|a, b| a.0.total_cmp(&b.0));
957 strips.push(
958 crossing
959 .chunks_exact(2)
960 .map(|pair| {
961 let (l, r) = (&edges[pair[0].1], &edges[pair[1].1]);
962 [x_at(l, top), x_at(r, top), x_at(l, bottom), x_at(r, bottom)]
963 })
964 .collect(),
965 );
966 }
967 let mut lines: Vec<Vec<f64>> = vec![vec![]; ys.len()];
969 for (k, spans) in strips.iter().enumerate() {
970 for span in spans {
971 lines[k].extend([span[0], span[1]]);
972 lines[k + 1].extend([span[2], span[3]]);
973 }
974 }
975 for line in &mut lines {
976 line.sort_by(f64::total_cmp);
977 line.dedup();
978 }
979 let mut out = vec![];
980 for (k, spans) in strips.iter().enumerate() {
981 let (top, bottom) = (f64::from(ys[k]), f64::from(ys[k + 1]));
982 for &[lt, rt, lb, rb] in spans {
983 let mut polygon: Vec<(f64, f64)> = vec![(lt, top)];
984 polygon.extend(lines[k].iter().filter(|&&x| x > lt && x < rt).map(|&x| (x, top)));
985 polygon.push((rt, top));
986 polygon.push((rb, bottom));
987 polygon.extend(lines[k + 1].iter().rev().filter(|&&x| x > lb && x < rb).map(|&x| (x, bottom)));
988 polygon.push((lb, bottom));
989 polygon.dedup();
990 if polygon.len() > 1 && polygon.first() == polygon.last() {
991 polygon.pop();
992 }
993 let area2 = |a: (f64, f64), b: (f64, f64), c: (f64, f64)| {
994 ((b.0 - a.0) * (c.1 - a.1) - (b.1 - a.1) * (c.0 - a.0)).abs()
995 };
996 if polygon.len() == 3 {
997 if area2(polygon[0], polygon[1], polygon[2]) > 0. {
998 out.push([polygon[0], polygon[1], polygon[2]]);
999 }
1000 } else if polygon.len() == 4 {
1001 for tri in [[polygon[0], polygon[1], polygon[2]], [polygon[0], polygon[2], polygon[3]]] {
1002 if area2(tri[0], tri[1], tri[2]) > 0. {
1003 out.push(tri);
1004 }
1005 }
1006 } else if polygon.len() > 4 {
1007 let n = polygon.len() as f64;
1008 let centre = (
1009 polygon.iter().map(|p| p.0).sum::<f64>() / n,
1010 polygon.iter().map(|p| p.1).sum::<f64>() / n,
1011 );
1012 for i in 0..polygon.len() {
1013 let tri = [centre, polygon[i], polygon[(i + 1) % polygon.len()]];
1014 if area2(tri[0], tri[1], tri[2]) > 0. {
1015 out.push(tri);
1016 }
1017 }
1018 }
1019 }
1020 }
1021 out
1022}
1023
1024pub fn fractured(piece: &FillPiece) -> Vec<Point> {
1030 let mut outer = piece.outer.clone();
1031 if ring_area(&outer) < 0. {
1032 outer.reverse();
1033 }
1034 let mut holes: Vec<Vec<Point>> = piece
1035 .holes
1036 .iter()
1037 .map(|h| {
1038 let mut h = h.clone();
1039 if ring_area(&h) > 0. {
1040 h.reverse();
1041 }
1042 let k = (0..h.len()).min_by_key(|&k| (h[k].x, h[k].y)).unwrap_or(0);
1044 h.rotate_left(k);
1045 h
1046 })
1047 .collect();
1048 holes.sort_by_key(|h| (h[0].x, h[0].y));
1049 for hole in holes {
1050 let v = hole[0];
1051 let mut best: Option<(f64, usize, Point)> = None;
1053 let n = outer.len();
1054 for i in 0..n {
1055 let (a, b) = (outer[i], outer[(i + 1) % n]);
1056 if (a.y <= v.y) == (b.y <= v.y) {
1058 continue;
1059 }
1060 let t = f64::from(v.y - a.y) / f64::from(b.y - a.y);
1061 let x = f64::from(a.x) + t * f64::from(b.x - a.x);
1062 if x > f64::from(v.x) {
1063 continue;
1064 }
1065 let d = f64::from(v.x) - x;
1066 if best.is_none_or(|(bd, ..)| d < bd) {
1067 best = Some((d, i, Point::new(x.round() as i32, v.y)));
1068 }
1069 }
1070 let Some((_, i, at)) = best else { continue };
1071 let mut spliced = Vec::with_capacity(n + hole.len() + 3);
1072 spliced.extend_from_slice(&outer[..=i]);
1073 if outer[i] != at {
1074 spliced.push(at);
1075 }
1076 spliced.extend(hole.iter().copied());
1077 spliced.push(v);
1078 spliced.push(at);
1079 spliced.extend_from_slice(&outer[i + 1..]);
1080 outer = spliced;
1081 }
1082 outer
1083}
1084
1085pub fn describe(zone: &Zone, layer_count: u8) -> String {
1087 format!("{} zone on {}", zone.net, super::layer_name(zone.layer, layer_count))
1088}