Skip to main content

brep_ecad_core/board/
zones.rs

1//! Copper zones: a polygon on one copper layer, given to one net, and FILLED with
2//! copper wherever the board's rules allow it — a ground pour.
3//!
4//! # The fill rule
5//!
6//! The fill of a zone on layer `L` for net `N` is the zone's polygon
7//!
8//! * inside the board outline by at least [`DesignRules::edge_clearance`](crate::board::DesignRules::edge_clearance);
9//! * minus a clearance round every piece of copper on `L` that is NOT on `N` —
10//!   pads, tracks and vias of other nets, and copper that carries no net at all
11//!   (an unrouted stub, a mechanical pad). The clearance is the larger of `N`'s net
12//!   class's and that copper's ([`DesignRules::clearance_between`](crate::board::DesignRules::clearance_between); netless copper
13//!   is Default);
14//! * minus the whole outline of every EARLIER zone on `L` of another net, grown by
15//!   the larger of the two nets' class clearances: zones are filled in the order they were drawn and the first
16//!   one keeps the ground they share (KiCad's priority, fixed to drawing order);
17//! * with same-net copper joined as follows — a surface-mount pad, a track and a
18//!   via of `N` are SOLID: the fill runs over them. A through-hole pad of `N` gets
19//!   a THERMAL RELIEF: a gap of [`Zone::thermal_gap`] (at least `N`'s class clearance) all
20//!   round it, bridged by up to four straight spokes, [`Zone::spoke_width`] wide,
21//!   left, right, up and down. A spoke is laid only where the fill is there to
22//!   meet it, so [`Thermal::spokes`] counts spokes that connect;
23//! * opened by [`Zone::min_width`]: every part of the fill narrower than that is
24//!   dropped (erode by half the width, grow back by half), before the spokes go
25//!   in so a spoke is never eroded away;
26//! * with its ISLANDS removed: a separate piece of fill that touches no copper of
27//!   `N` is dropped.
28//!
29//! A via with no net of its own whose centre is inside the zone's polygon is taken
30//! as a STITCHING via of the zone's net rather than as copper to keep clear of —
31//! a via dropped into a ground pour is there to join it to the other side.
32//! Which net a netless via stitches is decided ONCE for the board, per copper
33//! island, before any zone is filled: the nets of every zone that holds one of
34//! the island's vias. One net, and the island is that net's. Two or more — a
35//! via where a GND pour on one side and a VCC pour on the other overlap — and it
36//! is stitched to NONE: each fill keeps clear of it, as of any other copper, and
37//! the fill report and the design rule check both name it
38//! ([`Board::contested_vias`]). Stitched to both, the plated barrel would join
39//! the two fills and the Gerbers would carry the short.
40//!
41//! # How it is computed
42//!
43//! On a square grid of [`PITCH`] (finer when the clearance is small), each sample
44//! holds how far it is INSIDE the fill region: the least of its distance inside
45//! the zone, inside the outline less the edge clearance, and its distance from
46//! each piece of other-net copper less the clearance. The fill's boundary is that
47//! function's zero contour, traced by marching squares with the crossing on each
48//! grid edge interpolated — so an edge round a pad is a smooth curve and not a
49//! staircase — and every ring is simplified to within [`SIMPLIFY`]. The contour is
50//! taken at [`Self`]'s margin rather than at zero, so what interpolation and
51//! simplification can cost is paid out of the fill and never out of the
52//! clearance: a fill measured from its Gerber is never nearer other copper than
53//! the rule.
54//!
55//! # When it is filled
56//!
57//! On demand ([`Board::fill_zones`], the board's Fill zones action) and by the
58//! board view's design rule check, which refills before it checks. NOT on every
59//! edit: the fill is the costliest thing on a board after the autorouter, and a
60//! drag is sixty edits a second. What was filled is STORED in the zone, so the
61//! Gerbers, the 3D view and the STEP export all draw the copper the user saw; the
62//! fabrication export refills a copy first, so a stale fill is never what is
63//! sent to be made.
64use 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
69/// A thermal relief's default gap round a through-hole pad: KiCad's 0.5 mm.
70pub const DEFAULT_THERMAL_GAP: i32 = 500;
71/// A thermal spoke's default width: KiCad's 0.5 mm.
72pub const DEFAULT_SPOKE_WIDTH: i32 = 500;
73/// The narrowest fill kept by default: KiCad's 0.25 mm.
74pub const DEFAULT_MIN_WIDTH: i32 = 250;
75/// The fill grid's pitch in micrometres, unless the clearance asks for a finer one.
76pub const PITCH: i32 = 50;
77/// How far, in micrometres, a simplified fill edge may stray from the traced one.
78pub const SIMPLIFY: f64 = 2.;
79/// The most grid samples one zone's fill takes; a bigger zone gets a coarser grid.
80const 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/// A copper zone: an outline on one copper layer, the net it pours, and the copper
93/// its last fill made.
94#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
95pub struct Zone {
96    pub id: Uuid,
97    /// The net the zone pours, by name.
98    pub net: String,
99    pub layer: u8,
100    /// Closed outline polygon, in board micrometres.
101    pub outline: Vec<Point>,
102    /// Gap round a through-hole pad of the zone's net, bridged by spokes.
103    #[serde(default = "default_thermal_gap")]
104    pub thermal_gap: i32,
105    #[serde(default = "default_spoke_width")]
106    pub spoke_width: i32,
107    /// Fill narrower than this is dropped.
108    #[serde(default = "default_min_width")]
109    pub min_width: i32,
110    /// The copper the last fill made. Empty until the zone is filled.
111    #[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    /// Filled copper area in square micrometres.
128    pub fn fill_area(&self) -> f64 {
129        // `+ 0.`: an empty float sum is -0.0, which read "-0.0 mm²".
130        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/// One connected piece of a zone's fill: its outer ring and the holes in it.
158#[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    /// Whether `p` is copper of this piece: inside the outer ring and in no hole.
166    pub fn contains(&self, p: Point) -> bool {
167        polygon_contains(&self.outer, p) && !self.holes.iter().any(|h| polygon_contains(h, p))
168    }
169    /// Every edge of every ring.
170    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    /// Area in square micrometres.
176    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    /// The gap between this piece and a copper shape; zero when they touch or overlap.
183    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    /// Whether a copper shape touches or overlaps this piece, to within 0.5 µm:
192    /// [`Self::distance`] `<= 0.5`, without measuring the edges that are nowhere
193    /// near it. The board view asks this for every item on the zone's layer on
194    /// every frame, so it pays for the edges beside the shape and no others.
195    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    /// The gap between two pieces; zero when they touch or overlap.
205    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
228/// The signed area of a ring in square micrometres, positive when it
229/// turns from +x towards +y.
230pub 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/// A through-hole pad of a zone's net and the spokes that join it to the fill.
240#[derive(Clone, Debug, PartialEq)]
241pub struct Thermal {
242    pub owner: CopperRef,
243    pub at: Point,
244    /// Spokes laid, 0 to 4. Zero means the zone does not reach the pad.
245    pub spokes: u8,
246}
247
248/// What one zone's fill did.
249#[derive(Clone, Debug, PartialEq)]
250pub struct ZoneReport {
251    pub zone: Uuid,
252    pub pieces: usize,
253    /// Filled area in square micrometres.
254    pub area: f64,
255    /// Pieces dropped because they touched no copper of the zone's net.
256    pub islands_removed: usize,
257    pub thermals: Vec<Thermal>,
258    /// The grid pitch the fill was computed on, in micrometres.
259    pub pitch: i32,
260    /// Why the zone has no fill at all, when it has none.
261    pub empty_because: Option<String>,
262    /// Netless vias inside this zone that it did NOT stitch, because a zone of
263    /// another net holds them too: each via's centre and the other nets.
264    pub unstitched: Vec<(Point, Vec<String>)>,
265}
266
267/// A via with no net that zones of more than one net hold, and which is therefore
268/// stitched to none of them.
269#[derive(Clone, Debug, PartialEq)]
270pub struct ContestedVia {
271    /// Index into [`Board::vias`].
272    pub via: usize,
273    pub at: Point,
274    /// Every net whose zones hold a via of this via's copper island, in order.
275    pub nets: Vec<String>,
276    /// The zones that hold THIS via, by index into [`Board::zones`].
277    pub zones: Vec<usize>,
278}
279
280/// Which net each netless copper island is stitched to, decided once for the
281/// board: the island's vias, the zones whose polygon holds one of them on a
282/// layer the via reaches, and those zones' nets. `conn` is the connectivity
283/// WITHOUT any fill.
284struct Stitching {
285    /// The island's net, where exactly one net's zones hold its vias.
286    net: HashMap<usize, String>,
287    /// Every net claiming each island that more than one net claims.
288    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    /// Fill every zone of the board against the schematic's nets.
317    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    /// Refill every zone, in the order they were drawn, and say what each fill did.
325    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    /// Whether any zone's fill differs from what a fill now would make.
337    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    /// The vias with no net that zones of two or more nets hold, which the fill
346    /// therefore stitches to none of them, in the order of [`Board::vias`].
347    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    /// A design rule finding for each contested via ([`Self::contested_vias`]),
365    /// naming it by where it is and the zones that hold it.
366    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                // Held by zones of both nets itself, or by one net's zone and
374                // joined by copper to a via another net's zone holds.
375                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
400/// What the field at a sample is made of: the copper to keep clear of, and the
401/// pads to relieve.
402enum Obstacle {
403    /// Other-net copper: keep `clearance` from the shape.
404    Keep(Shape, f64),
405    /// Another zone's outline, taken whole: keep `clearance` from it.
406    Zone(Vec<Point>, f64),
407}
408
409/// Signed distance from `p` to a closed polygon: positive inside.
410fn 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
418/// A sampled scalar field over a rectangle of the board.
419struct 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    /// The field at any point, bilinear between samples; `-inf` off the grid.
435    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
449/// Buckets of obstacles by square cell, so a sample asks only those near it.
450struct 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
484/// The net each item's copper island carries, and which vias count as the zone's.
485fn item_net<'a>(conn: &'a Connectivity, i: usize) -> Option<&'a str> {
486    conn.island_net(conn.islands[i])
487}
488
489/// Fill zone `index` of `board`. `conn` is the board's connectivity WITHOUT any
490/// zone's fill, so a stale fill never decides which net a track is on.
491fn 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    // Each piece of copper is kept clear by the larger of its net's class
505    // clearance and the zone's ([`DesignRules::clearance_between`]); the zone's own
506    // class clearance is the least any obstacle is kept clear by.
507    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    // The rectangle to sample: the zone's bounds within the outline's.
518    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    // A pitch fine enough that a clearance spans two samples, coarse enough that
529    // the grid stays within MAX_SAMPLES.
530    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    // What interpolation, the simplification and rounding to whole micrometres can
537    // cost at worst, taken out of the fill: the chord across a cell of a curve of
538    // radius the clearance sags by (√2 h)² / 8r, and the rest is fixed.
539    let radius = f64::from(own.max(h));
540    let margin = (2. * f64::from(h * h) / (8. * radius) + SIMPLIFY + 1. + 1.) as f32;
541
542    // One ring of samples beyond the rectangle on every side, all outside, so every
543    // contour closes.
544    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    // The copper: what to keep clear of, what to relieve, what is solid.
550    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        // A netless via in the zone joins it only when its island was given the
559        // zone's net for the whole board ([`stitching`]); one another net's zone
560        // also holds is kept clear of, and said.
561        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    // A cutout is a hole in the board: the fill keeps the edge clearance from it
586    // as it does from the outline.
587    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    // Far from every obstacle the field only needs to be known up to a cap: past
597    // it, nothing the fill decides changes.
598    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    // The base field: how far inside the fill region each sample is, before the
615    // thermal gaps, and the thermal gaps.
616    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    // Open by the minimum width: a sample stays where some sample at least half the
644    // width deep is within half the width of it, measured to the edge of that deep
645    // sample's own disc (the field is a distance, so a sample `d` deep has a disc of
646    // radius `d - w/2` that is all deep).
647    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            // Slack of a micrometre so a wide region's own edge is not nibbled.
672            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    // Spokes: from each relieved pad's centre out along ±x and ±y, through the gap
679    // and a spoke's width into the fill, laid only where the fill is there to meet.
680    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    // Trace, sort into pieces, drop the islands.
715    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    // Each hole goes to the smallest outer ring that holds it.
740    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    // Largest first: the order a painter draws them in, and the one they are read in.
763    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
779/// The zero contour of a field, as closed rings in board micrometres, the fill
780/// (the positive side) on the left of each: outer rings turn positively, holes
781/// negatively. Marching squares, with each crossing interpolated along its grid
782/// edge and a saddle resolved by the cell's mean.
783fn 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    // Edge ids: 2·(j·nx + i) is the edge from sample (i, j) to (i+1, j); one more is
790    // the edge from (i, j) to (i, j+1).
791    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            // Edge k runs from corner k to corner k+1: an exit where the fill ends
816            // along it, an entry where it starts.
817            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
857/// A closed ring simplified to within `tolerance`: Douglas–Peucker on the two
858/// halves between the first point and the point farthest from it.
859fn 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
899/// Trapezoids covering a set of rings by the even-odd rule, as triangles: each
900/// strip between two consecutive vertex heights is cut where the rings' edges
901/// cross it and filled between alternate crossings. Robust for any rings that do
902/// not cross one another, holes included, which is what a fill is — and what
903/// neither a fan nor ear clipping without hole bridging can draw.
904///
905/// The triangles are WATERTIGHT: where a strip meets the next, each side's edge
906/// is split at every point the other side has on that line, and every point is
907/// computed once, so two neighbouring triangles share their corners exactly and
908/// no edge inside the fill is used by one triangle alone (the 3D view outlines a
909/// hovered face by exactly those edges). A trapezoid with points on its top or
910/// bottom edge is fanned from its centre.
911pub 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    // An edge's x at `y`, EXACT at both of its ends, so the edge that ends at a
929    // vertex and the one that starts there agree on it to the bit.
930    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    // Each strip's filled spans: (x left, x right) at its top and at its bottom.
940    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    // Every point on each horizontal line, from the strips on both sides of it.
968    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
1024/// A piece's rings as ONE ring, each hole joined to the outside by a cut-in: a
1025/// zero-width slit from the hole's leftmost vertex straight left to the nearest
1026/// edge, walked in and back out. The way a Gerber region carries a hole without a
1027/// clear-polarity step (which would also clear any copper drawn before it).
1028/// The outer ring comes out turning positively and each hole negatively.
1029pub 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            // Start each hole at its leftmost vertex.
1043            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        // The nearest edge of the ring so far that the ray from `v` leftwards meets.
1052        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            // Half-open, so a ring vertex level with `v` is met once.
1057            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
1085/// A zone's settings as a line: "GND on B.Cu".
1086pub fn describe(zone: &Zone, layer_count: u8) -> String {
1087    format!("{} zone on {}", zone.net, super::layer_name(zone.layer, layer_count))
1088}