Skip to main content

brep_render/engine_state/
board_geometry.rs

1//! The BOARD in 3D: the substrate solid, the copper on each layer, and the
2//! plated via barrels through it — derived from the document's `pcb` block,
3//! never a feature.
4//!
5//! # Why it is derived and not a feature
6//!
7//! A board's geometry is a READING of eCAD's board, the way a part's declared
8//! connection points are a reading of its `ports` block (the 2026-09-20 ports
9//! record). It has no parameters a user would edit in a dialog, no place in the
10//! history order — nothing downstream can reference it, because nothing is
11//! ordered against it — and it must follow every track the router lays down
12//! without an undo step of its own. So it is rebuilt at the TAIL, after the run
13//! ([`EngineState::finish_apply`]) and after any write to the `pcb` block, from
14//! the block alone. The PCB workbench still creates no feature of its own.
15//!
16//! It is built HERE rather than in the kernel for two reasons: the kernel is
17//! told only that a `pcb` block is PRESENT (`HistoryRequest::pcb_present`) and
18//! deliberately neither reads nor rewrites it, and this crate already holds
19//! both `brep_ecad_core` and the scene. The cost is stated plainly below.
20//!
21//! # DISPLAY geometry, not kernel solids
22//!
23//! Every body this module inserts is a synthesized [`SolidDisplay`] with
24//! `source_handle == 0` — triangles, not B-rep. That is the cheap thing, built
25//! first and on purpose: it is visible, correctly placed, coloured, listed in
26//! the Scene tree, hideable and pickable, and it costs one GPU buffer set per
27//! LAYER however many track segments the layer carries. What it cannot do:
28//!
29//!   * it cannot be cut against — no boolean takes it as a tool or a target;
30//!   * it has no mass properties and no measurable exact topology;
31//!   * a drawing sheet that draws it falls back to MESH hidden-line for the
32//!     whole view, because the analytic pass needs every drawn solid's B-rep;
33//!   * it is not what STEP export writes: the export builds the board again as
34//!     exact solids ([`step_solids`]), handed straight to the writer and never
35//!     entered in the scene or the kernel's registry.
36//!
37//! Real SCENE solids would have to be minted on the RUNNER thread, where the
38//! kernel's solid registry lives, which means a kernel tail, which means the
39//! kernel reading eCAD's block. That is a layering decision, not a day's work.
40//!
41//! # The stack
42//!
43//! Board coordinates are integer micrometres with +Y DOWN; BREP is millimetres
44//! with +Y up, so every point is `x / 1000, -y / 1000` — the same conversion
45//! the placement writer makes (`ecad_parts::follow_sheet`), which is what keeps
46//! a part's pins over its pads. `board::layer_z` puts F.Cu's plane at 0, B.Cu's
47//! at `-SUBSTRATE_THICKNESS` and the inner layers evenly between, so a 2-layer
48//! and a 4-layer board come out of the same arithmetic. The substrate fills
49//! `[-SUBSTRATE_THICKNESS, 0]`; copper stands `COPPER_THICKNESS` proud of its
50//! own plane, outward on the two outer layers and centred on an inner one.
51
52use super::*;
53use brep_ecad_core::board::{self, Board, CopperItem, Shape};
54use brep_ecad_core::graphic::GraphicLayer;
55use brep_ecad_core::Netlist;
56use brep_kernel::{DisplaySolidPayload, Mesh, Vec3};
57use std::collections::BTreeMap;
58
59/// Every board body's name leads with this, so the scene, the Scene tree and
60/// the stale sweep can tell one apart from a feature's solid. No `:` — that is
61/// the occurrence namespace an assembly reads.
62pub const BOARD_SOLID_PREFIX: &str = "PCB_";
63/// The substrate body's scene name.
64pub const SUBSTRATE_SOLID: &str = "PCB_Board";
65/// The via-barrel body's scene name.
66pub const VIAS_SOLID: &str = "PCB_Vias";
67
68/// Separates a board body's name from the ROLE of one of its faces —
69/// `PCB_F.Cu/GND` is the GND copper on F.Cu, `PCB_F.Mask/Opening` is the bare
70/// metal the mask leaves open. `:` is the assembly occurrence namespace and `|`
71/// is the kernel's edge-name convention, so neither may be borrowed here.
72///
73/// A face name is a metadata key and the label the UI shows for what the
74/// pointer is over, which is what makes net colouring readable WITHOUT a
75/// legend: the colour says "these are one net" and hovering says which.
76const FACE_SEPARATOR: char = '/';
77/// The face name of copper on an island that carries no single schematic net.
78const NO_NET_FACE: &str = "(no net)";
79/// The face name of the mask's bare-metal openings.
80const OPENING_FACE: &str = "Opening";
81/// The face name of the mask lacquer itself.
82const LACQUER_FACE: &str = "Lacquer";
83/// The face name of one of the substrate's side walls, numbered from 1 —
84/// `PCB_Board/Side 3`. One wall per side of the outline between two corners,
85/// so a rectangular board has four, as a box does.
86const SIDE_FACE: &str = "Side";
87/// The face name of one cutout's walls, numbered from 1 in the board's order of
88/// cutouts — `PCB_Board/Cutout 2`. A cutout is one wall all the way round.
89const CUTOUT_FACE: &str = "Cutout";
90/// A board outline corner turning by more than this, in radians, gets a
91/// vertical display edge down the wall. A corner a polygon rounds with many
92/// short sides turns a little at each and gets none, so a rounded board is not
93/// combed with verticals.
94const CORNER_TURN: f64 = 0.5;
95
96/// The substrate's cut EDGE: the pale fibreglass-and-epoxy core a board shows
97/// where it was routed out of its panel, since the green is only on its two
98/// faces. Drawn in the green, the edge read as a shadow of the top face and a
99/// user looking for the board's thickness did not find it.
100const EDGE_COLOR: [f32; 3] = [0xb8 as f32 / 255., 0xa8 as f32 / 255., 0x7a as f32 / 255.];
101/// FR-4 green.
102const SUBSTRATE_COLOR: [f32; 3] = [0x1c as f32 / 255., 0x5e as f32 / 255., 0x38 as f32 / 255.];
103/// Bare copper.
104const COPPER_COLOR: [f32; 3] = [0xc0 as f32 / 255., 0x7b as f32 / 255., 0x38 as f32 / 255.];
105/// Solder-mask lacquer — darker and glossier than the bare substrate, so a
106/// board with the mask shown and one with it hidden do not read the same.
107const MASK_COLOR: [f32; 3] = [0x12 as f32 / 255., 0x44 as f32 / 255., 0x26 as f32 / 255.];
108/// Silkscreen ink.
109const SILK_COLOR: [f32; 3] = [0xec as f32 / 255., 0xec as f32 / 255., 0xe4 as f32 / 255.];
110
111/// How far the mask lacquer stands over the copper it covers, in board
112/// micrometres. A CONSTANT and not a [`board::DesignRules`] field, for the
113/// reason `SUBSTRATE_THICKNESS` is one: a new always-serialized field puts
114/// every `pcb` block written before it out of step with its editor.
115const MASK_OVER_COPPER: i32 = 20;
116/// How thick the silkscreen ink is drawn, on top of the lacquer.
117const SILK_THICKNESS: i32 = 15;
118
119/// Facets per HALF-turn on a round copper end or a via barrel — so eight round
120/// a full circle. Small on purpose: a track end is a fraction of a millimetre
121/// across and a dense board has thousands of them, so this number multiplies
122/// the whole scene's triangle count. The measured figures in the validation
123/// record are at this value.
124const ARC_FACETS: usize = 4;
125
126/// Board micrometres to millimetres, +Y down to +Y up.
127fn xy(p: brep_ecad_core::Point) -> [f64; 2] {
128    [f64::from(p.x) / 1000., -f64::from(p.y) / 1000.]
129}
130
131/// Millimetres from board micrometres, for a length rather than a position.
132fn mm(v: i32) -> f64 {
133    f64::from(v) / 1000.
134}
135
136/// A triangle soup being built, with flat normals and one face id per triangle.
137/// A planar piece — a quad, a cap — shares its corners between its triangles.
138/// Triangles are emitted face by face, because the display builder groups each
139/// face's triangles by their first contiguous run.
140#[derive(Default)]
141struct Soup {
142    mesh: Mesh,
143}
144
145impl Soup {
146    fn vertex(&mut self, p: [f64; 3], n: [f64; 3]) -> u32 {
147        self.mesh.positions.extend(p);
148        self.mesh.normals.extend(n);
149        (self.mesh.positions.len() / 3 - 1) as u32
150    }
151
152    /// A planar quad as two triangles that SHARE its four corners. A hovered
153    /// face is outlined by the mesh edges only one of its triangles uses, so
154    /// a corner per triangle would outline the quad's diagonal as well.
155    fn quad(&mut self, a: [f64; 3], b: [f64; 3], c: [f64; 3], d: [f64; 3], face: u32) {
156        let n = normal(a, b, c);
157        let [ia, ib, ic, id] = [a, b, c, d].map(|p| self.vertex(p, n));
158        self.mesh.indices.extend([ia, ib, ic, ia, ic, id]);
159        self.mesh.face_ids.extend([face, face]);
160    }
161
162    /// The walls of the prism `loop_xy` sweeps between `lo` and `hi`. The loop
163    /// is counter-clockwise, so the walls face outwards: each quad runs
164    /// `a -> b` along the bottom, and the right of that direction — outside a
165    /// counter-clockwise loop — is where its normal points
166    /// (`every_wall_faces_out_of_the_copper_and_the_board` pins it).
167    fn walls(&mut self, loop_xy: &[[f64; 2]], lo: f64, hi: f64, face: u32) {
168        for i in 0..loop_xy.len() {
169            let a = loop_xy[i];
170            let b = loop_xy[(i + 1) % loop_xy.len()];
171            self.quad(
172                [a[0], a[1], lo],
173                [b[0], b[1], lo],
174                [b[0], b[1], hi],
175                [a[0], a[1], hi],
176                face,
177            );
178        }
179    }
180
181    /// The wall of one open run of an outline — `walls` without the quad that
182    /// closes the loop — so each side of the board is a face of its own.
183    fn walls_open(&mut self, run: &[[f64; 2]], lo: f64, hi: f64, face: u32) {
184        for pair in run.windows(2) {
185            let (a, b) = (pair[0], pair[1]);
186            self.quad([a[0], a[1], lo], [b[0], b[1], lo], [b[0], b[1], hi], [a[0], a[1], hi], face);
187        }
188    }
189
190    /// One cap of that prism, at `z`, facing `up` or down.
191    ///
192    /// Its triangles share the loop's corners, for the reason [`Self::quad`]'s
193    /// do: hovering the cap outlines the loop, not its triangulation.
194    fn cap(&mut self, loop_xy: &[[f64; 2]], triangles: &[[usize; 3]], z: f64, up: bool, face: u32) {
195        let n = if up { [0., 0., 1.] } else { [0., 0., -1.] };
196        let first = self.mesh.positions.len() as u32 / 3;
197        for p in loop_xy {
198            self.vertex([p[0], p[1], z], n);
199        }
200        for &[a, b, c] in triangles {
201            let (b, c) = if up { (b, c) } else { (c, b) };
202            self.mesh.indices.extend([a, b, c].map(|i| first + i as u32));
203            self.mesh.face_ids.push(face);
204        }
205    }
206
207    /// One piece of a zone's fill swept between `lo` and `hi`, as ONE face: its
208    /// caps from the even-odd trapezoids of its rings (`zones::fill_triangles`,
209    /// which draws the holes a fan or plain ear clipping cannot), and walls round
210    /// the outer ring and every hole, each facing out of the copper.
211    fn slab(&mut self, piece: &board::FillPiece, lo: f64, hi: f64, face: u32) {
212        let rings: Vec<&[brep_ecad_core::Point]> = std::iter::once(piece.outer.as_slice())
213            .chain(piece.holes.iter().map(Vec::as_slice))
214            .collect();
215        // The caps SHARE their corners: the triangles are watertight, and a
216        // hovered face is outlined by the edges only one triangle uses, so a
217        // corner per triangle would outline every triangle of the fill.
218        let triangles = board::zones::fill_triangles(&rings);
219        for (z, up) in [(hi, true), (lo, false)] {
220            let n = if up { [0., 0., 1.] } else { [0., 0., -1.] };
221            let mut shared: std::collections::HashMap<(u64, u64), u32> = std::collections::HashMap::new();
222            for &[a, b, c] in &triangles {
223                let ccw = (b.0 - a.0) * (c.1 - a.1) - (b.1 - a.1) * (c.0 - a.0) < 0.;
224                // Board +y is down, so a turn that is clockwise there is
225                // counter-clockwise here.
226                let (b, c) = if ccw == up { (b, c) } else { (c, b) };
227                let corners = [a, b, c].map(|(x, y)| {
228                    *shared
229                        .entry((x.to_bits(), y.to_bits()))
230                        .or_insert_with(|| self.vertex([x / 1000., -y / 1000., z], n))
231                });
232                self.mesh.indices.extend(corners);
233                self.mesh.face_ids.push(face);
234            }
235        }
236        for (k, ring) in rings.iter().enumerate() {
237            let mut ring: Vec<[f64; 2]> = ring.iter().copied().map(xy).collect();
238            if (signed_area2(&ring) < 0.) == (k == 0) {
239                ring.reverse();
240            }
241            self.walls(&ring, lo, hi, face);
242        }
243    }
244
245    /// A whole closed prism — bottom cap, top cap, walls — as ONE face.
246    fn prism(&mut self, loop_xy: &[[f64; 2]], lo: f64, hi: f64, face: u32) {
247        let triangles = fan_or_ears(loop_xy);
248        self.cap(loop_xy, &triangles, lo, false, face);
249        self.cap(loop_xy, &triangles, hi, true, face);
250        self.walls(loop_xy, lo, hi, face);
251    }
252}
253
254fn normal(a: [f64; 3], b: [f64; 3], c: [f64; 3]) -> [f64; 3] {
255    let u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
256    let v = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
257    let n = [
258        u[1] * v[2] - u[2] * v[1],
259        u[2] * v[0] - u[0] * v[2],
260        u[0] * v[1] - u[1] * v[0],
261    ];
262    let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
263    if len > 1e-12 {
264        [n[0] / len, n[1] / len, n[2] / len]
265    } else {
266        [0., 0., 1.]
267    }
268}
269
270/// Twice the signed area of `loop_xy` — positive counter-clockwise.
271fn signed_area2(loop_xy: &[[f64; 2]]) -> f64 {
272    let mut sum = 0.;
273    for i in 0..loop_xy.len() {
274        let a = loop_xy[i];
275        let b = loop_xy[(i + 1) % loop_xy.len()];
276        sum += a[0] * b[1] - b[0] * a[1];
277    }
278    sum
279}
280
281/// Triangulate a simple polygon given counter-clockwise, as index triples.
282///
283/// Ear clipping, because a board outline is an arbitrary simple polygon and a
284/// fan is only right for a convex one. Copper shapes ARE convex and clip in one
285/// pass, so they pay for the generality in comparisons rather than in passes.
286/// A polygon this cannot finish (self-crossing, or a hole the outline was drawn
287/// with) falls back to a fan, which draws something wrong rather than nothing —
288/// the board is a picture here, and a missing board reads as a bug in the
289/// router rather than in its outline.
290fn fan_or_ears(loop_xy: &[[f64; 2]]) -> Vec<[usize; 3]> {
291    let n = loop_xy.len();
292    if n < 3 {
293        return Vec::new();
294    }
295    let fan = || (1..n - 1).map(|i| [0, i, i + 1]).collect::<Vec<_>>();
296    let mut remaining: Vec<usize> = (0..n).collect();
297    let mut out = Vec::with_capacity(n - 2);
298    let convex = |a: [f64; 2], b: [f64; 2], c: [f64; 2]| {
299        (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
300    };
301    let inside = |a: [f64; 2], b: [f64; 2], c: [f64; 2], p: [f64; 2]| {
302        convex(a, b, p) >= 0. && convex(b, c, p) >= 0. && convex(c, a, p) >= 0.
303    };
304    // Each pass must clip at least one ear; a pass that clips none is a polygon
305    // this cannot handle, and the fan takes over.
306    while remaining.len() > 3 {
307        let before = remaining.len();
308        let mut i = 0;
309        while remaining.len() > 3 && i < remaining.len() {
310            let (ia, ib, ic) = (
311                remaining[(i + remaining.len() - 1) % remaining.len()],
312                remaining[i],
313                remaining[(i + 1) % remaining.len()],
314            );
315            let (a, b, c) = (loop_xy[ia], loop_xy[ib], loop_xy[ic]);
316            if convex(a, b, c) <= 0. {
317                i += 1;
318                continue;
319            }
320            if remaining
321                .iter()
322                .any(|&p| p != ia && p != ib && p != ic && inside(a, b, c, loop_xy[p]))
323            {
324                i += 1;
325                continue;
326            }
327            out.push([ia, ib, ic]);
328            remaining.remove(i);
329        }
330        if remaining.len() == before {
331            return fan();
332        }
333    }
334    out.push([remaining[0], remaining[1], remaining[2]]);
335    out
336}
337
338/// A copper primitive's outline in millimetres, counter-clockwise: a rectangle
339/// as four corners, a capsule as a stadium closed by two [`ARC_FACETS`] arcs
340/// (a circle when its ends coincide).
341fn shape_loop(shape: &Shape) -> Vec<[f64; 2]> {
342    match shape.clone() {
343        Shape::RoundRect { .. } | Shape::Polygon { .. } => {
344            // Board y points down, so the outline's turn reverses in millimetres:
345            // walk it backwards to stay counter-clockwise.
346            let mut out: Vec<[f64; 2]> = shape.outline(ARC_FACETS).into_iter().map(xy).collect();
347            out.reverse();
348            out
349        }
350        Shape::Rect { min, max } => {
351            let (a, b) = (xy(min), xy(max));
352            let (x0, x1) = (a[0].min(b[0]), a[0].max(b[0]));
353            let (y0, y1) = (a[1].min(b[1]), a[1].max(b[1]));
354            vec![[x0, y0], [x1, y0], [x1, y1], [x0, y1]]
355        }
356        Shape::Capsule { a, b, radius } => {
357            let (a, b, r) = (xy(a), xy(b), mm(radius).max(1e-4));
358            let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
359            let len = (dx * dx + dy * dy).sqrt();
360            // A circle: one closed ring about the single centre.
361            if len <= 1e-9 {
362                return (0..ARC_FACETS * 2)
363                    .map(|i| {
364                        let t = std::f64::consts::TAU * i as f64 / (ARC_FACETS * 2) as f64;
365                        [a[0] + r * t.cos(), a[1] + r * t.sin()]
366                    })
367                    .collect();
368            }
369            // A stadium: the half-ring round `b`, then the half-ring round `a`.
370            // `base` is the direction a->b, so the arcs sweep the far side of
371            // each end and the two straights close the loop.
372            let base = dy.atan2(dx) - std::f64::consts::FRAC_PI_2;
373            let mut out = Vec::with_capacity(2 * (ARC_FACETS + 1));
374            for (centre, start) in [(b, base), (a, base + std::f64::consts::PI)] {
375                for i in 0..=ARC_FACETS {
376                    let t = start + std::f64::consts::PI * i as f64 / ARC_FACETS as f64;
377                    out.push([centre[0] + r * t.cos(), centre[1] + r * t.sin()]);
378                }
379            }
380            out
381        }
382    }
383}
384
385/// The z span of copper on `layer`: proud of the board on the two outer layers,
386/// centred on its own plane on an inner one (where there is no "outward").
387fn copper_span(layer: u8, layer_count: u8) -> (f64, f64) {
388    let plane = mm(board::layer_z(layer, layer_count));
389    let t = mm(board::COPPER_THICKNESS);
390    let last = layer_count.saturating_sub(1);
391    if layer == 0 {
392        (plane, plane + t)
393    } else if layer >= last {
394        (plane - t, plane)
395    } else {
396        (plane - t * 0.5, plane + t * 0.5)
397    }
398}
399
400/// The OUTER plane of one side of the board and the direction that is "out of
401/// the board" there: the top side's plane is 0 and its outward `+1`, the bottom
402/// side's is `-SUBSTRATE_THICKNESS` and `-1`. Everything above the copper — the
403/// mask lacquer, its openings, the silkscreen — is stacked from here, so the
404/// two sides come out of one arithmetic the way the copper layers do.
405fn side_frame(top: bool) -> (f64, f64) {
406    if top {
407        (0., 1.)
408    } else {
409        (mm(-board::SUBSTRATE_THICKNESS), -1.)
410    }
411}
412
413/// A slab on one side of the board, `from`..`to` micrometres OUT from that
414/// side's plane, as an ordered `(lo, hi)` millimetre pair — [`Soup::prism`]
415/// wants its caps the right way up, and the bottom side's "out" is `-z`.
416fn side_span(top: bool, from: i32, to: i32) -> (f64, f64) {
417    let (plane, out) = side_frame(top);
418    let (a, b) = (plane + out * mm(from), plane + out * mm(to));
419    (a.min(b), a.max(b))
420}
421
422/// The top of the mask lacquer, in micrometres out from its side's plane: over
423/// the copper, because the lacquer covers the copper it is not open over.
424const LACQUER_TOP: i32 = board::COPPER_THICKNESS + MASK_OVER_COPPER;
425
426/// One copper primitive's shape grown by `grow` on every side — a pad's solder
427/// mask OPENING, which [`board::DesignRules::mask_expansion`] sizes. The same
428/// growth `fabrication`'s Gerber writer applies when it flashes the aperture.
429fn grown(shape: Shape, grow: i32) -> Shape {
430    shape.grown(grow)
431}
432
433/// The board outline in millimetres, wound counter-clockwise for the caps and
434/// walls. eCAD stores it in a +Y-down frame, so a polygon wound one way there
435/// is wound the other here. `None` for an outline that is not a polygon.
436fn oriented_outline(board: &Board) -> Option<Vec<[f64; 2]>> {
437    let mut outline: Vec<[f64; 2]> = board.outline.iter().copied().map(xy).collect();
438    // Board documents may explicitly close their polygon, or repeat a point
439    // between segments. Our loops close implicitly. Repeated vertices block
440    // ear clipping (the duplicate lies on an ear) and create zero-length walls.
441    // Normalize here so caps, walls, and display edges use the same boundary.
442    outline.dedup();
443    if outline.len() > 1 && outline.first() == outline.last() {
444        outline.pop();
445    }
446    if outline.len() < 3 {
447        return None;
448    }
449    if signed_area2(&outline) < 0. {
450        outline.reverse();
451    }
452    Some(outline)
453}
454
455/// The scene name of one side's solder mask, KiCad's own (`F.Mask` / `B.Mask`).
456fn mask_solid(top: bool) -> String {
457    format!("{BOARD_SOLID_PREFIX}{}.Mask", if top { "F" } else { "B" })
458}
459
460/// The scene name of one side's silkscreen, KiCad's own (`F.SilkS` / `B.SilkS`).
461fn silk_solid(top: bool) -> String {
462    format!("{BOARD_SOLID_PREFIX}{}.SilkS", if top { "F" } else { "B" })
463}
464
465/// The RAILS that have a conventional colour, the spellings of each this
466/// recognises, and that colour — consulted before the hash by [`net_color`].
467///
468/// **The convention is the ATX supply wire code plus the test-lead colours it
469/// grew out of**: ground black, the positive supply red, +3.3 V orange, +12 V
470/// yellow, −12 V blue. The CHOICE OF HUE is therefore not this project's
471/// invention. A wire colour has no hex, though, so the exact point inside each
472/// band IS chosen here — and it was chosen by MEASUREMENT, not by taste.
473///
474/// **Matching is EXACT, case-insensitively, against a spelling in this table.**
475/// That is forgiving about the two things eCAD tools actually disagree on —
476/// the case of a name and whether a voltage rail carries a `+` — and reckless
477/// about nothing: there is no prefix strip, no suffix strip and no substring
478/// test, so `AGND`, `DGND`, `GND1`, `VCC_IO` and `GNDBREAK` all fall through to
479/// the hash. A board that splits its ground names it split on purpose, and
480/// painting `AGND` and `DGND` the one ground colour would put back the very
481/// defect this table exists to fix.
482///
483/// **A row is a RAIL, not a net, so the map is deliberately many-to-one.** A
484/// board carrying `VCC` and `+5V` as two DISTINCT nets draws both in the
485/// supply red. That is the price of naming the rail rather than the net, and
486/// the face name — `PCB_F.Cu/VCC` against `PCB_F.Cu/+5V` — is what separates
487/// them, exactly as it does for two hashed nets that collide.
488const CURATED_RAILS: &[(&[&str], u32)] = &[
489    // Ground is black on a test lead, in an ATX loom and in an automotive
490    // harness alike. Drawn as a near-black GREY, not `#000`: the viewport
491    // background is a dark slate (`0x131b24` since 2026-10-14, `0x0b0d10`
492    // before) and a true black track loses its silhouette where it crosses
493    // the board edge.
494    (&["GND", "VSS", "0V"], 0x3a3a40),
495    // The positive supply is red by the same three conventions, and ATX's red
496    // IS +5 V — `VCC` was a 5 V rail before it was a name, so the supply names
497    // and the 5 V spellings are one row rather than two shades of one red.
498    (&["VCC", "VDD", "+5V", "5V"], 0xcc1111),
499    // ATX orange, unmodified — and the row that had to be MEASURED hardest,
500    // because bare copper is itself an orange. This clears the `(no net)`
501    // default by ΔE00 12.3, which is the smallest gap in the whole set and is
502    // reported rather than hidden; a duller orange does not. `#e07000` sits
503    // ΔE00 8.0 from bare copper and a 3.3 V track drawn in it would read as
504    // unnetted copper.
505    (&["+3V3", "3V3", "+3.3V", "3.3V"], 0xff8000),
506    // ATX yellow.
507    (&["+12V", "12V"], 0xe8d400),
508    // ATX blue, its only negative rail. `VEE` is NOT here: it means "the
509    // negative supply" at no particular voltage, and giving it this blue would
510    // be inventing a convention rather than following one.
511    (&["-12V"], 0x1b4fc8),
512];
513
514/// A stable colour for a NET: the conventional colour of the RAIL it names if
515/// it names one, and otherwise the app's own name-hashed palette — the same
516/// function that gives an unpainted BODY its colour, asked about the net's name
517/// rather than the body's.
518///
519/// One function either way, so a net is the same colour on F.Cu as on B.Cu.
520/// Two nets share a colour only if they are the same net OR they name the same
521/// rail in [`CURATED_RAILS`]; the hash gives no separation guarantee at all,
522/// which is why the rails that MUST be told apart are not left to it.
523fn net_color(net: &str) -> [f32; 3] {
524    curated_rail_color(net)
525        .unwrap_or_else(|| crate::color::solid_color_srgb(net))
526        .map(|c| c as f32)
527}
528
529/// The conventional colour of the rail `net` names, or `None` for a net that
530/// names no rail in [`CURATED_RAILS`].
531fn curated_rail_color(net: &str) -> Option<[f64; 3]> {
532    CURATED_RAILS.iter().find_map(|(spellings, hex)| {
533        spellings
534            .iter()
535            .any(|spelling| spelling.eq_ignore_ascii_case(net))
536            .then(|| crate::color::hex_to_srgb(*hex))
537    })
538}
539
540/// The colour a board body or one of its FACES draws in when the metadata store
541/// has none of its own for it — the fallback `sync_colors_from_metadata`
542/// reaches for, since a derived body has no producing feature to have been
543/// coloured by. `None` for every name that is not a board body's or a face of
544/// one; a stored `color` attribute still wins over all of it.
545pub fn default_color(name: &str) -> Option<[f32; 3]> {
546    let rest = name.strip_prefix(BOARD_SOLID_PREFIX)?;
547    // `PCB_<body>/<role>` is a face; anything else is a body. Only the bodies
548    // that need more than one colour name their faces at all — the barrels'
549    // Barrel and the silkscreen's Ink carry no prefix and inherit their body.
550    // The split is on the FIRST separator and no body's name contains one, so a
551    // net whose own name does round-trips.
552    let Some((body, role)) = rest.split_once(FACE_SEPARATOR) else {
553        return Some(body_color(rest));
554    };
555    // A face that would draw in its BODY'S OWN colour carries NO override.
556    // `face_style_palette` re-arms the renderer's whole-mesh fast path only for
557    // a solid with no per-face colours at all, so a board with no nets — every
558    // document nobody has drawn a schematic for — must not pay a style buffer
559    // and a per-face draw for one face that changes nothing.
560    let color = face_color(body, role);
561    (color != body_color(body)).then_some(color)
562}
563
564/// The default colour of a board body, named without [`BOARD_SOLID_PREFIX`].
565fn body_color(body: &str) -> [f32; 3] {
566    if body == "Board" {
567        SUBSTRATE_COLOR
568    } else if body.ends_with(".Mask") {
569        MASK_COLOR
570    } else if body.ends_with(".SilkS") {
571        SILK_COLOR
572    } else {
573        COPPER_COLOR
574    }
575}
576
577/// The default colour of one face of a board body. The BODY decides how to read
578/// the role, so a net that happens to be called `Opening` is still a net.
579fn face_color(body: &str, role: &str) -> [f32; 3] {
580    if body == "Board" {
581        if role.starts_with(SIDE_FACE) || role.starts_with(CUTOUT_FACE) {
582            EDGE_COLOR
583        } else {
584            SUBSTRATE_COLOR
585        }
586    } else if body.ends_with(".Mask") {
587        if role == OPENING_FACE {
588            COPPER_COLOR
589        } else {
590            MASK_COLOR
591        }
592    } else if role == NO_NET_FACE {
593        COPPER_COLOR
594    } else {
595        net_color(role)
596    }
597}
598
599/// One built body: its scene name, its colour, and the payload to display.
600struct Body {
601    name: String,
602    color: [f32; 3],
603    payload: DisplaySolidPayload,
604    /// The index of the first DISPLAY-ONLY edge in `payload.edges`: the copper
605    /// outline, which is drawn and not picked (see [`copper_outline`]).
606    aux_from: usize,
607}
608
609fn body(name: String, color: [f32; 3], faces: Vec<String>, soup: Soup) -> Option<Body> {
610    if soup.mesh.indices.is_empty() {
611        return None;
612    }
613    Some(Body {
614        name,
615        color,
616        aux_from: usize::MAX,
617        payload: DisplaySolidPayload {
618            faces: faces
619                .into_iter()
620                .enumerate()
621                .map(|(i, name)| (i as u64, Some(name)))
622                .collect(),
623            mesh: soup.mesh,
624            edges: Vec::new(),
625            vertices: Vec::new(),
626            chord_tolerance: 0.,
627        },
628    })
629}
630
631/// The substrate: the outline swept through the board's thickness, with its top
632/// face, its bottom face and its edge named apart so a user can pick one.
633///
634/// It is NOT drilled. Every via barrel below sits inside solid substrate rather
635/// than in a hole, which is right where it is and wrong about what surrounds
636/// it; cutting the holes wants a hole-aware cap triangulation this does not
637/// have. Hiding `PCB_Board` in the Scene tree shows the barrels. So there is no
638/// hole rim to draw either: the drilled board is the STEP export's.
639fn substrate(board: &Board) -> Option<Body> {
640    let outline = oriented_outline(board)?;
641    let cutouts = cutout_rings(board);
642    let (lo, hi) = (mm(-board::SUBSTRATE_THICKNESS), 0.);
643    let n = outline.len();
644    // The outline's SIDES: the runs between its corners. An outline with no
645    // corner at all — a round board — is one side all the way round.
646    let mut at = corners(&outline);
647    if at.is_empty() {
648        at.push(0);
649    }
650    let sides: Vec<Vec<[f64; 2]>> = (0..at.len())
651        .map(|k| {
652            let (from, to) = (at[k], at[(k + 1) % at.len()]);
653            let steps = (to + n - from - 1) % n + 1;
654            (0..=steps).map(|i| outline[(from + i) % n]).collect()
655        })
656        .collect();
657    let mut soup = Soup::default();
658    // A board with no cutout keeps the ear-clipped caps it always had; one with
659    // cutouts takes the even-odd caps a zone's fill uses, which draw holes.
660    let (corners_xy, triangles) = if board.cutouts.is_empty() {
661        (outline.clone(), fan_or_ears(&outline))
662    } else {
663        holed_cap(board)
664    };
665    soup.cap(&corners_xy, &triangles, hi, true, 0);
666    soup.cap(&corners_xy, &triangles, lo, false, 1);
667    for (k, side) in sides.iter().enumerate() {
668        soup.walls_open(side, lo, hi, 2 + k as u32);
669    }
670    for (k, ring) in cutouts.iter().enumerate() {
671        soup.walls(ring, lo, hi, (2 + sides.len() + k) as u32);
672    }
673    // Named under the body like every other board face, so the walls can
674    // carry a colour of their own ([`default_color`]) and hovering one says
675    // whose it is.
676    let face = |role: String| format!("{SUBSTRATE_SOLID}{FACE_SEPARATOR}{role}");
677    let side = |k: usize| face(format!("{SIDE_FACE} {}", k + 1));
678    let mut faces = vec![face("Top".into()), face("Bottom".into())];
679    faces.extend((0..sides.len()).map(side));
680    let cutout_face = |k: usize| face(format!("{CUTOUT_FACE} {}", k + 1));
681    faces.extend((0..cutouts.len()).map(cutout_face));
682    let mut body = body(SUBSTRATE_SOLID.to_string(), SUBSTRATE_COLOR, faces.clone(), soup)?;
683    // The edges a box has: each side's top and bottom edge, and a vertical
684    // where two sides meet — named, in the kernel's `faceA|faceB` spelling, by
685    // the two faces each one divides.
686    let mut push = |name: String, points: Vec<Vec3>| {
687        let id = body.payload.edges.len() as u64;
688        body.payload.edges.push((id, Some(name), points));
689    };
690    for (k, run) in sides.iter().enumerate() {
691        for (cap, z) in [(&faces[0], hi), (&faces[1], lo)] {
692            let points = run.iter().map(|p| Vec3::new(p[0], p[1], z)).collect();
693            push(format!("{cap}|{}", side(k)), points);
694        }
695    }
696    // Each cutout's rim on the top and the bottom.
697    for (k, ring) in cutouts.iter().enumerate() {
698        for (cap, z) in [(&faces[0], hi), (&faces[1], lo)] {
699            let points = ring.iter().chain(&ring[..1]).map(|p| Vec3::new(p[0], p[1], z)).collect();
700            push(format!("{cap}|{}", cutout_face(k)), points);
701        }
702    }
703    if sides.len() > 1 {
704        for k in 0..sides.len() {
705            let p = outline[at[k]];
706            let before = (k + sides.len() - 1) % sides.len();
707            push(
708                format!("{}|{}", side(before), side(k)),
709                vec![Vec3::new(p[0], p[1], hi), Vec3::new(p[0], p[1], lo)],
710            );
711        }
712    }
713    Some(body)
714}
715
716/// The board's cutouts in millimetres (+Y up), each wound clockwise so walls
717/// swept round it face into the hole.
718fn cutout_rings(board: &Board) -> Vec<Vec<[f64; 2]>> {
719    board
720        .cutouts
721        .iter()
722        .map(|c| {
723            let mut ring: Vec<[f64; 2]> = c.points.iter().copied().map(xy).collect();
724            if signed_area2(&ring) > 0. {
725                ring.reverse();
726            }
727            ring
728        })
729        .collect()
730}
731
732/// The substrate's cap for a board with cutouts: the outline and every cutout
733/// as one even-odd region ([`board::zones::fill_triangles`]), as corners in
734/// millimetres (+Y up) and counter-clockwise triangles over them. Corners are
735/// shared, so the cap is watertight and only its rims are outline edges.
736fn holed_cap(board: &Board) -> (Vec<[f64; 2]>, Vec<[usize; 3]>) {
737    let rings: Vec<&[brep_ecad_core::Point]> = std::iter::once(board.outline.as_slice())
738        .chain(board.cutouts.iter().map(|c| c.points.as_slice()))
739        .collect();
740    let mut corners: Vec<[f64; 2]> = vec![];
741    let mut index: BTreeMap<(u64, u64), usize> = BTreeMap::new();
742    let mut triangles = vec![];
743    for tri in board::zones::fill_triangles(&rings) {
744        let mut t = tri.map(|(x, y)| {
745            *index.entry((x.to_bits(), y.to_bits())).or_insert_with(|| {
746                corners.push([x / 1000., -y / 1000.]);
747                corners.len() - 1
748            })
749        });
750        let [a, b, c] = t.map(|i| corners[i]);
751        let turn = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
752        if turn == 0. {
753            continue;
754        }
755        if turn < 0. {
756            t.swap(1, 2);
757        }
758        triangles.push(t);
759    }
760    (corners, triangles)
761}
762
763/// The indices of the outline's CORNERS: every vertex where the outline turns
764/// by more than [`CORNER_TURN`].
765fn corners(outline: &[[f64; 2]]) -> Vec<usize> {
766    let n = outline.len();
767    (0..n)
768        .filter(|&i| {
769            let (a, b, c) = (outline[(i + n - 1) % n], outline[i], outline[(i + 1) % n]);
770            let (u, v) = ([b[0] - a[0], b[1] - a[1]], [c[0] - b[0], c[1] - b[1]]);
771            let turn = (u[0] * v[1] - u[1] * v[0]).atan2(u[0] * v[0] + u[1] * v[1]);
772            turn.abs() > CORNER_TURN
773        })
774        .collect()
775}
776
777/// The display edges of one copper layer: where its copper STOPS — the
778/// boundary of the union of every track, pad, via ring and fill on the layer,
779/// so a bend in a track, a track landing on a pad and a pad inside a fill draw
780/// no seam ([`outlines::union_boundary`]).
781///
782/// On ONE plane, the copper's outer face (`z`): the other is 35 µm away and
783/// lands on the same pixels from every angle but edge-on, and drawing it too
784/// doubled the edge instances the frame pays. Measured on the dense synthetic
785/// board in the validation record, both planes took a spin's frame from 119 to
786/// 230 ms on the headless renderer.
787///
788/// They are DISPLAY-ONLY ([`Body::aux_from`]): drawn, but never picked. An edge
789/// outranks a face under the pointer, and copper is thin enough that its outline
790/// is under the pointer wherever the copper is, so a pickable outline would take
791/// the hover from the NET face — whose name is what hovering copper is for.
792fn copper_outline(regions: &[outlines::Region], z: f64) -> Vec<Vec<Vec3>> {
793    outlines::union_boundary(regions)
794        .into_iter()
795        .map(|line| line.into_iter().map(|p| Vec3::new(p[0], p[1], z)).collect())
796        .collect()
797}
798
799/// The OUTER face of the copper on `layer`: the top of F.Cu, the underside of
800/// B.Cu, and the upper face of an inner layer (which has no outside).
801fn copper_face(layer: u8, layer_count: u8) -> f64 {
802    let (lo, hi) = copper_span(layer, layer_count);
803    if layer > 0 && layer + 1 >= layer_count { lo } else { hi }
804}
805
806/// One copper layer: every copper primitive the board carries THROUGH that
807/// layer — the tracks on it, the pads that reach it, and each via's annular
808/// ring — as one body, so a layer costs the scene one buffer set whatever it
809/// carries.
810///
811/// The layer is ONE body but not one face. Its copper is grouped by NET, one
812/// named face per net, and [`default_color`] gives each face the net's own
813/// colour — so a trace reads as part of a net at a glance, and hovering it
814/// names that net instead of naming the layer. The grouping is why this costs
815/// nothing extra: a face is a triangle RANGE, not a buffer, and the body count
816/// — the number the viewport lives or dies by — is unchanged.
817///
818/// `nets` is index-aligned with `copper`. Copper on an island that carries no
819/// single schematic net — an unrouted stub, a board with no schematic, or a
820/// short between two nets — goes on the [`NO_NET_FACE`] face and stays bare
821/// copper, so a board nobody has drawn a schematic for looks exactly as it did.
822fn copper_layer(
823    board: &Board,
824    copper: &[CopperItem],
825    nets: &[Option<String>],
826    layer: u8,
827) -> Option<Body> {
828    let (lo, hi) = copper_span(layer, board.layer_count);
829    // Grouped in a BTreeMap so the faces come out in one order whatever order
830    // the router laid the copper down in: a rebuild that reshuffled them would
831    // move every face's metadata key, and a per-net colour the user stored
832    // with it.
833    let mut by_net: BTreeMap<Option<&str>, (Vec<usize>, Vec<&board::FillPiece>)> = BTreeMap::new();
834    for (i, item) in copper.iter().enumerate() {
835        if item.layers.0 <= layer && layer <= item.layers.1 {
836            by_net.entry(nets[i].as_deref()).or_default().0.push(i);
837        }
838    }
839    // A zone's fill is its net's copper, on the same face as that net's tracks
840    // and pads: one colour, one name to hover, and no extra body.
841    for zone in board.zones.iter().filter(|z| z.layer == layer) {
842        by_net.entry(Some(zone.net.as_str())).or_default().1.extend(&zone.fill);
843    }
844    let name = format!("{BOARD_SOLID_PREFIX}{}", board::layer_name(layer, board.layer_count));
845    let mut soup = Soup::default();
846    let mut faces: Vec<String> = Vec::with_capacity(by_net.len());
847    // Every shape drawn, for the outline: the net does not matter to where
848    // copper stops, so it is one union for the whole layer.
849    let mut regions: Vec<outlines::Region> = Vec::new();
850    for (net, (items, fill)) in &by_net {
851        // The display builder reads a face's triangles as their FIRST
852        // contiguous run of face ids, so a net's copper is emitted all at once
853        // — and the id is claimed only once something has been drawn under it.
854        let face = faces.len() as u32;
855        let mut drawn = false;
856        for &i in items {
857            let outline = shape_loop(&copper[i].shape);
858            if outline.len() >= 3 {
859                soup.prism(&outline, lo, hi, face);
860                regions.push(outlines::Region::Convex(outline));
861                drawn = true;
862            }
863        }
864        for piece in fill {
865            if piece.outer.len() >= 3 {
866                soup.slab(piece, lo, hi, face);
867                let rings = std::iter::once(&piece.outer)
868                    .chain(&piece.holes)
869                    .map(|ring| ring.iter().copied().map(xy).collect())
870                    .collect();
871                regions.push(outlines::Region::Fill(rings));
872                drawn = true;
873            }
874        }
875        if drawn {
876            faces.push(format!("{name}{FACE_SEPARATOR}{}", net.unwrap_or(NO_NET_FACE)));
877        }
878    }
879    let mut body = body(name, COPPER_COLOR, faces, soup)?;
880    body.aux_from = body.payload.edges.len();
881    for line in copper_outline(&regions, copper_face(layer, board.layer_count)) {
882        let id = body.payload.edges.len() as u64;
883        body.payload.edges.push((id, None, line));
884    }
885    Some(body)
886}
887
888/// Every solder-mask OPENING on one side, as the shape the aperture takes.
889///
890/// The rule is `fabrication::mask`'s, not a new one: a pad whose copper reaches
891/// this side is open, a bottom-side drilled pad is open on the bottom whatever
892/// its copper does, and a VIA is tented — covered — which is why no via appears
893/// here. The aperture is the pad grown by
894/// [`board::DesignRules::mask_expansion`], the same growth the Gerber writer
895/// flashes.
896fn mask_openings(board: &Board, top: bool) -> impl Iterator<Item = Shape> + '_ {
897    // Vias open when the board's rules leave them untented, on a side they
898    // reach: a blind via on its outer side only, a buried one on neither.
899    let last = board.layer_count.saturating_sub(1);
900    let vias = board
901        .vias
902        .iter()
903        .filter(move |via| {
904            let (from, to) = via.layers(board.layer_count);
905            !board.rules.tent_vias && if top { from == 0 } else { to == last }
906        })
907        .map(move |via| grown(Shape::circle(via.at, via.diameter / 2), board.rules.mask_expansion));
908    vias.chain(board.placements.iter().flat_map(move |placement| {
909        placement.footprint.pads.iter().filter_map(move |pad| {
910            brep_ecad_core::fabrication::pad_mask_open(board, placement, pad, top).then(|| {
911                grown(
912                    placement.pad_shape(pad),
913                    pad.layers.mask_margin.unwrap_or(board.rules.mask_expansion),
914                )
915            })
916        })
917    }))
918}
919
920/// One side's SOLDER MASK: the lacquer sheet over the whole outline, and the
921/// bare-metal opening over every pad the mask is open on.
922///
923/// Which pads those are is `fabrication::mask`'s rule, not a new one: a pad
924/// whose copper reaches this side is open, a bottom-side drilled pad is open on
925/// the bottom whatever its copper does, and a VIA is tented — covered — which
926/// is why no via appears here. The opening is the pad's shape grown by
927/// [`board::DesignRules::mask_expansion`], the same growth the Gerber writer
928/// flashes.
929///
930/// **The lacquer is not cut.** An opening is a prism standing `COPPER_THICKNESS`
931/// proud of the sheet rather than a hole through it, so it COVERS the lacquer
932/// instead of removing it — the same approximation the undrilled substrate
933/// makes for a via barrel, and for the same reason: cutting apertures out of
934/// the outline polygon wants a hole-aware triangulation this module does not
935/// have, and hundreds of pads is exactly the size at which bridging them into
936/// the ear clipper stops being cheap.
937///
938/// **It is built HIDDEN.** Opaque lacquer over the copper hides the traces,
939/// which is the thing the 3D board was asked for; a user who wants to see the
940/// board as it will be manufactured ticks it on in the Scene tree.
941///
942/// **A side with no OPENING gets no mask body at all.** Lacquer on its own is
943/// the same green the substrate already draws over the same outline, so a board
944/// with no pads on this side would gain a hidden body that shows nothing when
945/// it is shown. A board nobody has placed a part on therefore still makes
946/// exactly the four bodies it made before this.
947fn mask_layer(board: &Board, top: bool) -> Option<Body> {
948    let outline = oriented_outline(board)?;
949    // Every opening this side has, collected first — a side with none gets no
950    // body, and the lacquer has to be emitted BEFORE them in one soup because
951    // the display builder reads a face's triangles as their first contiguous
952    // run of face ids.
953    let apertures: Vec<Vec<[f64; 2]>> = mask_openings(board, top)
954        .map(|shape| shape_loop(&shape))
955        .filter(|loop_xy| loop_xy.len() >= 3)
956        .collect();
957    if apertures.is_empty() {
958        return None;
959    }
960    let mut soup = Soup::default();
961    let (lo, hi) = side_span(top, 0, LACQUER_TOP);
962    if board.cutouts.is_empty() {
963        soup.prism(&outline, lo, hi, 0);
964    } else {
965        // The lacquer has the board's cutouts in it, as the substrate does.
966        let (corners_xy, triangles) = holed_cap(board);
967        soup.cap(&corners_xy, &triangles, lo, false, 0);
968        soup.cap(&corners_xy, &triangles, hi, true, 0);
969        soup.walls(&outline, lo, hi, 0);
970        for ring in cutout_rings(board) {
971            soup.walls(&ring, lo, hi, 0);
972        }
973    }
974    let (open_lo, open_hi) = side_span(top, 0, LACQUER_TOP + board::COPPER_THICKNESS);
975    for loop_xy in &apertures {
976        soup.prism(loop_xy, open_lo, open_hi, 1);
977    }
978    let name = mask_solid(top);
979    let faces = vec![
980        format!("{name}{FACE_SEPARATOR}{LACQUER_FACE}"),
981        format!("{name}{FACE_SEPARATOR}{OPENING_FACE}"),
982    ];
983    body(name, MASK_COLOR, faces, soup)
984}
985
986/// One side's SILKSCREEN: every drawn item of every footprint that lands on
987/// that side's silkscreen (`Placement::drawing_on`, the part's `silk` lines
988/// among them), inked on top of the mask.
989///
990/// A polyline is drawn the way the Gerber writer strokes it — a round pen of
991/// the item's width dragged along it — which here is one capsule prism per
992/// segment, the same primitive a track segment is; a filled shape is also its
993/// own prism. A footprint's silk is a handful of segments, so a whole board's
994/// ink is a rounding error beside its copper.
995///
996/// Reference designators are NOT drawn here; the Gerber legend writes them.
997fn silkscreen(board: &Board, top: bool) -> Option<Body> {
998    let (lo, hi) = side_span(top, LACQUER_TOP, LACQUER_TOP + SILK_THICKNESS);
999    let mut soup = Soup::default();
1000    let layer = if top { GraphicLayer::FrontSilk } else { GraphicLayer::BackSilk };
1001    // What is drawn on the board itself, then each part's own.
1002    let drawn = board
1003        .drawing_on(layer)
1004        .into_iter()
1005        .chain(board.placements.iter().flat_map(|p| p.drawing_on(layer)));
1006    {
1007        for (width, filled, strokes) in drawn {
1008            for line in strokes {
1009                if filled && line.len() >= 4 {
1010                    let mut loop_xy: Vec<[f64; 2]> = line[..line.len() - 1].iter().map(|p| xy(*p)).collect();
1011                    // The prism wants its outline counter-clockwise.
1012                    let area: f64 = (0..loop_xy.len())
1013                        .map(|i| {
1014                            let (a, b) = (loop_xy[i], loop_xy[(i + 1) % loop_xy.len()]);
1015                            a[0] * b[1] - b[0] * a[1]
1016                        })
1017                        .sum();
1018                    if area < 0. {
1019                        loop_xy.reverse();
1020                    }
1021                    if area.abs() > 0. {
1022                        soup.prism(&loop_xy, lo, hi, 0);
1023                    }
1024                }
1025                for pair in line.windows(2).filter(|_| width > 0) {
1026                    let shape = Shape::segment(pair[0], pair[1], width);
1027                    let loop_xy = shape_loop(&shape);
1028                    if loop_xy.len() >= 3 {
1029                        soup.prism(&loop_xy, lo, hi, 0);
1030                    }
1031                }
1032            }
1033        }
1034    }
1035    body(silk_solid(top), SILK_COLOR, vec!["Ink".to_string()], soup)
1036}
1037
1038/// The plated via barrels: for each via, the tube the plating makes on the wall
1039/// of its drilled hole, from the plane of the first copper layer it joins to
1040/// the plane of the last (top to bottom for a through via).
1041fn via_barrels(board: &Board) -> Option<Body> {
1042    let mut soup = Soup::default();
1043    let facets = ARC_FACETS * 2;
1044    for via in &board.vias {
1045        let (from, to) = via.layers(board.layer_count);
1046        let (lo, hi) = (
1047            mm(board::layer_z(to, board.layer_count)),
1048            mm(board::layer_z(from, board.layer_count)),
1049        );
1050        let centre = xy(via.at);
1051        let inner = mm(via.drill.max(1) / 2).max(1e-4);
1052        let outer = inner + mm(board::COPPER_THICKNESS);
1053        let ring = |r: f64| -> Vec<[f64; 2]> {
1054            (0..facets)
1055                .map(|i| {
1056                    let t = std::f64::consts::TAU * i as f64 / facets as f64;
1057                    [centre[0] + r * t.cos(), centre[1] + r * t.sin()]
1058                })
1059                .collect()
1060        };
1061        let (out_ring, in_ring) = (ring(outer), ring(inner));
1062        soup.walls(&out_ring, lo, hi, 0);
1063        // The bore, wound the other way so its wall faces into the hole.
1064        let mut bore = in_ring.clone();
1065        bore.reverse();
1066        soup.walls(&bore, lo, hi, 0);
1067        // The two annular ends.
1068        for (z, up) in [(hi, true), (lo, false)] {
1069            for i in 0..facets {
1070                let j = (i + 1) % facets;
1071                let (a, b) = (in_ring[i], in_ring[j]);
1072                let (c, d) = (out_ring[j], out_ring[i]);
1073                let quad = [
1074                    [a[0], a[1], z],
1075                    [b[0], b[1], z],
1076                    [c[0], c[1], z],
1077                    [d[0], d[1], z],
1078                ];
1079                if up {
1080                    soup.quad(quad[0], quad[1], quad[2], quad[3], 0);
1081                } else {
1082                    soup.quad(quad[3], quad[2], quad[1], quad[0], 0);
1083                }
1084            }
1085        }
1086    }
1087    body(VIAS_SOLID.to_string(), COPPER_COLOR, vec!["Barrel".to_string()], soup)
1088}
1089
1090/// Every copper primitive on the board, and the NET each one carries.
1091///
1092/// The nets come from [`Board::connectivity`], which walks the copper into
1093/// islands and reads each island's net off the pads it touches — so a track is
1094/// on a net because it reaches a pad of that net, which is the only sense in
1095/// which a track HAS one. `None` for an island carrying no net, or more than
1096/// one, which is a short and must not be painted as though it were a net.
1097///
1098/// With no netlist — a board whose document has no placement, so no pad can
1099/// carry a net — the copper is asked for directly and every item's net is
1100/// `None`. That skips the island walk entirely, which is why a board nobody has
1101/// drawn a schematic for pays nothing at all for net colouring.
1102fn copper_and_nets(
1103    board: &Board,
1104    netlist: Option<&Netlist>,
1105) -> (Vec<CopperItem>, Vec<Option<String>>) {
1106    let Some(netlist) = netlist else {
1107        let copper = board.copper();
1108        let nets = vec![None; copper.len()];
1109        return (copper, nets);
1110    };
1111    let connectivity = board.connectivity(netlist);
1112    let nets = connectivity
1113        .islands
1114        .iter()
1115        .map(|&island| connectivity.island_net(island).map(str::to_owned))
1116        .collect();
1117    (connectivity.items, nets)
1118}
1119
1120/// Every body a board contributes: the substrate, each copper layer from F.Cu
1121/// down to B.Cu, the via barrels, then the two outer surfaces — each side's
1122/// solder mask and its silkscreen. A layer, a side or a surface carrying
1123/// nothing contributes no body at all.
1124///
1125/// The copper stack comes FIRST and in its original order, so the names a
1126/// reader already knows (`PCB_Board`, `PCB_F.Cu`, …, `PCB_Vias`) are still the
1127/// first four of a two-layer board and the surfaces are appended behind them.
1128fn bodies(board: &Board, netlist: Option<&Netlist>) -> Vec<Body> {
1129    let (copper, nets) = copper_and_nets(board, netlist);
1130    let mut out = Vec::new();
1131    out.extend(substrate(board));
1132    for layer in 0..board.layer_count.max(1) {
1133        out.extend(copper_layer(board, &copper, &nets, layer));
1134    }
1135    out.extend(via_barrels(board));
1136    for top in [true, false] {
1137        out.extend(mask_layer(board, top));
1138    }
1139    for top in [true, false] {
1140        out.extend(silkscreen(board, top));
1141    }
1142    out
1143}
1144
1145/// Whether a board body is SHOWN the first time it reaches the scene.
1146///
1147/// Everything is, except the solder mask: opaque lacquer over the copper hides
1148/// the traces, and seeing the traces is what the 3D board is for. The mask is
1149/// built all the same, so ticking it on in the Scene tree costs nothing and
1150/// needs no rebuild.
1151fn default_visible(name: &str) -> bool {
1152    !name.ends_with(".Mask")
1153}
1154
1155/// What [`EngineState::refresh_board_geometry`] built, for the tests and the
1156/// cost figures in the validation record.
1157#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
1158pub struct BoardBuild {
1159    pub bodies: usize,
1160    pub triangles: usize,
1161    /// Display edges over every body, and the line segments they draw — the
1162    /// instance count the edge passes pay per frame.
1163    pub edges: usize,
1164    pub edge_segments: usize,
1165}
1166
1167impl EngineState {
1168    /// (Re)build the board's 3D bodies from the document's `pcb` block.
1169    ///
1170    /// Mirrors [`refresh_committed_sketches`](Self::refresh_committed_sketches)
1171    /// in shape and for the same reason: `apply_run_output` reconciles the scene
1172    /// against the RUN's outputs and drops everything else, so a derived body
1173    /// has to be re-inserted after it. Bodies shown last time and not this time
1174    /// (the block went away, a layer emptied, the board shrank) are removed.
1175    ///
1176    /// Cheap to call: the parsed board is compared against the one the current
1177    /// bodies were built from and an unchanged block returns without touching
1178    /// the scene. That is what lets the eCAD host call it on a track edit, which
1179    /// writes the block and — changing no placement — runs no history.
1180    ///
1181    /// A board that DID change is rebuilt and every body is then seated over
1182    /// whatever is resident under its name. Replacing, not skipping, is the
1183    /// point: see the seating comment below.
1184    pub fn refresh_board_geometry(&mut self) -> BoardBuild {
1185        // The ordinary document carries no `pcb` block and pays one `Option`
1186        // test per run for the whole of this module.
1187        let block = self.history.pcb_block();
1188        if block.is_none() && self.board_displays.is_empty() {
1189            return BoardBuild::default();
1190        }
1191        // The whole DOCUMENT, not just its board: a copper island's net is read
1192        // off the pads it touches, and which net a pad carries is the
1193        // SCHEMATIC's answer. The netlist is only asked for when the board has
1194        // a placement, because a board with no pads can carry no net and the
1195        // walk would be work for a guaranteed `None`.
1196        let document = block
1197            .cloned()
1198            .and_then(|value| brep_ecad_core::Document::from_value(value).ok());
1199        let (board, netlist) = match document {
1200            Some(document) => {
1201                let netlist = (!document.board.placements.is_empty()).then(|| document.netlist());
1202                (Some(document.board), netlist)
1203            }
1204            None => (None, None),
1205        };
1206        // The rebuild test is the board AND the pin-to-net map, because those
1207        // two together decide every triangle and every face colour this module
1208        // makes. Renaming a net on the schematic moves no copper, so the board
1209        // alone would report nothing to do and the traces would keep the old
1210        // net's colour until the next routed track.
1211        let pin_nets = netlist
1212            .as_ref()
1213            .map(brep_ecad_core::board::pin_nets)
1214            .unwrap_or_default();
1215        let rebuilt = board != self.board_built_from || pin_nets != self.board_pin_nets;
1216        if rebuilt {
1217            self.board_pin_nets = pin_nets;
1218            self.rebuild_board_displays(board, netlist.as_ref());
1219        }
1220        // Seat the bodies. Two different things bring us here and each needs
1221        // its own half of the condition:
1222        //
1223        // - a REBUILD made new displays, and a body's name does not change with
1224        //   what is on it — `PCB_F.Cu` is `PCB_F.Cu` whether one track is routed
1225        //   on it or a thousand. The OLD display is still resident under that
1226        //   name, so "insert it if it is missing" leaves the stale geometry in
1227        //   the scene and the 3D board follows the 2D board only once something
1228        //   else has swept the scene (a reload, or any history run). That was
1229        //   the staleness the user saw while routing;
1230        // - a RECONCILE dropped them. `apply_run_output` keeps only the RUN's
1231        //   own outputs, so after a run the scene has none of these and every
1232        //   one goes back in. Nothing was rebuilt, so the kept displays are
1233        //   copied in rather than remade: rebuilding a dense board costs two
1234        //   orders of magnitude more than copying it, and the kept `revision`
1235        //   is what lets the renderer reuse its GPU buffers.
1236        //
1237        // A schematic edit, which writes the SAME board back, is neither: it
1238        // rebuilds nothing, finds every body resident, and touches no solid.
1239        let mut seated = false;
1240        for index in 0..self.board_displays.len() {
1241            // What the scene already shows under this name, if anything. Read
1242            // out by value so the scene is free to be written to below.
1243            let name = self.board_displays[index].name.clone();
1244            let resident = self
1245                .scene
1246                .solid(&name)
1247                .map(|solid| (solid.visible, solid.color_override));
1248            if let Some((visible, _)) = resident {
1249                // The SCENE is where a hide lives, and a history run wipes the
1250                // scene — so the kept display takes the hide back with it here,
1251                // while there is still a resident body to read it off. Without
1252                // this the mask, which is built hidden, would come back hidden
1253                // after every feature edit however many times the user ticked
1254                // it on.
1255                self.board_displays[index].visible = visible;
1256            }
1257            if !rebuilt && resident.is_some() {
1258                continue;
1259            }
1260            let mut fresh = self.board_displays[index].clone();
1261            if let Some((_, color)) = resident {
1262                // A rebuild changes the body's GEOMETRY. It does not undo what
1263                // the user has done TO the body, and replacing the whole
1264                // display would: a stored colour is meant to win over the
1265                // board's default, and nothing re-derives it on this path,
1266                // because `sync_colors_from_metadata` runs in `finish_apply`
1267                // and no history runs when a track is routed. (The other half
1268                // of that — the user's HIDE — was carried into the kept display
1269                // a few lines up, so `fresh` already has it.)
1270                //
1271                // `visibility`, the per-FACE hide map, is deliberately NOT
1272                // carried: `SolidDisplay` says a re-tessellated solid resets to
1273                // all-visible, and this is a re-tessellation.
1274                fresh.color_override = color;
1275            }
1276            self.scene.insert_solid(fresh);
1277            seated = true;
1278        }
1279        if seated {
1280            // A body's FACES are coloured too now — a copper layer's net faces,
1281            // the mask's bare openings — and a face colour the user stored is a
1282            // metadata record like any other. Resolving them through the one
1283            // seam that owns colour, rather than carrying them across by hand,
1284            // is what keeps a painted net painted on the frame it is routed on;
1285            // the pass is a no-op when nothing moved, so an untouched board
1286            // costs a compare per face.
1287            self.sync_colors_from_metadata();
1288        }
1289        self.dirty |= seated;
1290        self.board_build
1291    }
1292
1293    /// Build `board`'s bodies, sweeping out any the last board left behind that
1294    /// this one does not make (the block went away, a layer emptied, the last
1295    /// via was deleted). It does NOT put the new displays in the scene — the
1296    /// caller's seating pass does, and must, because a name that survives a
1297    /// rebuild still holds the OLD body.
1298    fn rebuild_board_displays(&mut self, board: Option<Board>, netlist: Option<&Netlist>) {
1299        let built: Vec<Body> = board
1300            .as_ref()
1301            .map(|board| bodies(board, netlist))
1302            .unwrap_or_default();
1303        let mut build = BoardBuild::default();
1304        // What each body was SHOWING before this rebuild, so a rebuild does not
1305        // un-hide a body the user hid — the mask included, which starts hidden
1306        // and stays hidden only until the user says otherwise.
1307        let was_visible: std::collections::HashMap<&str, bool> = self
1308            .board_displays
1309            .iter()
1310            .map(|display| (display.name.as_str(), display.visible))
1311            .collect();
1312        let displays: Vec<crate::scene::SolidDisplay> = built
1313            .into_iter()
1314            .map(|Body { name, color, payload, aux_from }| {
1315                build.bodies += 1;
1316                build.triangles += payload.mesh.face_ids.len();
1317                let mut solid = crate::scene::solid_display_from_payload(&name, payload);
1318                for edge in solid.edges.iter_mut().skip(aux_from) {
1319                    edge.aux = true;
1320                }
1321                build.edges += solid.edges.len();
1322                build.edge_segments += solid.edges.iter().map(|e| e.polyline.len().saturating_sub(1)).sum::<usize>();
1323                solid.color_override = Some(color);
1324                // Every named face's DEFAULT colour, stamped at build time.
1325                // The seating pass re-resolves all of them through
1326                // `sync_colors_from_metadata` — which is what makes a colour the
1327                // user STORED win — but that pass bumps the `revision` of any
1328                // solid it CHANGES, and a bumped revision re-uploads the body's
1329                // buffers. A kept display that did not already carry the colour
1330                // the pass resolves would therefore be re-uploaded on every
1331                // single history run, which is the cost the kept displays exist
1332                // to avoid. So the two are not redundant: the stamp is what
1333                // keeps the revision stable, the pass is what honours the store.
1334                for face in &mut solid.faces {
1335                    face.color_override = default_color(&face.name);
1336                }
1337                solid.visible = was_visible
1338                    .get(name.as_str())
1339                    .copied()
1340                    .unwrap_or_else(|| default_visible(&name));
1341                solid
1342            })
1343            .collect();
1344        let fed: Vec<String> = displays.iter().map(|solid| solid.name.clone()).collect();
1345        for name in std::mem::replace(&mut self.shown_board_ids, fed) {
1346            if !self.shown_board_ids.contains(&name) {
1347                self.scene.remove_solid(&name);
1348            }
1349        }
1350        self.board_displays = displays;
1351        self.board_built_from = board;
1352        self.board_build = build;
1353        self.sync_view_frame();
1354        self.dirty = true;
1355    }
1356
1357    /// What the last [`refresh_board_geometry`](Self::refresh_board_geometry)
1358    /// built — body and triangle counts, for the cost the record reports.
1359    pub fn board_build(&self) -> BoardBuild {
1360        self.board_build
1361    }
1362
1363    /// Remember that the user SHOWED or HID a board body, so the kept displays
1364    /// carry it across a history run.
1365    ///
1366    /// A run reconciles the scene against its own outputs and drops every
1367    /// derived body, so by the time the refresh at the tail of `finish_apply`
1368    /// runs there is nothing resident to read the state off — and the body
1369    /// would come back at its build-time default. That matters most for the
1370    /// solder mask, which is built HIDDEN: without this, showing it would last
1371    /// until the next feature edit.
1372    ///
1373    /// Called from [`set_visible`](Self::set_visible), which is the one seam
1374    /// the Scene tree and the BOM panel both hide a solid through.
1375    pub(super) fn remember_board_visibility(&mut self, name: &str, visible: bool) {
1376        if !name.starts_with(BOARD_SOLID_PREFIX) {
1377            return;
1378        }
1379        if let Some(display) = self
1380            .board_displays
1381            .iter_mut()
1382            .find(|display| display.name == name)
1383        {
1384            display.visible = visible;
1385        }
1386    }
1387
1388    /// The document's board as EXACT solids, for STEP export — `None` when the
1389    /// document has no `pcb` block or its board has no usable outline. Built
1390    /// from the block every call rather than kept: an export is rare, and the
1391    /// booleans that drill the holes are not what a track edit should pay for.
1392    pub(crate) fn board_step_solids(&self) -> Option<step_solids::BoardStepSolids> {
1393        let document = brep_ecad_core::Document::from_value(self.history.pcb_block()?.clone()).ok()?;
1394        let netlist = (!document.board.placements.is_empty()).then(|| document.netlist());
1395        step_solids::board_step_solids(&document.board, netlist.as_ref())
1396    }
1397
1398    /// The scene names of the board bodies currently shown, in stack order.
1399    pub fn board_solid_names(&self) -> &[String] {
1400        &self.shown_board_ids
1401    }
1402}
1403
1404mod outlines;
1405mod step_solids;
1406