Skip to main content

brep_render/sheets/
hlr.rs

1//! The ANALYTIC hidden-line pass: what a sheet draws of the model, computed
2//! from the B-rep rather than from the display mesh.
3//!
4//! # The algorithm
5//!
6//! 1. **Candidate curves.** Every non-degenerate B-rep edge, sampled on its
7//!    own curve, and the SILHOUETTE of every curved face — the locus on the
8//!    exact surface where the viewing direction is tangent to it: two
9//!    generator lines of a cylinder or cone (closed form), one great circle of
10//!    a sphere (closed form), and for a torus, a general revolution or a
11//!    fitted surface the zero set of `n(u, v) · d` traced over the face's
12//!    parameter box and solved onto the surface through its own evaluator.
13//!    Each silhouette is trimmed to its face. An edge is INKED when its two
14//!    faces meet at a crease past [`EDGE_ANGLE_DEG`]
15//!    (the rule the mesh pass used, read here off the exact normals), when it
16//!    is a TANGENT LINE — a smooth edge between two surfaces, a round's or a
17//!    blend's, told from a split of one surface by the jump in curvature
18//!    across it (`one_surface`) — when it bounds only one face, or when more
19//!    than two share it; a smooth edge between two fragments of one surface
20//!    is kept as a SPLITTER only, and a seam (one face on both sides) is
21//!    neither.
22//! 2. **Splitting.** Every candidate is split where its projection crosses
23//!    another's, and where another's END lands on it — the only places the
24//!    number of surfaces in front of a line can change. The crossing test is
25//!    the kernel's own `segment_intersection` over the sampled paper chords.
26//! 3. **Visibility.** Each piece is decided at its MIDPOINT, evaluated on the
27//!    exact curve (a chord's midpoint sits inside a curved surface, and the
28//!    ray from there to the eye can cross the very surface it bounds): the
29//!    view ray from that point toward the eye is intersected with every face
30//!    whose paper box holds the point — a plane in closed form, anything else
31//!    through the kernel's `intersect_curve_surface` on the exact carrier —
32//!    and the piece is hidden when a hit inside that face's trim is nearer the
33//!    eye than the piece by more than the depth floor.
34//! 4. **Runs.** Consecutive visible pieces of one candidate are one run, so a
35//!    straight edge a hidden line crosses still comes back as its two ends,
36//!    and edge runs chain through a vertex exactly two inked edges share.
37//!
38//! # The two floors
39//!
40//! Both are the B-rep's own agreement bar, `KernelTolerances::pcurve_consistency`
41//! (the largest disagreement a valid in-memory B-rep allows between an edge's
42//! curve and the carriers it lies on), carried to the paper at the view's
43//! scale:
44//!
45//! - the **depth floor** — a face must be nearer the eye than the piece by
46//!   more than that bar to hide it, because an edge's own curve may sit that
47//!   far off the face it bounds;
48//! - the **crossing floor** — two projected curves closer than that bar touch,
49//!   and two split points closer than it along a curve are one. A touch is
50//!   measured against a CHORD, so it also admits the chord's own sag,
51//!   [`CHORD_MM`].
52//!
53//! Visibility is exact to those floors: no raster cell, no bias, no dropped
54//! fringe. What it does not see is what the SAMPLING does not: a trim notch
55//! or a silhouette loop smaller than one chord.
56//!
57//! # Before the B-rep arrives
58//!
59//! Steps 2 to 4 also run on a DISPLAY ([`visible_mesh_lines`]): the display
60//! edges and the mesh's silhouettes as candidates, the display triangles as
61//! what hides them. It is what a placement draws while its solids' topology is
62//! not in the scene, and the drawing says so — a stated approximation, the
63//! tessellation's chords in place of the exact curves.
64
65use std::collections::HashMap;
66
67use brep_kernel::{
68    containment_lane, intersect_analytic_pair, intersect_curve_surface, intersect_surfaces,
69    make_line, make_plane, parameter_point_in_face, project_point_to_curve,
70    project_point_to_surface, segment_intersection, trim_sample_count, trim_station,
71    AnalyticSurface, BrepSolid, ContainmentLane, FaceRecord, KernelTolerances, NurbsCurve,
72    NurbsSurface, PolygonClass, SurfaceIntersectionOptions, Vec2, Vec3,
73};
74
75use super::project::{ViewFrame, EDGE_ANGLE_DEG};
76use super::PlacedView;
77
78/// How far a sampled paper polyline may sit off its exact curve, paper
79/// millimetres. The comparand is the model line's own stroke,
80/// `EDGE_WIDTH` = 0.35 mm: seventy times finer, so
81/// no printed or zoomed drawing can show the chord.
82pub const CHORD_MM: f64 = 0.005;
83
84/// Deepest a sampled interval is halved in search of [`CHORD_MM`].
85const MAX_SUBDIVISION: u32 = 14;
86
87/// The same for [`hidden_line_drawing`], whose chords may be asked a
88/// billionth of the solid's size: far past what that needs of any curve.
89const EXACT_SUBDIVISION: u32 = 48;
90
91/// The kernel's tangency bar on a curve-surface hit (`intersect_curve_surface`
92/// flags `|n · t| <= 1e-3`), used for the closed-form plane too: a face the
93/// view ray only grazes has no area in front of the piece to hide it with.
94const GRAZING_COS: f64 = 1e-3;
95
96/// The fewest stations a silhouette is classified at against its face's trim,
97/// whatever its chord sampling: a trim notch shorter than 1/64 of the curve
98/// between two chord samples is what this pass does not see of a silhouette.
99const TRIM_STATIONS: usize = 64;
100
101/// Bisection steps when a curve's parameter is pinned where it leaves a face,
102/// crosses the cutting plane or crosses the detail circle — 2^-40 of one
103/// sampled interval, far under every floor.
104const BISECTION_STEPS: u32 = 40;
105
106
107fn v3(p: [f64; 3]) -> Vec3 {
108    Vec3::new(p[0], p[1], p[2])
109}
110
111fn a3(p: Vec3) -> [f64; 3] {
112    [p.x, p.y, p.z]
113}
114
115// ---------------------------------------------------------------------------
116// Inputs
117// ---------------------------------------------------------------------------
118
119/// What the drawn model is restricted to before anything is decided.
120pub enum Clip<'a> {
121    /// A plain placement: the whole model.
122    Whole,
123    /// A SECTION: the half-space at or beyond the cutting plane, which is the
124    /// view's own target plane (depth zero, the camera looking along its
125    /// normal). `cap` is the cut region on the paper — the exact section
126    /// curves — which hides everything behind it. `whole`, per solid (by
127    /// index; absent is false), marks a solid the section leaves whole — a
128    /// shaft, a fastener: drawn on both sides of the plane, hiding from both,
129    /// and contributing nothing to the cut. `half`, a HALF section's second
130    /// plane, keeps everything on its side whole as well (and `cap` is then
131    /// closed along its line).
132    Beyond { cap: &'a [Vec<[f64; 2]>], whole: &'a [bool], half: Option<HalfLine> },
133    /// A DETAIL: the cylinder of MODEL radius `radius` along the viewing
134    /// direction through the view's target.
135    Circle { radius: f64 },
136}
137
138impl Clip<'_> {
139    /// Whether solid `index` is drawn whole under this clip.
140    fn whole(&self, index: usize) -> bool {
141        matches!(self, Clip::Beyond { whole, .. } if whole.get(index) == Some(&true))
142    }
143
144    /// A section's margin at view point `view`, model units: negative where
145    /// the cut removes material — in front of the cutting plane and, for a
146    /// half section, on the removed side of its second plane too.
147    fn margin(&self, view: [f64; 3]) -> f64 {
148        match self {
149            Clip::Beyond { half: Some(half), .. } => view[2].max(half.at(view)),
150            _ => view[2],
151        }
152    }
153}
154
155/// A HALF section's second plane, perpendicular to the cutting plane and so
156/// edge-on to the section view: a line on the paper. In view units, `normal`
157/// is its unit normal in the view's `(right, up)` and `offset` its distance
158/// from the view's target; the side the normal points to is kept whole.
159#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
160pub struct HalfLine {
161    pub normal: [f64; 2],
162    pub offset: f64,
163}
164
165impl HalfLine {
166    /// Signed distance of view point `view` from the line, positive on the
167    /// side kept whole.
168    pub fn at(&self, view: [f64; 3]) -> f64 {
169        view[0] * self.normal[0] + view[1] * self.normal[1] - self.offset
170    }
171}
172
173/// The floors of one placement, see the module docs.
174#[derive(Debug, Clone, Copy)]
175pub struct Floors {
176    /// The B-rep's agreement bar, model units.
177    pub bar: f64,
178    /// The depth floor, paper millimetres (`bar × scale`).
179    pub depth_mm: f64,
180    /// The crossing floor, paper millimetres (`bar × scale`).
181    pub crossing_mm: f64,
182}
183
184impl Floors {
185    pub fn of(scale: f64) -> Floors {
186        let bar = EXACT_BAR.with(|bar| bar.get()).unwrap_or(KernelTolerances::default().pcurve_consistency);
187        Floors { bar, depth_mm: bar * scale, crossing_mm: bar * scale }
188    }
189}
190
191thread_local! {
192    /// The agreement bar of the pass running on this thread where it is not
193    /// the B-rep's own: [`hidden_line_drawing`] reads its solid far finer
194    /// than any sheet does.
195    static EXACT_BAR: std::cell::Cell<Option<f64>> = const { std::cell::Cell::new(None) };
196}
197
198/// The exact result of one placement: the visible runs on the paper, plus
199/// what the A/B comparison and the tests read.
200#[derive(Debug, Clone, Default)]
201pub struct HlrResult {
202    pub runs: Vec<Vec<[f64; 2]>>,
203    /// The hidden runs on the paper: the pieces the solids hide, chained as
204    /// the visible ones are (a sheet draws them only as hidden lines).
205    pub hidden: Vec<Vec<[f64; 2]>>,
206    /// Inked candidate curves before splitting (edges and silhouette pieces).
207    pub inked: usize,
208    /// Silhouette pieces among them.
209    pub silhouettes: usize,
210    /// Pieces the splitting produced and visibility decided.
211    pub pieces: usize,
212    /// How many times the pass asked the kernel whether a point is inside a
213    /// face's trim (`parameter_point_in_face`) — the question the projected and
214    /// parameter trims exist to answer first.
215    pub trim_queries: usize,
216    /// How many view rays the pass intersected with a curved face's carrier
217    /// (`intersect_curve_surface`).
218    pub ray_queries: usize,
219}
220
221thread_local! {
222    /// The kernel questions of the pass running on this thread, for
223    /// [`HlrResult::trim_queries`] and [`HlrResult::ray_queries`].
224    static TRIM_QUERIES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
225    static RAY_QUERIES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
226}
227
228
229
230// ---------------------------------------------------------------------------
231// Curves
232// ---------------------------------------------------------------------------
233
234/// A candidate's exact carrier, evaluated at its own parameter.
235#[derive(Clone)]
236enum Carrier<'a> {
237    /// A B-rep edge's curve.
238    Edge(&'a NurbsCurve),
239    /// A curve the kernel handed back (an exact section of a carrier).
240    Curve(NurbsCurve),
241    /// A straight generator from `a` (s = 0) to `b` (s = 1).
242    Line { a: Vec3, b: Vec3 },
243    /// `centre + e1 cos s + e2 sin s` — `e1`, `e2` carry the radius.
244    Circle { centre: Vec3, e1: Vec3, e2: Vec3 },
245    /// A silhouette TRACED on a general surface: `uv[floor(s)]` toward
246    /// `uv[floor(s) + 1]`, re-solved onto `n · d = 0` at every evaluation.
247    Traced { surface: &'a NurbsSurface, uv: Vec<[f64; 2]>, dir: Vec3 },
248    /// A marched section polyline (`intersect_surfaces`): `s` indexes the
249    /// points, which the marcher already put on both carriers.
250    Polyline(Vec<Vec3>),
251}
252
253impl Carrier<'_> {
254    fn at(&self, s: f64) -> Option<Vec3> {
255        match self {
256            Carrier::Edge(curve) => curve.evaluate(s).ok(),
257            Carrier::Curve(curve) => curve.evaluate(s).ok(),
258            Carrier::Line { a, b } => Some(a.add(b.sub(*a).scale(s))),
259            Carrier::Circle { centre, e1, e2 } => Some(centre.add(e1.scale(s.cos())).add(e2.scale(s.sin()))),
260            Carrier::Traced { surface, uv, dir } => {
261                let (point, _) = traced_at(surface, uv, *dir, s)?;
262                Some(point)
263            }
264            Carrier::Polyline(points) => {
265                let last = points.len().checked_sub(1)?;
266                let i = (s.floor().max(0.0) as usize).min(last.saturating_sub(1));
267                let f = (s - i as f64).clamp(0.0, 1.0);
268                let (a, b) = (points[i], points[(i + 1).min(last)]);
269                Some(a.add(b.sub(a).scale(f)))
270            }
271        }
272    }
273
274    /// Whether the carrier is a straight line, so sampling needs no interior
275    /// point to be exact.
276    fn straight(&self) -> bool {
277        match self {
278            Carrier::Line { .. } => true,
279            Carrier::Edge(curve) => curve.degree == 1 && curve.control_points.len() == 2,
280            Carrier::Curve(curve) => curve.degree == 1 && curve.control_points.len() == 2,
281            _ => false,
282        }
283    }
284}
285
286/// `n(u, v) · d` with the normal normalised — the silhouette's defining
287/// function, sign-blind (the locus is the same for either orientation).
288fn grazing(surface: &NurbsSurface, dir: Vec3, u: f64, v: f64) -> Option<f64> {
289    surface.normal(u, v).ok().map(|n| n.dot(dir))
290}
291
292/// A traced silhouette at fractional station `s`: the straight uv step
293/// between the two bracketing stations, then a root of `n · d` along the uv
294/// direction PERPENDICULAR to that step, bracketed within one step's length.
295fn traced_at(surface: &NurbsSurface, uv: &[[f64; 2]], dir: Vec3, s: f64) -> Option<(Vec3, [f64; 2])> {
296    let last = uv.len().checked_sub(1)?;
297    if last == 0 {
298        let p = surface.evaluate(uv[0][0], uv[0][1]).ok()?;
299        return Some((p, uv[0]));
300    }
301    let i = (s.floor().max(0.0) as usize).min(last - 1);
302    let f = (s - i as f64).clamp(0.0, 1.0);
303    let (a, b) = (uv[i], uv[i + 1]);
304    let base = [a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f];
305    let step = [b[0] - a[0], b[1] - a[1]];
306    let length = (step[0] * step[0] + step[1] * step[1]).sqrt();
307    let solved = if f <= 0.0 || f >= 1.0 || length <= 0.0 {
308        base
309    } else {
310        let across = [-step[1], step[0]];
311        root_along(surface, dir, base, across).unwrap_or(base)
312    };
313    let p = surface.evaluate(solved[0], solved[1]).ok()?;
314    Some((p, solved))
315}
316
317/// A root of `n · d` on the uv segment `base ± across`, by bisection from the
318/// first sign change outward from `base`.
319fn root_along(surface: &NurbsSurface, dir: Vec3, base: [f64; 2], across: [f64; 2]) -> Option<[f64; 2]> {
320    let at = |t: f64| [base[0] + across[0] * t, base[1] + across[1] * t];
321    let g0 = {
322        let p = at(0.0);
323        grazing(surface, dir, p[0], p[1])?
324    };
325    if g0 == 0.0 {
326        return Some(base);
327    }
328    for (lo, hi) in [(0.0, 0.5), (0.0, -0.5), (0.5, 1.0), (-0.5, -1.0)] {
329        let (p_lo, p_hi) = (at(lo), at(hi));
330        let g_lo = grazing(surface, dir, p_lo[0], p_lo[1])?;
331        let g_hi = grazing(surface, dir, p_hi[0], p_hi[1])?;
332        if g_lo.signum() == g_hi.signum() {
333            continue;
334        }
335        let (mut lo, mut hi, mut g_lo) = (lo, hi, g_lo);
336        for _ in 0..BISECTION_STEPS {
337            let mid = 0.5 * (lo + hi);
338            let p = at(mid);
339            let g = grazing(surface, dir, p[0], p[1])?;
340            if g.signum() == g_lo.signum() {
341                lo = mid;
342                g_lo = g;
343            } else {
344                hi = mid;
345            }
346        }
347        return Some(at(0.5 * (lo + hi)));
348    }
349    None
350}
351
352/// The paper image of a model point, and its view depth in MODEL units.
353fn project(frame: &ViewFrame, placed: &PlacedView, p: Vec3) -> ([f64; 2], [f64; 3]) {
354    let view = frame.to_view(a3(p));
355    ([placed.position[0] + view[0] * placed.scale, placed.position[1] - view[1] * placed.scale], view)
356}
357
358fn paper_distance(a: [f64; 2], b: [f64; 2]) -> f64 {
359    ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2)).sqrt()
360}
361
362/// Distance from `p` to the paper segment `a`–`b`, and the segment parameter
363/// of the foot.
364fn segment_foot(p: [f64; 2], a: [f64; 2], b: [f64; 2]) -> (f64, f64) {
365    let d = [b[0] - a[0], b[1] - a[1]];
366    let length2 = d[0] * d[0] + d[1] * d[1];
367    let t = if length2 > 0.0 {
368        (((p[0] - a[0]) * d[0] + (p[1] - a[1]) * d[1]) / length2).clamp(0.0, 1.0)
369    } else {
370        0.0
371    };
372    let foot = [a[0] + d[0] * t, a[1] + d[1] * t];
373    (paper_distance(p, foot), t)
374}
375
376/// One sampled curve: parameters, model points and paper points, in order.
377#[derive(Debug, Clone, Default)]
378struct Samples {
379    params: Vec<f64>,
380    points: Vec<Vec3>,
381    paper: Vec<[f64; 2]>,
382    view: Vec<[f64; 3]>,
383}
384
385impl Samples {
386    fn push(&mut self, s: f64, p: Vec3, frame: &ViewFrame, placed: &PlacedView) {
387        let (paper, view) = project(frame, placed, p);
388        self.params.push(s);
389        self.points.push(p);
390        self.paper.push(paper);
391        self.view.push(view);
392    }
393
394    fn len(&self) -> usize {
395        self.params.len()
396    }
397
398    fn paper_length(&self) -> f64 {
399        self.paper.windows(2).map(|w| paper_distance(w[0], w[1])).sum()
400    }
401}
402
403/// Sample `carrier` over `[s0, s1]` so every chord is within [`CHORD_MM`] of
404/// the exact curve ON THE PAPER, starting from `initial` equal intervals. The
405/// test is against the chord as a SEGMENT, so a curve that doubles back in
406/// projection (a circle seen edge-on) is still subdivided at its turn.
407fn sample(
408    carrier: &Carrier,
409    s0: f64,
410    s1: f64,
411    initial: usize,
412    frame: &ViewFrame,
413    placed: &PlacedView,
414) -> Samples {
415    let mut out = Samples::default();
416    let initial = if carrier.straight() { 1 } else { initial.max(2) };
417    let Some(first) = carrier.at(s0) else { return out };
418    out.push(s0, first, frame, placed);
419    let mut stations: Vec<f64> = (0..=initial).map(|k| s0 + (s1 - s0) * k as f64 / initial as f64).collect();
420    // For [`hidden_line_drawing`], every knot of the curve inside the range is
421    // a station too, so each stretch halved is one polynomial span: a kink or
422    // a short span between two stations is never stepped over.
423    if EXACT_BAR.with(|bar| bar.get()).is_some() {
424        let knots = match carrier {
425            Carrier::Edge(curve) => Some(&curve.knots),
426            Carrier::Curve(curve) => Some(&curve.knots),
427            _ => None,
428        };
429        if let Some(knots) = knots {
430            let (low, high) = (s0.min(s1), s0.max(s1));
431            stations.extend(knots.iter().copied().filter(|&k| k > low && k < high));
432            stations.sort_by(|a, b| if s1 >= s0 { a.total_cmp(b) } else { b.total_cmp(a) });
433            stations.dedup();
434        }
435    }
436    for w in stations.windows(2) {
437        let (a, b) = (w[0], w[1]);
438        let (Some(pa), Some(pb)) = (carrier.at(a), carrier.at(b)) else { continue };
439        subdivide(carrier, (a, pa), (b, pb), 0, frame, placed, &mut out);
440    }
441    out
442}
443
444fn subdivide(
445    carrier: &Carrier,
446    (a, pa): (f64, Vec3),
447    (b, pb): (f64, Vec3),
448    depth: u32,
449    frame: &ViewFrame,
450    placed: &PlacedView,
451    out: &mut Samples,
452) {
453    let deepest = if EXACT_BAR.with(|bar| bar.get()).is_some() { EXACT_SUBDIVISION } else { MAX_SUBDIVISION };
454    if depth < deepest && !carrier.straight() {
455        let mid = 0.5 * (a + b);
456        if let Some(pm) = carrier.at(mid) {
457            let (paper_a, _) = project(frame, placed, pa);
458            let (paper_b, _) = project(frame, placed, pb);
459            let (paper_m, _) = project(frame, placed, pm);
460            if segment_foot(paper_m, paper_a, paper_b).0 > CHORD_MM {
461                subdivide(carrier, (a, pa), (mid, pm), depth + 1, frame, placed, out);
462                subdivide(carrier, (mid, pm), (b, pb), depth + 1, frame, placed, out);
463                return;
464            }
465        }
466    }
467    out.push(b, pb, frame, placed);
468}
469
470// ---------------------------------------------------------------------------
471// Candidates
472// ---------------------------------------------------------------------------
473
474/// Which B-rep vertex an edge candidate starts or ends on, for chaining.
475type VertexKey = (usize, u64);
476
477struct Candidate<'a> {
478    carrier: Carrier<'a>,
479    samples: Samples,
480    /// Drawn (an inked edge or a silhouette) or only a SPLITTER.
481    inked: bool,
482    silhouette: bool,
483    /// The B-rep edge an edge candidate samples.
484    edge: Option<(usize, u64)>,
485    ends: Option<(VertexKey, VertexKey)>,
486    /// Paper box of the samples.
487    bounds: [f64; 4],
488    /// Its solid is left whole by the section ([`Clip::Beyond`]).
489    whole: bool,
490}
491
492fn bounds_of(paper: &[[f64; 2]]) -> [f64; 4] {
493    let mut b = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY];
494    for p in paper {
495        b[0] = b[0].min(p[0]);
496        b[1] = b[1].min(p[1]);
497        b[2] = b[2].max(p[0]);
498        b[3] = b[3].max(p[1]);
499    }
500    b
501}
502
503/// Initial sampling density of a NURBS curve: a few intervals per span.
504fn curve_initial(curve: &NurbsCurve) -> usize {
505    let spans = curve.control_points.len().saturating_sub(curve.degree).max(1);
506    (spans * (curve.degree + 1)).clamp(2, 256)
507}
508
509/// The outward normal of `face` at model point `p` (the carrier's normal,
510/// turned by `same_sense`), through the carrier's own projection.
511fn outward_normal(face: &FaceRecord, p: Vec3) -> Option<Vec3> {
512    let foot = project_point_to_surface(&face.surface, p).ok()?;
513    let n = face.surface.normal(foot.u, foot.v).ok()?;
514    Some(if face.same_sense { n } else { n.scale(-1.0) })
515}
516
517/// Whether an edge between `a` and `b` is a CREASE anywhere along it: the two
518/// outward normals more than [`EDGE_ANGLE_DEG`] apart at any of five interior
519/// stations. A normal that cannot be evaluated counts as a crease — drawn
520/// rather than guessed away.
521fn is_crease(curve: &NurbsCurve, t0: f64, t1: f64, a: &FaceRecord, b: &FaceRecord) -> bool {
522    let bar = EDGE_ANGLE_DEG.to_radians().cos();
523    for k in 1..=5 {
524        let t = t0 + (t1 - t0) * k as f64 / 6.0;
525        let Ok(p) = curve.evaluate(t) else { return true };
526        let (Some(na), Some(nb)) = (outward_normal(a, p), outward_normal(b, p)) else { return true };
527        if na.dot(nb) < bar {
528            return true;
529        }
530    }
531    false
532}
533
534/// Every face's index by the edges its loops use: `edge id -> [(face index)]`.
535fn edge_faces(solid: &BrepSolid) -> HashMap<u64, Vec<(usize, usize)>> {
536    let mut map: HashMap<u64, Vec<(usize, usize)>> = HashMap::new();
537    for (shell_index, shell) in solid.shells.iter().enumerate() {
538        for (face_index, face) in shell.faces.iter().enumerate() {
539            for lp in &face.loops {
540                for coedge in &lp.coedges {
541                    map.entry(coedge.edge_id).or_default().push((shell_index, face_index));
542                }
543            }
544        }
545    }
546    map
547}
548
549/// The diagonal of the box two faces' BOUNDARIES span — both ends and the
550/// middle of every edge either face's loops use: how far, to the scale
551/// [`one_surface`] needs, the pair reaches from an edge it shares. A face that
552/// bulges past its own boundary reaches farther than this.
553fn pair_extent(solid: &BrepSolid, a: &FaceRecord, b: &FaceRecord, edge_index: &HashMap<u64, usize>) -> f64 {
554    let mut lo = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
555    let mut hi = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
556    for coedge in [a, b].into_iter().flat_map(|face| &face.loops).flat_map(|lp| &lp.coedges) {
557        let Some(edge) = edge_index.get(&coedge.edge_id).map(|&i| &solid.edges[i]) else { continue };
558        for t in [edge.t0, 0.5 * (edge.t0 + edge.t1), edge.t1] {
559            if let Ok(q) = edge.curve.evaluate(t) {
560                lo = Vec3::new(lo.x.min(q.x), lo.y.min(q.y), lo.z.min(q.z));
561                hi = Vec3::new(hi.x.max(q.x), hi.y.max(q.y), hi.z.max(q.z));
562            }
563        }
564    }
565    if lo.x <= hi.x {
566        hi.sub(lo).length()
567    } else {
568        0.0
569    }
570}
571
572/// The normal curvature of `face` at `p` ACROSS the direction `tangent`,
573/// signed against the face's outward normal, read off the carrier's second
574/// derivatives at the foot of `p`.
575fn curvature_across(face: &FaceRecord, p: Vec3, tangent: Vec3) -> Option<f64> {
576    let foot = project_point_to_surface(&face.surface, p).ok()?;
577    let d = face.surface.derivatives(foot.u, foot.v, 2).ok()?;
578    let (su, sv) = (d[1][0], d[0][1]);
579    let normal = su.cross(sv).normalized().ok()?;
580    let normal = if face.same_sense { normal } else { normal.scale(-1.0) };
581    let across = normal.cross(tangent).normalized().ok()?;
582    // `across` in the carrier's own tangent basis, then II / I along it.
583    let (e, f, g) = (su.dot(su), su.dot(sv), sv.dot(sv));
584    let det = e * g - f * f;
585    if det.abs() <= f64::EPSILON * e * g {
586        return None;
587    }
588    let (cu, cv) = (across.dot(su), across.dot(sv));
589    let (a, b) = ((g * cu - f * cv) / det, (e * cv - f * cu) / det);
590    let second = d[2][0].dot(normal) * a * a + 2.0 * d[1][1].dot(normal) * a * b + d[0][2].dot(normal) * b * b;
591    let first = e * a * a + 2.0 * f * a * b + g * b * b;
592    (first > 0.0).then(|| second / first)
593}
594
595/// Whether the two faces of a SMOOTH edge are ONE surface — fragments of a
596/// split no merge removed, whose shared edge is not a line of the part —
597/// rather than two surfaces meeting tangentially, where the edge is a TANGENT
598/// LINE (a round's, a blend's) and is drawn.
599///
600/// Two carriers tangent along an edge whose normal curvatures across it
601/// differ by Δκ part by Δκ·w²/2 at a distance w from it. They are one surface
602/// when that parting, over `extent` ([`pair_extent`]), is within the B-rep bar at every one of five interior stations —
603/// the same stations and the same doubt rule as [`is_crease`]: a curvature
604/// that cannot be evaluated draws the line. Read at the edge, where both
605/// carriers are inside their own domains, so a fragment's carrier being
606/// bounded to its fragment does not matter. What it does not see is a
607/// curvature-CONTINUOUS (G2) joint between two surfaces: its edge is drawn
608/// as one surface's.
609fn one_surface(curve: &NurbsCurve, t0: f64, t1: f64, a: &FaceRecord, b: &FaceRecord, extent: f64, bar: f64) -> bool {
610    for k in 1..=5 {
611        let t = t0 + (t1 - t0) * k as f64 / 6.0;
612        let (Ok(p), Ok(d)) = (curve.evaluate(t), curve.derivatives(t, 1)) else { return false };
613        let (Some(ka), Some(kb)) = (curvature_across(a, p, d[1]), curvature_across(b, p, d[1])) else { return false };
614        if (ka - kb).abs() * extent * extent * 0.5 > bar {
615            return false;
616        }
617    }
618    true
619}
620
621fn edge_candidates<'a>(
622    solid_index: usize,
623    solid: &'a BrepSolid,
624    frame: &ViewFrame,
625    placed: &PlacedView,
626    floors: &Floors,
627) -> Vec<Candidate<'a>> {
628    let faces = edge_faces(solid);
629    let edge_index: HashMap<u64, usize> = solid.edges.iter().enumerate().map(|(i, edge)| (edge.id, i)).collect();
630    // How far each smooth pair of faces reaches, read once per pair.
631    let mut extents: HashMap<[(usize, usize); 2], f64> = HashMap::new();
632    let mut out = Vec::new();
633    for edge in &solid.edges {
634        if edge.degenerate {
635            continue;
636        }
637        let owners = faces.get(&edge.id).cloned().unwrap_or_default();
638        let mut distinct = owners.clone();
639        distinct.sort_unstable();
640        distinct.dedup();
641        let inked = match distinct.len() {
642            // A seam: the face meets itself. Not a line of the drawing, and
643            // not a place visibility can change (the surface is one surface
644            // across it), so it is not even a splitter.
645            1 if owners.len() >= 2 => continue,
646            // A crease, or a tangent line between two surfaces; an edge
647            // between two fragments of one surface is a splitter only.
648            2 => {
649                let face = |(s, f): (usize, usize)| &solid.shells[s].faces[f];
650                let (a, b) = (face(distinct[0]), face(distinct[1]));
651                is_crease(&edge.curve, edge.t0, edge.t1, a, b) || {
652                    let extent = *extents
653                        .entry([distinct[0], distinct[1]])
654                        .or_insert_with(|| pair_extent(solid, a, b, &edge_index));
655                    !one_surface(&edge.curve, edge.t0, edge.t1, a, b, extent, floors.bar)
656                }
657            }
658            _ => true,
659        };
660        let carrier = Carrier::Edge(&edge.curve);
661        let samples = sample(&carrier, edge.t0, edge.t1, curve_initial(&edge.curve), frame, placed);
662        if samples.len() < 2 {
663            continue;
664        }
665        let bounds = bounds_of(&samples.paper);
666        out.push(Candidate {
667            carrier,
668            samples,
669            inked,
670            silhouette: false,
671            edge: Some((solid_index, edge.id)),
672            ends: Some(((solid_index, edge.start_vertex_id), (solid_index, edge.end_vertex_id))),
673            bounds,
674            whole: false,
675        });
676    }
677    out
678}
679
680/// Whether a face is flat: a recognized plane, or an affine bilinear patch.
681fn planar(surface: &NurbsSurface) -> bool {
682    matches!(surface.analytic(), Some(AnalyticSurface::Plane { .. })) || surface.is_affine().unwrap_or(false)
683}
684
685/// The uv box of a face's trim: the control points of every loop's pcurves,
686/// clamped to the carrier's domain (a pcurve lies in its own control hull).
687fn trim_box(face: &FaceRecord) -> Option<[f64; 4]> {
688    let du = face.surface.domain_u().ok()?;
689    let dv = face.surface.domain_v().ok()?;
690    let mut b = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY];
691    for lp in &face.loops {
692        for coedge in &lp.coedges {
693            for cp in &coedge.pcurve.control_points {
694                let w = if cp.w != 0.0 { cp.w } else { 1.0 };
695                b[0] = b[0].min(cp.x / w);
696                b[1] = b[1].min(cp.y / w);
697                b[2] = b[2].max(cp.x / w);
698                b[3] = b[3].max(cp.y / w);
699            }
700        }
701    }
702    if !(b[0] <= b[2]) {
703        return Some([du[0], dv[0], du[1], dv[1]]);
704    }
705    Some([b[0].max(du[0]), b[1].max(dv[0]), b[2].min(du[1]), b[3].min(dv[1])])
706}
707
708/// What a pass learns about every trim of one solid that no camera, scale or
709/// clip changes: each face's `TrimTests`, `[shell][face]`. The projection
710/// cache keeps one per solid it draws ([`crate::sheets::project`]), so a
711/// re-projection — another scale, a section or a detail of the same part —
712/// asks nothing a previous one built.
713pub struct SolidTrims {
714    faces: Vec<Vec<TrimTests>>,
715}
716
717impl SolidTrims {
718    pub fn of(solid: &BrepSolid) -> SolidTrims {
719        SolidTrims { faces: solid.shells.iter().map(|shell| shell.faces.iter().map(|_| TrimTests::new()).collect()).collect() }
720    }
721}
722
723/// What a pass learns about a face's trim, so the kernel is asked only what
724/// nothing cheaper can answer: which of the kernel's containment lanes the face
725/// is in ([`containment_lane`]), its [`UvReach`], and — the first time a
726/// question gets past that — its [`UvTrim`]. All are read off the face alone,
727/// so they hold for any view of it, and each is learned the first time a
728/// question about the face needs it.
729struct TrimTests {
730    lane: std::cell::OnceCell<Option<ContainmentLane>>,
731    reach: std::cell::OnceCell<Option<UvReach>>,
732    uv: std::cell::OnceCell<Option<UvTrim>>,
733}
734
735impl TrimTests {
736    fn new() -> TrimTests {
737        TrimTests { lane: std::cell::OnceCell::new(), reach: std::cell::OnceCell::new(), uv: std::cell::OnceCell::new() }
738    }
739
740    /// The kernel's lane for the face; `None` where preparing it fails, where
741    /// the kernel's own answer is an error and nothing answers ahead of it.
742    fn lane(&self, face: &FaceRecord) -> Option<&ContainmentLane> {
743        self.lane.get_or_init(|| containment_lane(face).ok()).as_ref()
744    }
745
746    /// The face's [`UvReach`].
747    fn reach(&self, face: &FaceRecord) -> Option<&UvReach> {
748        self.reach.get_or_init(|| self.lane(face).and_then(|lane| UvReach::of(face, lane))).as_ref()
749    }
750
751    /// The face's [`UvTrim`], built the first time the kernel would be asked.
752    fn uv_trim(&self, face: &FaceRecord) -> Option<&UvTrim> {
753        self.uv
754            .get_or_init(|| {
755                let reach = self.reach(face)?;
756                UvTrim::of(face, reach, self.lane(face)?)
757            })
758            .as_ref()
759    }
760}
761
762/// A face's trim in its carrier's parameters, as the kernel's containment
763/// test reads it, so that a point clear of its chords is classified here and
764/// only a point near them is asked of the kernel. Two of the kernel's lanes
765/// are mirrored; any other face has none.
766///
767/// **The plain lane** — the kernel's generic scan, for a face
768/// [`containment_lane`] puts there without the sphere chart — samples each
769/// pcurve at the kernel's [`trim_sample_count`] stations, [`trim_station`]
770/// apart (`max(2, (k + 1)(p + 1)·4)`, `k` the distinct interior knots), and
771/// answers `Boundary` (inside) within its band
772/// of a chord, counts crossings of that polygon farther than one chord's length
773/// from the nearest chord, and takes the side of the pcurve itself nearer than
774/// that. This polygon's vertices are a subset of those stations — one per
775/// power-of-two stride, halved on the kernel's own stations wherever the
776/// chord's middle sits off it by more than the kernel's band at the trim's
777/// middle — and `margin` is the largest such middle's distance off its chord
778/// (and the gaps where one pcurve's end meets the next one's start). The
779/// kernel's polygon and the pcurves both lie within that of this one, so a
780/// point farther than the kernel's band plus `margin` from every chord is
781/// outside that band of the kernel's polygon and on the same side of it as of
782/// this one and of the pcurves: whichever rule the kernel uses there, its
783/// answer is this polygon's even-odd count. The side rule assumes the loops
784/// run with the material to the left of each pcurve on a same-sense face (to
785/// the right otherwise); a face whose loops do not is left to the kernel.
786///
787/// **The seam-horizon lane**, for a face [`containment_lane`] puts in the
788/// kernel's wrapped-horizon lane: the loops the kernel published, unwrapped
789/// sample to sample, `Boundary` within the band of a chord at any of the
790/// query's three period images, otherwise each loop's even-odd count summed
791/// over the images, mod 2. Here the polygon IS the kernel's, every station
792/// kept, and a point is asked of the kernel within twice its band of a chord at
793/// any image. With the kernel's per-image fallback switched on
794/// ([`brep_kernel::horizon_cross_frame`] false) it is not built.
795///
796/// Not built for a face in any other lane: the seam band, the sphere cap, the
797/// covering rim strip, or the generic scan where the sphere chart substitutes
798/// for its parity count.
799struct UvTrim {
800    /// `(from, to, loop)`.
801    segments: Vec<([f64; 2], [f64; 2], usize)>,
802    loops: usize,
803    grid: Grid,
804    /// How far beyond the kernel's band a point must be from every chord.
805    margin: Margin,
806    /// The period images the query is counted at.
807    images: Vec<f64>,
808}
809
810#[derive(Debug, Clone, Copy)]
811enum Margin {
812    /// Plus this, in the carrier's parameters.
813    Plus(f64),
814    /// The kernel's band again.
815    Twice,
816}
817
818impl UvTrim {
819    fn of(face: &FaceRecord, reach: &UvReach, lane: &ContainmentLane) -> Option<UvTrim> {
820        match lane {
821            ContainmentLane::WrappedHorizon { loops, u_period, cross_frame: true } => {
822                let loops = loops.iter().map(|lp| lp.iter().map(|p| [p.x, p.y]).collect()).collect();
823                return Some(UvTrim::grid_of(loops, Margin::Twice, vec![-u_period, 0.0, *u_period]));
824            }
825            ContainmentLane::Generic { sphere_chart: false } => {}
826            _ => return None,
827        }
828        let surface = &face.surface;
829        // Chords no coarser than the band the kernel asks with at the trim's
830        // middle, where the curve allows it.
831        let centre = [0.5 * (reach.lo[0] + reach.hi[0]), 0.5 * (reach.lo[1] + reach.hi[1])];
832        let fine = trim_band(surface, centre, KernelTolerances::default().pcurve_consistency);
833        let mut rings: Vec<Vec<[f64; 2]>> = Vec::with_capacity(face.loops.len());
834        let mut sag: f64 = 0.0;
835        for lp in &face.loops {
836            let mut ring = Vec::new();
837            for coedge in &lp.coedges {
838                let curve = &coedge.pcurve;
839                let [start, end] = curve.domain().ok()?;
840                let count = trim_sample_count(curve);
841                let station = |i: usize| if i < count { trim_station(start, end, i, count) } else { end };
842                let at = |i: usize| -> Option<[f64; 2]> { curve.evaluate(station(i)).ok().map(|p| [p.x, p.y]) };
843                // Every station ours is one of the kernel's, the coarsest a
844                // power-of-two stride that still gives two chords.
845                let mut stride = 1;
846                while count % (stride * 2) == 0 && count / (stride * 2) >= 2 {
847                    stride *= 2;
848                }
849                let mut a = at(0)?;
850                // The kernel's polygon runs from a pcurve's last station
851                // straight to the next one's first; both polygons meet the
852                // pcurves' own ends only to the gap between them.
853                if let Some(previous) = ring.last() {
854                    sag = sag.max(paper_distance(*previous, a));
855                }
856                for from in (0..count).step_by(stride) {
857                    let to = from + stride;
858                    let b = at(to)?;
859                    // Halve on the kernel's stations while the middle sits
860                    // off the chord by more than `fine`; a single kernel
861                    // chord is measured at its parameter middle.
862                    let mut pending = vec![(from, a, to, b)];
863                    while let Some((i, pi, j, pj)) = pending.pop() {
864                        if j - i >= 2 {
865                            let m = (i + j) / 2;
866                            let pm = at(m)?;
867                            let off = segment_foot(pm, pi, pj).0;
868                            if off > fine {
869                                pending.push((m, pm, j, pj));
870                                pending.push((i, pi, m, pm));
871                                continue;
872                            }
873                            sag = sag.max(off);
874                        } else {
875                            let pm = curve.evaluate(0.5 * (station(i) + station(j))).ok()?;
876                            sag = sag.max(segment_foot([pm.x, pm.y], pi, pj).0);
877                        }
878                        ring.push(pi);
879                    }
880                    a = b;
881                }
882                ring.push(a);
883            }
884            if let (Some(first), Some(last)) = (ring.first(), ring.last()) {
885                sag = sag.max(paper_distance(*first, *last));
886            }
887            if ring.len() >= 2 {
888                rings.push(ring);
889            }
890        }
891        let area = |ring: &[[f64; 2]]| -> f64 {
892            (0..ring.len()).map(|i| {
893                let (a, b) = (ring[i], ring[(i + 1) % ring.len()]);
894                a[0] * b[1] - b[0] * a[1]
895            }).sum()
896        };
897        let areas: Vec<f64> = rings.iter().map(|ring| area(ring)).collect();
898        let outer = (0..rings.len()).max_by(|&i, &j| areas[i].abs().partial_cmp(&areas[j].abs()).unwrap_or(std::cmp::Ordering::Equal))?;
899        let left = if face.same_sense { 1.0 } else { -1.0 };
900        for (index, a) in areas.iter().enumerate() {
901            let expected = if index == outer { left } else { -left };
902            if !(a * expected > 0.0) {
903                return None;
904            }
905        }
906        Some(UvTrim::grid_of(rings, Margin::Plus(sag), vec![0.0]))
907    }
908
909    fn grid_of(rings: Vec<Vec<[f64; 2]>>, margin: Margin, images: Vec<f64>) -> UvTrim {
910        let mut segments = Vec::new();
911        for (index, ring) in rings.iter().enumerate() {
912            for i in 0..ring.len() {
913                segments.push((ring[i], ring[(i + 1) % ring.len()], index));
914            }
915        }
916        let mut extent = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY];
917        let boxed = |(a, b, _): &([f64; 2], [f64; 2], usize)| [a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])];
918        for segment in &segments {
919            let g = boxed(segment);
920            extent = [extent[0].min(g[0]), extent[1].min(g[1]), extent[2].max(g[2]), extent[3].max(g[3])];
921        }
922        let mut grid = Grid::new(extent, segments.len().max(1));
923        for (index, segment) in segments.iter().enumerate() {
924            grid.insert(boxed(segment), index);
925        }
926        UvTrim { segments, loops: rings.len(), grid, margin, images }
927    }
928
929    /// Inside the trim, or `None` near enough a chord that only the kernel
930    /// can say, `band` being the band the kernel is asked with.
931    fn covers(&self, uv: [f64; 2], band: f64) -> Option<bool> {
932        let near = match self.margin {
933            Margin::Plus(sag) => band + sag,
934            Margin::Twice => 2.0 * band,
935        };
936        let mut odd = vec![0u32; self.loops];
937        for shift in &self.images {
938            let image = [uv[0] + shift, uv[1]];
939            let (x0, y0, x1, y1) = self.grid.range([image[0] - near, image[1] - near, image[0] + near, image[1] + near]);
940            for y in y0..=y1 {
941                for x in x0..=x1 {
942                    for &index in &self.grid.buckets[y * self.grid.width + x] {
943                        let (a, b, _) = self.segments[index];
944                        if segment_foot(image, a, b).0 <= near {
945                            return None;
946                        }
947                    }
948                }
949            }
950            // The lane's own count: crossings of +u, half-open in v, per loop.
951            let (column, row, _, _) = self.grid.range([image[0], image[1], image[0], image[1]]);
952            let mut inside = vec![false; self.loops];
953            for x in column..self.grid.width {
954                for &index in &self.grid.buckets[row * self.grid.width + x] {
955                    let (a, b, ring) = self.segments[index];
956                    if (a[1] > image[1]) == (b[1] > image[1]) {
957                        continue;
958                    }
959                    let crossing = a[0] + (image[1] - a[1]) / (b[1] - a[1]) * (b[0] - a[0]);
960                    if crossing > image[0] && self.grid.range([crossing, image[1], crossing, image[1]]).0 == x {
961                        inside[ring] = !inside[ring];
962                    }
963                }
964            }
965            for (ring, inside) in inside.into_iter().enumerate() {
966                odd[ring] += inside as u32;
967            }
968        }
969        Some(odd.iter().map(|hits| hits % 2).sum::<u32>() % 2 == 1)
970    }
971}
972
973/// A flat face's trim on the paper: its loops closed from the paper samples of
974/// its boundary edges, each segment signed by its loop's orientation (the
975/// loop of largest projected area is the outer one, the rest are holes) and
976/// bucketed on a grid.
977///
978/// A flat face that is not edge-on maps onto the paper one to one, so the view
979/// ray through a paper point meets it inside its trim exactly when the
980/// projected loops wind round the point. The projected loops are not the trim,
981/// and differ from it by at most the band [`PaperTrim::covers`] keeps clear of
982/// them: [`CHORD_MM`], the samples' chords against the exact edge curves, plus
983/// the crossing floor twice — once for an edge curve sitting the B-rep bar off
984/// the trim its pcurves draw (and a loop closed across two edges' ends that
985/// agree only to that bar), once for the band the kernel's trim test counts as
986/// inside.
987///
988/// It answers ONE way. A point the loops wind round by more than the band is
989/// inside the trim, and the kernel's test says so too: within its band of its
990/// chord polygon it answers inside, near the pcurve it takes the pcurve's own
991/// side, and farther out its polygon's count agrees with the pcurve's. A point
992/// the loops do not wind round is NOT reliably outside for the kernel: it
993/// counts anything within its band of its own chords as inside, and a chord
994/// can sit well inside a rim it samples coarsely — measured on `booleanIssue`,
995/// where a hole's circle is sampled at twelve stations and a point 0.023 paper
996/// mm into the hole reads `Boundary`. So "not covered" goes to the trim test in
997/// the carrier's parameters ([`UvTrim`], then the kernel).
998///
999/// This is what made the pass fast: one flat face of `gear-hex-bore-push`
1000/// carries 562 boundary edges and 36 530 pcurve control points, and the
1001/// kernel's test scans every sample of that trim for every point it is asked
1002/// about — 37 of the pass's 43 seconds.
1003#[derive(Debug, Clone)]
1004struct PaperTrim {
1005    /// `(from, to, sign)`: the sign turns every loop to the outer-positive,
1006    /// holes-negative orientation.
1007    segments: Vec<([f64; 2], [f64; 2], i32)>,
1008    /// Each segment, in every cell its box grown by the band touches.
1009    grid: Grid,
1010    band: f64,
1011}
1012
1013impl PaperTrim {
1014    /// `None` when a boundary edge has no samples (a seam has none), or a loop
1015    /// does not close on the paper within the bar the B-rep keeps its edges'
1016    /// ends to.
1017    fn of(solid: &BrepSolid, face: &FaceRecord, paper_of_edge: &HashMap<u64, &[[f64; 2]]>, floors: &Floors) -> Option<PaperTrim> {
1018        let band = CHORD_MM + 2.0 * floors.crossing_mm;
1019        let gap = 2.0 * floors.crossing_mm + CHORD_MM;
1020        let mut rings: Vec<Vec<[f64; 2]>> = Vec::with_capacity(face.loops.len());
1021        for lp in &face.loops {
1022            let mut pieces: Vec<&[[f64; 2]]> = Vec::with_capacity(lp.coedges.len());
1023            for coedge in &lp.coedges {
1024                match paper_of_edge.get(&coedge.edge_id) {
1025                    Some(paper) if paper.len() >= 2 => pieces.push(paper),
1026                    _ if solid.edges.iter().any(|edge| edge.id == coedge.edge_id && edge.degenerate) => {}
1027                    _ => return None,
1028                }
1029            }
1030            let Some(first) = pieces.first() else { continue };
1031            // Walk the loop, each edge's samples the way round that starts
1032            // nearest the previous one's end; the first is turned to end
1033            // nearest the second.
1034            let ends = |piece: &[[f64; 2]]| (piece[0], piece[piece.len() - 1]);
1035            let first_forward = pieces.get(1).is_none_or(|next| {
1036                let (n0, n1) = ends(next);
1037                let near = |p: [f64; 2]| paper_distance(p, n0).min(paper_distance(p, n1));
1038                near(ends(first).1) <= near(ends(first).0)
1039            });
1040            let mut ring: Vec<[f64; 2]> = if first_forward { first.to_vec() } else { first.iter().rev().copied().collect() };
1041            for piece in &pieces[1..] {
1042                let last = ring[ring.len() - 1];
1043                let (p0, p1) = ends(piece);
1044                let forward = paper_distance(last, p0) <= paper_distance(last, p1);
1045                if paper_distance(last, if forward { p0 } else { p1 }) > gap {
1046                    return None;
1047                }
1048                if forward {
1049                    ring.extend_from_slice(piece);
1050                } else {
1051                    ring.extend(piece.iter().rev());
1052                }
1053            }
1054            if paper_distance(ring[0], ring[ring.len() - 1]) > gap {
1055                return None;
1056            }
1057            rings.push(ring);
1058        }
1059        // Twice the signed area of each ring, and the outer one.
1060        let areas: Vec<f64> = rings
1061            .iter()
1062            .map(|ring| (0..ring.len()).map(|i| {
1063                let (a, b) = (ring[i], ring[(i + 1) % ring.len()]);
1064                a[0] * b[1] - b[0] * a[1]
1065            }).sum())
1066            .collect();
1067        let outer = (0..rings.len()).max_by(|&i, &j| areas[i].abs().partial_cmp(&areas[j].abs()).unwrap_or(std::cmp::Ordering::Equal))?;
1068        let mut segments: Vec<([f64; 2], [f64; 2], i32)> = Vec::new();
1069        for (index, ring) in rings.iter().enumerate() {
1070            let turned = if areas[index] < 0.0 { -1 } else { 1 };
1071            let sign = if index == outer { turned } else { -turned };
1072            segments.extend((0..ring.len()).map(|i| (ring[i], ring[(i + 1) % ring.len()], sign)));
1073        }
1074        let mut extent = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY];
1075        let grown = |(a, b, _): &([f64; 2], [f64; 2], i32)| {
1076            [a[0].min(b[0]) - band, a[1].min(b[1]) - band, a[0].max(b[0]) + band, a[1].max(b[1]) + band]
1077        };
1078        for segment in &segments {
1079            let g = grown(segment);
1080            extent = [extent[0].min(g[0]), extent[1].min(g[1]), extent[2].max(g[2]), extent[3].max(g[3])];
1081        }
1082        let mut grid = Grid::new(extent, segments.len());
1083        for (index, segment) in segments.iter().enumerate() {
1084            grid.insert(grown(segment), index);
1085        }
1086        Some(PaperTrim { segments, grid, band })
1087    }
1088
1089    /// Whether the face covers paper point `p` — its projected loops wind
1090    /// round it — or `None` within the band of them, where only the kernel
1091    /// can say.
1092    fn covers(&self, p: [f64; 2]) -> Option<bool> {
1093        // A segment within the band has its grown box round `p`, so it is in
1094        // `p`'s own cell.
1095        if self.grid.at(p).iter().any(|&index| {
1096            let (a, b, _) = self.segments[index];
1097            segment_foot(p, a, b).0 <= self.band
1098        }) {
1099            return None;
1100        }
1101        // Signed crossings along +x, half-open in y. A segment the ray
1102        // crosses is in the cell of the crossing, and is counted there only.
1103        let (column, row, _, _) = self.grid.range([p[0], p[1], p[0], p[1]]);
1104        let mut winding = 0;
1105        for x in column..self.grid.width {
1106            for &index in &self.grid.buckets[row * self.grid.width + x] {
1107                let (a, b, sign) = self.segments[index];
1108                if (a[1] > p[1]) == (b[1] > p[1]) {
1109                    continue;
1110                }
1111                let crossing = a[0] + (p[1] - a[1]) / (b[1] - a[1]) * (b[0] - a[0]);
1112                if crossing > p[0] && self.grid.range([crossing, p[1], crossing, p[1]]).0 == x {
1113                    winding += if b[1] > p[1] { sign } else { -sign };
1114                }
1115            }
1116        }
1117        Some(winding != 0)
1118    }
1119}
1120
1121/// The uv coincidence band a trim is asked with: the B-rep bar carried into
1122/// the carrier's parameters by its own speed at `uv`.
1123fn trim_band(surface: &NurbsSurface, uv: [f64; 2], bar: f64) -> f64 {
1124    let speed = surface
1125        .derivatives(uv[0], uv[1], 1)
1126        .ok()
1127        .map(|d| d[1][0].length().max(d[0][1].length()))
1128        .unwrap_or(0.0);
1129    if speed > 1e-12 {
1130        bar / speed
1131    } else {
1132        1e-9
1133    }
1134}
1135
1136/// Inside (or on) a face's trim: the kernel's `parameter_point_in_face`,
1137/// unless what the pass has learned about the trim ([`TrimTests`]) answers
1138/// first.
1139fn in_face(face: &FaceRecord, tests: Option<&TrimTests>, uv: [f64; 2], bar: f64) -> bool {
1140    let band = trim_band(&face.surface, uv, bar);
1141    if let Some(tests) = tests {
1142        if tests.reach(face).is_some_and(|reach| reach.outside(uv, band)) {
1143            return false;
1144        }
1145        if let Some(inside) = tests.uv_trim(face).and_then(|trim| trim.covers(uv, band)) {
1146            return inside;
1147        }
1148    }
1149    TRIM_QUERIES.with(|count| count.set(count.get() + 1));
1150    !matches!(
1151        parameter_point_in_face(face, Vec2 { x: uv[0], y: uv[1] }, band),
1152        Ok(PolygonClass::Outside) | Err(_)
1153    )
1154}
1155
1156/// Where in its carrier's parameters a face's trim can put material: the box
1157/// of every loop's pcurve control points — a pcurve with positive weights
1158/// lies in the hull of its own — read modulo the period along a closed
1159/// direction. A point outside that box by more than the band the trim is
1160/// asked with is outside every loop and within the band of none, so the
1161/// kernel's answer there is `Outside` and is not asked for.
1162///
1163/// It is the containment question's cheap half: a silhouette generator of a
1164/// small cylinder patch, or a view ray through its carrier far from the
1165/// patch, is decided without sampling the trim.
1166///
1167/// The box holds for the lanes that answer inside the loops' own polygons: the
1168/// generic scan without the sphere chart and the wrapped horizon.
1169#[derive(Debug, Clone)]
1170struct UvReach {
1171    lo: [f64; 2],
1172    hi: [f64; 2],
1173    period: [Option<f64>; 2],
1174}
1175
1176impl UvReach {
1177    /// `None` where the kernel's lane ([`containment_lane`]) can put material
1178    /// outside the pcurve box: the sphere cap, which holds a pole the loop does
1179    /// not enclose in uv; the sphere chart, which decides on the ball; the seam
1180    /// band, which reads a band of punctures as all material; and the covering
1181    /// rim strip, whose rims need only span the period to within 2%, so a
1182    /// point below both can count one crossing.
1183    fn of(face: &FaceRecord, lane: &ContainmentLane) -> Option<UvReach> {
1184        if !matches!(lane, ContainmentLane::Generic { sphere_chart: false } | ContainmentLane::WrappedHorizon { .. }) {
1185            return None;
1186        }
1187        let surface = &face.surface;
1188        let closed = surface.closed_directions().ok()?;
1189        let (du, dv) = (surface.domain_u().ok()?, surface.domain_v().ok()?);
1190        let mut lo = [f64::INFINITY; 2];
1191        let mut hi = [f64::NEG_INFINITY; 2];
1192        for cp in face.loops.iter().flat_map(|lp| &lp.coedges).flat_map(|coedge| &coedge.pcurve.control_points) {
1193            if !(cp.w > 0.0) {
1194                return None;
1195            }
1196            let (u, v) = (cp.x / cp.w, cp.y / cp.w);
1197            lo = [lo[0].min(u), lo[1].min(v)];
1198            hi = [hi[0].max(u), hi[1].max(v)];
1199        }
1200        if !(lo[0] <= hi[0] && lo[1] <= hi[1]) {
1201            return None;
1202        }
1203        let period = [closed.0.then_some(du[1] - du[0]), closed.1.then_some(dv[1] - dv[0])];
1204        Some(UvReach { lo, hi, period })
1205    }
1206
1207    fn outside(&self, uv: [f64; 2], band: f64) -> bool {
1208        (0..2).any(|k| {
1209            let (lo, hi) = (self.lo[k] - band, self.hi[k] + band);
1210            match self.period[k] {
1211                None => uv[k] < lo || uv[k] > hi,
1212                Some(period) if period > 0.0 && hi - lo < period => {
1213                    uv[k] - ((uv[k] - lo) / period).floor() * period > hi
1214                }
1215                Some(_) => false,
1216            }
1217        })
1218    }
1219}
1220
1221/// The uv of a model point that lies ON `face`'s carrier (within `bar`).
1222fn uv_on(face: &FaceRecord, p: Vec3, bar: f64) -> Option<[f64; 2]> {
1223    let foot = project_point_to_surface(&face.surface, p).ok()?;
1224    (foot.distance <= bar).then_some([foot.u, foot.v])
1225}
1226
1227/// The silhouette curves of one face, trimmed to it.
1228/// The silhouette curves of one face, trimmed to it.
1229fn silhouette_candidates<'a>(
1230    face: &'a FaceRecord,
1231    tests: &TrimTests,
1232    frame: &ViewFrame,
1233    placed: &PlacedView,
1234    floors: &Floors,
1235) -> Vec<Candidate<'a>> {
1236    let surface = &face.surface;
1237    if planar(surface) {
1238        return Vec::new();
1239    }
1240    let dir = v3(frame.forward);
1241    let mut carriers: Vec<(Carrier<'a>, f64, f64, usize)> = Vec::new();
1242    match surface.analytic() {
1243        Some(AnalyticSurface::RuledRevolution { frame: rev, rho0, rho1, height }) => {
1244            // n ∝ h·r(θ) − (ρ1 − ρ0)·axis, so n·d = 0 is A cos θ + B sin θ = C.
1245            let a = height * dir.dot(rev.x_axis);
1246            let b = height * dir.dot(rev.y_axis);
1247            let c = (rho1 - rho0) * dir.dot(rev.axis);
1248            let r = (a * a + b * b).sqrt();
1249            if r > 1e-12 * (height.abs() + 1.0) && c.abs() <= r {
1250                let base = b.atan2(a);
1251                let spread = (c / r).clamp(-1.0, 1.0).acos();
1252                let mut angles = vec![base + spread];
1253                if spread > 1e-12 {
1254                    angles.push(base - spread);
1255                }
1256                for theta in angles {
1257                    let radial = rev.x_axis.scale(theta.cos()).add(rev.y_axis.scale(theta.sin()));
1258                    let start = rev.origin.add(radial.scale(*rho0));
1259                    let end = rev.origin.add(rev.axis.scale(*height)).add(radial.scale(*rho1));
1260                    carriers.push((Carrier::Line { a: start, b: end }, 0.0, 1.0, 1));
1261                }
1262            }
1263        }
1264        Some(AnalyticSurface::Sphere { frame: rev, radius }) => {
1265            let Ok(e1) = dir.perpendicular().and_then(|e| e.normalized()) else { return Vec::new() };
1266            let e2 = dir.cross(e1);
1267            carriers.push((
1268                Carrier::Circle { centre: rev.origin, e1: e1.scale(*radius), e2: e2.scale(*radius) },
1269                0.0,
1270                std::f64::consts::TAU,
1271                16,
1272            ));
1273        }
1274        _ => {
1275            let traced = trace_silhouette(face, dir);
1276            for uv in traced {
1277                let n = uv.len();
1278                if n < 2 {
1279                    continue;
1280                }
1281                carriers.push((Carrier::Traced { surface, uv, dir }, 0.0, (n - 1) as f64, n - 1));
1282            }
1283        }
1284    }
1285    let mut out = Vec::new();
1286    for (carrier, s0, s1, initial) in carriers {
1287        let samples = sample(&carrier, s0, s1, initial, frame, placed);
1288        let spans_found = trimmed_spans(&carrier, &samples, face, tests, floors.bar);
1289        for (lo, hi) in spans_found {
1290            let piece = sample(&carrier, lo, hi, initial_between(&samples, lo, hi), frame, placed);
1291            if piece.len() < 2 || piece.paper_length() < floors.crossing_mm {
1292                continue;
1293            }
1294            let bounds = bounds_of(&piece.paper);
1295            out.push(Candidate {
1296                carrier: carrier.clone(),
1297                samples: piece,
1298                inked: true,
1299                silhouette: true,
1300                edge: None,
1301                ends: None,
1302                bounds,
1303                whole: false,
1304            });
1305        }
1306    }
1307    out
1308}
1309
1310/// How many initial intervals a re-sample of `[lo, hi]` needs: as many as the
1311/// full sampling had there, so the chord test starts no coarser.
1312fn initial_between(samples: &Samples, lo: f64, hi: f64) -> usize {
1313    samples.params.iter().filter(|s| **s > lo && **s < hi).count() + 1
1314}
1315
1316/// The parameter spans of a sampled silhouette that lie on its face, each
1317/// transition pinned by bisection on the exact curve.
1318fn trimmed_spans(carrier: &Carrier, samples: &Samples, face: &FaceRecord, tests: &TrimTests, bar: f64) -> Vec<(f64, f64)> {
1319    // The chord samples, and never fewer than TRIM_STATIONS: a straight
1320    // generator is two chord samples, and a trim it enters and leaves between
1321    // them would be invisible to its ends.
1322    let (s0, s1) = (samples.params[0], *samples.params.last().unwrap());
1323    let mut stations: Vec<f64> = (0..=TRIM_STATIONS).map(|k| s0 + (s1 - s0) * k as f64 / TRIM_STATIONS as f64).collect();
1324    stations.extend(samples.params.iter().copied());
1325    stations.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
1326    stations.dedup();
1327    let inside = |s: f64| -> bool {
1328        let uv = match carrier {
1329            Carrier::Traced { surface, uv, dir } => traced_at(surface, uv, *dir, s).map(|(_, uv)| uv),
1330            _ => carrier.at(s).and_then(|p| uv_on(face, p, bar)),
1331        };
1332        uv.is_some_and(|uv| in_face(face, Some(tests), uv, bar))
1333    };
1334    let flags: Vec<bool> = stations.iter().map(|s| inside(*s)).collect();
1335    let mut spans = Vec::new();
1336    let mut start: Option<f64> = None;
1337    for i in 0..flags.len() {
1338        if i > 0 && flags[i] != flags[i - 1] {
1339            let (mut lo, mut hi) = (stations[i - 1], stations[i]);
1340            let lo_flag = flags[i - 1];
1341            for _ in 0..BISECTION_STEPS {
1342                let mid = 0.5 * (lo + hi);
1343                if inside(mid) == lo_flag {
1344                    lo = mid;
1345                } else {
1346                    hi = mid;
1347                }
1348            }
1349            let cut = 0.5 * (lo + hi);
1350            if flags[i] {
1351                start = Some(cut);
1352            } else if let Some(s) = start.take() {
1353                spans.push((s, cut));
1354            }
1355        } else if i == 0 && flags[0] {
1356            start = Some(stations[0]);
1357        }
1358    }
1359    if let (Some(s), Some(last)) = (start, stations.last()) {
1360        spans.push((s, *last));
1361    }
1362    spans
1363}
1364
1365/// The zero set of `n · d` over a face's uv box, as uv polylines: marching
1366/// squares on a grid of the carrier's own normals, each crossing pinned on
1367/// its grid edge by bisection, the crossings chained cell to cell.
1368fn trace_silhouette(face: &FaceRecord, dir: Vec3) -> Vec<Vec<[f64; 2]>> {
1369    let surface = &face.surface;
1370    let Some(uv_box) = trim_box(face) else { return Vec::new() };
1371    let spans = |knots: &[f64], degree: usize| knots.len().saturating_sub(2 * degree + 1).max(1);
1372    let nu = (spans(&surface.knots_u, surface.degree_u) * (surface.degree_u + 1) * 2).clamp(12, 96);
1373    let nv = (spans(&surface.knots_v, surface.degree_v) * (surface.degree_v + 1) * 2).clamp(12, 96);
1374    let at = |i: usize, j: usize| {
1375        [
1376            uv_box[0] + (uv_box[2] - uv_box[0]) * i as f64 / nu as f64,
1377            uv_box[1] + (uv_box[3] - uv_box[1]) * j as f64 / nv as f64,
1378        ]
1379    };
1380    let mut values = vec![None; (nu + 1) * (nv + 1)];
1381    for j in 0..=nv {
1382        for i in 0..=nu {
1383            let p = at(i, j);
1384            values[j * (nu + 1) + i] = grazing(surface, dir, p[0], p[1]);
1385        }
1386    }
1387    let value = |i: usize, j: usize| values[j * (nu + 1) + i];
1388    // A crossing on a grid edge, keyed by the edge: (i, j, horizontal).
1389    let mut nodes: HashMap<(usize, usize, bool), [f64; 2]> = HashMap::new();
1390    let mut crossing = |i: usize, j: usize, horizontal: bool| -> Option<(usize, usize, bool)> {
1391        let (i2, j2) = if horizontal { (i + 1, j) } else { (i, j + 1) };
1392        let (g0, g1) = (value(i, j)?, value(i2, j2)?);
1393        if (g0 < 0.0) == (g1 < 0.0) {
1394            return None;
1395        }
1396        let key = (i, j, horizontal);
1397        if !nodes.contains_key(&key) {
1398            let (a, b) = (at(i, j), at(i2, j2));
1399            let (mut lo, mut hi, mut g_lo) = (0.0, 1.0, g0);
1400            for _ in 0..BISECTION_STEPS {
1401                let mid = 0.5 * (lo + hi);
1402                let p = [a[0] + (b[0] - a[0]) * mid, a[1] + (b[1] - a[1]) * mid];
1403                let Some(g) = grazing(surface, dir, p[0], p[1]) else { break };
1404                if (g < 0.0) == (g_lo < 0.0) {
1405                    lo = mid;
1406                    g_lo = g;
1407                } else {
1408                    hi = mid;
1409                }
1410            }
1411            let t = 0.5 * (lo + hi);
1412            nodes.insert(key, [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]);
1413        }
1414        Some(key)
1415    };
1416    let mut links: Vec<[(usize, usize, bool); 2]> = Vec::new();
1417    for j in 0..nv {
1418        for i in 0..nu {
1419            let edges = [
1420                crossing(i, j, true),
1421                crossing(i + 1, j, false),
1422                crossing(i, j + 1, true),
1423                crossing(i, j, false),
1424            ];
1425            let hits: Vec<_> = edges.iter().flatten().copied().collect();
1426            match hits.len() {
1427                2 => links.push([hits[0], hits[1]]),
1428                4 => {
1429                    // A saddle: pair by the centre's sign, the usual rule.
1430                    let centre = at(i, j);
1431                    let half = [
1432                        centre[0] + (uv_box[2] - uv_box[0]) * 0.5 / nu as f64,
1433                        centre[1] + (uv_box[3] - uv_box[1]) * 0.5 / nv as f64,
1434                    ];
1435                    let g = grazing(surface, dir, half[0], half[1]).unwrap_or(0.0);
1436                    let corner = value(i, j).unwrap_or(0.0);
1437                    if (g < 0.0) == (corner < 0.0) {
1438                        links.push([hits[0], hits[1]]);
1439                        links.push([hits[2], hits[3]]);
1440                    } else {
1441                        links.push([hits[0], hits[3]]);
1442                        links.push([hits[1], hits[2]]);
1443                    }
1444                }
1445                _ => {}
1446            }
1447        }
1448    }
1449    // Chain the links through shared crossings.
1450    let mut incident: HashMap<(usize, usize, bool), Vec<usize>> = HashMap::new();
1451    for (index, link) in links.iter().enumerate() {
1452        incident.entry(link[0]).or_default().push(index);
1453        incident.entry(link[1]).or_default().push(index);
1454    }
1455    let mut used = vec![false; links.len()];
1456    let mut order: Vec<usize> = (0..links.len()).collect();
1457    // Start from an END (a crossing one link touches) so open curves keep
1458    // their ends; what is left is closed.
1459    order.sort_by_key(|&i| {
1460        let open = incident[&links[i][0]].len() == 1 || incident[&links[i][1]].len() == 1;
1461        (!open, i)
1462    });
1463    let mut out = Vec::new();
1464    for start in order {
1465        if used[start] {
1466            continue;
1467        }
1468        used[start] = true;
1469        let [a, b] = links[start];
1470        let (head, mut tail) = if incident[&a].len() == 1 { (a, b) } else { (b, a) };
1471        let mut path = vec![head, tail];
1472        while let Some(next) = incident[&tail].iter().copied().find(|i| !used[*i]) {
1473            used[next] = true;
1474            tail = if links[next][0] == tail { links[next][1] } else { links[next][0] };
1475            path.push(tail);
1476            if tail == head {
1477                break;
1478            }
1479        }
1480        out.push(path.into_iter().map(|key| nodes[&key]).collect());
1481    }
1482    out
1483}
1484
1485// ---------------------------------------------------------------------------
1486// Occluders
1487// ---------------------------------------------------------------------------
1488
1489/// Something that can hide a piece, and its box on the paper.
1490struct Occluder<'a> {
1491    cover: Cover<'a>,
1492    bounds: [f64; 4],
1493    /// Its solid is left whole by the section: it hides from the removed side too.
1494    whole: bool,
1495}
1496
1497/// What an [`Occluder`] is.
1498enum Cover<'a> {
1499    /// A B-rep face: the exact pass.
1500    Face {
1501        face: &'a FaceRecord,
1502        /// `(point, unit normal)` of a flat face, for the closed-form ray hit.
1503        plane: Option<(Vec3, Vec3)>,
1504        /// The carrier's per-SPAN control hulls that meet the trim's uv box,
1505        /// each as its paper box, its projected convex hull and its nearest
1506        /// view depth: a NURBS patch lies inside the hull of the control points
1507        /// of each of its knot spans, and a projection of a convex hull is the
1508        /// convex hull of the projections, so a point outside every hull — or
1509        /// in front of every hull that holds it — is not covered by the face.
1510        /// Much tighter than one hull for a lofted face, and than a box for a
1511        /// slanted one.
1512        spans: Vec<SpanHull>,
1513        /// What the pass has learned about the trim.
1514        tests: &'a TrimTests,
1515        /// A flat face's trim on the paper, when its loops close there.
1516        trim: Option<PaperTrim>,
1517    },
1518    /// A triangle of a display mesh: the mesh approximation
1519    /// ([`visible_mesh_lines`]). Its corners and unit normal.
1520    Triangle { corners: [Vec3; 3], normal: Vec3 },
1521}
1522
1523/// The paper box a face can cover: its boundary and silhouettes when those
1524/// were computed in closed form, otherwise the carrier's control hull (a
1525/// NURBS patch lies inside it, so the box is never short).
1526fn face_bounds(
1527    face: &FaceRecord,
1528    boundary: &[[f64; 4]],
1529    silhouettes: &[[f64; 4]],
1530    frame: &ViewFrame,
1531    placed: &PlacedView,
1532) -> [f64; 4] {
1533    let exact_outline = planar(&face.surface)
1534        || matches!(face.surface.analytic(), Some(AnalyticSurface::RuledRevolution { .. } | AnalyticSurface::Sphere { .. }));
1535    let mut b = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY];
1536    let mut grow = |c: [f64; 4]| {
1537        b[0] = b[0].min(c[0]);
1538        b[1] = b[1].min(c[1]);
1539        b[2] = b[2].max(c[2]);
1540        b[3] = b[3].max(c[3]);
1541    };
1542    if exact_outline && !boundary.is_empty() {
1543        for c in boundary.iter().chain(silhouettes) {
1544            grow(*c);
1545        }
1546    } else {
1547        for row in &face.surface.control_points {
1548            for cp in row {
1549                let w = if cp.w != 0.0 { cp.w } else { 1.0 };
1550                let (paper, _) = project(frame, placed, Vec3::new(cp.x / w, cp.y / w, cp.z / w));
1551                grow([paper[0], paper[1], paper[0], paper[1]]);
1552            }
1553        }
1554    }
1555    b
1556}
1557
1558/// One knot span's control hull on the paper.
1559struct SpanHull {
1560    bounds: [f64; 4],
1561    /// The projected control points' convex hull, counter-clockwise.
1562    hull: Vec<[f64; 2]>,
1563    /// The nearest view depth of its control points.
1564    near: f64,
1565}
1566
1567impl SpanHull {
1568    /// Whether `p` is inside the hull or within `pad` of it.
1569    fn holds(&self, p: [f64; 2], pad: f64) -> bool {
1570        let b = self.bounds;
1571        if p[0] < b[0] - pad || p[0] > b[2] + pad || p[1] < b[1] - pad || p[1] > b[3] + pad {
1572            return false;
1573        }
1574        let n = self.hull.len();
1575        if n >= 3 && (0..n).all(|k| {
1576            let (a, c) = (self.hull[k], self.hull[(k + 1) % n]);
1577            (c[0] - a[0]) * (p[1] - a[1]) - (c[1] - a[1]) * (p[0] - a[0]) >= 0.0
1578        }) {
1579            return true;
1580        }
1581        (0..n.max(1)).any(|k| segment_foot(p, self.hull[k], self.hull[(k + 1) % n]).0 <= pad)
1582    }
1583}
1584
1585/// The convex hull of paper points, counter-clockwise (monotone chain).
1586fn convex_hull(mut points: Vec<[f64; 2]>) -> Vec<[f64; 2]> {
1587    points.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
1588    points.dedup();
1589    if points.len() < 3 {
1590        return points;
1591    }
1592    let turn = |o: [f64; 2], a: [f64; 2], b: [f64; 2]| (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
1593    let mut hull: Vec<[f64; 2]> = Vec::with_capacity(points.len() + 1);
1594    for pass in 0..2 {
1595        let start = hull.len();
1596        let ordered: Box<dyn Iterator<Item = &[f64; 2]>> =
1597            if pass == 0 { Box::new(points.iter()) } else { Box::new(points.iter().rev()) };
1598        for &p in ordered {
1599            while hull.len() >= start + 2 && turn(hull[hull.len() - 2], hull[hull.len() - 1], p) <= 0.0 {
1600                hull.pop();
1601            }
1602            hull.push(p);
1603        }
1604        hull.pop();
1605    }
1606    hull
1607}
1608
1609/// The control hull on the paper of each knot span of `face`'s carrier, for
1610/// the spans whose parameter interval meets the trim's uv box.
1611fn span_hulls(face: &FaceRecord, frame: &ViewFrame, placed: &PlacedView) -> Vec<SpanHull> {
1612    let surface = &face.surface;
1613    let uv_box = trim_box(face).unwrap_or([f64::NEG_INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::INFINITY]);
1614    let spans = |knots: &[f64], degree: usize, count: usize, lo: f64, hi: f64| -> Vec<usize> {
1615        // Span i covers [knots[i], knots[i + 1]] and is shaped by control
1616        // points i − degree ..= i.
1617        (degree..count)
1618            .filter(|&i| knots[i + 1] > knots[i] && knots[i + 1] >= lo && knots[i] <= hi)
1619            .collect()
1620    };
1621    let rows = surface.control_points.len();
1622    let columns = surface.control_points.first().map_or(0, Vec::len);
1623    let su = spans(&surface.knots_u, surface.degree_u, rows, uv_box[0], uv_box[2]);
1624    let sv = spans(&surface.knots_v, surface.degree_v, columns, uv_box[1], uv_box[3]);
1625    let mut out = Vec::with_capacity(su.len() * sv.len());
1626    for &i in &su {
1627        for &j in &sv {
1628            let mut b = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY];
1629            let mut near = f64::INFINITY;
1630            let mut points = Vec::with_capacity((surface.degree_u + 1) * (surface.degree_v + 1));
1631            for row in &surface.control_points[i - surface.degree_u..=i] {
1632                for cp in &row[j - surface.degree_v..=j] {
1633                    let w = if cp.w != 0.0 { cp.w } else { 1.0 };
1634                    let (paper, view) = project(frame, placed, Vec3::new(cp.x / w, cp.y / w, cp.z / w));
1635                    b = [b[0].min(paper[0]), b[1].min(paper[1]), b[2].max(paper[0]), b[3].max(paper[1])];
1636                    near = near.min(view[2]);
1637                    points.push(paper);
1638                }
1639            }
1640            out.push(SpanHull { bounds: b, hull: convex_hull(points), near });
1641        }
1642    }
1643    out
1644}
1645
1646/// A uniform bucket grid over paper boxes.
1647#[derive(Debug, Clone)]
1648struct Grid {
1649    origin: [f64; 2],
1650    cell: f64,
1651    width: usize,
1652    height: usize,
1653    buckets: Vec<Vec<usize>>,
1654}
1655
1656impl Grid {
1657    fn new(extent: [f64; 4], count: usize) -> Grid {
1658        let span = (extent[2] - extent[0]).max(extent[3] - extent[1]).max(1e-9);
1659        let per_side = ((count as f64).sqrt().ceil() as usize).clamp(1, 256);
1660        let cell = span / per_side as f64;
1661        let width = (((extent[2] - extent[0]) / cell).ceil() as usize).clamp(1, 512);
1662        let height = (((extent[3] - extent[1]) / cell).ceil() as usize).clamp(1, 512);
1663        Grid { origin: [extent[0], extent[1]], cell, width, height, buckets: vec![Vec::new(); width * height] }
1664    }
1665
1666    fn range(&self, b: [f64; 4]) -> (usize, usize, usize, usize) {
1667        let clamp = |v: f64, n: usize| (v.floor().max(0.0) as usize).min(n - 1);
1668        (
1669            clamp((b[0] - self.origin[0]) / self.cell, self.width),
1670            clamp((b[1] - self.origin[1]) / self.cell, self.height),
1671            clamp((b[2] - self.origin[0]) / self.cell, self.width),
1672            clamp((b[3] - self.origin[1]) / self.cell, self.height),
1673        )
1674    }
1675
1676    fn insert(&mut self, b: [f64; 4], id: usize) {
1677        let (x0, y0, x1, y1) = self.range(b);
1678        for y in y0..=y1 {
1679            for x in x0..=x1 {
1680                self.buckets[y * self.width + x].push(id);
1681            }
1682        }
1683    }
1684
1685    fn at(&self, p: [f64; 2]) -> &[usize] {
1686        let (x, y, _, _) = self.range([p[0], p[1], p[0], p[1]]);
1687        &self.buckets[y * self.width + x]
1688    }
1689}
1690
1691/// Everything the visibility test reads.
1692struct Scene<'a> {
1693    frame: ViewFrame,
1694    placed: &'a PlacedView,
1695    floors: Floors,
1696    occluders: Vec<Occluder<'a>>,
1697    grid: Grid,
1698    /// Nearest view depth of the model, model units, less a margin: where a
1699    /// view ray toward the eye can stop looking.
1700    near: f64,
1701    clip: &'a Clip<'a>,
1702    /// Pin each split where a curve's end lands on another on that curve's
1703    /// exact image, and let it stand for the chord crossings of a tangential
1704    /// meeting near it ([`hidden_line_drawing`]); a sheet keeps the chords'.
1705    exact_cuts: bool,
1706}
1707
1708impl Scene<'_> {
1709    /// Whether a piece whose exact midpoint is `p` is hidden. `hint` is the
1710    /// face that hid the previous piece of the same curve, tried first — the
1711    /// next piece along is usually behind the same face — and is set to the
1712    /// face that hides this one.
1713    fn hidden(&self, p: Vec3, hint: &mut Option<usize>) -> bool {
1714        let (paper, view) = project(&self.frame, self.placed, p);
1715        let bar = self.floors.bar;
1716        if let Clip::Beyond { cap, .. } = self.clip {
1717            if view[2] > bar && inside_region(cap, paper) {
1718                return true;
1719            }
1720        }
1721        let forward = v3(self.frame.forward);
1722        // A hit in front of the piece by more than the depth floor, and (in a
1723        // section) not in the material the cut removed.
1724        // A face of a solid the section leaves whole hides from the removed side too.
1725        let in_front = |hit: Vec3, whole: bool| {
1726            let depth = dot3(sub3(a3(hit), self.frame.target), self.frame.forward);
1727            depth <= view[2] - bar
1728                && !(matches!(self.clip, Clip::Beyond { .. })
1729                    && !whole
1730                    && depth < -bar
1731                    && self.clip.margin(self.frame.to_view(a3(hit))) < -bar)
1732        };
1733        // The ray toward the eye against a flat carrier through `origin`.
1734        let plane_hit = |origin: Vec3, normal: Vec3| -> Option<Vec3> {
1735            let denominator = normal.dot(forward);
1736            if denominator.abs() <= GRAZING_COS {
1737                return None;
1738            }
1739            let lambda = normal.dot(origin.sub(p)) / denominator;
1740            (lambda < -bar).then(|| p.add(forward.scale(lambda)))
1741        };
1742        // A curved face: the ray toward the eye against its carrier, a hit in
1743        // front of the piece and inside the trim. The ray is the same line for
1744        // every face the piece is asked of, so it is made once.
1745        let reach = view[2] - self.near;
1746        let ray = std::cell::OnceCell::new();
1747        let curved_hides = |face: &FaceRecord, tests: &TrimTests, whole: bool| -> bool {
1748            if reach <= bar {
1749                return false;
1750            }
1751            let Some(ray) = ray.get_or_init(|| make_line(p.sub(forward.scale(reach)), p.sub(forward.scale(bar))).ok()) else {
1752                return false;
1753            };
1754            RAY_QUERIES.with(|count| count.set(count.get() + 1));
1755            let fit = KernelTolerances::default().intersection_fit;
1756            let hits = intersect_curve_surface(ray, &face.surface, fit);
1757            hits.is_ok_and(|hits| {
1758                hits.into_iter()
1759                    .filter(|hit| !hit.tangential)
1760                    .any(|hit| in_front(hit.point, whole) && in_face(face, Some(tests), [hit.u, hit.v], bar))
1761            })
1762        };
1763        // A flat face's one hit, in front of the piece, asked of the trim test.
1764        let flat_hides = |face: &FaceRecord, tests: &TrimTests, hit: Vec3| -> bool {
1765            uv_on(face, hit, bar).is_some_and(|uv| in_face(face, Some(tests), uv, bar))
1766        };
1767        // The piece is hidden when ANY occluder hides it, so the order they are
1768        // asked in is free, and it is chosen for cost. The face that hid the
1769        // previous piece is asked first, whole. Then every other face the paper
1770        // or a closed form decides — a triangle, a flat face whose projected
1771        // trim covers the point — then each curved face's ray, and last a flat
1772        // face the paper does not cover: near a trim of thousands of edges that
1773        // question goes to the kernel and costs more than all the others.
1774        let mut curved: Vec<usize> = Vec::new();
1775        let mut flat: Vec<(usize, Vec3)> = Vec::new();
1776        let first = hint.take();
1777        for index in first.into_iter().chain(self.grid.at(paper).iter().copied().filter(|index| Some(*index) != first)) {
1778            let occluder = &self.occluders[index];
1779            let pad = self.floors.crossing_mm + CHORD_MM;
1780            let holds = |b: &[f64; 4]| {
1781                paper[0] >= b[0] - pad && paper[0] <= b[2] + pad && paper[1] >= b[1] - pad && paper[1] <= b[3] + pad
1782            };
1783            if !holds(&occluder.bounds) {
1784                continue;
1785            }
1786            let hides = match &occluder.cover {
1787                Cover::Triangle { corners, normal } => {
1788                    plane_hit(corners[0], *normal).is_some_and(|hit| in_front(hit, occluder.whole) && in_triangle(corners, *normal, hit, bar))
1789                }
1790                Cover::Face { face, plane, spans, tests, trim } => {
1791                    if !spans.iter().any(|span| span.near <= view[2] - bar && span.holds(paper, pad)) {
1792                        continue;
1793                    }
1794                    let asked_first = Some(index) == first;
1795                    match plane {
1796                        Some((origin, normal)) => {
1797                            let Some(hit) = plane_hit(*origin, *normal).filter(|hit| in_front(*hit, occluder.whole)) else { continue };
1798                            if trim.as_ref().and_then(|trim| trim.covers(paper)) == Some(true) {
1799                                true
1800                            } else if asked_first {
1801                                flat_hides(face, tests, hit)
1802                            } else {
1803                                flat.push((index, hit));
1804                                continue;
1805                            }
1806                        }
1807                        None if asked_first => curved_hides(face, tests, occluder.whole),
1808                        None => {
1809                            curved.push(index);
1810                            continue;
1811                        }
1812                    }
1813                }
1814            };
1815            if hides {
1816                *hint = Some(index);
1817                return true;
1818            }
1819        }
1820        let face_of = |index: usize| match &self.occluders[index].cover {
1821            Cover::Face { face, tests, .. } => Some((*face, tests)),
1822            Cover::Triangle { .. } => None,
1823        };
1824        let hider = curved
1825            .into_iter()
1826            .find(|&index| face_of(index).is_some_and(|(face, tests)| curved_hides(face, tests, self.occluders[index].whole)))
1827            .or_else(|| {
1828                flat.into_iter()
1829                    .find(|&(index, hit)| face_of(index).is_some_and(|(face, tests)| flat_hides(face, tests, hit)))
1830                    .map(|(index, _)| index)
1831            });
1832        if hider.is_some() {
1833            *hint = hider;
1834        }
1835        hider.is_some()
1836    }
1837}
1838
1839/// Whether `hit`, a point in the plane of the triangle `corners` (unit normal
1840/// `normal`), is inside it or within `bar` of it — the band a face's trim is
1841/// asked with ([`in_face`]), so a hit on the edge two triangles share is
1842/// inside both rather than in the crack between them.
1843fn in_triangle(corners: &[Vec3; 3], normal: Vec3, hit: Vec3, bar: f64) -> bool {
1844    (0..3).all(|k| {
1845        let (a, b) = (corners[k], corners[(k + 1) % 3]);
1846        let side = b.sub(a);
1847        let length = side.length();
1848        length <= 0.0 || side.cross(hit.sub(a)).dot(normal) / length >= -bar
1849    })
1850}
1851
1852use crate::geometry3d::sub3;
1853
1854use crate::geometry3d::dot3;
1855
1856/// Even-odd crossing count of a paper point against a set of polylines —
1857/// the cut region of a section.
1858pub fn inside_region(region: &[Vec<[f64; 2]>], p: [f64; 2]) -> bool {
1859    let mut inside = false;
1860    for line in region {
1861        for w in line.windows(2) {
1862            let (a, b) = (w[0], w[1]);
1863            if (a[1] <= p[1]) == (b[1] <= p[1]) {
1864                continue;
1865            }
1866            let x = a[0] + (b[0] - a[0]) * (p[1] - a[1]) / (b[1] - a[1]);
1867            if x > p[0] {
1868                inside = !inside;
1869            }
1870        }
1871    }
1872    inside
1873}
1874
1875// ---------------------------------------------------------------------------
1876// The pass
1877// ---------------------------------------------------------------------------
1878
1879/// The visible model lines of `solids` through `frame` at `placed`'s scale,
1880/// restricted to `clip`.
1881pub fn visible_edges(solids: &[&BrepSolid], frame: &ViewFrame, placed: &PlacedView, clip: &Clip) -> HlrResult {
1882    let trims: Vec<SolidTrims> = solids.iter().map(|solid| SolidTrims::of(solid)).collect();
1883    let trims: Vec<&SolidTrims> = trims.iter().collect();
1884    visible_edges_with(solids, &trims, frame, placed, clip)
1885}
1886
1887/// A solid's hidden-line drawing looking along `direction`: its inked edges
1888/// and outlines in the view plane, split into what the viewer sees and what
1889/// the solid hides.
1890#[derive(Debug, Clone, Default, PartialEq)]
1891pub struct HiddenLineDrawing {
1892    pub visible: Vec<Vec<[f64; 2]>>,
1893    pub hidden: Vec<Vec<[f64; 2]>>,
1894}
1895
1896/// The hidden-line drawing of `solid` looking along `direction`, by the exact
1897/// pass ([`visible_edges`]), each polyline's points on its exact curve and
1898/// each chord within `tolerance` of it. The view plane's axes are `u`,
1899/// `direction × z` made unit (`direction × x` when it runs along z: when
1900/// `|direction × z|² < 1e-12` for the unit direction, as the conformance
1901/// protocol's `view_axes` reads it), and `v = u × direction`; a point `p`
1902/// draws at `(p·u, p·v)`.
1903///
1904/// The pass samples to its paper chord floor, so the drawing is made at the
1905/// paper scale that puts that floor at the lesser of half `tolerance` and a
1906/// ten-millionth of the solid's diagonal: the places a curve passes behind
1907/// another, found on those chords, then lie that close to the exact ones.
1908/// Refuses a direction that is not finite and non-zero, and a tolerance that
1909/// is not positive or is under a billionth of the solid's size.
1910pub fn hidden_line_drawing(solid: &BrepSolid, direction: [f64; 3], tolerance: f64) -> Result<HiddenLineDrawing, brep_kernel::KernelRefusal> {
1911    let refuse = |what: &'static str, message: String| brep_kernel::KernelRefusal::input(brep_kernel::KernelStage::Collect, what, message);
1912    // Scaled by its largest component first, so no square of one overflows
1913    // or underflows.
1914    let largest = direction.iter().fold(0.0f64, |m, x| m.max(x.abs()));
1915    if !(largest.is_finite() && largest > 0.0) || direction.iter().any(|x| !x.is_finite()) {
1916        return Err(refuse("hidden_line_direction", format!("hidden_line_drawing: the direction {direction:?} is not a direction")));
1917    }
1918    let d = Vec3::new(direction[0] / largest, direction[1] / largest, direction[2] / largest);
1919    let d = d.scale(1.0 / d.length());
1920    if !(tolerance.is_finite() && tolerance > 0.0) {
1921        return Err(refuse("hidden_line_tolerance", format!("hidden_line_drawing: the tolerance {tolerance} is not positive")));
1922    }
1923    let across = d.cross(Vec3::new(0.0, 0.0, 1.0));
1924    let u = if across.dot(across) < 1e-12 { d.cross(Vec3::new(1.0, 0.0, 0.0)) } else { across };
1925    let u = u.scale(1.0 / u.length());
1926    let v = u.cross(d);
1927    let [low, high] = brep_kernel::solid_least_box(solid, 1e-7)?;
1928    let diagonal = high.sub(low).length().max(1e-9);
1929    if tolerance < 1e-9 * diagonal {
1930        return Err(refuse(
1931            "hidden_line_tolerance",
1932            format!("hidden_line_drawing: the tolerance {tolerance} is under a billionth of the solid's size ({diagonal}), the pass's own floors"),
1933        ));
1934    }
1935    let scale = CHORD_MM / (0.5 * tolerance).min(1e-7 * diagonal);
1936    let frame = ViewFrame { target: [0.0; 3], right: a3(u), up: a3(v), forward: a3(d) };
1937    let placed = PlacedView {
1938        id: String::new(),
1939        view: String::new(),
1940        position: [0.0, 0.0],
1941        scale,
1942        projection: super::ORTHOGRAPHIC.into(),
1943        flatten_text: false,
1944        three_d: false,
1945        section: None,
1946        detail: None,
1947    };
1948    let trims = SolidTrims::of(solid);
1949    // The pass's floors at a billionth of the solid's diagonal: the drawing
1950    // is asked for its cuts and ends far inside the B-rep's own agreement bar
1951    // (which a primitive's exact trims meet), and the floors in paper units
1952    // scale with it.
1953    struct Restore(Option<f64>);
1954    impl Drop for Restore {
1955        fn drop(&mut self) {
1956            EXACT_BAR.with(|bar| bar.set(self.0));
1957        }
1958    }
1959    let _restore = Restore(EXACT_BAR.with(|bar| bar.replace(Some(1e-9 * diagonal))));
1960    let result = edges_pass(&[solid], &[&trims], &frame, &placed, &Clip::Whole, true);
1961    // The paper runs x right and y down, in millimetres of the scale.
1962    let back = |runs: Vec<Vec<[f64; 2]>>| runs.into_iter().map(|run| run.into_iter().map(|p| [p[0] / scale, -p[1] / scale]).collect()).collect();
1963    Ok(HiddenLineDrawing { visible: back(result.runs), hidden: back(result.hidden) })
1964}
1965
1966/// [`visible_edges`] with each solid's [`SolidTrims`] kept from before.
1967pub fn visible_edges_with(
1968    solids: &[&BrepSolid],
1969    trims: &[&SolidTrims],
1970    frame: &ViewFrame,
1971    placed: &PlacedView,
1972    clip: &Clip,
1973) -> HlrResult {
1974    edges_pass(solids, trims, frame, placed, clip, false)
1975}
1976
1977fn edges_pass(
1978    solids: &[&BrepSolid],
1979    trims: &[&SolidTrims],
1980    frame: &ViewFrame,
1981    placed: &PlacedView,
1982    clip: &Clip,
1983    exact_cuts: bool,
1984) -> HlrResult {
1985    TRIM_QUERIES.with(|count| count.set(0));
1986    RAY_QUERIES.with(|count| count.set(0));
1987    let floors = Floors::of(placed.scale);
1988    let mut candidates: Vec<Candidate> = Vec::new();
1989    // Per face: the paper boxes of its boundary edges and its silhouettes.
1990    let mut face_boxes: HashMap<(usize, usize, usize), (Vec<[f64; 4]>, Vec<[f64; 4]>)> = HashMap::new();
1991    // Per flat face: its trim on the paper, from its boundary edges' samples.
1992    let mut paper_trims: HashMap<(usize, usize, usize), Option<PaperTrim>> = HashMap::new();
1993    for (solid_index, solid) in solids.iter().enumerate() {
1994        let owners = edge_faces(solid);
1995        let edges = edge_candidates(solid_index, solid, frame, placed, &floors);
1996        for candidate in &edges {
1997            let Some((_, edge_id)) = candidate.edge else { continue };
1998            for (shell, face) in owners.get(&edge_id).into_iter().flatten() {
1999                face_boxes.entry((solid_index, *shell, *face)).or_default().0.push(candidate.bounds);
2000            }
2001        }
2002        let paper_of_edge: HashMap<u64, &[[f64; 2]]> =
2003            edges.iter().filter_map(|c| c.edge.map(|(_, id)| (id, c.samples.paper.as_slice()))).collect();
2004        let mut silhouettes: Vec<Candidate> = Vec::new();
2005        for (shell_index, shell) in solid.shells.iter().enumerate() {
2006            for (face_index, face) in shell.faces.iter().enumerate() {
2007                let found = silhouette_candidates(face, &trims[solid_index].faces[shell_index][face_index], frame, placed, &floors);
2008                let entry = face_boxes.entry((solid_index, shell_index, face_index)).or_default();
2009                entry.1.extend(found.iter().map(|c| c.bounds));
2010                silhouettes.extend(found);
2011                if planar(&face.surface) {
2012                    paper_trims.insert((solid_index, shell_index, face_index), PaperTrim::of(solid, face, &paper_of_edge, &floors));
2013                }
2014            }
2015        }
2016        let whole = clip.whole(solid_index);
2017        candidates.extend(edges.into_iter().chain(silhouettes).map(|c| Candidate { whole, ..c }));
2018    }
2019    let mut occluders: Vec<Occluder> = Vec::new();
2020    let mut near = f64::INFINITY;
2021    let mut extent = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY];
2022    for (solid_index, solid) in solids.iter().enumerate() {
2023        for (shell_index, shell) in solid.shells.iter().enumerate() {
2024            for (face_index, face) in shell.faces.iter().enumerate() {
2025                let (boundary, silhouettes) =
2026                    face_boxes.get(&(solid_index, shell_index, face_index)).cloned().unwrap_or_default();
2027                let bounds = face_bounds(face, &boundary, &silhouettes, frame, placed);
2028                if !(bounds[0] <= bounds[2]) {
2029                    continue;
2030                }
2031                let spans = span_hulls(face, frame, placed);
2032                near = spans.iter().fold(near, |near, span| near.min(span.near));
2033                extent = [
2034                    extent[0].min(bounds[0]),
2035                    extent[1].min(bounds[1]),
2036                    extent[2].max(bounds[2]),
2037                    extent[3].max(bounds[3]),
2038                ];
2039                let plane = if planar(&face.surface) {
2040                    let du = face.surface.domain_u().unwrap_or([0.0, 1.0]);
2041                    let dv = face.surface.domain_v().unwrap_or([0.0, 1.0]);
2042                    let (u, v) = (0.5 * (du[0] + du[1]), 0.5 * (dv[0] + dv[1]));
2043                    match (face.surface.evaluate(u, v), face.surface.normal(u, v)) {
2044                        (Ok(origin), Ok(normal)) => Some((origin, normal)),
2045                        _ => None,
2046                    }
2047                } else {
2048                    None
2049                };
2050                let trim = paper_trims.remove(&(solid_index, shell_index, face_index)).flatten();
2051                let tests = &trims[solid_index].faces[shell_index][face_index];
2052                occluders.push(Occluder { cover: Cover::Face { face, plane, spans, tests, trim }, bounds, whole: clip.whole(solid_index) });
2053            }
2054        }
2055    }
2056    decide(candidates, occluders, extent, near, frame, placed, clip, exact_cuts)
2057}
2058
2059/// The shared back half of both passes: split every candidate where the
2060/// projection can change what is in front of it, decide each piece against
2061/// `occluders`, and join the visible pieces into runs.
2062fn decide(
2063    candidates: Vec<Candidate>,
2064    occluders: Vec<Occluder>,
2065    extent: [f64; 4],
2066    near: f64,
2067    frame: &ViewFrame,
2068    placed: &PlacedView,
2069    clip: &Clip,
2070    exact_cuts: bool,
2071) -> HlrResult {
2072    let floors = Floors::of(placed.scale);
2073    let mut result = HlrResult::default();
2074    if occluders.is_empty() {
2075        return result;
2076    }
2077    let mut grid = Grid::new(extent, occluders.len());
2078    for (index, occluder) in occluders.iter().enumerate() {
2079        grid.insert(occluder.bounds, index);
2080    }
2081    let scene = Scene {
2082        frame: *frame,
2083        placed,
2084        floors,
2085        occluders,
2086        grid,
2087        near: near - floors.bar * 10.0 - 1.0,
2088        clip,
2089        exact_cuts,
2090    };
2091
2092    let stations = split_parameters(&candidates, &scene);
2093    result.inked = candidates.iter().filter(|c| c.inked).count();
2094    result.silhouettes = candidates.iter().filter(|c| c.silhouette).count();
2095
2096    // How many INKED edges meet at each vertex — the model's topology, not
2097    // what survived visibility: a silhouette corner of a box is where two
2098    // visible edges and a hidden one meet, and it stays a corner.
2099    let mut valence: HashMap<VertexKey, usize> = HashMap::new();
2100    for candidate in candidates.iter().filter(|c| c.inked) {
2101        if let Some((start, end)) = candidate.ends {
2102            *valence.entry(start).or_default() += 1;
2103            *valence.entry(end).or_default() += 1;
2104        }
2105    }
2106    let (mut runs, mut hidden): (Vec<Run>, Vec<Run>) = (Vec::new(), Vec::new());
2107    for (index, candidate) in candidates.iter().enumerate() {
2108        if !candidate.inked {
2109            continue;
2110        }
2111        let pieces = pieces_of(candidate, &stations[index], &scene);
2112        result.pieces += pieces.len();
2113        runs.extend(runs_of(candidate, &pieces, &scene, true));
2114        hidden.extend(runs_of(candidate, &pieces, &scene, false));
2115    }
2116    result.runs = chain_runs(runs, &valence, floors.crossing_mm);
2117    result.hidden = chain_runs(hidden, &valence, floors.crossing_mm);
2118    result.trim_queries = TRIM_QUERIES.with(|count| count.get());
2119    result.ray_queries = RAY_QUERIES.with(|count| count.get());
2120    result
2121}
2122
2123// ---------------------------------------------------------------------------
2124// The mesh approximation
2125// ---------------------------------------------------------------------------
2126
2127/// One solid's DISPLAY, in world coordinates: what a placement is drawn from
2128/// while its B-rep has not reached the scene.
2129#[derive(Debug, Clone, Default)]
2130pub struct MeshSolid {
2131    pub positions: Vec<[f64; 3]>,
2132    pub triangles: Vec<[u32; 3]>,
2133    /// Per triangle, the display face it tessellates.
2134    pub faces: Vec<u32>,
2135    /// Every drawn display edge — each B-rep edge the tessellator emitted.
2136    pub edges: Vec<MeshEdge>,
2137}
2138
2139/// One display edge of a [`MeshSolid`]: its polyline, and the topology
2140/// vertices it starts and ends on — where runs chain, as the exact pass chains
2141/// through the B-rep's own `start_vertex_id` / `end_vertex_id`. `None` when
2142/// either end is not recoverably one vertex.
2143#[derive(Debug, Clone, Default)]
2144pub struct MeshEdge {
2145    pub points: Vec<[f64; 3]>,
2146    pub ends: Option<(u64, u64)>,
2147}
2148
2149/// The model lines of `meshes` through `frame` at `placed`'s scale, restricted
2150/// to `clip` — the STATED APPROXIMATION a placement draws while the exact
2151/// solids are not in the scene (their topology request is in flight, or the
2152/// registry could not clone a handle). It is the analytic pass's own split,
2153/// visibility and run code on different inputs:
2154///
2155/// - **candidates** are every display edge (each B-rep edge's tessellated
2156///   polyline, so a round's tangent lines are drawn like any other edge)
2157///   except a SEAM — an edge whose every chord is a mesh edge with the same
2158///   face's triangles on both sides — and the display mesh's SILHOUETTES, the
2159///   mesh edges inside one face whose two triangles face opposite ways along
2160///   the view;
2161/// - **occluders** are the display triangles, each hit in closed form.
2162///
2163/// What it gives up is what the display gave up: a curve is its
2164/// tessellation's chords, and an edge between two fragments of one surface is
2165/// drawn, because nothing in a display tells a split from a tangent line.
2166pub fn visible_mesh_lines(meshes: &[MeshSolid], frame: &ViewFrame, placed: &PlacedView, clip: &Clip) -> HlrResult {
2167    TRIM_QUERIES.with(|count| count.set(0));
2168    RAY_QUERIES.with(|count| count.set(0));
2169    let forward = v3(frame.forward);
2170    let mut candidates: Vec<Candidate> = Vec::new();
2171    let mut occluders: Vec<Occluder> = Vec::new();
2172    let mut near = f64::INFINITY;
2173    let mut extent = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY];
2174    for (solid_index, mesh) in meshes.iter().enumerate() {
2175        let points: Vec<Vec3> = mesh.positions.iter().map(|p| v3(*p)).collect();
2176        let welded = WeldedMesh::of(mesh, &points, forward);
2177        for edge in &mesh.edges {
2178            let chain: Vec<Vec3> = edge.points.iter().map(|p| v3(*p)).collect();
2179            if welded.seam(&chain) {
2180                continue;
2181            }
2182            // Runs chain through the topology vertices the edge runs between —
2183            // the model's adjacency, never the distance between two ends.
2184            if let Some(candidate) = polyline_candidate(chain, false, frame, placed) {
2185                candidates.push(Candidate {
2186                    ends: edge.ends.map(|(start, end)| ((solid_index, start), (solid_index, end))),
2187                    whole: clip.whole(solid_index),
2188                    ..candidate
2189                });
2190            }
2191        }
2192        for chain in welded.silhouettes() {
2193            candidates.extend(polyline_candidate(chain, true, frame, placed).map(|c| Candidate { whole: clip.whole(solid_index), ..c }));
2194        }
2195        for triangle in &mesh.triangles {
2196            let Some(corners) = triangle.iter().map(|&i| points.get(i as usize).copied()).collect::<Option<Vec<Vec3>>>() else {
2197                continue;
2198            };
2199            let corners = [corners[0], corners[1], corners[2]];
2200            let Ok(normal) = corners[1].sub(corners[0]).cross(corners[2].sub(corners[0])).normalized() else {
2201                continue;
2202            };
2203            let mut bounds = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY];
2204            for corner in corners {
2205                let (paper, view) = project(frame, placed, corner);
2206                bounds = [bounds[0].min(paper[0]), bounds[1].min(paper[1]), bounds[2].max(paper[0]), bounds[3].max(paper[1])];
2207                near = near.min(view[2]);
2208            }
2209            extent = [extent[0].min(bounds[0]), extent[1].min(bounds[1]), extent[2].max(bounds[2]), extent[3].max(bounds[3])];
2210            occluders.push(Occluder { cover: Cover::Triangle { corners, normal }, bounds, whole: clip.whole(solid_index) });
2211        }
2212    }
2213    decide(candidates, occluders, extent, near, frame, placed, clip, false)
2214}
2215
2216/// An inked candidate on a model polyline (a display edge, a mesh silhouette
2217/// chain), or `None` when it has no length.
2218fn polyline_candidate<'a>(chain: Vec<Vec3>, silhouette: bool, frame: &ViewFrame, placed: &PlacedView) -> Option<Candidate<'a>> {
2219    if chain.len() < 2 {
2220        return None;
2221    }
2222    let last = (chain.len() - 1) as f64;
2223    let intervals = chain.len() - 1;
2224    let carrier = Carrier::Polyline(chain);
2225    let samples = sample(&carrier, 0.0, last, intervals, frame, placed);
2226    if samples.len() < 2 || samples.paper_length() <= 0.0 {
2227        return None;
2228    }
2229    let bounds = bounds_of(&samples.paper);
2230    Some(Candidate { carrier, samples, inked: true, silhouette, edge: None, ends: None, bounds, whole: false })
2231}
2232
2233/// A display mesh welded by its exact coordinates — the tessellator writes a
2234/// point its triangles share as one value, whatever copies the shading split
2235/// it into — with the faces and facings of the triangles on each mesh edge.
2236struct WeldedMesh {
2237    index: HashMap<[u64; 3], u32>,
2238    position: Vec<Vec3>,
2239    /// Per welded mesh edge: `(face, faces the eye)` of each triangle on it.
2240    owners: HashMap<[u32; 2], Vec<(u32, bool)>>,
2241}
2242
2243impl WeldedMesh {
2244    fn of(mesh: &MeshSolid, points: &[Vec3], forward: Vec3) -> WeldedMesh {
2245        let key = |p: Vec3| [p.x.to_bits(), p.y.to_bits(), p.z.to_bits()];
2246        let mut index: HashMap<[u64; 3], u32> = HashMap::new();
2247        let mut position = Vec::new();
2248        let welded: Vec<u32> = points
2249            .iter()
2250            .map(|p| {
2251                *index.entry(key(*p)).or_insert_with(|| {
2252                    position.push(*p);
2253                    (position.len() - 1) as u32
2254                })
2255            })
2256            .collect();
2257        let mut owners: HashMap<[u32; 2], Vec<(u32, bool)>> = HashMap::new();
2258        for (t, triangle) in mesh.triangles.iter().enumerate() {
2259            if triangle.iter().any(|&i| i as usize >= points.len()) {
2260                continue;
2261            }
2262            let [a, b, c] = [points[triangle[0] as usize], points[triangle[1] as usize], points[triangle[2] as usize]];
2263            let facing = b.sub(a).cross(c.sub(a)).dot(forward);
2264            if facing == 0.0 {
2265                continue;
2266            }
2267            let face = mesh.faces.get(t).copied().unwrap_or(u32::MAX);
2268            let w = [welded[triangle[0] as usize], welded[triangle[1] as usize], welded[triangle[2] as usize]];
2269            for k in 0..3 {
2270                let (i, j) = (w[k], w[(k + 1) % 3]);
2271                if i != j {
2272                    owners.entry([i.min(j), i.max(j)]).or_default().push((face, facing < 0.0));
2273                }
2274            }
2275        }
2276        WeldedMesh { index, position, owners }
2277    }
2278
2279    /// The faces on the mesh edge between two model points, when both are
2280    /// mesh vertices joined by one.
2281    fn faces_on(&self, a: Vec3, b: Vec3) -> Option<&[(u32, bool)]> {
2282        let key = |p: Vec3| [p.x.to_bits(), p.y.to_bits(), p.z.to_bits()];
2283        let (i, j) = (*self.index.get(&key(a))?, *self.index.get(&key(b))?);
2284        self.owners.get(&[i.min(j), i.max(j)]).map(Vec::as_slice)
2285    }
2286
2287    /// Whether a display edge is a SEAM: every chord of it a mesh edge with
2288    /// two triangles of ONE face on it — the surface meeting itself, not a
2289    /// line of the model. An edge whose chords are not mesh edges is drawn.
2290    fn seam(&self, chain: &[Vec3]) -> bool {
2291        chain.windows(2).all(|w| {
2292            self.faces_on(w[0], w[1]).is_some_and(|faces| faces.len() == 2 && faces[0].0 == faces[1].0)
2293        })
2294    }
2295
2296    /// The silhouette chains: every mesh edge whose two triangles belong to
2297    /// ONE display face and face opposite ways along the view, chained through
2298    /// vertices exactly two of them meet at. An edge between two faces is a
2299    /// display edge already.
2300    fn silhouettes(&self) -> Vec<Vec<Vec3>> {
2301        let mut segments: Vec<[u32; 2]> = self
2302            .owners
2303            .iter()
2304            .filter(|(_, list)| list.len() == 2 && list[0].0 == list[1].0 && list[0].1 != list[1].1)
2305            .map(|(edge, _)| *edge)
2306            .collect();
2307        // HashMap order is not a drawing's business.
2308        segments.sort_unstable();
2309        let mut incident: HashMap<u32, Vec<usize>> = HashMap::new();
2310        for (i, segment) in segments.iter().enumerate() {
2311            incident.entry(segment[0]).or_default().push(i);
2312            incident.entry(segment[1]).or_default().push(i);
2313        }
2314        let valence = |v: u32| incident.get(&v).map_or(0, Vec::len);
2315        let mut used = vec![false; segments.len()];
2316        let mut starts: Vec<usize> = (0..segments.len()).collect();
2317        // From a chain END first, so an open chain keeps its ends.
2318        starts.sort_by_key(|&i| (valence(segments[i][0]) == 2 && valence(segments[i][1]) == 2, i));
2319        let mut out = Vec::new();
2320        for start in starts {
2321            if used[start] {
2322                continue;
2323            }
2324            used[start] = true;
2325            let segment = segments[start];
2326            let (head, mut tail) = if valence(segment[0]) != 2 { (segment[0], segment[1]) } else { (segment[1], segment[0]) };
2327            let mut path = vec![head, tail];
2328            while valence(tail) == 2 && tail != head {
2329                let Some(next) = incident[&tail].iter().copied().find(|i| !used[*i]) else { break };
2330                used[next] = true;
2331                tail = if segments[next][0] == tail { segments[next][1] } else { segments[next][0] };
2332                path.push(tail);
2333            }
2334            out.push(path.into_iter().map(|v| self.position[v as usize]).collect());
2335        }
2336        out
2337    }
2338}
2339
2340/// Every place a candidate must be split, as sorted curve parameters: where
2341/// another candidate crosses it or ends on it, and where it leaves the clip.
2342fn split_parameters(candidates: &[Candidate], scene: &Scene) -> Vec<Vec<f64>> {
2343    let floors = scene.floors;
2344    let mut splits: Vec<Vec<f64>> = vec![Vec::new(); candidates.len()];
2345    // The segment grid.
2346    let mut extent = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY];
2347    let mut count = 0;
2348    for c in candidates {
2349        extent = [extent[0].min(c.bounds[0]), extent[1].min(c.bounds[1]), extent[2].max(c.bounds[2]), extent[3].max(c.bounds[3])];
2350        count += c.samples.len();
2351    }
2352    if !(extent[0] <= extent[2]) {
2353        return splits;
2354    }
2355    let mut grid = Grid::new(extent, count.max(1));
2356    let mut segments: Vec<(usize, usize)> = Vec::new();
2357    for (ci, c) in candidates.iter().enumerate() {
2358        for si in 0..c.samples.len().saturating_sub(1) {
2359            let (a, b) = (c.samples.paper[si], c.samples.paper[si + 1]);
2360            let pad = floors.crossing_mm + CHORD_MM;
2361            grid.insert(
2362                [a[0].min(b[0]) - pad, a[1].min(b[1]) - pad, a[0].max(b[0]) + pad, a[1].max(b[1]) + pad],
2363                segments.len(),
2364            );
2365            segments.push((ci, si));
2366        }
2367    }
2368    let param_at = |ci: usize, si: usize, t: f64| {
2369        let params = &candidates[ci].samples.params;
2370        params[si] + (params[si + 1] - params[si]) * t
2371    };
2372    let tolerance = floors.crossing_mm + CHORD_MM;
2373    let mut seen: std::collections::HashSet<(usize, usize)> = std::collections::HashSet::new();
2374    // In exact mode: each candidate's chord crossings (parameter, paper
2375    // point, how far off they may be, the other curve) and the paper points
2376    // ends land at (with the curve that ends there).
2377    let mut crossings: Vec<Vec<(f64, [f64; 2], f64, usize)>> = vec![Vec::new(); candidates.len()];
2378    let mut landings: Vec<Vec<([f64; 2], usize)>> = vec![Vec::new(); candidates.len()];
2379    for bucket in &grid.buckets {
2380        for (k, &first) in bucket.iter().enumerate() {
2381            for &second in &bucket[k + 1..] {
2382                let (lo, hi) = (first.min(second), first.max(second));
2383                let ((ca, sa), (cb, sb)) = (segments[lo], segments[hi]);
2384                if ca == cb && sa.abs_diff(sb) <= 1 {
2385                    continue;
2386                }
2387                if !candidates[ca].inked && !candidates[cb].inked {
2388                    continue;
2389                }
2390                if !seen.insert((lo, hi)) {
2391                    continue;
2392                }
2393                let pa = &candidates[ca].samples.paper;
2394                let pb = &candidates[cb].samples.paper;
2395                let vec2 = |p: [f64; 2]| Vec2 { x: p[0], y: p[1] };
2396                if let Some([ta, tb]) = segment_intersection(vec2(pa[sa]), vec2(pa[sa + 1]), vec2(pb[sb]), vec2(pb[sb + 1]), tolerance) {
2397                    if scene.exact_cuts {
2398                        // How far along the chords the crossing may stand
2399                        // from the curves' own: their sag over the sine of
2400                        // the angle they cross at.
2401                        let (da, db) = ([pa[sa + 1][0] - pa[sa][0], pa[sa + 1][1] - pa[sa][1]], [pb[sb + 1][0] - pb[sb][0], pb[sb + 1][1] - pb[sb][1]]);
2402                        let sine = (da[0] * db[1] - da[1] * db[0]).abs() / (da[0].hypot(da[1]) * db[0].hypot(db[1])).max(f64::MIN_POSITIVE);
2403                        let reach = 4.0 * tolerance / sine.max(1e-12);
2404                        let at = [pa[sa][0] + da[0] * ta, pa[sa][1] + da[1] * ta];
2405                        crossings[ca].push((param_at(ca, sa, ta), at, reach, cb));
2406                        crossings[cb].push((param_at(cb, sb, tb), at, reach, ca));
2407                    } else {
2408                        splits[ca].push(param_at(ca, sa, ta));
2409                        splits[cb].push(param_at(cb, sb, tb));
2410                    }
2411                }
2412                // An END of one on the other, including along a collinear
2413                // overlap the crossing test does not report.
2414                for (from, from_seg, onto, onto_seg) in [(ca, sa, cb, sb), (cb, sb, ca, sa)] {
2415                    let fp = &candidates[from].samples.paper;
2416                    let op = &candidates[onto].samples.paper;
2417                    let last = fp.len() - 1;
2418                    for (end_seg, end) in [(0usize, fp[0]), (last - 1, fp[last])] {
2419                        if from_seg != end_seg {
2420                            continue;
2421                        }
2422                        let (distance, t) = segment_foot(end, op[onto_seg], op[onto_seg + 1]);
2423                        if distance <= tolerance {
2424                            if scene.exact_cuts {
2425                                let params = &candidates[onto].samples.params;
2426                                let s = landing(&candidates[onto].carrier, end, (params[onto_seg], params[onto_seg + 1]), (params[0], *params.last().unwrap()), scene);
2427                                splits[onto].push(s);
2428                                landings[onto].push((end, from));
2429                            } else {
2430                                splits[onto].push(param_at(onto, onto_seg, t));
2431                            }
2432                        }
2433                    }
2434                }
2435            }
2436        }
2437    }
2438    // A crossing with a curve whose end lands on this one, as near that
2439    // landing as the crossing may be off, is that meeting read on the chords:
2440    // the landing stands for it.
2441    for (ci, list) in crossings.into_iter().enumerate() {
2442        for (s, at, reach, partner) in list {
2443            if !landings[ci].iter().any(|&(end, from)| from == partner && paper_distance(end, at) <= reach) {
2444                splits[ci].push(s);
2445            }
2446        }
2447    }
2448    // The clip's own boundary (a solid the section leaves whole crosses it uncut).
2449    for (ci, c) in candidates.iter().enumerate() {
2450        if !c.inked || c.whole {
2451            continue;
2452        }
2453        let side = |view: [f64; 3]| -> f64 {
2454            match scene.clip {
2455                Clip::Whole => 1.0,
2456                Clip::Beyond { .. } => scene.clip.margin(view),
2457                Clip::Circle { radius } => radius - (view[0] * view[0] + view[1] * view[1]).sqrt(),
2458            }
2459        };
2460        if matches!(scene.clip, Clip::Whole) {
2461            continue;
2462        }
2463        for i in 1..c.samples.len() {
2464            let (g0, g1) = (side(c.samples.view[i - 1]), side(c.samples.view[i]));
2465            if (g0 < 0.0) == (g1 < 0.0) {
2466                continue;
2467            }
2468            let (mut lo, mut hi) = (c.samples.params[i - 1], c.samples.params[i]);
2469            for _ in 0..BISECTION_STEPS {
2470                let mid = 0.5 * (lo + hi);
2471                let Some(p) = c.carrier.at(mid) else { break };
2472                let g = side(scene.frame.to_view(a3(p)));
2473                if (g < 0.0) == (g0 < 0.0) {
2474                    lo = mid;
2475                } else {
2476                    hi = mid;
2477                }
2478            }
2479            splits[ci].push(0.5 * (lo + hi));
2480        }
2481    }
2482    for list in &mut splits {
2483        list.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
2484    }
2485    splits
2486}
2487
2488/// The parameter in `[lo, hi]` (widened by its own length each way, inside
2489/// the sampled range `[first, last]`) where the curve's image passes nearest
2490/// the paper point `end`, by golden-section search.
2491fn landing(carrier: &Carrier, end: [f64; 2], (lo, hi): (f64, f64), (first, last): (f64, f64), scene: &Scene) -> f64 {
2492    let width = hi - lo;
2493    let (mut lo, mut hi) = ((lo - width).max(first.min(last)), (hi + width).min(first.max(last)));
2494    let gap = |s: f64| carrier.at(s).map_or(f64::INFINITY, |p| paper_distance(project(&scene.frame, scene.placed, p).0, end));
2495    let ratio = 0.5 * (5f64.sqrt() - 1.0);
2496    let (mut x, mut y) = (hi - ratio * (hi - lo), lo + ratio * (hi - lo));
2497    let (mut fx, mut fy) = (gap(x), gap(y));
2498    for _ in 0..80 {
2499        if fx <= fy {
2500            hi = y;
2501            (y, fy) = (x, fx);
2502            x = hi - ratio * (hi - lo);
2503            fx = gap(x);
2504        } else {
2505            lo = x;
2506            (x, fx) = (y, fy);
2507            y = lo + ratio * (hi - lo);
2508            fy = gap(y);
2509        }
2510    }
2511    0.5 * (lo + hi)
2512}
2513
2514/// One decided piece of a candidate: its parameter span and its paper ends.
2515struct Piece {
2516    lo: f64,
2517    hi: f64,
2518    visible: bool,
2519    /// Inside the clip: a piece the clip removes is neither seen nor hidden.
2520    kept: bool,
2521}
2522
2523/// Cut a candidate at its split parameters (merging any closer together on
2524/// the paper than the crossing floor) and decide each piece.
2525fn pieces_of(candidate: &Candidate, splits: &[f64], scene: &Scene) -> Vec<Piece> {
2526    let samples = &candidate.samples;
2527    let (s0, s1) = (samples.params[0], *samples.params.last().unwrap());
2528    let mut cuts = vec![s0];
2529    let paper_at = |s: f64| candidate.carrier.at(s).map(|p| project(&scene.frame, scene.placed, p).0);
2530    let mut last_paper = samples.paper[0];
2531    for &s in splits {
2532        if s <= s0 || s >= s1 {
2533            continue;
2534        }
2535        let Some(p) = paper_at(s) else { continue };
2536        if paper_distance(p, last_paper) < scene.floors.crossing_mm {
2537            continue;
2538        }
2539        cuts.push(s);
2540        last_paper = p;
2541    }
2542    let end_paper = *samples.paper.last().unwrap();
2543    if cuts.len() > 1 && paper_distance(last_paper, end_paper) < scene.floors.crossing_mm {
2544        cuts.pop();
2545    }
2546    cuts.push(s1);
2547    let mut pieces = Vec::with_capacity(cuts.len() - 1);
2548    let mut hint = None;
2549    for w in cuts.windows(2) {
2550        let (lo, hi) = (w[0], w[1]);
2551        let Some(mid) = candidate.carrier.at(0.5 * (lo + hi)) else { continue };
2552        let view = scene.frame.to_view(a3(mid));
2553        let kept = match scene.clip {
2554            Clip::Whole => true,
2555            Clip::Beyond { .. } => candidate.whole || scene.clip.margin(view) >= -scene.floors.bar,
2556            Clip::Circle { radius } => (view[0] * view[0] + view[1] * view[1]).sqrt() <= radius + scene.floors.bar,
2557        };
2558        let visible = kept && !scene.hidden(mid, &mut hint);
2559        pieces.push(Piece { lo, hi, visible, kept });
2560    }
2561    pieces
2562}
2563
2564/// A visible run on the paper, with the B-rep vertices it touches (for
2565/// chaining through a vertex two inked edges share).
2566struct Run {
2567    points: Vec<[f64; 2]>,
2568    start: Option<VertexKey>,
2569    end: Option<VertexKey>,
2570}
2571
2572/// The visible runs of one candidate (or, `seen` false, its hidden runs):
2573/// maximal chains of consecutive pieces of that kind, wrapped round the seam
2574/// of a closed curve. A run keeps its own ends and the SAMPLES strictly
2575/// between them, so a straight edge is two points.
2576fn runs_of(candidate: &Candidate, pieces: &[Piece], scene: &Scene, seen: bool) -> Vec<Run> {
2577    let samples = &candidate.samples;
2578    let closed = samples.len() > 2
2579        && paper_distance(samples.paper[0], *samples.paper.last().unwrap()) < scene.floors.crossing_mm
2580        && samples.points[0].sub(*samples.points.last().unwrap()).length() <= scene.floors.bar;
2581    let mut spans: Vec<(f64, f64, bool, bool)> = Vec::new(); // (lo, hi, touches start, touches end)
2582    let mut i = 0;
2583    while i < pieces.len() {
2584        let of_kind = |piece: &Piece| piece.kept && piece.visible == seen;
2585        if !of_kind(&pieces[i]) {
2586            i += 1;
2587            continue;
2588        }
2589        let first = i;
2590        while i < pieces.len() && of_kind(&pieces[i]) {
2591            i += 1;
2592        }
2593        spans.push((pieces[first].lo, pieces[i - 1].hi, first == 0, i == pieces.len()));
2594    }
2595    let (s0, s1) = (samples.params[0], *samples.params.last().unwrap());
2596    // A closed curve visible across its seam is one run, not two.
2597    let mut wrapped: Option<(f64, f64)> = None;
2598    if closed && spans.len() >= 2 && spans[0].2 && spans.last().unwrap().3 {
2599        let head = spans.remove(0);
2600        let tail = spans.pop().unwrap();
2601        wrapped = Some((tail.0, head.1));
2602    }
2603    let point_at = |s: f64| candidate.carrier.at(s).map(|p| project(&scene.frame, scene.placed, p).0);
2604    let mut out = Vec::new();
2605    let mut emit = |pieces: &[(f64, f64)], start: Option<VertexKey>, end: Option<VertexKey>| {
2606        let mut points = Vec::new();
2607        for (k, &(lo, hi)) in pieces.iter().enumerate() {
2608            if k == 0 {
2609                if let Some(p) = point_at(lo) {
2610                    points.push(p);
2611                }
2612            }
2613            for (index, s) in samples.params.iter().enumerate() {
2614                if *s > lo && *s < hi {
2615                    points.push(samples.paper[index]);
2616                }
2617            }
2618            if let Some(p) = point_at(hi) {
2619                points.push(p);
2620            }
2621        }
2622        if points.len() >= 2 {
2623            out.push(Run { points, start, end });
2624        }
2625    };
2626    if let Some((lo, hi)) = wrapped {
2627        emit(&[(lo, s1), (s0, hi)], None, None);
2628    }
2629    for (lo, hi, at_start, at_end) in spans {
2630        let ends = candidate.ends;
2631        let whole_closed = closed && at_start && at_end;
2632        emit(
2633            &[(lo, hi)],
2634            if at_start && !whole_closed { ends.map(|e| e.0) } else { None },
2635            if at_end && !whole_closed { ends.map(|e| e.1) } else { None },
2636        );
2637    }
2638    out
2639}
2640
2641/// Chain runs through every vertex exactly two INKED edges meet at — the
2642/// mesh pass's rule read on the B-rep's own vertices — when both runs reach it.
2643fn chain_runs(runs: Vec<Run>, valence: &HashMap<VertexKey, usize>, floor: f64) -> Vec<Vec<[f64; 2]>> {
2644    let mut at_vertex: HashMap<VertexKey, Vec<(usize, bool)>> = HashMap::new();
2645    for (index, run) in runs.iter().enumerate() {
2646        if let Some(v) = run.start {
2647            at_vertex.entry(v).or_default().push((index, true));
2648        }
2649        if let Some(v) = run.end {
2650            at_vertex.entry(v).or_default().push((index, false));
2651        }
2652    }
2653    // Neighbour through each end: (run, whether we enter at its start).
2654    let mut next: Vec<[Option<(usize, bool)>; 2]> = vec![[None, None]; runs.len()];
2655    for (vertex, list) in &at_vertex {
2656        if valence.get(vertex) != Some(&2) || list.len() != 2 || list[0].0 == list[1].0 {
2657            continue;
2658        }
2659        let ((a, a_start), (b, b_start)) = (list[0], list[1]);
2660        let (pa, pb) = (
2661            if a_start { runs[a].points[0] } else { *runs[a].points.last().unwrap() },
2662            if b_start { runs[b].points[0] } else { *runs[b].points.last().unwrap() },
2663        );
2664        if paper_distance(pa, pb) > floor + CHORD_MM {
2665            continue;
2666        }
2667        next[a][if a_start { 0 } else { 1 }] = Some((b, b_start));
2668        next[b][if b_start { 0 } else { 1 }] = Some((a, a_start));
2669    }
2670    let mut used = vec![false; runs.len()];
2671    let mut out = Vec::new();
2672    // Open chains first (from a run with a free end), then closed rings.
2673    let mut order: Vec<usize> = (0..runs.len()).collect();
2674    order.sort_by_key(|&i| (next[i][0].is_some() && next[i][1].is_some(), i));
2675    for start in order {
2676        if used[start] {
2677            continue;
2678        }
2679        used[start] = true;
2680        // Walk forward from the start run's END; a free START end is where
2681        // the chain begins.
2682        let mut points = runs[start].points.clone();
2683        if next[start][0].is_some() && next[start][1].is_none() {
2684            points.reverse();
2685            let mut cursor = next[start][0];
2686            extend_chain(&runs, &next, &mut used, &mut points, &mut cursor);
2687        } else {
2688            let mut cursor = next[start][1];
2689            extend_chain(&runs, &next, &mut used, &mut points, &mut cursor);
2690        }
2691        out.push(points);
2692    }
2693    out
2694}
2695
2696fn extend_chain(
2697    runs: &[Run],
2698    next: &[[Option<(usize, bool)>; 2]],
2699    used: &mut [bool],
2700    points: &mut Vec<[f64; 2]>,
2701    cursor: &mut Option<(usize, bool)>,
2702) {
2703    while let Some((run, enter_at_start)) = *cursor {
2704        if used[run] {
2705            break;
2706        }
2707        used[run] = true;
2708        let mut piece = runs[run].points.clone();
2709        if !enter_at_start {
2710            piece.reverse();
2711        }
2712        points.extend(piece.into_iter().skip(1));
2713        *cursor = next[run][if enter_at_start { 1 } else { 0 }];
2714    }
2715}
2716
2717// ---------------------------------------------------------------------------
2718// The exact section
2719// ---------------------------------------------------------------------------
2720
2721/// One cut curve of a section on the paper, ORIENTED so the cut region lies
2722/// to its left as the section camera sees it (the region's outward normal is
2723/// toward the eye): a whole set of them sums to the region's signed area.
2724pub type CutCurve = Vec<[f64; 2]>;
2725
2726/// The exact section of `solids` by the view's target plane (the camera
2727/// looks along its normal): per face, the plane's intersection with the
2728/// carrier — the kernel's closed forms for a plane against a cylinder, cone,
2729/// sphere or torus (`intersect_analytic_pair`), marched for a fitted surface
2730/// (`intersect_surfaces`), and for a plane against a plane the line their two
2731/// equations share, which the kernel's analytic lane leaves to its iso path on
2732/// purpose — trimmed to the face where its boundary edges cross the plane.
2733pub fn section_curves(solids: &[&BrepSolid], frame: &ViewFrame, placed: &PlacedView) -> Vec<CutCurve> {
2734    let trims: Vec<SolidTrims> = solids.iter().map(|solid| SolidTrims::of(solid)).collect();
2735    let trims: Vec<&SolidTrims> = trims.iter().collect();
2736    section_curves_with(solids, &trims, frame, placed)
2737}
2738
2739/// [`section_curves`] with each solid's [`SolidTrims`] kept from before.
2740pub fn section_curves_with(solids: &[&BrepSolid], trims: &[&SolidTrims], frame: &ViewFrame, placed: &PlacedView) -> Vec<CutCurve> {
2741    let floors = Floors::of(placed.scale);
2742    let tolerances = KernelTolerances::default();
2743    let normal = v3(frame.forward);
2744    let target = v3(frame.target);
2745    let mut out = Vec::new();
2746    for (solid, trims) in solids.iter().zip(trims) {
2747        let mut reach: f64 = 1.0;
2748        for shell in &solid.shells {
2749            for face in &shell.faces {
2750                for row in &face.surface.control_points {
2751                    for cp in row {
2752                        let w = if cp.w != 0.0 { cp.w } else { 1.0 };
2753                        reach = reach.max(Vec3::new(cp.x / w, cp.y / w, cp.z / w).sub(target).length());
2754                    }
2755                }
2756            }
2757        }
2758        let reach = reach * 1.5;
2759        let (right, up) = (v3(frame.right), v3(frame.up));
2760        let Ok(cutting) = make_plane(target.sub(right.scale(reach)).sub(up.scale(reach)), right, up, 2.0 * reach, 2.0 * reach)
2761        else {
2762            continue;
2763        };
2764        for (shell, shell_trims) in solid.shells.iter().zip(&trims.faces) {
2765            for (face, tests) in shell.faces.iter().zip(shell_trims) {
2766                for carrier in section_carriers(&cutting, face, normal, target, reach, &tolerances) {
2767                    for curve in trim_section(solid, face, Some(tests), carrier, &cutting, frame, placed, &floors) {
2768                        out.push(curve);
2769                    }
2770                }
2771            }
2772        }
2773    }
2774    out
2775}
2776
2777/// The untrimmed intersection of the cutting plane with one face's carrier.
2778fn section_carriers<'a>(
2779    cutting: &NurbsSurface,
2780    face: &'a FaceRecord,
2781    normal: Vec3,
2782    target: Vec3,
2783    reach: f64,
2784    tolerances: &KernelTolerances,
2785) -> Vec<(Carrier<'a>, f64, f64)> {
2786    let surface = &face.surface;
2787    if planar(surface) {
2788        let du = surface.domain_u().unwrap_or([0.0, 1.0]);
2789        let dv = surface.domain_v().unwrap_or([0.0, 1.0]);
2790        let (u, v) = (0.5 * (du[0] + du[1]), 0.5 * (dv[0] + dv[1]));
2791        let (Ok(origin), Ok(face_normal)) = (surface.evaluate(u, v), surface.normal(u, v)) else { return Vec::new() };
2792        let direction = normal.cross(face_normal);
2793        let Ok(direction) = direction.normalized() else { return Vec::new() }; // parallel or coplanar
2794        // The point of both planes nearest the target: solve n·x = n·t,
2795        // m·x = m·o in the span of the two normals.
2796        let (h1, h2) = (normal.dot(target), face_normal.dot(origin));
2797        let c = normal.dot(face_normal);
2798        let det = 1.0 - c * c;
2799        if det.abs() < 1e-18 {
2800            return Vec::new();
2801        }
2802        let a = (h1 - h2 * c) / det;
2803        let b = (h2 - h1 * c) / det;
2804        let point = normal.scale(a).add(face_normal.scale(b));
2805        let point = point.add(direction.scale(target.sub(point).dot(direction)));
2806        return vec![(
2807            Carrier::Line { a: point.sub(direction.scale(reach)), b: point.add(direction.scale(reach)) },
2808            0.0,
2809            1.0,
2810        )];
2811    }
2812    if let Some(curves) = intersect_analytic_pair(cutting, surface, tolerances.intersection_fit) {
2813        return curves
2814            .into_iter()
2815            .filter_map(|curve| {
2816                let [t0, t1] = curve.domain().ok()?;
2817                Some((Carrier::Curve(curve), t0, t1))
2818            })
2819            .collect();
2820    }
2821    let options = SurfaceIntersectionOptions { tolerance: tolerances.intersection_fit, ..Default::default() };
2822    match intersect_surfaces(cutting, surface, &options) {
2823        Ok(curves) => curves
2824            .into_iter()
2825            .filter(|curve| curve.points.len() >= 2)
2826            .map(|curve| {
2827                let mut points = curve.points;
2828                if curve.closed && points.first().map(|p| p.sub(*points.last().unwrap()).length()) > Some(0.0) {
2829                    points.push(points[0]);
2830                }
2831                let last = (points.len() - 1) as f64;
2832                (Carrier::Polyline(points), 0.0, last)
2833            })
2834            .collect(),
2835        Err(_) => Vec::new(),
2836    }
2837}
2838
2839/// The spans of one cut carrier that lie on `face`: split where the face's
2840/// boundary edges cross the cutting plane (`intersect_curve_surface`), each
2841/// span kept when its midpoint classifies inside the trim, then sampled
2842/// against the chord and oriented.
2843fn trim_section(
2844    solid: &BrepSolid,
2845    face: &FaceRecord,
2846    tests: Option<&TrimTests>,
2847    carrier: (Carrier, f64, f64),
2848    cutting: &NurbsSurface,
2849    frame: &ViewFrame,
2850    placed: &PlacedView,
2851    floors: &Floors,
2852) -> Vec<CutCurve> {
2853    let (carrier, s0, s1) = carrier;
2854    let tolerances = KernelTolerances::default();
2855    let initial = match &carrier {
2856        Carrier::Polyline(points) => points.len().saturating_sub(1).max(1),
2857        Carrier::Curve(curve) => curve_initial(curve),
2858        _ => 1,
2859    };
2860    let base = sample(&carrier, s0, s1, initial, frame, placed);
2861    if base.len() < 2 {
2862        return Vec::new();
2863    }
2864    // Where the face's boundary crosses the plane, as carrier parameters.
2865    let mut cuts: Vec<f64> = vec![s0, s1];
2866    for lp in &face.loops {
2867        for coedge in &lp.coedges {
2868            let Some(edge) = solid.edges.iter().find(|e| e.id == coedge.edge_id) else { continue };
2869            let Ok(hits) = intersect_curve_surface(&edge.curve, cutting, tolerances.intersection_fit) else { continue };
2870            for hit in hits {
2871                if hit.t < edge.t0.min(edge.t1) - 1e-12 || hit.t > edge.t0.max(edge.t1) + 1e-12 {
2872                    continue;
2873                }
2874                if let Some(s) = nearest_parameter(&carrier, &base, hit.point) {
2875                    cuts.push(s);
2876                }
2877            }
2878        }
2879    }
2880    cuts.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
2881    let mut out = Vec::new();
2882    for w in cuts.windows(2) {
2883        let (lo, hi) = (w[0], w[1]);
2884        if hi - lo <= 0.0 {
2885            continue;
2886        }
2887        let Some(mid) = carrier.at(0.5 * (lo + hi)) else { continue };
2888        let Some(uv) = uv_on(face, mid, floors.bar) else { continue };
2889        if !in_face(face, tests, uv, floors.bar) {
2890            continue;
2891        }
2892        let piece = sample(&carrier, lo, hi, initial_between(&base, lo, hi), frame, placed);
2893        if piece.len() < 2 || piece.paper_length() < floors.crossing_mm {
2894            continue;
2895        }
2896        let mut paper = piece.paper;
2897        // Orient: the tangent along m × n_F, m the cap's outward normal
2898        // (toward the eye) and n_F the face's outward normal — the region is
2899        // then on the left as the eye sees it.
2900        let step = (hi - lo) * 1e-4;
2901        let tangent = match (carrier.at(0.5 * (lo + hi) + step), carrier.at(0.5 * (lo + hi) - step)) {
2902            (Some(a), Some(b)) => a.sub(b),
2903            _ => piece.points[piece.points.len() - 1].sub(piece.points[0]),
2904        };
2905        if let Some(n_face) = outward_normal(face, mid) {
2906            let eye = v3(frame.forward).scale(-1.0);
2907            if tangent.dot(eye.cross(n_face)) < 0.0 {
2908                paper.reverse();
2909            }
2910        }
2911        out.push(paper);
2912    }
2913    out
2914}
2915
2916/// The carrier parameter nearest a model point.
2917fn nearest_parameter(carrier: &Carrier, samples: &Samples, p: Vec3) -> Option<f64> {
2918    if let Carrier::Edge(curve) = carrier {
2919        return project_point_to_curve(curve, p).ok().map(|foot| foot.u);
2920    }
2921    // Nearest chord, then its foot's parameter.
2922    let mut best: Option<(f64, f64)> = None;
2923    for i in 0..samples.len().saturating_sub(1) {
2924        let (a, b) = (samples.points[i], samples.points[i + 1]);
2925        let d = b.sub(a);
2926        let length2 = d.dot(d);
2927        let t = if length2 > 0.0 { (p.sub(a).dot(d) / length2).clamp(0.0, 1.0) } else { 0.0 };
2928        let distance = p.sub(a.add(d.scale(t))).length();
2929        let s = samples.params[i] + (samples.params[i + 1] - samples.params[i]) * t;
2930        if best.is_none_or(|(bd, _)| distance < bd) {
2931            best = Some((distance, s));
2932        }
2933    }
2934    best.map(|(_, s)| s)
2935}
2936