Skip to main content

brep_render/sheets/
project.rs

1//! Projecting a placed PMI view onto its sheet: the model as edge LINES with
2//! hidden lines removed, plus EVERY annotation of the saved view, all in
3//! paper millimetres.
4//!
5//! # Annotations
6//!
7//! An annotation is laid out through the same [`pmi_present`] the 3D overlay
8//! and the STEP presentation use — in its own annotation plane when it has
9//! one — and the result is projected through the view camera exactly as the
10//! overlay draws it. There is no plane filter: a plane oblique to the view
11//! draws foreshortened, a plane EDGE-ON to it draws as a line and the row
12//! says so ([`AnnotationDrawing::note`]). Circles and arcs in the plane are
13//! polylines before they are projected, so they come out as the ellipses any
14//! parallel projection gives. Annotations are NOT hidden-line tested: they
15//! are drawn on top of the model, which is what the viewport overlay does and
16//! what a drawing wants — a dimension behind the part is still a dimension.
17//!
18//! # The model lines
19//!
20//! Drawn by the ANALYTIC hidden-line pass, [`super::hlr`]: candidate curves
21//! from the B-rep (edges and the silhouettes of curved faces), split where
22//! they cross in the projection plane, each piece shown or hidden by an exact
23//! depth comparison against the faces in front of it. A section cuts the
24//! B-rep with its plane exactly ([`super::hlr::section_curves`]) and a detail
25//! decides visibility inside its circle's cylinder at its own scale. The
26//! result is cached per placement by what it depends on — the geometry, the
27//! camera, the scale and the clip — and never by where the placement sits on
28//! the paper, so a drag does not re-run it.
29//!
30//! # Before the B-rep arrives
31//!
32//! The exact pass needs every drawn solid's B-rep, which the scene PULLS from
33//! the runner when a sheet first shows it. Until it lands — and for a handle
34//! the registry could not clone — the placement is drawn by the same pass on
35//! the DISPLAY instead ([`super::hlr::visible_mesh_lines`]): the display edges
36//! and the mesh's silhouettes, split and decided against the display
37//! triangles. That is a stated approximation, never a silent one:
38//! [`ViewDrawing::hidden_line`] says `mesh`, and the PDF and SVG writers carry
39//! it into the files they write.
40
41use crate::scene::RenderScene;
42use brep_kernel::{
43    pmi_present, PmiAnnotationReport, PmiCamera, PmiLayoutStyle, PmiProjection, PmiStatus,
44    PmiView, PmiViewReport,
45};
46
47use super::{PlacedView, ORTHOGRAPHIC};
48
49/// Dihedral threshold for a drawn edge, degrees — `EdgesGeometry(geo, 30)`,
50/// the value `BREP_mcp_core::render_mesh` matches three.js on. The analytic
51/// pass reads the same bar off the exact face normals along a B-rep edge.
52pub const EDGE_ANGLE_DEG: f64 = 30.0;
53
54/// Points per millimetre: a PMI view's text size is in POINTS, and a sheet is
55/// in millimetres.
56pub const MM_PER_POINT: f64 = 25.4 / 72.0;
57
58/// The arrowhead length as a multiple of the text cap height — the viewport
59/// overlay's own proportion (12 px arrow against an 11 px cap at 12 pt), so an
60/// annotation on paper has the arrowheads it has on screen.
61pub(super) const ARROW_PER_TEXT: f64 = 12.0 / 11.0;
62
63/// The PMI stroke font's monospace advance as a multiple of the cap height
64/// (the kernel's `font::ADVANCE`, mirrored because the kernel does not publish
65/// its font metrics). The sheet renders the text with a real proportional
66/// face, which is narrower, so a box measured with this is slightly generous —
67/// which is the right way round for a clearance.
68pub(super) const TEXT_ADVANCE: f64 = 0.75;
69
70/// Clear space kept around a text run before a line is broken for it, as a
71/// multiple of the cap height.
72const TEXT_PAD: f64 = 0.3;
73
74/// A section's HATCH spacing, PAPER millimetres. A hatch is a drawing
75/// convention rather than a property of the model, so it is a paper distance
76/// at every sheet scale — a 2:1 section is hatched at the same pitch as a 1:1
77/// one, which is what makes two sections of a drawing read as one drawing.
78pub const HATCH_SPACING_MM: f64 = 2.5;
79
80/// The most hatch lines one cut face may draw. A section of a part a metre
81/// across at 1:1 would otherwise ask for four hundred thousand of them; past
82/// this the hatch is THINNED (the spacing doubles until it fits) rather than
83/// refused, because a thinned hatch still says "this is cut material" and an
84/// absent one says nothing.
85const MAX_HATCH_LINES: usize = 2000;
86
87/// When an annotation plane is EDGE-ON to the view: the cosine of the angle
88/// between the plane's normal and the viewing direction. Below this the
89/// plane projects to a line, and so does everything laid out in it. The bar
90/// is the kernel's own (`annotation_plane` accepts a plane against its
91/// geometry at `sin < 1e-3`), read on the other axis.
92pub const EDGE_ON_COS: f64 = 1e-3;
93
94// ---------------------------------------------------------------------------
95// Output
96// ---------------------------------------------------------------------------
97
98/// A whole sheet, projected — the sheet viewport draws this and the SVG and PDF
99/// writers serialise it.
100#[derive(Debug, Clone, PartialEq, serde::Serialize)]
101pub struct SheetDrawing {
102    pub id: String,
103    pub name: String,
104    #[serde(rename = "widthMm")]
105    pub width_mm: f64,
106    #[serde(rename = "heightMm")]
107    pub height_mm: f64,
108    pub views: Vec<ViewDrawing>,
109    /// The sheet's OWN dimensions — authored on the paper, anchored to the
110    /// placements' projected geometry rather than to a saved PMI view. They
111    /// live beside the views rather than inside one because a dimension is the
112    /// SHEET's (see [`super::dimension`]).
113    pub dimensions: Vec<super::dimension::DimensionDrawing>,
114    /// The sheet's ORDINATE SETS, laid out ([`super::ordinate`]). Beside the
115    /// dimensions for the same reason they are beside them in the block: a set
116    /// is its own object, not a dimension of a fifth kind.
117    pub ordinates: Vec<super::ordinate::OrdinateDrawing>,
118    /// The paper's own furniture — the border and the title block — in the same
119    /// millimetres and the same lines-and-text as the views. `None` on a sheet
120    /// that draws neither. It is built by the ENGINE rather than here
121    /// ([`crate::sheets::frame::frame`]): a title block carries the document's
122    /// name and the date, which a projection knows nothing about.
123    #[serde(skip_serializing_if = "Option::is_none")]
124    pub frame: Option<super::frame::FrameDrawing>,
125}
126
127/// One placed view, projected. Paper millimetres throughout, measured from the
128/// paper's TOP-LEFT corner with y running DOWN — SVG's own frame, so the
129/// writer transforms nothing.
130#[derive(Debug, Clone, PartialEq, serde::Serialize)]
131pub struct ViewDrawing {
132    /// The placed view's id (`SV2`).
133    pub id: String,
134    /// The saved PMI view it places (`VIEW1`).
135    pub view: String,
136    /// The saved view's name, for the panel and the SVG group label.
137    pub name: String,
138    pub position: [f64; 2],
139    pub scale: f64,
140    /// Empty when the view projected; the reason it did not otherwise (no such
141    /// saved view, no captured camera, a perspective camera).
142    #[serde(skip_serializing_if = "String::is_empty")]
143    pub error: String,
144    /// The scene names of the solids this placement draws: the model's
145    /// visible solids less the ones the saved view hides (its captured
146    /// baseline and its hide steps), in scene order.
147    #[serde(skip_serializing_if = "Vec::is_empty")]
148    pub solids: Vec<String>,
149    /// The model as VISIBLE edge lines, one polyline per visible run.
150    pub edges: Vec<Vec<[f64; 2]>>,
151    /// Visible runs drawn in the HIGHLIGHT stroke (the manufacturing
152    /// instructions draw the parts a step adds this way); empty on a sheet.
153    /// They are not among `edges`.
154    #[serde(skip_serializing_if = "Vec::is_empty")]
155    pub highlighted: Vec<Vec<[f64; 2]>>,
156    /// Every enabled, resolved annotation of the saved view, projected.
157    pub annotations: Vec<AnnotationDrawing>,
158    /// Every point of this projection a SHEET dimension can be anchored to —
159    /// each named vertex, each named edge's two ends and its midpoint, and the
160    /// centre of each circular edge. The anchor space is the MODEL's topology,
161    /// so the hidden-line pass has no vote on it: a candidate whose ink the
162    /// pass removed is still here, and a dimension anchored to it still draws.
163    pub anchors: Vec<AnchorPoint>,
164    /// The saved view's text size in PAPER millimetres — what a sheet
165    /// dimension on this placement is drawn at, so it reads at the size of the
166    /// annotations it sits among.
167    #[serde(rename = "textMm")]
168    pub text_mm: f64,
169    /// This placement IS a section view: the cut face's hatch and its caption
170    /// ([`SectionDrawing`]). `None` on a plain placement.
171    #[serde(skip_serializing_if = "Option::is_none")]
172    pub section: Option<SectionDrawing>,
173    /// The section LINES drawn on THIS placement — one per section view cut
174    /// through it. A plain placement that nothing sections has none.
175    #[serde(rename = "sectionMarks", skip_serializing_if = "Vec::is_empty")]
176    pub section_marks: Vec<SectionMark>,
177    /// This placement IS a detail view: its boundary circle and its caption
178    /// ([`DetailDrawing`]). `None` on every other placement.
179    #[serde(skip_serializing_if = "Option::is_none")]
180    pub detail: Option<DetailDrawing>,
181    /// The detail CIRCLES drawn on THIS placement — one per detail view drawn
182    /// from it.
183    #[serde(rename = "detailMarks", skip_serializing_if = "Vec::is_empty")]
184    pub detail_marks: Vec<DetailMark>,
185    /// `[x0, y0, x1, y1]` over everything drawn — empty geometry gives the
186    /// placement point twice.
187    pub bounds: [f64; 4],
188    /// Which hidden-line pass drew [`Self::edges`]: `analytic` (the exact
189    /// pass on the B-rep, [`super::hlr::visible_edges`]) or `mesh` (the same
190    /// pass on the display, [`super::hlr::visible_mesh_lines`] — the stated
191    /// approximation while a drawn solid's B-rep has not reached the scene).
192    /// Empty on a placement that did not project.
193    #[serde(rename = "hiddenLine", skip_serializing_if = "String::is_empty")]
194    pub hidden_line: String,
195    /// The saved view's PMI dimensions that carry a tolerance block (or read
196    /// as a reference dimension), by what they MEASURE on this paper: what a
197    /// sheet dimension anchored to the same points inherits
198    /// ([`super::dimension`]). Engine-side only — the drawing does not
199    /// publish them; a dimension that inherits says so on its own row.
200    #[serde(skip)]
201    pub tolerances: Vec<ToleranceSource>,
202}
203
204/// A PMI dimension of a placement's view with a tolerance block to hand on, by
205/// what it measures on the paper.
206#[derive(Debug, Clone, PartialEq)]
207pub struct ToleranceSource {
208    /// The annotation's id (`DIM4`).
209    pub id: String,
210    pub measures: Measures,
211    pub block: brep_kernel::ToleranceBlock,
212    pub reference: bool,
213}
214
215/// What a [`ToleranceSource`] measures, projected.
216#[derive(Debug, Clone, PartialEq)]
217pub enum Measures {
218    /// A free linear dimension between the paper images of its two measured
219    /// points. A component (X / Y / Z) row measures a different number than
220    /// any sheet dimension between the same two points can.
221    Linear { a: [f64; 2], b: [f64; 2] },
222    /// A radial or diametral dimension of the circle centred at the paper
223    /// image of `centre`, of MODEL radius `radius`.
224    Radial { centre: [f64; 2], radius: f64, diameter: bool },
225}
226
227impl ViewDrawing {
228    /// A placement with nothing drawn yet: its id, its position and a bounds
229    /// box of the placement point, so a view that draws nothing still has a
230    /// row and a grab rect on the paper.
231    fn empty(placed: &PlacedView, name: String) -> ViewDrawing {
232        ViewDrawing {
233            id: placed.id.clone(),
234            view: placed.view.clone(),
235            name,
236            position: placed.position,
237            scale: placed.scale,
238            error: String::new(),
239            solids: Vec::new(),
240            edges: Vec::new(),
241            highlighted: Vec::new(),
242            annotations: Vec::new(),
243            anchors: Vec::new(),
244            text_mm: 0.0,
245            section: None,
246            section_marks: Vec::new(),
247            detail: None,
248            detail_marks: Vec::new(),
249            bounds: [placed.position[0], placed.position[1], placed.position[0], placed.position[1]],
250            hidden_line: String::new(),
251            tolerances: Vec::new(),
252        }
253    }
254}
255
256/// A detail placement's own marks: the circle its drawing is clipped to and
257/// the `DETAIL B` / `SCALE 4:1` caption under it.
258///
259/// The model lines are not here — they are in [`ViewDrawing::edges`], already
260/// clipped to [`Self::circle`].
261#[derive(Debug, Clone, PartialEq, serde::Serialize)]
262pub struct DetailDrawing {
263    pub label: String,
264    /// The circle's centre on the paper — the placement's own position.
265    pub centre: [f64; 2],
266    /// The circle's radius on the paper: the model radius at this placement's
267    /// scale.
268    #[serde(rename = "radiusMm")]
269    pub radius_mm: f64,
270    /// The boundary, as a closed polyline.
271    pub circle: Vec<[f64; 2]>,
272    /// The caption: the letter, then the detail's own scale.
273    pub texts: Vec<SheetText>,
274}
275
276/// One detail CIRCLE, drawn on the placement it was picked on: the circle
277/// round the region the detail redraws, and its letter beside it.
278#[derive(Debug, Clone, PartialEq, serde::Serialize)]
279pub struct DetailMark {
280    /// The DETAIL placement's id — which view this circle is the region of.
281    pub id: String,
282    pub label: String,
283    pub centre: [f64; 2],
284    #[serde(rename = "radiusMm")]
285    pub radius_mm: f64,
286    pub lines: Vec<Vec<[f64; 2]>>,
287    pub texts: Vec<SheetText>,
288}
289
290/// A section placement's own marks: the hatch over its cut faces and the
291/// `SECTION A-A` caption under the drawing.
292///
293/// The cut OUTLINE is not here — it is in [`ViewDrawing::edges`] with every
294/// other model line, because the clip's new boundary edges go through the very
295/// same weld, classify and chain pass the rest of the model does. One
296/// extractor, so the ink and the hatch cannot disagree about where the cut is.
297#[derive(Debug, Clone, PartialEq, serde::Serialize)]
298pub struct SectionDrawing {
299    /// The section's letter.
300    pub label: String,
301    /// The cut face's hatch: parallel 45\u{00B0} lines clipped to the cut region by
302    /// an even-odd crossing count against [`Self::cut`].
303    pub hatch: Vec<Vec<[f64; 2]>>,
304    /// The cut region's boundary, in paper millimetres: one polyline per
305    /// trimmed piece of the plane's curve with a face, sampled from the exact
306    /// curve and oriented consistently round the region (their shoelace sum
307    /// is the cut area, the holes taken out). In the mesh approximation, one
308    /// segment per display triangle the plane cuts instead. What the hatch was
309    /// clipped to, and what a reader can check the hatched region against.
310    pub cut: Vec<Vec<[f64; 2]>>,
311    /// The `SECTION A-A` caption.
312    pub texts: Vec<SheetText>,
313}
314
315/// One section LINE, drawn on the placement the cut was picked in: the line
316/// through the two anchors, an arrow at each end pointing the way the section
317/// looks, and the letter beside each arrow.
318#[derive(Debug, Clone, PartialEq, serde::Serialize)]
319pub struct SectionMark {
320    /// The SECTION placement's id — which view this line is the cut of.
321    pub id: String,
322    pub label: String,
323    pub lines: Vec<Vec<[f64; 2]>>,
324    pub texts: Vec<SheetText>,
325}
326
327/// One annotation, laid out at sheet scale.
328#[derive(Debug, Clone, PartialEq, serde::Serialize)]
329pub struct AnnotationDrawing {
330    pub id: String,
331    #[serde(rename = "type")]
332    pub kind: String,
333    /// The kernel-formatted value — in MODEL units, never divided by the
334    /// sheet scale: a 10 mm feature drawn at 2:1 still reads `10.000`.
335    pub text: String,
336    /// Dimension / extension / leader lines, arrowhead outlines and frames.
337    pub lines: Vec<Vec<[f64; 2]>>,
338    pub texts: Vec<SheetText>,
339    /// What the projection has to say about this row, empty when it has
340    /// nothing: an annotation plane EDGE-ON to the view projects to a LINE,
341    /// so the row's geometry is a line and — with `flattenText` off — its
342    /// text falls on that line. Said out loud rather than dropped, which is
343    /// what the first sheets slice did with every non-parallel plane.
344    #[serde(skip_serializing_if = "String::is_empty")]
345    pub note: String,
346}
347
348/// One point of a placement's projection a sheet dimension can anchor to.
349///
350/// `anchor` is the reference string ([`super::dimension::SheetAnchor`]) — the
351/// name that survives a re-projection — and `at` is where it landed on the
352/// paper THIS time. The sheet viewport publishes one hit rect per candidate
353/// while the reference picker is up for a sheet object, and a dimension resolves its anchors by
354/// looking its references up in this list: an anchor that is not here is a
355/// LOST anchor, which is what marks its dimension unresolved.
356#[derive(Debug, Clone, PartialEq, serde::Serialize)]
357pub struct AnchorPoint {
358    #[serde(rename = "ref")]
359    pub anchor: String,
360    /// `vertex`, `edge` or `circle`.
361    pub kind: String,
362    /// Paper millimetres.
363    pub at: [f64; 2],
364    /// The 3D point before projection, in model units, with this view's poses
365    /// applied. Aligned dimensions measure here so an oblique camera cannot
366    /// foreshorten their values; `at` remains the point used for layout.
367    pub model: [f64; 3],
368    /// The unit PAPER direction of a STRAIGHT display edge — an `edge`
369    /// candidate only, and `None` on a curved edge or one that projects to a
370    /// point (an edge parallel to the viewing direction). It is what an
371    /// ANGULAR dimension measures between: the edge's direction as this view
372    /// projects it, so a foreshortened angle reads its projected value.
373    ///
374    /// Straightness is judged in the MODEL, not on the paper: a circular edge
375    /// seen edge-on projects to a straight segment and is not a straight edge.
376    /// All three fractions of one edge carry the same direction — it is the
377    /// EDGE's, not the point's.
378    #[serde(skip_serializing_if = "Option::is_none")]
379    pub dir: Option<[f64; 2]>,
380    /// The circle's MODEL radius — a `circle` candidate only.
381    #[serde(skip_serializing_if = "Option::is_none")]
382    pub radius: Option<f64>,
383    /// The paper images of the circle's two conjugate radii: the projected
384    /// circle is the ellipse `at + u cos t + v sin t`. A `circle` candidate
385    /// only, and what a radial dimension's leader measures its reach along.
386    #[serde(skip_serializing_if = "Option::is_none")]
387    pub u: Option<[f64; 2]>,
388    #[serde(skip_serializing_if = "Option::is_none")]
389    pub v: Option<[f64; 2]>,
390}
391
392/// A placed text run, centred on `anchor`.
393///
394/// The run is drawn in its OWN basis: [`SheetText::right`] and
395/// [`SheetText::up`] are the paper images of ONE CAP HEIGHT along the run's
396/// reading and up directions, in the drawing's millimetres (y DOWN, SVG's
397/// frame). A run laid flat on the sheet has `right = [h, 0]` and
398/// `up = [0, -h]`; a run projected out of an oblique annotation plane has a
399/// pair that is neither perpendicular nor equal in length, because the
400/// projection foreshortens and shears it, and the SVG and PDF writers carry
401/// the pair as a text matrix.
402///
403/// `height` and `angle` are that basis SUMMARISED — the cap height the run
404/// draws at (`|up|`) and the angle its baseline reads along, degrees
405/// CLOCKWISE (SVG's positive direction). They describe a flat or merely
406/// rotated run completely; the sheet viewport draws every run from them
407/// because egui cannot shear a text shape, so an oblique run previews as its
408/// rotation and its foreshortened height while the two files carry it exactly.
409#[derive(Debug, Clone, PartialEq, serde::Serialize)]
410pub struct SheetText {
411    pub text: String,
412    pub anchor: [f64; 2],
413    pub height: f64,
414    pub angle: f64,
415    pub right: [f64; 2],
416    pub up: [f64; 2],
417}
418
419impl SheetText {
420    /// A run from its projected basis; `height` and `angle` are derived here
421    /// and nowhere else, so the summary cannot disagree with the basis.
422    pub fn new(text: String, anchor: [f64; 2], right: [f64; 2], up: [f64; 2]) -> SheetText {
423        SheetText {
424            text,
425            anchor,
426            height: (up[0] * up[0] + up[1] * up[1]).sqrt(),
427            // atan2(0, 0) is 0: an EDGE-ON run has no reading direction left
428            // to report, and its row carries the note that says so.
429            angle: right[1].atan2(right[0]).to_degrees(),
430            right,
431            up,
432        }
433    }
434
435    /// A run laid FLAT on the sheet: reading left to right, `height`
436    /// millimetres of cap height. The title block's cells and every run of a
437    /// placement with `flattenText` on.
438    pub fn flat(text: String, anchor: [f64; 2], height: f64) -> SheetText {
439        SheetText::new(text, anchor, [height, 0.0], [0.0, -height])
440    }
441}
442
443// ---------------------------------------------------------------------------
444// The view frame
445// ---------------------------------------------------------------------------
446
447/// The saved camera as an orthonormal frame: `right` / `up` span the
448/// projection plane, `forward` runs eye → target. Points are measured from the
449/// camera's TARGET, which is the point the placement positions on the paper.
450#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
451pub struct ViewFrame {
452    pub target: [f64; 3],
453    pub right: [f64; 3],
454    pub up: [f64; 3],
455    pub forward: [f64; 3],
456}
457
458use crate::geometry3d::sub3 as sub;
459
460use crate::geometry3d::cross3 as cross;
461
462use crate::geometry3d::dot3 as dot;
463
464fn norm(v: [f64; 3]) -> [f64; 3] {
465    let len = dot(v, v).sqrt();
466    if len < 1e-12 {
467        [0.0, 0.0, 0.0]
468    } else {
469        [v[0] / len, v[1] / len, v[2] / len]
470    }
471}
472
473impl ViewFrame {
474    /// The frame of a saved camera. Mirrors [`crate::view::ViewCamera::basis`]
475    /// exactly (right = forward × up, true up = right × forward), so a sheet
476    /// view is oriented the way the viewport showed it.
477    pub fn of(camera: &PmiCamera) -> ViewFrame {
478        let forward = norm(sub(camera.target, camera.eye));
479        let forward = if forward == [0.0, 0.0, 0.0] { [0.0, 0.0, -1.0] } else { forward };
480        let mut right = norm(cross(forward, camera.up));
481        if right == [0.0, 0.0, 0.0] {
482            // The up vector is parallel to the view direction: any in-plane
483            // axis will do, and this one is continuous in the other cases.
484            right = norm(cross(forward, [0.0, 0.0, 1.0]));
485            if right == [0.0, 0.0, 0.0] {
486                right = norm(cross(forward, [0.0, 1.0, 0.0]));
487            }
488        }
489        let up = cross(right, forward);
490        ViewFrame { target: camera.target, right, up, forward }
491    }
492
493    /// `(x, y, depth)` in view space: x right, y UP, depth along the viewing
494    /// direction from the target plane (larger = further from the eye).
495    pub fn to_view(&self, p: [f64; 3]) -> [f64; 3] {
496        let d = sub(p, self.target);
497        [dot(d, self.right), dot(d, self.up), dot(d, self.forward)]
498    }
499}
500
501/// View-space `(x, y)` → paper millimetres for a placement.
502fn to_paper(placed: &PlacedView, x: f64, y: f64) -> [f64; 2] {
503    [placed.position[0] + x * placed.scale, placed.position[1] - y * placed.scale]
504}
505
506// ---------------------------------------------------------------------------
507// Entry
508// ---------------------------------------------------------------------------
509
510/// Project one placed view. `view` is the saved PMI view it names and `report`
511/// that view's resolved annotations (both `None` when the block no longer
512/// carries it, which is an error row rather than a dropped placement).
513pub fn project_view(
514    scene: &RenderScene,
515    placed: &PlacedView,
516    view: Option<&PmiView>,
517    report: Option<&PmiViewReport>,
518) -> ViewDrawing {
519    let (unposed, env) = (Unposed::new(), brep_kernel::Env::default());
520    project_view_through(&Model { scene, unposed: &unposed, env: &env }, placed, view, report, None, None, &mut LinesMode::Compute)
521}
522
523/// What a projection reads beside the sheet and its PMI views: the scene, the
524/// displays the viewport's active view posed in place (un-posed, see
525/// [`Unposed`]), and the document's expression sheet — a PMI row's tolerance
526/// may be an expression, and a sheet dimension that inherits it needs its
527/// value.
528pub struct Model<'a> {
529    pub scene: &'a RenderScene,
530    pub unposed: &'a Unposed,
531    pub env: &'a brep_kernel::Env,
532}
533
534/// The displays the viewport's ACTIVE PMI view has posed in place, un-posed —
535/// the engine's `pmi_explode_originals`. A sheet draws every placement with
536/// its OWN view's poses, so it reads a display through this first.
537pub type Unposed = std::collections::HashMap<String, crate::scene::SolidDisplay>;
538
539/// Which pass drew a placement's model lines ([`ViewDrawing::hidden_line`]).
540#[derive(Debug, Clone, Copy, PartialEq, Eq)]
541pub enum HiddenLine {
542    /// The exact pass on the B-rep ([`super::hlr::visible_edges`]).
543    Analytic,
544    /// The same pass on the display ([`super::hlr::visible_mesh_lines`]): the
545    /// stated approximation while a drawn solid's B-rep is not in the scene.
546    Mesh,
547}
548
549impl HiddenLine {
550    pub fn label(self) -> &'static str {
551        match self {
552            HiddenLine::Analytic => "analytic",
553            HiddenLine::Mesh => "mesh",
554        }
555    }
556}
557
558/// What a SECTION placement projects through, once its cut has been resolved
559/// against the source placement's projection: the derived camera frame, the
560/// half-space to keep, the second plane of a half section, and the letter.
561pub struct SectionSetup {
562    pub frame: ViewFrame,
563    pub plane: ClipPlane,
564    pub half: Option<super::hlr::HalfLine>,
565    pub label: String,
566}
567
568/// What a DETAIL placement projects through, once its circle has been
569/// resolved against the source placement's projection: the source's own
570/// camera frame re-targeted on the circle's centre, and the circle's radius
571/// in MODEL units.
572pub struct DetailSetup {
573    pub frame: ViewFrame,
574    pub radius: f64,
575    pub label: String,
576}
577
578/// A placement whose camera is DERIVED from another placement rather than
579/// read off its saved view.
580pub enum Derived {
581    Section(SectionSetup),
582    Detail(DetailSetup),
583}
584
585/// Project one placed view, optionally through a DERIVED camera — a
586/// section's or a detail's — instead of its saved one.
587///
588/// With a SECTION, the frame is the derived one, the model is cut by the
589/// section plane exactly ([`super::hlr::section_curves`]), and the pass keeps
590/// only what is at or beyond the plane with the cut region as a cap in front
591/// of what lies behind it. The candidate, split and visibility code and the
592/// ANCHOR space are the very same as a plain placement's.
593///
594/// With a DETAIL, the frame is the source's camera re-targeted on the circle's
595/// centre (so this placement's `position` is where the centre lands), and
596/// visibility is decided inside the circle's cylinder at the detail's own
597/// scale; `clip_to_circle` then trims only a chord that bows past the rim.
598///
599/// Both draw the model ONLY: the saved view's annotations were laid out
600/// against THAT view's camera and scale, and a section's camera is a different
601/// one, while a detail's circle would cut a dimension or a frame in half.
602///
603/// `letter` captions a plain placement of a SECTIONED saved view
604/// ([`super::Sheet::view_letters`]); a derived view carries its own.
605pub fn project_view_through(
606    model: &Model,
607    placed: &PlacedView,
608    view: Option<&PmiView>,
609    report: Option<&PmiViewReport>,
610    derived: Option<Derived>,
611    letter: Option<&str>,
612    mode: &mut LinesMode,
613) -> ViewDrawing {
614    let (scene, unposed) = (model.scene, model.unposed);
615    let mut out = ViewDrawing::empty(placed, view.map(|v| v.name.clone()).unwrap_or_default());
616    let Some(view) = view else {
617        out.error = format!("no PMI view '{}'", placed.view);
618        return out;
619    };
620    let Some(camera) = view.camera.as_ref() else {
621        out.error = format!("PMI view '{}' has no captured camera", placed.view);
622        return out;
623    };
624    if !matches!(camera.projection, PmiProjection::Orthographic { .. }) {
625        out.error = format!(
626            "PMI view '{}' is a perspective camera; a sheet draws {ORTHOGRAPHIC} views only",
627            placed.view
628        );
629        return out;
630    }
631    if !placed.projection.eq_ignore_ascii_case(ORTHOGRAPHIC) {
632        out.error = format!("projection '{}' is not drawn on a sheet", placed.projection);
633        return out;
634    }
635
636    let saved_section = derived.is_none() && view.display.section.is_some();
637    // A half section draws as one: the second plane is edge-on to the section
638    // view, a line on the paper. Any other set of planes has no such drawing.
639    let planes = if derived.is_none() { view.section_planes_in(report) } else { Vec::new() };
640    if planes.len() > 2 || planes.get(1).is_some_and(|(_, second)| dot(*second, planes[0].1).abs() > 1e-6) {
641        out.error = format!(
642            "PMI view '{}' is sectioned by {} planes; a sheet draws one plane, or a half section of two perpendicular planes",
643            placed.view,
644            planes.len()
645        );
646        return out;
647    }
648    let derived = derived.or_else(|| planes.first().map(|&(point, normal)| {
649        let original = ViewFrame::of(camera);
650        let seed = if dot(original.up, normal).abs() < 0.99 { original.up } else if normal[0].abs() < 0.9 { [1., 0., 0.] } else { [0., 1., 0.] };
651        let right = norm(cross(normal, seed));
652        let frame = ViewFrame { target: point, right, up: cross(right, normal), forward: normal };
653        let half = planes.get(1).map(|&(at, second)| {
654            let (normal, at) = ([dot(second, frame.right), dot(second, frame.up)], frame.to_view(at));
655            super::hlr::HalfLine { normal, offset: normal[0] * at[0] + normal[1] * at[1] }
656        });
657        Derived::Section(SectionSetup { frame, plane: ClipPlane { point, normal }, half, label: letter.unwrap_or("A").to_string() })
658    }));
659    let frame = match &derived {
660        Some(Derived::Section(setup)) => setup.frame,
661        Some(Derived::Detail(setup)) => setup.frame,
662        None => ViewFrame::of(camera),
663    };
664    out.text_mm = view.display.text_size_pt * MM_PER_POINT;
665    out.solids = drawn_solids(scene, unposed, view).iter().map(|solid| solid.name.clone()).collect();
666    let cap = if out.text_mm > 1e-9 { out.text_mm } else { 12.0 * MM_PER_POINT };
667    // The exact pass needs every drawn solid's B-rep; a solid whose topology
668    // did not reach the scene sends the placement to the mesh approximation,
669    // and so does a pass handed to the runner that has not come back yet. The
670    // placement says which drew it rather than drawing that solid as nothing.
671    let plan = exact_solids(scene, unposed, view, report);
672    let clip = match &derived {
673        None => LinesClip::Whole,
674        Some(Derived::Detail(setup)) => LinesClip::Circle { radius: setup.radius },
675        Some(Derived::Section(setup)) => LinesClip::Section { half: setup.half },
676    };
677    let exact = plan.as_ref().and_then(|plan| exact_lines_for(plan, &frame, placed, clip, mode));
678    if matches!(mode, LinesMode::Export(_)) && exact.is_none() {
679        if plan.is_none() {
680            out.error = "exact geometry is unavailable for this picture".into();
681        }
682        return out;
683    }
684    out.hidden_line = if exact.is_some() { HiddenLine::Analytic } else { HiddenLine::Mesh }.label().into();
685    match &derived {
686        None => {
687            out.edges = match exact {
688                Some(lines) => lines.runs,
689                None => mesh_lines_for(scene, unposed, view, report, &frame, placed, LinesClip::Whole, None).runs,
690            };
691            out.annotations = annotations(report, view, &frame, placed);
692            out.tolerances = tolerance_sources(report, view, &frame, placed, model.env);
693        }
694        Some(Derived::Detail(setup)) => {
695            let radius_mm = setup.radius * placed.scale;
696            // Analytic: visibility is decided on the model inside the
697            // circle's cylinder, sampled at THIS placement's scale. The
698            // circle clip after it only trims a chord that bows past the rim.
699            let lines = match exact {
700                Some(lines) => lines.runs,
701                None => mesh_lines_for(scene, unposed, view, report, &frame, placed, clip, None).runs,
702            };
703            out.edges = clip_to_circle(lines, placed.position, radius_mm);
704            out.detail = Some(DetailDrawing {
705                label: setup.label.clone(),
706                centre: placed.position,
707                radius_mm,
708                circle: circle_polyline(placed.position, radius_mm),
709                texts: Vec::new(),
710            });
711        }
712        Some(Derived::Section(setup)) => match exact {
713            Some(ExactLines { runs, cut }) => {
714                // The cut curves are model lines in their own right: nothing
715                // is in front of a cut face to hide them.
716                let mut edges = runs;
717                edges.extend(cut.iter().cloned());
718                out.edges = edges;
719                out.section = Some(SectionDrawing {
720                    label: setup.label.clone(),
721                    hatch: hatch(&segments_of(&cut)),
722                    cut,
723                    texts: Vec::new(),
724                });
725            }
726            None => {
727                let ExactLines { runs, cut: cut_paper } =
728                    mesh_lines_for(scene, unposed, view, report, &frame, placed, clip, Some(&setup.plane));
729                let mut edges = runs;
730                edges.extend(cut_paper.iter().cloned());
731                out.edges = edges;
732                out.section = Some(SectionDrawing {
733                    label: setup.label.clone(),
734                    hatch: hatch(&cut_paper),
735                    cut: cut_paper,
736                    texts: Vec::new(),
737                });
738            }
739        },
740    }
741    if saved_section {
742        out.annotations = annotations(report, view, &frame, placed);
743        out.tolerances = tolerance_sources(report, view, &frame, placed, model.env);
744    }
745    out.anchors = anchor_points(scene, unposed, view, report, &frame, placed);
746    // A detail offers the anchors INSIDE its circle and no others. The anchor
747    // space is still the model's topology — the hidden-line pass has no vote
748    // on it, here as everywhere — but a point outside the circle is not on
749    // this placement at all: nothing of the detail is drawn there, and at the
750    // detail's scale it would land anywhere on the paper, over other views,
751    // where the sheet picker's markers would offer it as a point of theirs.
752    if let Some(detail) = &out.detail {
753        let reach = detail.radius_mm * (1.0 + 1e-9) + 1e-9;
754        out.anchors.retain(|anchor| {
755            let (dx, dy) = (anchor.at[0] - detail.centre[0], anchor.at[1] - detail.centre[1]);
756            (dx * dx + dy * dy).sqrt() <= reach
757        });
758    }
759    out.bounds = bounds_of(&out, placed);
760    // The caption goes UNDER the finished drawing, so it is placed once the
761    // bounds are known — and the bounds are then re-read to take it in, or a
762    // placement drag would grab a rect the caption hangs out of.
763    let middle = (out.bounds[0] + out.bounds[2]) * 0.5;
764    let below = out.bounds[3] + cap * 2.0;
765    if let Some(section) = out.section.as_mut() {
766        section.texts.push(SheetText::flat(
767            format!("SECTION {}\u{2014}{}", section.label, section.label),
768            [middle, below],
769            cap,
770        ));
771        out.bounds = bounds_of(&out, placed);
772    }
773    // A detail's caption says which circle it is and — the one thing that
774    // distinguishes it from its source — the scale it is drawn at.
775    if let Some(detail) = out.detail.as_mut() {
776        detail.texts.push(SheetText::flat(format!("DETAIL {}", detail.label), [middle, below], cap));
777        detail.texts.push(SheetText::flat(
778            format!("SCALE {}", super::frame::ratio_text(placed.scale)),
779            [middle, below + cap * 1.8],
780            cap * 0.8,
781        ));
782        out.bounds = bounds_of(&out, placed);
783    }
784    out
785}
786
787/// The whole sheet: the paper's furniture, then every placement projected, in
788/// order. `context` is what the border and title block need and a projection
789/// cannot know — the document's name and the day (see
790/// [`super::frame::FrameContext`]). Every exact pass runs HERE, on the calling
791/// thread; [`project_sheet_with`] can hand them over instead.
792pub fn project_sheet(
793    scene: &RenderScene,
794    sheet: &super::Sheet,
795    views: &[PmiView],
796    report: Option<&brep_kernel::PmiReport>,
797    context: &super::frame::FrameContext,
798) -> SheetDrawing {
799    let (unposed, env) = (Unposed::new(), brep_kernel::Env::default());
800    project_sheet_with(&Model { scene, unposed: &unposed, env: &env }, sheet, views, report, context, &mut LinesMode::Compute)
801}
802
803/// [`project_sheet`], with what an exact-lines miss does chosen by `mode`: the
804/// engine's viewport hands the pass to the runner and draws the mesh
805/// approximation until the answer lands; an export computes it here.
806pub fn project_sheet_with(
807    model: &Model,
808    sheet: &super::Sheet,
809    views: &[PmiView],
810    report: Option<&brep_kernel::PmiReport>,
811    context: &super::frame::FrameContext,
812    mode: &mut LinesMode,
813) -> SheetDrawing {
814    let (width_mm, height_mm) = sheet.millimetres();
815    // PLAIN placements first, then the DERIVED ones: a section's camera and a
816    // detail's circle are both read off where their anchors landed in the
817    // source's projection, so the source has to be drawn before either can
818    // know where it is looking from. Every derived placement's source must be
819    // a PLAIN one — a section or a detail OF a section or a detail is refused
820    // by name rather than ordered, because this pass is one pass and a chain
821    // would need as many.
822    let letters = sheet.view_letters(views);
823    let mut drawn: Vec<ViewDrawing> = sheet
824        .views
825        .iter()
826        .zip(&letters)
827        .map(|(placed, letter)| {
828            let saved = views.iter().find(|view| view.id == placed.view);
829            if placed.section.is_some() || placed.detail.is_some() {
830                // A stand-in until the second pass: it holds the id and the
831                // position, so a derived view that cannot resolve still has a
832                // row and a grab rect on the paper.
833                ViewDrawing::empty(placed, saved.map(|v| v.name.clone()).unwrap_or_default())
834            } else {
835                project_view_through(model, placed, saved, report.and_then(|report| report.view(&placed.view)), None, letter.as_deref(), mode)
836            }
837        })
838        .collect();
839    for (index, placed) in sheet.views.iter().enumerate() {
840        let Some(circle) = placed.detail.as_ref() else { continue };
841        match detail_setup(sheet, &drawn, circle, views) {
842            Err(error) => drawn[index].error = error,
843            Ok((setup, source, mark)) => {
844                drawn[index] = project_view_through(
845                    model,
846                    placed,
847                    views.iter().find(|view| view.id == placed.view),
848                    report.and_then(|report| report.view(&placed.view)),
849                    Some(Derived::Detail(setup)),
850                    None,
851                    mode,
852                );
853                let mark = DetailMark { id: placed.id.clone(), ..mark };
854                drawn[source].detail_marks.push(mark);
855                let source_placed = &sheet.views[source];
856                drawn[source].bounds = bounds_of(&drawn[source], source_placed);
857            }
858        }
859    }
860    for (index, placed) in sheet.views.iter().enumerate() {
861        let Some(cut) = placed.section.as_ref() else { continue };
862        match section_setup(sheet, &drawn, placed, cut, views) {
863            Err(error) => drawn[index].error = error,
864            Ok((setup, source, mark)) => {
865                drawn[index] = project_view_through(
866                    model,
867                    placed,
868                    views.iter().find(|view| view.id == placed.view),
869                    report.and_then(|report| report.view(&placed.view)),
870                    Some(Derived::Section(setup)),
871                    None,
872                    mode,
873                );
874                // The LINE goes on the source, where it was picked. Its own
875                // bounds grow to take it in, so dragging that placement still
876                // grabs everything it draws.
877                drawn[source].section_marks.push(mark);
878                let source_placed = &sheet.views[source];
879                drawn[source].bounds = bounds_of(&drawn[source], source_placed);
880            }
881        }
882    }
883    // A saved sectioned view's cutting plane, on every plain placement that
884    // sees it edge-on: its line, arrows and letter, as a picked cut's.
885    for (index, placed) in sheet.views.iter().enumerate() {
886        if placed.section.is_some() || placed.detail.is_some() {
887            continue;
888        }
889        let Some(label) = drawn[index].section.as_ref().map(|section| section.label.clone()) else { continue };
890        let Some(view) = views.iter().find(|view| view.id == placed.view) else { continue };
891        let Some((point, normal)) = view.section_plane_in(report.and_then(|report| report.view(&placed.view))) else { continue };
892        for (other, source) in sheet.views.iter().enumerate() {
893            if other == index || source.section.is_some() || source.detail.is_some() {
894                continue;
895            }
896            if drawn[other].section.is_some() || !drawn[other].error.is_empty() {
897                continue;
898            }
899            let Some(camera) = views.iter().find(|view| view.id == source.view).and_then(|view| view.camera.as_ref()) else { continue };
900            let frame = ViewFrame::of(camera);
901            if dot(normal, frame.forward).abs() > 1e-6 {
902                continue;
903            }
904            let Some(mark) = plane_mark(&drawn[other], source, &frame, point, normal, &placed.id, &label) else { continue };
905            drawn[other].section_marks.push(mark);
906            drawn[other].bounds = bounds_of(&drawn[other], source);
907        }
908    }
909    // The sheet's own dimensions come LAST: they anchor to the placements'
910    // projections, so they are laid out over the finished drawing rather than
911    // inside any one placement.
912    let dimensions = super::dimension::layout_dimensions(
913        &sheet.dimensions,
914        &drawn,
915        [width_mm * 0.5, height_mm * 0.5],
916    );
917    let ordinates = super::ordinate::layout_ordinates(
918        &sheet.ordinates,
919        &drawn,
920        [width_mm * 0.5, height_mm * 0.5],
921    );
922    SheetDrawing {
923        id: sheet.id.clone(),
924        name: sheet.name.clone(),
925        width_mm,
926        height_mm,
927        frame: super::frame::frame(sheet, context),
928        views: drawn,
929        dimensions,
930        ordinates,
931    }
932}
933
934/// Resolve a section's cut against the SOURCE placement's finished projection:
935/// the derived camera frame, the half-space to keep, which placement carries
936/// the line, and the line itself.
937///
938/// # The camera
939///
940/// The two anchors are paper points of the source's projection. Lifted back
941/// into the source camera's own plane they give two 3D points, and the CUTTING
942/// PLANE is the plane through them containing the source's viewing direction —
943/// which is what "a line drawn on a view" means: every point of the paper line
944/// is a whole ray of the model.
945///
946/// The section camera then looks along that plane's NORMAL, and its up is the
947/// source's viewing direction REVERSED. Those two are perpendicular for free,
948/// because the plane contains the source's viewing direction and its normal is
949/// perpendicular to everything in it — so the frame is orthonormal by
950/// construction rather than by a re-orthogonalisation that could quietly tilt
951/// the section. It is also the drawing convention: section a TOP view and the
952/// section is an elevation with model up ON the page.
953///
954/// # Which way it looks
955///
956/// 90\u{00B0} clockwise from `from` \u{2192} `to` on the SOURCE's paper — the side a reader
957/// walking from the first arrow to the second has on their right. The pick
958/// ORDER is therefore the choice, and `flip` is the form's way to change its
959/// mind without re-picking.
960fn section_setup(
961    sheet: &super::Sheet,
962    drawn: &[ViewDrawing],
963    placed: &PlacedView,
964    cut: &super::SectionCut,
965    views: &[PmiView],
966) -> Result<(SectionSetup, usize, SectionMark), String> {
967    // A section the Section view button made has no line until its form's
968    // Cutting line row is picked — say what it is waiting for.
969    if cut.from.is_empty() || cut.to.is_empty() {
970        return Err("no cutting line yet \u{2014} pick its two anchors on a placed view".into());
971    }
972    let Some(source_index) = sheet.views.iter().position(|v| v.id == cut.source) else {
973        return Err(format!("no placement '{}' to cut through on this sheet", cut.source));
974    };
975    let source_placed = &sheet.views[source_index];
976    if source_placed.section.is_some() {
977        return Err(format!(
978            "'{}' is itself a section; a section of a section is not drawn",
979            cut.source
980        ));
981    }
982    if source_placed.detail.is_some() {
983        return Err(format!(
984            "'{}' is a detail; a section of a detail is not drawn",
985            cut.source
986        ));
987    }
988    let source = &drawn[source_index];
989    if !source.error.is_empty() {
990        return Err(format!("placement '{}' did not project", cut.source));
991    }
992    let (from, to) = (point_of(source, &cut.from)?, point_of(source, &cut.to)?);
993    let span = [to[0] - from[0], to[1] - from[1]];
994    let length = (span[0] * span[0] + span[1] * span[1]).sqrt();
995    if !(length > 1e-9) {
996        return Err(format!(
997            "'{}' and '{}' are the same point; a cutting line needs two",
998            cut.from, cut.to
999        ));
1000    }
1001    let Some(camera) = views
1002        .iter()
1003        .find(|view| view.id == source_placed.view)
1004        .and_then(|view| view.camera.as_ref())
1005    else {
1006        return Err(format!("placement '{}' has no captured camera to cut in", cut.source));
1007    };
1008    let source_frame = ViewFrame::of(camera);
1009    if source_placed.scale <= 0.0 {
1010        return Err(format!("placement '{}' has no scale", cut.source));
1011    }
1012    // Paper -> the source camera's own plane. The depth along the source's
1013    // viewing direction is free — the cutting plane contains that direction,
1014    // so every choice names the same plane — and the target plane is the one
1015    // choice with no arbitrary number in it.
1016    let (p0, p1) = (lift(&source_frame, source_placed, from), lift(&source_frame, source_placed, to));
1017    let along = norm(sub(p1, p0));
1018    let mut forward = norm(cross(source_frame.forward, along));
1019    if forward == [0.0, 0.0, 0.0] {
1020        return Err("the cutting line has no direction in this view".into());
1021    }
1022    if cut.flip {
1023        forward = [-forward[0], -forward[1], -forward[2]];
1024    }
1025    let up = [-source_frame.forward[0], -source_frame.forward[1], -source_frame.forward[2]];
1026    let right = norm(cross(forward, up));
1027    let target = [(p0[0] + p1[0]) * 0.5, (p0[1] + p1[1]) * 0.5, (p0[2] + p1[2]) * 0.5];
1028    let setup = SectionSetup {
1029        frame: ViewFrame { target, right, up: cross(right, forward), forward },
1030        plane: ClipPlane { point: target, normal: forward },
1031        half: None,
1032        label: cut.label.clone(),
1033    };
1034    let cap = if source.text_mm > 1e-9 { source.text_mm } else { 12.0 * MM_PER_POINT };
1035    Ok((setup, source_index, section_mark(placed, cut, from, to, cap)))
1036}
1037
1038/// The section LINE on the source's paper: the line through the two anchors
1039/// with a tail past each, an arrow at each end pointing the way the section
1040/// looks, and the letter beside each arrow.
1041fn section_mark(
1042    placed: &PlacedView,
1043    cut: &super::SectionCut,
1044    from: [f64; 2],
1045    to: [f64; 2],
1046    cap: f64,
1047) -> SectionMark {
1048    let span = [to[0] - from[0], to[1] - from[1]];
1049    let length = (span[0] * span[0] + span[1] * span[1]).sqrt().max(1e-9);
1050    let along = [span[0] / length, span[1] / length];
1051    // The viewing direction, as the SOURCE's paper sees it: 90 degrees
1052    // clockwise from the travel direction (paper y runs DOWN, so that is
1053    // `(-dy, dx)`), turned round by `flip`. Derived here from the same pick
1054    // order the camera is, so the arrows point where the section looks.
1055    let sign = if cut.flip { -1.0 } else { 1.0 };
1056    let look = [-along[1] * sign, along[0] * sign];
1057    cutting_mark(&placed.id, &cut.label, from, to, look, cap)
1058}
1059
1060/// A saved section's cutting plane `(point, normal)` on a plain placement
1061/// whose camera `frame` sees it edge-on: the plane's trace across the
1062/// placement's drawn edges, arrows the way the section looks. `None` when the
1063/// placement draws nothing to cross.
1064fn plane_mark(
1065    source: &ViewDrawing,
1066    placed: &PlacedView,
1067    frame: &ViewFrame,
1068    point: [f64; 3],
1069    normal: [f64; 3],
1070    id: &str,
1071    label: &str,
1072) -> Option<SectionMark> {
1073    let paper = |v: [f64; 3]| {
1074        let length = (v[0] * v[0] + v[1] * v[1]).sqrt();
1075        (length > 1e-9).then(|| [v[0] / length, v[1] / length])
1076    };
1077    // Paper y runs DOWN: a view direction's paper image is (right, −up).
1078    let at = frame.to_view(point);
1079    let centre = to_paper(placed, at[0], at[1]);
1080    let trace = cross(normal, frame.forward);
1081    let along = paper([dot(trace, frame.right), -dot(trace, frame.up), 0.0])?;
1082    let look = paper([dot(normal, frame.right), -dot(normal, frame.up), 0.0])?;
1083    let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
1084    for p in source.edges.iter().flatten() {
1085        let t = (p[0] - centre[0]) * along[0] + (p[1] - centre[1]) * along[1];
1086        lo = lo.min(t);
1087        hi = hi.max(t);
1088    }
1089    if !(hi > lo) {
1090        return None;
1091    }
1092    let from = [centre[0] + along[0] * lo, centre[1] + along[1] * lo];
1093    let to = [centre[0] + along[0] * hi, centre[1] + along[1] * hi];
1094    let cap = if source.text_mm > 1e-9 { source.text_mm } else { 12.0 * MM_PER_POINT };
1095    Some(cutting_mark(id, label, from, to, look, cap))
1096}
1097
1098/// A cutting line from `from` to `to` on the paper, with a tail past each end,
1099/// an arrow at each pointing `look` (a unit paper direction), and `label`
1100/// beside each arrow — for the SECTION placement `id`.
1101fn cutting_mark(id: &str, label: &str, from: [f64; 2], to: [f64; 2], look: [f64; 2], cap: f64) -> SectionMark {
1102    let span = [to[0] - from[0], to[1] - from[1]];
1103    let length = (span[0] * span[0] + span[1] * span[1]).sqrt().max(1e-9);
1104    let along = [span[0] / length, span[1] / length];
1105    let tail = cap * 1.5;
1106    let arrow = cap * 1.2;
1107    let mut lines = vec![vec![
1108        [from[0] - along[0] * tail, from[1] - along[1] * tail],
1109        [to[0] + along[0] * tail, to[1] + along[1] * tail],
1110    ]];
1111    let mut texts = Vec::new();
1112    for (end, outward) in [(from, [-along[0], -along[1]]), (to, along)] {
1113        let root = [end[0] + outward[0] * tail, end[1] + outward[1] * tail];
1114        let tip = [root[0] + look[0] * arrow * 2.0, root[1] + look[1] * arrow * 2.0];
1115        // The stem, then the head as a closed outline — the sheet's contract
1116        // is lines, so an arrowhead is its own boundary here exactly as it is
1117        // in the shared dimension layout.
1118        lines.push(vec![root, tip]);
1119        let across = [-look[1] * arrow * 0.35, look[0] * arrow * 0.35];
1120        lines.push(vec![
1121            tip,
1122            [tip[0] - look[0] * arrow + across[0], tip[1] - look[1] * arrow + across[1]],
1123            [tip[0] - look[0] * arrow - across[0], tip[1] - look[1] * arrow - across[1]],
1124            tip,
1125        ]);
1126        texts.push(SheetText::flat(
1127            label.to_string(),
1128            [
1129                root[0] + outward[0] * cap * 1.2 + look[0] * cap * 0.6,
1130                root[1] + outward[1] * cap * 1.2 + look[1] * cap * 0.6,
1131            ],
1132            cap,
1133        ));
1134    }
1135    SectionMark { id: id.to_string(), label: label.to_string(), lines, texts }
1136}
1137
1138/// Where anchor `reference` landed on a finished placement's paper, or the
1139/// reason a derived view built on it cannot resolve.
1140fn point_of(source: &ViewDrawing, reference: &str) -> Result<[f64; 2], String> {
1141    source
1142        .anchors
1143        .iter()
1144        .find(|a| a.anchor == reference)
1145        .map(|a| a.at)
1146        .ok_or_else(|| format!("'{reference}' is not a point of '{}' any more", source.id))
1147}
1148
1149/// A paper point of `placed` lifted back into its camera's TARGET plane: the
1150/// inverse of [`to_paper`] with the depth set to zero.
1151fn lift(frame: &ViewFrame, placed: &PlacedView, p: [f64; 2]) -> [f64; 3] {
1152    let x = (p[0] - placed.position[0]) / placed.scale;
1153    let y = -(p[1] - placed.position[1]) / placed.scale;
1154    [
1155        frame.target[0] + frame.right[0] * x + frame.up[0] * y,
1156        frame.target[1] + frame.right[1] * x + frame.up[1] * y,
1157        frame.target[2] + frame.right[2] * x + frame.up[2] * y,
1158    ]
1159}
1160
1161/// Resolve a detail's circle against the SOURCE placement's finished
1162/// projection: the camera the detail looks through, which placement carries
1163/// the circle, and the circle itself as drawn there.
1164///
1165/// # The camera
1166///
1167/// The SOURCE's, unchanged in every direction: the detail is the same view at
1168/// a larger scale, so its right, up and viewing direction are the source's.
1169/// Only the TARGET moves — to the circle's centre, lifted back into the source
1170/// camera's own plane — which is what makes this placement's `position` the
1171/// point the circle's centre lands on. The depth of that target is free (a
1172/// parallel projection does not care where along the viewing direction the
1173/// target plane is), and the source's own target plane is the choice with no
1174/// arbitrary number in it.
1175///
1176/// # The radius
1177///
1178/// The distance between the two anchors on the SOURCE's paper over the
1179/// source's scale: a model length, so the circle holds the same region of the
1180/// model at any detail scale. Measured in the projection plane, which is where
1181/// the circle is.
1182fn detail_setup(
1183    sheet: &super::Sheet,
1184    drawn: &[ViewDrawing],
1185    circle: &super::DetailCircle,
1186    views: &[PmiView],
1187) -> Result<(DetailSetup, usize, DetailMark), String> {
1188    // A detail the Detail view button made has no circle until its form's
1189    // Centre and rim rows are picked.
1190    if circle.centre.is_empty() || circle.rim.is_empty() {
1191        return Err("no detail circle yet \u{2014} pick its centre and a point on its rim on a placed view".into());
1192    }
1193    let Some(source_index) = sheet.views.iter().position(|v| v.id == circle.source) else {
1194        return Err(format!("no placement '{}' to draw a detail of on this sheet", circle.source));
1195    };
1196    let source_placed = &sheet.views[source_index];
1197    if source_placed.detail.is_some() {
1198        return Err(format!(
1199            "'{}' is itself a detail; a detail of a detail is not drawn",
1200            circle.source
1201        ));
1202    }
1203    if source_placed.section.is_some() {
1204        return Err(format!(
1205            "'{}' is a section; a detail of a section is not drawn",
1206            circle.source
1207        ));
1208    }
1209    let source = &drawn[source_index];
1210    if !source.error.is_empty() {
1211        return Err(format!("placement '{}' did not project", circle.source));
1212    }
1213    let (centre, rim) = (point_of(source, &circle.centre)?, point_of(source, &circle.rim)?);
1214    let radius_mm = ((rim[0] - centre[0]).powi(2) + (rim[1] - centre[1]).powi(2)).sqrt();
1215    if !(radius_mm > 1e-9) {
1216        return Err(format!(
1217            "'{}' and '{}' land on the same point of '{}'; a detail circle needs a radius",
1218            circle.centre, circle.rim, circle.source
1219        ));
1220    }
1221    let Some(camera) = views
1222        .iter()
1223        .find(|view| view.id == source_placed.view)
1224        .and_then(|view| view.camera.as_ref())
1225    else {
1226        return Err(format!("placement '{}' has no captured camera to draw a detail of", circle.source));
1227    };
1228    if source_placed.scale <= 0.0 {
1229        return Err(format!("placement '{}' has no scale", circle.source));
1230    }
1231    let source_frame = ViewFrame::of(camera);
1232    let setup = DetailSetup {
1233        frame: ViewFrame { target: lift(&source_frame, source_placed, centre), ..source_frame },
1234        radius: radius_mm / source_placed.scale,
1235        label: circle.label.clone(),
1236    };
1237    let cap = if source.text_mm > 1e-9 { source.text_mm } else { 12.0 * MM_PER_POINT };
1238    // The letter sits outside the circle up and to the right, a cap and a
1239    // half clear of the rim, so it names the circle without touching what the
1240    // circle encloses.
1241    let d = std::f64::consts::FRAC_1_SQRT_2;
1242    let reach = radius_mm + cap * 1.5;
1243    let mark = DetailMark {
1244        id: String::new(),
1245        label: circle.label.clone(),
1246        centre,
1247        radius_mm,
1248        lines: vec![circle_polyline(centre, radius_mm)],
1249        texts: vec![SheetText::flat(
1250            circle.label.clone(),
1251            [centre[0] + reach * d, centre[1] - reach * d],
1252            cap,
1253        )],
1254    };
1255    Ok((setup, source_index, mark))
1256}
1257
1258/// How many straight pieces a detail circle is drawn with. A circle is a
1259/// polyline on a sheet like every other curve; at this count a 100 mm circle
1260/// misses the true one by 0.05 mm, under a stroke width.
1261const CIRCLE_SEGMENTS: usize = 96;
1262
1263/// A closed circle polyline in paper millimetres, back to its first point.
1264fn circle_polyline(centre: [f64; 2], radius: f64) -> Vec<[f64; 2]> {
1265    (0..=CIRCLE_SEGMENTS)
1266        .map(|k| {
1267            let t = std::f64::consts::TAU * k as f64 / CIRCLE_SEGMENTS as f64;
1268            [centre[0] + radius * t.cos(), centre[1] + radius * t.sin()]
1269        })
1270        .collect()
1271}
1272
1273/// Keep the parts of `lines` inside the circle, splitting a polyline wherever
1274/// it leaves and re-enters.
1275///
1276/// Exact per segment — each piece is cut where it crosses the TRUE circle, not
1277/// the polyline it is drawn with — so a line leaving the detail ends on the
1278/// boundary a reader sees rather than a stroke short of it. A segment lying
1279/// wholly inside keeps its own two ends, so a straight edge inside the circle
1280/// comes back as the two points it went in as.
1281fn clip_to_circle(lines: Vec<Vec<[f64; 2]>>, centre: [f64; 2], radius: f64) -> Vec<Vec<[f64; 2]>> {
1282    let mut out: Vec<Vec<[f64; 2]>> = Vec::new();
1283    let flush = |current: &mut Vec<[f64; 2]>, out: &mut Vec<Vec<[f64; 2]>>| {
1284        if current.len() >= 2 {
1285            out.push(std::mem::take(current));
1286        } else {
1287            current.clear();
1288        }
1289    };
1290    for line in lines {
1291        let mut current: Vec<[f64; 2]> = Vec::new();
1292        for pair in line.windows(2) {
1293            let (p, q) = (pair[0], pair[1]);
1294            let d = [q[0] - p[0], q[1] - p[1]];
1295            let f = [p[0] - centre[0], p[1] - centre[1]];
1296            let a = d[0] * d[0] + d[1] * d[1];
1297            let c = f[0] * f[0] + f[1] * f[1] - radius * radius;
1298            // The parameter span of the segment inside the circle, if any.
1299            let span = if a < 1e-24 {
1300                (c <= 0.0).then_some((0.0, 1.0))
1301            } else {
1302                let b = 2.0 * (f[0] * d[0] + f[1] * d[1]);
1303                let disc = b * b - 4.0 * a * c;
1304                if disc < 0.0 {
1305                    None
1306                } else {
1307                    let root = disc.sqrt();
1308                    let (t0, t1) = (((-b - root) / (2.0 * a)).max(0.0), ((-b + root) / (2.0 * a)).min(1.0));
1309                    (t1 > t0).then_some((t0, t1))
1310                }
1311            };
1312            let at = |t: f64| [p[0] + d[0] * t, p[1] + d[1] * t];
1313            match span {
1314                None => flush(&mut current, &mut out),
1315                Some((t0, t1)) => {
1316                    if t0 <= 0.0 {
1317                        if current.is_empty() {
1318                            current.push(p);
1319                        }
1320                        if t1 >= 1.0 {
1321                            current.push(q);
1322                        } else {
1323                            current.push(at(t1));
1324                            flush(&mut current, &mut out);
1325                        }
1326                    } else {
1327                        flush(&mut current, &mut out);
1328                        current.push(at(t0));
1329                        if t1 >= 1.0 {
1330                            current.push(q);
1331                        } else {
1332                            current.push(at(t1));
1333                            flush(&mut current, &mut out);
1334                        }
1335                    }
1336                }
1337            }
1338        }
1339        flush(&mut current, &mut out);
1340    }
1341    out
1342}
1343
1344fn bounds_of(view: &ViewDrawing, placed: &PlacedView) -> [f64; 4] {
1345    let mut bounds = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY];
1346    let mut add = |p: [f64; 2]| {
1347        bounds[0] = bounds[0].min(p[0]);
1348        bounds[1] = bounds[1].min(p[1]);
1349        bounds[2] = bounds[2].max(p[0]);
1350        bounds[3] = bounds[3].max(p[1]);
1351    };
1352    for polyline in &view.edges {
1353        for point in polyline {
1354            add(*point);
1355        }
1356    }
1357    for annotation in &view.annotations {
1358        for polyline in &annotation.lines {
1359            for point in polyline {
1360                add(*point);
1361            }
1362        }
1363        for text in &annotation.texts {
1364            add(text.anchor);
1365        }
1366    }
1367    if let Some(section) = &view.section {
1368        for polyline in section.hatch.iter().chain(section.cut.iter()) {
1369            for point in polyline {
1370                add(*point);
1371            }
1372        }
1373        for text in &section.texts {
1374            add(text.anchor);
1375        }
1376    }
1377    for mark in &view.section_marks {
1378        for polyline in &mark.lines {
1379            for point in polyline {
1380                add(*point);
1381            }
1382        }
1383        for text in &mark.texts {
1384            add(text.anchor);
1385        }
1386    }
1387    if let Some(detail) = &view.detail {
1388        for point in &detail.circle {
1389            add(*point);
1390        }
1391        for text in &detail.texts {
1392            add(text.anchor);
1393        }
1394    }
1395    for mark in &view.detail_marks {
1396        for polyline in &mark.lines {
1397            for point in polyline {
1398                add(*point);
1399            }
1400        }
1401        for text in &mark.texts {
1402            add(text.anchor);
1403        }
1404    }
1405    if bounds[0] > bounds[2] {
1406        [placed.position[0], placed.position[1], placed.position[0], placed.position[1]]
1407    } else {
1408        bounds
1409    }
1410}
1411
1412// ---------------------------------------------------------------------------
1413// The exact solids
1414// ---------------------------------------------------------------------------
1415
1416/// One explode row's pose of a drawn solid: `p' = R((p − c) ∘ s) + c + t`, the
1417/// viewport's own formula (`pmi_ops`), read off the view's report.
1418#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
1419pub struct SolidPose {
1420    pub translate: [f64; 3],
1421    #[serde(rename = "rotateDeg")]
1422    pub rotate_deg: [f64; 3],
1423    pub scale: [f64; 3],
1424    pub center: [f64; 3],
1425}
1426
1427impl SolidPose {
1428    pub fn apply(&self, p: [f64; 3]) -> [f64; 3] {
1429        let (center, scale, translate) = (self.center, self.scale, self.translate);
1430        let local = [(p[0] - center[0]) * scale[0], (p[1] - center[1]) * scale[1], (p[2] - center[2]) * scale[2]];
1431        // Degrees, as the kernel's explode rows and balloon anchors read them.
1432        let rotated = crate::engine_state::rotate_euler_xyz_f64(local, self.rotate_deg.map(f64::to_radians));
1433        [
1434            rotated[0] + center[0] + translate[0],
1435            rotated[1] + center[1] + translate[1],
1436            rotated[2] + center[2] + translate[2],
1437        ]
1438    }
1439
1440    /// The pose as a column-major 4×4: p' = R·S·(p − c) + c + t, so the linear
1441    /// part is R·S and the translation c + t − R·S·c.
1442    pub fn matrix(&self) -> [f64; 16] {
1443        let radians = self.rotate_deg.map(f64::to_radians);
1444        let column = |axis: [f64; 3]| crate::engine_state::rotate_euler_xyz_f64(axis, radians);
1445        let cols = [
1446            column([self.scale[0], 0.0, 0.0]),
1447            column([0.0, self.scale[1], 0.0]),
1448            column([0.0, 0.0, self.scale[2]]),
1449        ];
1450        let c = self.center;
1451        let lc = [
1452            cols[0][0] * c[0] + cols[1][0] * c[1] + cols[2][0] * c[2],
1453            cols[0][1] * c[0] + cols[1][1] * c[1] + cols[2][1] * c[2],
1454            cols[0][2] * c[0] + cols[1][2] * c[1] + cols[2][2] * c[2],
1455        ];
1456        let t = [c[0] + self.translate[0] - lc[0], c[1] + self.translate[1] - lc[1], c[2] + self.translate[2] - lc[2]];
1457        [
1458            cols[0][0], cols[0][1], cols[0][2], 0.0,
1459            cols[1][0], cols[1][1], cols[1][2], 0.0,
1460            cols[2][0], cols[2][1], cols[2][2], 0.0,
1461            t[0], t[1], t[2], 1.0,
1462        ]
1463    }
1464
1465    /// The pose to the bit, as it enters an identity.
1466    fn identity(&self) -> String {
1467        let bits = |v: &[f64; 3]| format!("{:x},{:x},{:x}", v[0].to_bits(), v[1].to_bits(), v[2].to_bits());
1468        format!(
1469            "pose[{}|{}|{}|{}];",
1470            bits(&self.translate),
1471            bits(&self.rotate_deg),
1472            bits(&self.scale),
1473            bits(&self.center)
1474        )
1475    }
1476}
1477
1478/// Every pose the view's enabled, resolved explode rows apply to `name`, in
1479/// row order — what the exact pass and the mesh approximation both draw a
1480/// solid with.
1481pub(crate) fn poses_of(report: Option<&PmiViewReport>, name: &str) -> Vec<SolidPose> {
1482    let Some(report) = report else { return Vec::new() };
1483    report
1484        .annotations
1485        .iter()
1486        .filter(|row| row.enabled && row.status == PmiStatus::Ok)
1487        .filter_map(|row| match &row.geometry {
1488            brep_kernel::PmiGeometry::Explode { solids, translate, rotate_deg, scale, center, .. }
1489                if solids.iter().any(|target| target == name) =>
1490            {
1491                Some(SolidPose { translate: *translate, rotate_deg: *rotate_deg, scale: *scale, center: *center })
1492            }
1493            _ => None,
1494        })
1495        .collect()
1496}
1497
1498/// One solid of an exact pass, by what the RUNNER holds it as: its name, the
1499/// resident handle, the content fingerprint the main side read off its copy,
1500/// and the poses the view applies to it.
1501#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
1502pub struct LinesSolid {
1503    pub name: String,
1504    pub handle: u32,
1505    pub fingerprint: u64,
1506    pub poses: Vec<SolidPose>,
1507    /// The view's section leaves it whole (its **Not cut** list): a section
1508    /// draws it uncut and takes no cut from it.
1509    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1510    pub whole: bool,
1511}
1512
1513impl LinesSolid {
1514    /// What the drawn geometry IS: the content fingerprint and every pose
1515    /// applied to it, to the bit. Not the resident handle: a handle is unique
1516    /// only within one runner's registry, and a restarted runner or a second
1517    /// document tab counts from one again.
1518    fn identity(&self) -> String {
1519        let mut identity = format!("{}#{:016x};", self.name, self.fingerprint);
1520        for pose in &self.poses {
1521            identity.push_str(&pose.identity());
1522        }
1523        if self.whole {
1524            identity.push_str("whole;");
1525        }
1526        identity
1527    }
1528}
1529
1530/// The exact solids a saved view draws, as a PLAN: which B-rep each is and how
1531/// it is posed, without posing anything — a projection whose lines are cached,
1532/// or computed on the runner, never needs the posed copies on this side.
1533struct ExactPlan<'a> {
1534    solids: Vec<LinesSolid>,
1535    /// The main side's copy of each, unposed.
1536    sources: Vec<&'a brep_kernel::BrepSolid>,
1537    /// Each solid's identity, and all of them together.
1538    each: Vec<String>,
1539    identity: String,
1540}
1541
1542impl ExactPlan<'_> {
1543    /// The B-rep of every solid, POSED by the view's own explode rows.
1544    ///
1545    /// The pose is the view's, not the viewport's: the display meshes are posed
1546    /// only while a view is ACTIVE, and a sheet draws every placement's view at
1547    /// once. A pose is affine, and a NURBS carrier is invariant under an affine
1548    /// map of its control points, so the posed solid is exact.
1549    fn posed(&self) -> Vec<std::borrow::Cow<'_, brep_kernel::BrepSolid>> {
1550        self.solids
1551            .iter()
1552            .zip(&self.sources)
1553            .map(|(solid, source)| posed_solid(std::borrow::Cow::Borrowed(*source), &solid.poses))
1554            .collect()
1555    }
1556}
1557
1558fn posed_solid<'a>(
1559    solid: std::borrow::Cow<'a, brep_kernel::BrepSolid>,
1560    poses: &[SolidPose],
1561) -> std::borrow::Cow<'a, brep_kernel::BrepSolid> {
1562    poses.iter().fold(solid, |solid, pose| std::borrow::Cow::Owned(pose_solid(&solid, &|p| pose.apply(p))))
1563}
1564
1565/// Whether the view's section leaves solid `name` uncut (its **Not cut** list).
1566fn left_whole(view: &PmiView, name: &str) -> bool {
1567    view.display.section.as_ref().is_some_and(|section| section.excludes(name))
1568}
1569
1570/// The plan of every solid a saved view draws, or `None` when any of them has
1571/// no topology in the scene.
1572fn exact_solids<'a>(scene: &'a RenderScene, unposed: &Unposed, view: &PmiView, report: Option<&PmiViewReport>) -> Option<ExactPlan<'a>> {
1573    let mut plan = ExactPlan { solids: Vec::new(), sources: Vec::new(), each: Vec::new(), identity: String::new() };
1574    for solid in drawn_solids(scene, unposed, view) {
1575        let (brep, fingerprint) = scene.exact_solid_fingerprinted(&solid.name)?;
1576        let planned = LinesSolid {
1577            name: solid.name.clone(),
1578            handle: solid.source_handle,
1579            fingerprint,
1580            poses: poses_of(report, &solid.name),
1581            whole: left_whole(view, &solid.name),
1582        };
1583        plan.each.push(planned.identity());
1584        plan.solids.push(planned);
1585        plan.sources.push(brep);
1586    }
1587    plan.identity = plan.each.concat();
1588    Some(plan)
1589}
1590
1591// ---------------------------------------------------------------------------
1592// The exact lines, and the job that computes them off the UI thread
1593// ---------------------------------------------------------------------------
1594
1595/// What an exact pass is restricted to, as a job carries it: a SECTION's cap
1596/// is the cut the job computes itself, so it carries only a half section's
1597/// second plane.
1598#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
1599pub enum LinesClip {
1600    Whole,
1601    Circle { radius: f64 },
1602    Section { half: Option<super::hlr::HalfLine> },
1603}
1604
1605impl LinesClip {
1606    /// The clip's part of an exact-lines key.
1607    fn key(&self) -> String {
1608        match self {
1609            LinesClip::Whole => "whole".into(),
1610            LinesClip::Circle { radius } => format!("circle {:x}", radius.to_bits()),
1611            LinesClip::Section { half: None } => "section".into(),
1612            LinesClip::Section { half: Some(half) } => format!(
1613                "section half {:x},{:x},{:x}",
1614                half.normal[0].to_bits(),
1615                half.normal[1].to_bits(),
1616                half.offset.to_bits()
1617            ),
1618        }
1619    }
1620}
1621
1622/// ONE placement's analytic pass, as the runner is asked to run it: everything
1623/// `exact_lines` would compute on a miss, by reference to the runner's own
1624/// resident solids rather than a copy of them.
1625#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
1626pub struct LinesJob {
1627    /// The exact-lines key the answer is cached under.
1628    pub key: String,
1629    /// The placement it draws: a later job for the same placement SUPERSEDES
1630    /// this one (the engine drops a superseded answer).
1631    pub placement: String,
1632    pub solids: Vec<LinesSolid>,
1633    pub frame: ViewFrame,
1634    /// The placement at the paper origin — the lines are relative to it.
1635    pub placed: PlacedView,
1636    pub clip: LinesClip,
1637}
1638
1639/// What a projection does on an exact-lines MISS.
1640pub enum LinesMode<'a> {
1641    /// Run the pass here and now, on this thread — an export, a test, a runner
1642    /// that cannot run the job.
1643    Compute,
1644    /// Hand the job over. The answer comes back as the lines (a runner that
1645    /// answered at once), `None` while it is being computed elsewhere — the
1646    /// placement then draws its mesh approximation — or [`Deferred::Here`] to
1647    /// run it on this thread after all.
1648    Defer(&'a mut dyn FnMut(LinesJob) -> Deferred),
1649    /// An export waits for exact lines without drawing a mesh preview on the UI thread.
1650    Export(&'a mut dyn FnMut(LinesJob) -> Deferred),
1651}
1652
1653/// A deferred job's answer.
1654pub enum Deferred {
1655    Lines(ExactLines),
1656    Pending,
1657    Here,
1658}
1659
1660/// Run `job` against the resident registry of THIS thread — the runner's side
1661/// of [`LinesMode::Defer`]. Refused when the registry no longer holds a handle,
1662/// or holds different geometry under it than the main side fingerprinted (an
1663/// assembly solve re-poses a resident solid in place): lines of the wrong
1664/// geometry cached under this key would be a silent error.
1665pub fn run_lines_job(job: &LinesJob) -> Result<ExactLines, String> {
1666    let mut posed = Vec::with_capacity(job.solids.len());
1667    for solid in &job.solids {
1668        let brep = brep_kernel::registered_solid_clone(solid.handle)
1669            .map_err(|error| format!("'{}' (handle {}): {error}", solid.name, solid.handle))?;
1670        if crate::scene::brep_fingerprint(&brep) != solid.fingerprint {
1671            return Err(format!("'{}' changed under handle {}", solid.name, solid.handle));
1672        }
1673        posed.push(posed_solid(std::borrow::Cow::Owned(brep), &solid.poses).into_owned());
1674    }
1675    let solids: Vec<&brep_kernel::BrepSolid> = posed.iter().collect();
1676    let each: Vec<String> = job.solids.iter().map(LinesSolid::identity).collect();
1677    let whole: Vec<bool> = job.solids.iter().map(|solid| solid.whole).collect();
1678    Ok(compute_exact_lines(&solids, &each, &whole, &job.frame, &job.placed, job.clip))
1679}
1680
1681/// The analytic pass itself, relative to `origin` (a placement at the paper
1682/// origin): the visible runs and, for a section, the cut curves.
1683fn compute_exact_lines(
1684    solids: &[&brep_kernel::BrepSolid],
1685    each: &[String],
1686    whole: &[bool],
1687    frame: &ViewFrame,
1688    origin: &PlacedView,
1689    clip: LinesClip,
1690) -> ExactLines {
1691    let trims = solid_trims(each, solids);
1692    let trims: Vec<&super::hlr::SolidTrims> = trims.iter().map(|t| t.as_ref()).collect();
1693    match clip {
1694        LinesClip::Whole => ExactLines {
1695            runs: super::hlr::visible_edges_with(solids, &trims, frame, origin, &super::hlr::Clip::Whole).runs,
1696            cut: Vec::new(),
1697        },
1698        LinesClip::Circle { radius } => ExactLines {
1699            runs: super::hlr::visible_edges_with(solids, &trims, frame, origin, &super::hlr::Clip::Circle { radius }).runs,
1700            cut: Vec::new(),
1701        },
1702        LinesClip::Section { half } => {
1703            // The exact cut: the plane against every face, trimmed. Its curves
1704            // are the hatch's boundary, the cap that hides what is behind the
1705            // cut face, and model lines in their own right.
1706            // A solid the section leaves whole adds nothing to the cut, and a
1707            // half section's cut stops at its second plane.
1708            let cut_by = |index: &usize| !whole.get(*index).copied().unwrap_or(false);
1709            let cut_solids: Vec<&brep_kernel::BrepSolid> = (0..solids.len()).filter(cut_by).map(|i| solids[i]).collect();
1710            let cut_trims: Vec<&super::hlr::SolidTrims> = (0..solids.len()).filter(cut_by).map(|i| trims[i]).collect();
1711            let cut = super::hlr::section_curves_with(&cut_solids, &cut_trims, frame, origin);
1712            let cut = match half {
1713                Some(half) => close_on_half(cut, half, origin),
1714                None => cut,
1715            };
1716            let clip = super::hlr::Clip::Beyond { cap: &cut, whole, half };
1717            ExactLines { runs: super::hlr::visible_edges_with(solids, &trims, frame, origin, &clip).runs, cut }
1718        }
1719    }
1720}
1721
1722/// A placement's exact lines ON the paper at its position: from the cache,
1723/// else as `mode` says. `None` when the job was handed over and has not come
1724/// back — the caller draws the mesh approximation.
1725fn exact_lines_for(
1726    plan: &ExactPlan,
1727    frame: &ViewFrame,
1728    placed: &PlacedView,
1729    clip: LinesClip,
1730    mode: &mut LinesMode,
1731) -> Option<ExactLines> {
1732    let key = exact_key(&plan.identity, frame, placed.scale, &clip.key());
1733    let origin = PlacedView { position: [0.0, 0.0], ..placed.clone() };
1734    let relative = match cached_exact_lines(&key) {
1735        Some(lines) => lines,
1736        None => {
1737            let deferred = match mode {
1738                LinesMode::Compute => Deferred::Here,
1739                LinesMode::Defer(defer) | LinesMode::Export(defer) => defer(LinesJob {
1740                    key: key.clone(),
1741                    placement: placed.id.clone(),
1742                    solids: plan.solids.clone(),
1743                    frame: *frame,
1744                    placed: origin.clone(),
1745                    clip,
1746                }),
1747            };
1748            let lines = match deferred {
1749                Deferred::Lines(lines) => lines,
1750                Deferred::Pending => return None,
1751                Deferred::Here => {
1752                    let posed = plan.posed();
1753                    let solids: Vec<&brep_kernel::BrepSolid> = posed.iter().map(|solid| solid.as_ref()).collect();
1754                    let whole: Vec<bool> = plan.solids.iter().map(|solid| solid.whole).collect();
1755                    compute_exact_lines(&solids, &plan.each, &whole, frame, &origin, clip)
1756                }
1757            };
1758            store_exact_lines(key, lines.clone());
1759            lines
1760        }
1761    };
1762    let shift = |lines: Vec<Vec<[f64; 2]>>| -> Vec<Vec<[f64; 2]>> {
1763        lines
1764            .into_iter()
1765            .map(|line| line.into_iter().map(|p| [p[0] + placed.position[0], p[1] + placed.position[1]]).collect())
1766            .collect()
1767    };
1768    Some(ExactLines { runs: shift(relative.runs), cut: shift(relative.cut) })
1769}
1770
1771/// How many solids' trims the projection keeps: one for every placement the
1772/// exact-lines cache keeps.
1773const TRIM_CACHE_SOLIDS: usize = EXACT_CACHE_ENTRIES;
1774
1775thread_local! {
1776    /// Each drawn solid's [`super::hlr::SolidTrims`] by its identity (content
1777    /// fingerprint and pose): what the pass learns about a trim holds for any
1778    /// camera, scale or clip, so a new scale, a section or a detail of a part
1779    /// already drawn builds none of it again. Most recent last.
1780    static TRIM_CACHE: std::cell::RefCell<std::collections::VecDeque<(String, std::rc::Rc<super::hlr::SolidTrims>)>> =
1781        const { std::cell::RefCell::new(std::collections::VecDeque::new()) };
1782}
1783
1784
1785
1786/// The cached trims of each solid, built for any the cache does not hold.
1787fn solid_trims(identities: &[String], solids: &[&brep_kernel::BrepSolid]) -> Vec<std::rc::Rc<super::hlr::SolidTrims>> {
1788    TRIM_CACHE.with(|cache| {
1789        let mut cache = cache.borrow_mut();
1790        identities
1791            .iter()
1792            .zip(solids)
1793            .map(|(identity, solid)| {
1794                let trims = match cache.iter().position(|(key, _)| key == identity) {
1795                    Some(index) => cache.remove(index).map(|(_, trims)| trims).unwrap(),
1796                    None => std::rc::Rc::new(super::hlr::SolidTrims::of(solid)),
1797                };
1798                cache.push_back((identity.clone(), trims.clone()));
1799                while cache.len() > TRIM_CACHE_SOLIDS {
1800                    cache.pop_front();
1801                }
1802                trims
1803            })
1804            .collect()
1805    })
1806}
1807
1808/// The analytic pass's lines for one placement, RELATIVE to its position
1809/// (paper millimetres from the placement point): the visible runs and, for a
1810/// section, the cut curves. What a [`LinesJob`] answers with.
1811#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
1812pub struct ExactLines {
1813    pub runs: Vec<Vec<[f64; 2]>>,
1814    pub cut: Vec<Vec<[f64; 2]>>,
1815}
1816
1817/// How many placements' exact lines are kept.
1818const EXACT_CACHE_ENTRIES: usize = 64;
1819
1820thread_local! {
1821    /// The exact lines by what they depend on — the geometry's identity, the
1822    /// camera frame, the scale and the clip, never the placement's POSITION —
1823    /// so dragging a placement, dragging a PMI label or editing a dimension
1824    /// re-projects the sheet without re-running the pass. Most recent last.
1825    /// On the UI thread it is also where a job's answer lands
1826    /// ([`store_exact_lines`]).
1827    static EXACT_CACHE: std::cell::RefCell<std::collections::VecDeque<(String, ExactLines)>> =
1828        const { std::cell::RefCell::new(std::collections::VecDeque::new()) };
1829}
1830
1831/// The cached exact lines for `key`, relative to the placement point.
1832pub(crate) fn cached_exact_lines(key: &str) -> Option<ExactLines> {
1833    EXACT_CACHE.with(|cache| cache.borrow().iter().find(|(k, _)| k == key).map(|(_, lines)| lines.clone()))
1834}
1835
1836/// Keep `lines` under `key`, most recent last — a pass run here, or a job's
1837/// answer from the runner.
1838pub(crate) fn store_exact_lines(key: String, lines: ExactLines) {
1839    EXACT_CACHE.with(|cache| {
1840        let mut cache = cache.borrow_mut();
1841        cache.retain(|(k, _)| *k != key);
1842        cache.push_back((key, lines));
1843        while cache.len() > EXACT_CACHE_ENTRIES {
1844            cache.pop_front();
1845        }
1846    });
1847}
1848
1849/// The part of an exact-lines key a placement's frame, scale and clip give.
1850fn exact_key(identity: &str, frame: &ViewFrame, scale: f64, clip: &str) -> String {
1851    let bits = |v: [f64; 3]| format!("{:x},{:x},{:x}", v[0].to_bits(), v[1].to_bits(), v[2].to_bits());
1852    format!(
1853        "{identity}|{}|{}|{}|{}|{:x}|{clip}",
1854        bits(frame.target),
1855        bits(frame.right),
1856        bits(frame.up),
1857        bits(frame.forward),
1858        scale.to_bits()
1859    )
1860}
1861
1862/// `solid` with every model point mapped through the affine `pose`: vertices,
1863/// edge curves' and carriers' control points (a rational control point is
1864/// mapped as its Euclidean point and re-weighted). Carriers are REBUILT
1865/// rather than cloned, so no analytic recognition cached on the unposed
1866/// surface survives onto the posed one. Pcurves live in parameter space and
1867/// are unchanged.
1868fn pose_solid(solid: &brep_kernel::BrepSolid, pose: &dyn Fn([f64; 3]) -> [f64; 3]) -> brep_kernel::BrepSolid {
1869    let map = |cp: &brep_kernel::Vec4| -> brep_kernel::Vec4 {
1870        let w = if cp.w != 0.0 { cp.w } else { 1.0 };
1871        let p = pose([cp.x / w, cp.y / w, cp.z / w]);
1872        brep_kernel::Vec4 { x: p[0] * w, y: p[1] * w, z: p[2] * w, w: cp.w }
1873    };
1874    let mut out = solid.clone();
1875    for vertex in &mut out.vertices {
1876        let p = pose([vertex.point.x, vertex.point.y, vertex.point.z]);
1877        vertex.point = brep_kernel::Vec3::new(p[0], p[1], p[2]);
1878    }
1879    for edge in &mut out.edges {
1880        let points = edge.curve.control_points.iter().map(map).collect();
1881        if let Ok(curve) = brep_kernel::NurbsCurve::new(edge.curve.degree, edge.curve.knots.clone(), points) {
1882            edge.curve = curve;
1883        }
1884    }
1885    for shell in &mut out.shells {
1886        for face in &mut shell.faces {
1887            let s = &face.surface;
1888            let points = s.control_points.iter().map(|row| row.iter().map(map).collect()).collect();
1889            if let Ok(surface) =
1890                brep_kernel::NurbsSurface::new(s.degree_u, s.degree_v, s.knots_u.clone(), s.knots_v.clone(), points)
1891            {
1892                face.surface = surface;
1893            }
1894        }
1895    }
1896    out
1897}
1898
1899/// Polylines as the two-point segments [`hatch`] counts crossings against.
1900/// A half section's cut on the paper of a placement at `origin`: the section
1901/// curves on the side the second plane removes, closed along its line — each
1902/// run of the line between two crossings of the cut, taken in pairs, is the
1903/// edge the two cut faces share. The result is the region the hatch fills and
1904/// the cap hides behind, both of which read it by parity.
1905fn close_on_half(cut: Vec<Vec<[f64; 2]>>, half: super::hlr::HalfLine, origin: &PlacedView) -> Vec<Vec<[f64; 2]>> {
1906    let side = |p: [f64; 2]| {
1907        half.at([(p[0] - origin.position[0]) / origin.scale, (origin.position[1] - p[1]) / origin.scale, 0.0])
1908    };
1909    let mut out: Vec<Vec<[f64; 2]>> = Vec::new();
1910    let mut crossings: Vec<[f64; 2]> = Vec::new();
1911    for line in cut {
1912        let mut run: Vec<[f64; 2]> = Vec::new();
1913        for (i, &p) in line.iter().enumerate() {
1914            let g = side(p);
1915            if i > 0 {
1916                let q = line[i - 1];
1917                let h = side(q);
1918                if (h < 0.0) != (g < 0.0) {
1919                    let t = h / (h - g);
1920                    let x = [q[0] + (p[0] - q[0]) * t, q[1] + (p[1] - q[1]) * t];
1921                    crossings.push(x);
1922                    run.push(x);
1923                    if g >= 0.0 {
1924                        out.push(std::mem::take(&mut run));
1925                    }
1926                }
1927            }
1928            if g < 0.0 {
1929                run.push(p);
1930            }
1931        }
1932        if run.len() > 1 {
1933            out.push(run);
1934        }
1935    }
1936    // Along the line on the paper (y runs down the paper, so the paper
1937    // direction of the view's (−n_y, n_x) is (−n_y, −n_x)).
1938    let along = |p: &[f64; 2]| -p[0] * half.normal[1] - p[1] * half.normal[0];
1939    crossings.sort_by(|a, b| along(a).partial_cmp(&along(b)).unwrap_or(std::cmp::Ordering::Equal));
1940    out.extend(crossings.chunks_exact(2).map(|pair| vec![pair[0], pair[1]]));
1941    out.retain(|line| line.len() > 1);
1942    out
1943}
1944
1945fn segments_of(lines: &[Vec<[f64; 2]>]) -> Vec<Vec<[f64; 2]>> {
1946    lines.iter().flat_map(|line| line.windows(2).map(|w| vec![w[0], w[1]])).collect()
1947}
1948
1949// ---------------------------------------------------------------------------
1950// The drawn meshes
1951// ---------------------------------------------------------------------------
1952
1953/// The solids a saved view draws, each read UN-POSED (the viewport's active
1954/// view may have hidden or clipped it for its own section): visible, not
1955/// hidden by the view itself (`PmiView::hides`: its captured baseline or one
1956/// of its hide steps), and not a committed SKETCH (a drawing shows the model,
1957/// not the sketches it was built from).
1958fn drawn_solids<'a>(scene: &'a RenderScene, unposed: &'a Unposed, view: &PmiView) -> Vec<&'a crate::scene::SolidDisplay> {
1959    scene
1960        .solids()
1961        .iter()
1962        .map(|solid| unposed.get(&solid.name).unwrap_or(solid))
1963        .filter(|solid| solid.visible && !solid.is_sketch)
1964        .filter(|solid| !view.hides(&solid.name))
1965        .filter(|solid| solid.mesh.indices.len() >= 3)
1966        .collect()
1967}
1968
1969/// The names of every solid some placement of `sheet` draws: the solids whose
1970/// topology its exact pass needs.
1971pub fn sheet_solid_names(scene: &RenderScene, unposed: &Unposed, sheet: &super::Sheet, views: &[PmiView]) -> Vec<String> {
1972    let mut names: Vec<String> = Vec::new();
1973    for placed in &sheet.views {
1974        let Some(view) = views.iter().find(|view| view.id == placed.view) else { continue };
1975        for solid in drawn_solids(scene, unposed, view) {
1976            if !names.contains(&solid.name) {
1977                names.push(solid.name.clone());
1978            }
1979        }
1980    }
1981    names
1982}
1983
1984/// The DISPLAY each drawn solid is read from: the un-posed one where the
1985/// viewport's active view posed it in place, so every placement starts from
1986/// the model as built and applies its own view's poses.
1987fn drawn_displays<'a>(scene: &'a RenderScene, unposed: &'a Unposed, view: &PmiView) -> Vec<&'a crate::scene::SolidDisplay> {
1988    drawn_solids(scene, unposed, view)
1989}
1990
1991
1992/// Every drawn solid's DISPLAY as the mesh approximation reads it
1993/// ([`super::hlr::visible_mesh_lines`]), POSED by the view's own explode rows
1994/// exactly as the exact pass poses the B-rep: the triangles with their faces,
1995/// and every display edge that is a boundary of the model — not an auxiliary
1996/// or centreline edge — with the two topology VERTICES it runs between.
1997///
1998/// **The ends are the kernel's adjacency, recovered exactly.** A display edge
1999/// carries no vertex ids, but the tessellator writes an edge's first and last
2000/// samples AS its start and end vertex's own points
2001/// (`watertight_tessellation::edge_sampling`), and the display narrows both to
2002/// `f32` the same way. So an end whose `f32` bits are one display vertex's is
2003/// that vertex, with no distance and no bar; an end shared by two vertices
2004/// narrowed to one `f32` point is no vertex (nothing chains through it), and
2005/// so is an end that is none. The ends are read BEFORE the pose, off the
2006/// display's own numbers.
2007fn mesh_solids(displays: &[&crate::scene::SolidDisplay], report: Option<&PmiViewReport>) -> Vec<super::hlr::MeshSolid> {
2008    let world = |p: &[f32; 3]| [p[0] as f64, p[1] as f64, p[2] as f64];
2009    displays
2010        .iter()
2011        .map(|solid| {
2012            let poses = poses_of(report, &solid.name);
2013            let pose = |p: [f64; 3]| poses.iter().fold(p, |p, pose| pose.apply(p));
2014            let count = solid.mesh.positions.len();
2015            let (triangles, faces) = solid
2016                .mesh
2017                .indices
2018                .chunks_exact(3)
2019                .enumerate()
2020                .filter(|(_, c)| c.iter().all(|i| (*i as usize) < count))
2021                .map(|(t, c)| ([c[0], c[1], c[2]], solid.mesh.face_ids.get(t).copied().unwrap_or(u32::MAX)))
2022                .unzip();
2023            let bits = |p: [f32; 3]| [p[0].to_bits(), p[1].to_bits(), p[2].to_bits()];
2024            let mut at: std::collections::HashMap<[u32; 3], Option<u64>> = std::collections::HashMap::new();
2025            for vertex in &solid.vertices {
2026                let p = vertex.position;
2027                at.entry(bits([p[0] as f32, p[1] as f32, p[2] as f32]))
2028                    .and_modify(|id| *id = None)
2029                    .or_insert(Some(vertex.topo_id));
2030            }
2031            let vertex_of = |p: &[f32; 3]| at.get(&bits(*p)).copied().flatten();
2032            super::hlr::MeshSolid {
2033                positions: solid.mesh.positions.iter().map(|p| pose(world(p))).collect(),
2034                triangles,
2035                faces,
2036                edges: solid
2037                    .edges
2038                    .iter()
2039                    .filter(|edge| !edge.aux && !edge.centerline && edge.polyline.len() >= 2)
2040                    .map(|edge| super::hlr::MeshEdge {
2041                        points: edge.polyline.iter().map(|p| pose(world(p))).collect(),
2042                        ends: vertex_of(&edge.polyline[0]).zip(vertex_of(edge.polyline.last().unwrap())),
2043                    })
2044                    .collect(),
2045            }
2046        })
2047        .collect()
2048}
2049
2050/// How many placements' mesh approximations are kept.
2051const MESH_CACHE_ENTRIES: usize = 16;
2052
2053thread_local! {
2054    /// The mesh approximation's lines by what they depend on — each drawn
2055    /// display's content revision and poses, the camera frame, the scale, the
2056    /// clip and a section's plane — never the placement's position, exactly as
2057    /// the exact lines are kept. A placement waiting for its exact pass is
2058    /// re-projected by every edit on the sheet, and the approximation of a
2059    /// large part is tens of milliseconds a time. Most recent last.
2060    static MESH_CACHE: std::cell::RefCell<std::collections::VecDeque<(String, ExactLines)>> =
2061        const { std::cell::RefCell::new(std::collections::VecDeque::new()) };
2062}
2063
2064/// A placement's mesh approximation ON the paper at its position: the runs
2065/// and, for a section, the cut through the display triangles.
2066#[allow(clippy::too_many_arguments)]
2067fn mesh_lines_for(
2068    scene: &RenderScene,
2069    unposed: &Unposed,
2070    view: &PmiView,
2071    report: Option<&PmiViewReport>,
2072    frame: &ViewFrame,
2073    placed: &PlacedView,
2074    clip: LinesClip,
2075    plane: Option<&ClipPlane>,
2076) -> ExactLines {
2077    let displays = drawn_displays(scene, unposed, view);
2078    let mut identity = String::from("mesh|");
2079    let whole: Vec<bool> = displays.iter().map(|display| left_whole(view, &display.name)).collect();
2080    for (display, whole) in displays.iter().zip(&whole) {
2081        identity.push_str(&format!("{}@{};", display.name, display.revision));
2082        for pose in poses_of(report, &display.name) {
2083            identity.push_str(&pose.identity());
2084        }
2085        if *whole {
2086            identity.push_str("whole;");
2087        }
2088    }
2089    let bits = |v: [f64; 3]| format!("{:x},{:x},{:x}", v[0].to_bits(), v[1].to_bits(), v[2].to_bits());
2090    let plane_key = plane.map(|plane| format!("{}|{}", bits(plane.point), bits(plane.normal))).unwrap_or_default();
2091    let key = exact_key(&identity, frame, placed.scale, &format!("{}{plane_key}", clip.key()));
2092    let hit = MESH_CACHE.with(|cache| cache.borrow().iter().find(|(k, _)| *k == key).map(|(_, lines)| lines.clone()));
2093    let relative = match hit {
2094        Some(lines) => lines,
2095        None => {
2096            let origin = PlacedView { position: [0.0, 0.0], ..placed.clone() };
2097            let meshes = mesh_solids(&displays, report);
2098            let lines = match (clip, plane) {
2099                (LinesClip::Section { half }, Some(plane)) => {
2100                    let cut_meshes: Vec<_> = meshes.iter().zip(&whole).filter(|(_, whole)| !**whole).map(|(mesh, _)| mesh.clone()).collect();
2101                    let cut: Vec<Vec<[f64; 2]>> = mesh_cut(&cut_meshes, plane)
2102                        .iter()
2103                        .map(|segment| {
2104                            segment
2105                                .iter()
2106                                .map(|p| {
2107                                    let v = frame.to_view(*p);
2108                                    to_paper(&origin, v[0], v[1])
2109                                })
2110                                .collect()
2111                        })
2112                        .collect();
2113                    let cut = match half {
2114                        Some(half) => close_on_half(cut, half, &origin),
2115                        None => cut,
2116                    };
2117                    let beyond = super::hlr::Clip::Beyond { cap: &cut, whole: &whole, half };
2118                    ExactLines { runs: super::hlr::visible_mesh_lines(&meshes, frame, &origin, &beyond).runs, cut }
2119                }
2120                (LinesClip::Circle { radius }, _) => ExactLines {
2121                    runs: super::hlr::visible_mesh_lines(&meshes, frame, &origin, &super::hlr::Clip::Circle { radius }).runs,
2122                    cut: Vec::new(),
2123                },
2124                _ => ExactLines {
2125                    runs: super::hlr::visible_mesh_lines(&meshes, frame, &origin, &super::hlr::Clip::Whole).runs,
2126                    cut: Vec::new(),
2127                },
2128            };
2129            MESH_CACHE.with(|cache| {
2130                let mut cache = cache.borrow_mut();
2131                cache.push_back((key, lines.clone()));
2132                while cache.len() > MESH_CACHE_ENTRIES {
2133                    cache.pop_front();
2134                }
2135            });
2136            lines
2137        }
2138    };
2139    let shift = |lines: Vec<Vec<[f64; 2]>>| -> Vec<Vec<[f64; 2]>> {
2140        lines
2141            .into_iter()
2142            .map(|line| line.into_iter().map(|p| [p[0] + placed.position[0], p[1] + placed.position[1]]).collect())
2143            .collect()
2144    };
2145    ExactLines { runs: shift(relative.runs), cut: shift(relative.cut) }
2146}
2147
2148// ---------------------------------------------------------------------------
2149// The cutting plane
2150// ---------------------------------------------------------------------------
2151
2152/// The half-space a SECTION placement draws: everything with
2153/// `(p \u{2212} point) \u{00B7} normal >= 0` is KEPT, and `normal` is the direction the
2154/// section camera looks.
2155///
2156/// Because the camera looks ALONG the normal, the cutting plane is a plane of
2157/// CONSTANT view depth — and the plane passes through the camera's target, so
2158/// that depth is exactly zero. Everything that follows leans on it: the pass
2159/// keeps what is at or beyond depth zero, the cut region is a cap at one depth,
2160/// and the hatch is a plain two-dimensional fill. A section view is defined as
2161/// the one that looks straight down its own cutting plane's normal.
2162#[derive(Debug, Clone, Copy)]
2163pub struct ClipPlane {
2164    pub point: [f64; 3],
2165    pub normal: [f64; 3],
2166}
2167
2168/// The mesh approximation's cut: the segment where the plane crosses each
2169/// display triangle that keeps area on the kept side — the section's outline
2170/// and the region its hatch fills and its cap hides behind, while the exact
2171/// cut ([`super::hlr::section_curves`]) waits for the B-rep.
2172fn mesh_cut(meshes: &[super::hlr::MeshSolid], plane: &ClipPlane) -> Vec<[[f64; 3]; 2]> {
2173    // The on-plane bar, relative to the model's own extent: a vertex this
2174    // close to the plane IS on it, and treating it as one side or the other
2175    // would open the cut boundary by one triangle.
2176    let mut extent: f64 = 0.0;
2177    for mesh in meshes {
2178        for p in &mesh.positions {
2179            extent = extent.max(dot(sub(*p, plane.point), plane.normal).abs());
2180        }
2181    }
2182    let eps = (extent * 1e-9).max(f64::MIN_POSITIVE);
2183
2184    let mut cut: Vec<[[f64; 3]; 2]> = Vec::new();
2185    for mesh in meshes {
2186        let side: Vec<f64> = mesh
2187            .positions
2188            .iter()
2189            .map(|p| dot(sub(*p, plane.point), plane.normal))
2190            .collect();
2191        for tri in &mesh.triangles {
2192            let corners = [tri[0] as usize, tri[1] as usize, tri[2] as usize];
2193            let d = [side[corners[0]], side[corners[1]], side[corners[2]]];
2194            if d.iter().all(|v| *v < -eps) || d.iter().all(|v| *v > eps) {
2195                continue; // wholly cut away, or wholly kept
2196            }
2197            // Straddling (or touching): walk the edges, counting what is on or
2198            // in front of the plane and collecting the crossing points.
2199            let mut kept = 0;
2200            let mut on_plane: Vec<[f64; 3]> = Vec::with_capacity(2);
2201            for k in 0..3 {
2202                let (i, j) = (k, (k + 1) % 3);
2203                let (pi, pj) = (mesh.positions[corners[i]], mesh.positions[corners[j]]);
2204                let (di, dj) = (d[i], d[j]);
2205                if di >= -eps {
2206                    kept += 1;
2207                    if di.abs() <= eps {
2208                        on_plane.push(pi);
2209                    }
2210                }
2211                if (di > eps && dj < -eps) || (di < -eps && dj > eps) {
2212                    let t = di / (di - dj);
2213                    kept += 1;
2214                    on_plane.push([
2215                        pi[0] + (pj[0] - pi[0]) * t,
2216                        pi[1] + (pj[1] - pi[1]) * t,
2217                        pi[2] + (pj[2] - pi[2]) * t,
2218                    ]);
2219                }
2220            }
2221            // A cut edge belongs to the triangle that KEPT AREA on it, and to
2222            // exactly that one. Two on-plane points is the edge; three is a
2223            // triangle lying IN the plane, whose own edges already bound the
2224            // region, and one is a triangle touching the plane at a corner.
2225            //
2226            // The kept-area half is not a nicety. A cutting plane through a
2227            // mesh VERTEX RING — which is what a plane through the middle of a
2228            // tessellated cylinder is, and hardly a rare accident — gives the
2229            // ring's edge to two triangles at once: the one above it, which
2230            // keeps a real triangle, and the one below, which is cut away
2231            // entirely and keeps only that edge. Counting both would put the
2232            // boundary in twice, and an even-odd fill crossing a boundary
2233            // twice reads the inside as the outside.
2234            if kept >= 3 && on_plane.len() == 2 {
2235                cut.push([on_plane[0], on_plane[1]]);
2236            }
2237        }
2238    }
2239    cut
2240}
2241
2242/// The hatch over a cut region: parallel 45\u{00B0} paper lines, each kept only
2243/// where an EVEN-ODD crossing count against the cut boundary says it is inside
2244/// the material.
2245///
2246/// Even-odd against the SEGMENTS rather than against chained loops, on purpose:
2247/// the cut of a closed solid is a closed set of curves however the segments
2248/// happen to group, so the parity is right without a chaining pass that could
2249/// break a loop at a vertex three edges meet in — and a section through a bore
2250/// is exactly such a region, an outer loop with a hole in it.
2251fn hatch(cut: &[Vec<[f64; 2]>]) -> Vec<Vec<[f64; 2]>> {
2252    if cut.is_empty() {
2253        return Vec::new();
2254    }
2255    // The hatch runs up and to the right; `n` is its normal, so a line of the
2256    // family is `p \u{00B7} n = c` and a point's place ALONG it is `p \u{00B7} u`.
2257    let d = std::f64::consts::FRAC_1_SQRT_2;
2258    let u = [d, -d];
2259    let n = [d, d];
2260    let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
2261    for segment in cut {
2262        for p in segment {
2263            let c = p[0] * n[0] + p[1] * n[1];
2264            lo = lo.min(c);
2265            hi = hi.max(c);
2266        }
2267    }
2268    if !lo.is_finite() || hi <= lo {
2269        return Vec::new();
2270    }
2271    let mut spacing = HATCH_SPACING_MM;
2272    while (hi - lo) / spacing > MAX_HATCH_LINES as f64 {
2273        spacing *= 2.0;
2274    }
2275    // Start on a multiple of the spacing, so two sections of the same drawing
2276    // hatch in step rather than each from its own corner.
2277    let first = (lo / spacing).ceil() * spacing;
2278    let mut out = Vec::new();
2279    let mut c = first;
2280    while c <= hi {
2281        let mut crossings: Vec<f64> = Vec::new();
2282        for segment in cut {
2283            let (a, b) = (segment[0], segment[segment.len() - 1]);
2284            let (ca, cb) = (a[0] * n[0] + a[1] * n[1], b[0] * n[0] + b[1] * n[1]);
2285            // Half-open in `c`, so a vertex two segments share is counted once
2286            // and the parity survives it.
2287            if (ca <= c) == (cb <= c) {
2288                continue;
2289            }
2290            let t = (c - ca) / (cb - ca);
2291            let hit = [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t];
2292            crossings.push(hit[0] * u[0] + hit[1] * u[1]);
2293        }
2294        crossings.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
2295        for pair in crossings.chunks_exact(2) {
2296            if pair[1] - pair[0] < 1e-9 {
2297                continue;
2298            }
2299            out.push(vec![
2300                [u[0] * pair[0] + n[0] * c, u[1] * pair[0] + n[1] * c],
2301                [u[0] * pair[1] + n[0] * c, u[1] * pair[1] + n[1] * c],
2302            ]);
2303        }
2304        c += spacing;
2305    }
2306    out
2307}
2308
2309// ---------------------------------------------------------------------------
2310// Anchor candidates
2311// ---------------------------------------------------------------------------
2312
2313/// The angular span a circular edge must cover before it is offered as a
2314/// CIRCLE anchor. Three samples fix a circle exactly, but three samples a
2315/// degree apart fix it badly: a short fillet rim would hand a radial dimension
2316/// a centre with no precision behind it.
2317const CIRCLE_MIN_SPAN_DEG: f64 = 20.0;
2318
2319/// How far a sampled point may sit off the fitted circle, as a fraction of the
2320/// radius, before the edge is not a circle. The display polyline is SAMPLED on
2321/// the curve, so a real circular edge misses by f32 rounding alone; anything
2322/// looser than this is a spline that happens to start out round.
2323const CIRCLE_FIT_TOLERANCE: f64 = 1e-4;
2324
2325/// How far a sampled point may sit off the CHORD, as a fraction of the chord's
2326/// length, before the display edge is not STRAIGHT. The same bar as the circle
2327/// fit and for the same reason: the polyline is sampled on the curve, so a real
2328/// straight edge misses its own chord by f32 rounding alone.
2329const STRAIGHT_TOLERANCE: f64 = 1e-4;
2330
2331/// Every point of this placement's projection a sheet dimension can anchor to.
2332///
2333/// One candidate per display VERTEX, three per named display EDGE (its two
2334/// ends and its midpoint by arc length) and one more per CIRCULAR edge, at the
2335/// circle's projected centre. Visibility plays no part: the hidden-line pass
2336/// decides what ink the model leaves on the paper, and the anchor space is the
2337/// model's topology.
2338fn anchor_points(
2339    scene: &RenderScene,
2340    unposed: &Unposed,
2341    view: &PmiView,
2342    report: Option<&PmiViewReport>,
2343    frame: &ViewFrame,
2344    placed: &PlacedView,
2345) -> Vec<AnchorPoint> {
2346    let project = |p: [f64; 3]| -> [f64; 2] {
2347        let v = frame.to_view(p);
2348        to_paper(placed, v[0], v[1])
2349    };
2350    let mut out = Vec::new();
2351    for solid in drawn_displays(scene, unposed, view) {
2352        // The anchors are where the placement DRAWS the model: posed by its
2353        // own view's explode rows, as the lines are.
2354        let poses = poses_of(report, &solid.name);
2355        let pose = |p: [f64; 3]| poses.iter().fold(p, |p, pose| pose.apply(p));
2356        for vertex in &solid.vertices {
2357            out.push(AnchorPoint {
2358                anchor: super::dimension::SheetAnchor::vertex(&placed.id, &solid.name, vertex.topo_id)
2359                    .to_ref(),
2360                kind: super::dimension::VERTEX.to_string(),
2361                at: project(pose(vertex.position)),
2362                model: pose(vertex.position),
2363                dir: None,
2364                radius: None,
2365                u: None,
2366                v: None,
2367            });
2368        }
2369        for edge in &solid.edges {
2370            // An edge with no name cannot be REFERRED to, and an auxiliary or
2371            // centreline display edge is not a BREP boundary — neither is a
2372            // point of the model a drawing may dimension.
2373            if edge.name.is_empty() || edge.aux || edge.centerline || edge.polyline.len() < 2 {
2374                continue;
2375            }
2376            let points: Vec<[f64; 3]> = edge
2377                .polyline
2378                .iter()
2379                .map(|p| pose([p[0] as f64, p[1] as f64, p[2] as f64]))
2380                .collect();
2381            // The EDGE's own paper direction, once — every fraction of it
2382            // carries the same one, because it is the edge's and not the
2383            // point's. `None` on a curved edge, which an angular dimension
2384            // refuses by name.
2385            let dir = straight_chord(&points).and_then(|d| {
2386                let paper = [dot(d, frame.right), -dot(d, frame.up)];
2387                let length = (paper[0] * paper[0] + paper[1] * paper[1]).sqrt();
2388                (length > 1e-9).then(|| [paper[0] / length, paper[1] / length])
2389            });
2390            for fraction in [0.0, 0.5, 1.0] {
2391                let Some(point) = along(&points, fraction) else { continue };
2392                out.push(AnchorPoint {
2393                    anchor: super::dimension::SheetAnchor::edge(
2394                        &placed.id,
2395                        &solid.name,
2396                        &edge.name,
2397                        fraction,
2398                    )
2399                    .to_ref(),
2400                    kind: super::dimension::EDGE.to_string(),
2401                    at: project(point),
2402                    model: point,
2403                    dir,
2404                    radius: None,
2405                    u: None,
2406                    v: None,
2407                });
2408            }
2409            if let Some((centre, axis, radius)) = fit_circle(&points) {
2410                // The projected circle is an ellipse: `u` and `v` are the paper
2411                // images of one pair of conjugate radii, which is everything a
2412                // radial dimension needs to find where its leader meets the rim.
2413                let u3 = norm(sub(points[0], centre));
2414                let v3 = cross(axis, u3);
2415                let image = |d: [f64; 3]| -> [f64; 2] {
2416                    [
2417                        dot(d, frame.right) * radius * placed.scale,
2418                        -dot(d, frame.up) * radius * placed.scale,
2419                    ]
2420                };
2421                out.push(AnchorPoint {
2422                    anchor: super::dimension::SheetAnchor::circle(&placed.id, &solid.name, &edge.name)
2423                        .to_ref(),
2424                    kind: super::dimension::CIRCLE.to_string(),
2425                    at: project(centre),
2426                    model: centre,
2427                    dir: None,
2428                    radius: Some(radius),
2429                    u: Some(image(u3)),
2430                    v: Some(image(v3)),
2431                });
2432            }
2433        }
2434    }
2435    out
2436}
2437
2438/// The unit MODEL direction of a straight display edge, or `None` when the
2439/// polyline is curved or closed on itself.
2440///
2441/// Straight means every SAMPLE lies on the chord between the two ends, within
2442/// [`STRAIGHT_TOLERANCE`] of its length. Judged in the model rather than on the
2443/// paper on purpose: a circular edge seen edge-on projects to a straight
2444/// segment, and an angle measured to it would be an angle to nothing.
2445fn straight_chord(points: &[[f64; 3]]) -> Option<[f64; 3]> {
2446    let (first, last) = (*points.first()?, *points.last()?);
2447    let span = sub(last, first);
2448    let length = dot(span, span).sqrt();
2449    if length < 1e-12 {
2450        // A closed edge (a full circle) has no chord at all.
2451        return None;
2452    }
2453    let direction = [span[0] / length, span[1] / length, span[2] / length];
2454    let bar = length * STRAIGHT_TOLERANCE;
2455    for point in points {
2456        let offset = sub(*point, first);
2457        let along = dot(offset, direction);
2458        let away = [
2459            offset[0] - direction[0] * along,
2460            offset[1] - direction[1] * along,
2461            offset[2] - direction[2] * along,
2462        ];
2463        if dot(away, away).sqrt() > bar {
2464            return None;
2465        }
2466    }
2467    Some(direction)
2468}
2469
2470/// The point `fraction` of the way along a polyline BY ARC LENGTH.
2471fn along(points: &[[f64; 3]], fraction: f64) -> Option<[f64; 3]> {
2472    if points.len() < 2 {
2473        return None;
2474    }
2475    let steps: Vec<f64> = points
2476        .windows(2)
2477        .map(|pair| dot(sub(pair[1], pair[0]), sub(pair[1], pair[0])).sqrt())
2478        .collect();
2479    let total: f64 = steps.iter().sum();
2480    if !(total > 0.0) {
2481        return Some(points[0]);
2482    }
2483    let target = total * fraction.clamp(0.0, 1.0);
2484    let mut walked = 0.0;
2485    for (index, step) in steps.iter().enumerate() {
2486        if walked + step >= target || index + 1 == steps.len() {
2487            let t = if *step > 0.0 { ((target - walked) / step).clamp(0.0, 1.0) } else { 0.0 };
2488            let (a, b) = (points[index], points[index + 1]);
2489            return Some([
2490                a[0] + (b[0] - a[0]) * t,
2491                a[1] + (b[1] - a[1]) * t,
2492                a[2] + (b[2] - a[2]) * t,
2493            ]);
2494        }
2495        walked += step;
2496    }
2497    points.last().copied()
2498}
2499
2500/// `(centre, unit axis, radius)` when every sampled point of `points` lies on
2501/// one circle, else `None`.
2502///
2503/// The circle through three of the samples, then VERIFIED against all of them:
2504/// a display polyline is sampled ON its curve, so a real circular edge's
2505/// samples sit on that circle to f32 rounding while a spline's do not. The
2506/// axis follows the right-hand rule along the polyline's own direction, the
2507/// kernel's `SelectionGeometry::Circle` convention.
2508fn fit_circle(points: &[[f64; 3]]) -> Option<([f64; 3], [f64; 3], f64)> {
2509    if points.len() < 4 {
2510        return None;
2511    }
2512    let last = points.len() - 1;
2513    let (a, b, c) = (points[0], points[last / 3], points[last * 2 / 3]);
2514    let (ab, ac) = (sub(b, a), sub(c, a));
2515    let n = cross(ab, ac);
2516    let n2 = dot(n, n);
2517    if n2 < 1e-24 {
2518        return None;
2519    }
2520    // The circumcentre of a triangle, in the triangle's own plane.
2521    let centre = {
2522        let (ab2, ac2) = (dot(ab, ab), dot(ac, ac));
2523        let to = cross(
2524            [
2525                ab2 * ac[0] - ac2 * ab[0],
2526                ab2 * ac[1] - ac2 * ab[1],
2527                ab2 * ac[2] - ac2 * ab[2],
2528            ],
2529            n,
2530        );
2531        [
2532            a[0] + to[0] / (2.0 * n2),
2533            a[1] + to[1] / (2.0 * n2),
2534            a[2] + to[2] / (2.0 * n2),
2535        ]
2536    };
2537    let axis = norm(n);
2538    let radius = dot(sub(a, centre), sub(a, centre)).sqrt();
2539    if !(radius > 1e-12) {
2540        return None;
2541    }
2542    let bar = radius * CIRCLE_FIT_TOLERANCE;
2543    for p in points {
2544        let d = sub(*p, centre);
2545        if (dot(d, d).sqrt() - radius).abs() > bar || dot(d, axis).abs() > bar {
2546            return None;
2547        }
2548    }
2549    // A rim too short to fit reliably is not offered: three samples a degree
2550    // apart give a centre with no precision behind it.
2551    let first = norm(sub(points[0], centre));
2552    let mut span = 0.0;
2553    for p in points {
2554        let d = norm(sub(*p, centre));
2555        let angle = dot(d, first).clamp(-1.0, 1.0).acos();
2556        span = f64::max(span, angle);
2557    }
2558    if span.to_degrees() < CIRCLE_MIN_SPAN_DEG {
2559        return None;
2560    }
2561    Some((centre, axis, radius))
2562}
2563
2564// ---------------------------------------------------------------------------
2565// Annotations
2566// ---------------------------------------------------------------------------
2567
2568/// A blocking box in paper millimetres: `centre`, the paper images of one
2569/// LOCAL unit along the box's own two axes, and the half extents in those
2570/// units. The axes are a text run's own — under an oblique projection they
2571/// are sheared, so the box is a parallelogram and not a rotated rectangle.
2572#[derive(Debug, Clone, Copy)]
2573struct Box2 {
2574    centre: [f64; 2],
2575    right: [f64; 2],
2576    up: [f64; 2],
2577    half: [f64; 2],
2578}
2579
2580impl Box2 {
2581    /// `p` in the box's own units, or `None` when the basis is DEGENERATE —
2582    /// an edge-on plane projects its two axes onto one line, and a box with
2583    /// no area blocks nothing.
2584    fn local(&self, p: [f64; 2]) -> Option<[f64; 2]> {
2585        let det = self.right[0] * self.up[1] - self.right[1] * self.up[0];
2586        if det.abs() < 1e-12 {
2587            return None;
2588        }
2589        let d = [p[0] - self.centre[0], p[1] - self.centre[1]];
2590        Some([
2591            (d[0] * self.up[1] - d[1] * self.up[0]) / det,
2592            (d[1] * self.right[0] - d[0] * self.right[1]) / det,
2593        ])
2594    }
2595
2596    /// The box a text run occupies: its own basis, its character extent in
2597    /// cap heights, and [`TEXT_PAD`] of clearance on every side.
2598    fn of_text(run: &SheetText) -> Box2 {
2599        let rows = run.text.lines().count().max(1) as f64;
2600        Box2 {
2601            centre: run.anchor,
2602            right: run.right,
2603            up: run.up,
2604            half: [text_half_width(&run.text, 1.0), rows * 0.5 + TEXT_PAD],
2605        }
2606    }
2607}
2608
2609/// How far a FLAT run of `text` at cap height `height` blocks a line either
2610/// side of its anchor along its reading direction: its character extent at
2611/// [`TEXT_ADVANCE`] plus [`TEXT_PAD`] of clearance — the box
2612/// [`break_for_text_boxes`] breaks a line with.
2613pub(super) fn text_half_width(text: &str, height: f64) -> f64 {
2614    let columns = text.lines().map(|line| line.chars().count()).max().unwrap_or(0) as f64;
2615    (columns * TEXT_ADVANCE * 0.5 + TEXT_PAD) * height
2616}
2617
2618/// Break `lines` where a text run — or a framed symbol's outline — sits.
2619///
2620/// The kernel's layout runs the dimension line THROUGH the label — the
2621/// viewport hides that under the label's chip and the STEP presentation leaves
2622/// it — but a sheet has no chip and a value struck through by its own
2623/// dimension line is not a drawing. Breaking the line is a SHEET-layer
2624/// decision, so it is made here rather than in the shared layout: the gap is
2625/// the text's own box plus a clearance, subtracted from every line of the same
2626/// annotation. A framed symbol (an FCF, a datum) adds its FRAME as a box with
2627/// no clearance, which is what re-attaches its leader to the box's nearest
2628/// edge when the frame has been flattened out from under it. The frame's own
2629/// outline is never offered to this pass — it would erase itself.
2630fn break_for_text(lines: Vec<Vec<[f64; 2]>>, boxes: &[Box2]) -> Vec<Vec<[f64; 2]>> {
2631    if boxes.is_empty() {
2632        return lines;
2633    }
2634    let mut out: Vec<Vec<[f64; 2]>> = Vec::new();
2635    for line in lines {
2636        // Each run of consecutive UNBROKEN segments becomes one polyline.
2637        let mut current: Vec<[f64; 2]> = Vec::new();
2638        for pair in line.windows(2) {
2639            let (p, q) = (pair[0], pair[1]);
2640            let mut kept = visible_spans(p, q, boxes);
2641            if kept.is_empty() {
2642                if current.len() >= 2 {
2643                    out.push(std::mem::take(&mut current));
2644                } else {
2645                    current.clear();
2646                }
2647                continue;
2648            }
2649            let full = kept.len() == 1 && kept[0].0 <= 0.0 && kept[0].1 >= 1.0;
2650            let at = |t: f64| [p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t];
2651            if full {
2652                if current.is_empty() {
2653                    current.push(p);
2654                }
2655                current.push(q);
2656                continue;
2657            }
2658            // A broken segment ends whatever was running and contributes its
2659            // own pieces.
2660            if !kept.is_empty() && kept[0].0 <= 0.0 {
2661                let (_, end) = kept.remove(0);
2662                if current.is_empty() {
2663                    current.push(p);
2664                }
2665                current.push(at(end));
2666            }
2667            if current.len() >= 2 {
2668                out.push(std::mem::take(&mut current));
2669            } else {
2670                current.clear();
2671            }
2672            for (start, end) in kept {
2673                if end >= 1.0 {
2674                    current = vec![at(start), q];
2675                } else {
2676                    out.push(vec![at(start), at(end)]);
2677                }
2678            }
2679        }
2680        if current.len() >= 2 {
2681            out.push(current);
2682        }
2683    }
2684    out
2685}
2686
2687/// Break `lines` around the text `runs` — the door [`super::dimension`] uses,
2688/// so a sheet dimension's value is cleared out of its own dimension line by
2689/// the very same pass that clears a placed annotation's.
2690pub(super) fn break_for_text_boxes(
2691    lines: Vec<Vec<[f64; 2]>>,
2692    runs: &[SheetText],
2693) -> Vec<Vec<[f64; 2]>> {
2694    let boxes: Vec<Box2> = runs.iter().map(Box2::of_text).collect();
2695    break_for_text(lines, &boxes)
2696}
2697
2698/// The parameter spans of segment `p`→`q` that lie OUTSIDE every box, as
2699/// `(start, end)` pairs in increasing order.
2700fn visible_spans(p: [f64; 2], q: [f64; 2], boxes: &[Box2]) -> Vec<(f64, f64)> {
2701    let mut blocked: Vec<(f64, f64)> = Vec::new();
2702    for box2 in boxes {
2703        let (Some(a), Some(b)) = (box2.local(p), box2.local(q)) else {
2704            continue;
2705        };
2706        // Liang-Barsky against the box's two slabs.
2707        let (mut t0, mut t1) = (0.0f64, 1.0f64);
2708        let mut inside = true;
2709        for (axis, half) in [(0usize, box2.half[0]), (1usize, box2.half[1])] {
2710            let delta = b[axis] - a[axis];
2711            if delta.abs() < 1e-12 {
2712                if a[axis].abs() > half {
2713                    inside = false;
2714                    break;
2715                }
2716                continue;
2717            }
2718            let (lo, hi) = ((-half - a[axis]) / delta, (half - a[axis]) / delta);
2719            let (lo, hi) = if lo <= hi { (lo, hi) } else { (hi, lo) };
2720            t0 = t0.max(lo);
2721            t1 = t1.min(hi);
2722            if t0 > t1 {
2723                inside = false;
2724                break;
2725            }
2726        }
2727        if inside && t1 > t0 {
2728            blocked.push((t0, t1));
2729        }
2730    }
2731    if blocked.is_empty() {
2732        return vec![(0.0, 1.0)];
2733    }
2734    blocked.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
2735    let mut spans = Vec::new();
2736    let mut cursor = 0.0f64;
2737    for (start, end) in blocked {
2738        if start > cursor + 1e-9 {
2739            spans.push((cursor, start.min(1.0)));
2740        }
2741        cursor = cursor.max(end);
2742        if cursor >= 1.0 {
2743            break;
2744        }
2745    }
2746    if cursor < 1.0 - 1e-9 {
2747        spans.push((cursor, 1.0));
2748    }
2749    spans
2750}
2751
2752/// Whether an annotation plane is EDGE-ON to a view looking along `forward`:
2753/// its normal perpendicular to the viewing direction, so the plane and
2754/// everything laid out in it project onto one line. An annotation with no
2755/// picked plane is laid out in the view's own plane and is never edge-on.
2756pub fn plane_is_edge_on(row: &PmiAnnotationReport, forward: [f64; 3]) -> bool {
2757    match row.plane.as_ref() {
2758        None => false,
2759        Some(plane) => dot(norm(plane.normal), forward).abs() < EDGE_ON_COS,
2760    }
2761}
2762
2763/// The view's PMI dimensions a sheet dimension can inherit a tolerance from:
2764/// every enabled, resolved free linear, radial or diametral row whose params
2765/// carry a tolerance block or the reference flag (the kernel's own
2766/// `ToleranceBlock::read`, against the document's expressions), with its
2767/// measured points through the view camera.
2768fn tolerance_sources(
2769    report: Option<&PmiViewReport>,
2770    view: &PmiView,
2771    frame: &ViewFrame,
2772    placed: &PlacedView,
2773    env: &brep_kernel::Env,
2774) -> Vec<ToleranceSource> {
2775    let Some(report) = report else { return Vec::new() };
2776    let project = |p: [f64; 3]| -> [f64; 2] {
2777        let v = frame.to_view(p);
2778        to_paper(placed, v[0], v[1])
2779    };
2780    let mut out = Vec::new();
2781    for row in report.annotations.iter().filter(|row| row.enabled && row.status == PmiStatus::Ok) {
2782        let Some(annotation) = view.annotations.iter().find(|annotation| annotation.id() == row.id) else { continue };
2783        let Ok(block) = brep_kernel::ToleranceBlock::read(annotation, env) else { continue };
2784        let reference = annotation.flag("isReference");
2785        if block.mode == brep_kernel::ToleranceMode::None && !reference {
2786            continue;
2787        }
2788        let measures = match &row.geometry {
2789            brep_kernel::PmiGeometry::Linear { a, b, component: None } => Measures::Linear { a: project(*a), b: project(*b) },
2790            brep_kernel::PmiGeometry::Radial { center, radius, diameter, sphere: false, .. } => {
2791                Measures::Radial { centre: project(*center), radius: *radius, diameter: *diameter }
2792            }
2793            _ => continue,
2794        };
2795        out.push(ToleranceSource { id: row.id.clone(), measures, block, reference });
2796    }
2797    out
2798}
2799
2800fn annotations(
2801    report: Option<&PmiViewReport>,
2802    view: &PmiView,
2803    frame: &ViewFrame,
2804    placed: &PlacedView,
2805) -> Vec<AnnotationDrawing> {
2806    let Some(report) = report else {
2807        return Vec::new();
2808    };
2809    // The text is sized on PAPER: a view's text size is in points, so the
2810    // model-unit cap height the layout needs is the paper height over the
2811    // placement's scale.
2812    let paper_text = view.display.text_size_pt * MM_PER_POINT;
2813    let text_height = paper_text / placed.scale.max(1e-9);
2814    let style = PmiLayoutStyle {
2815        arrow: text_height * ARROW_PER_TEXT,
2816        text_height,
2817        view_dir: frame.forward,
2818        view_up: frame.up,
2819        plane: None,
2820    };
2821    let flatten = placed.flatten_text;
2822    let mut out = Vec::new();
2823    for row in &report.annotations {
2824        if !row.enabled || row.status != PmiStatus::Ok {
2825            continue;
2826        }
2827        let row_style = PmiLayoutStyle { plane: row.plane, ..style };
2828        let drawn = pmi_present(&row.geometry, row.label_world, &row.text, &row_style);
2829        // Paper millimetres, through the view camera — the ONE map every
2830        // piece of an annotation's geometry goes through.
2831        let project = |p: [f64; 3]| -> [f64; 2] {
2832            let v = frame.to_view(p);
2833            to_paper(placed, v[0], v[1])
2834        };
2835        let project_line = |polyline: &Vec<[f64; 3]>| -> Vec<[f64; 2]> {
2836            polyline.iter().map(|p| project(*p)).collect()
2837        };
2838        let mut lines: Vec<Vec<[f64; 2]>> = drawn.polylines.iter().map(project_line).collect();
2839        // Arrowheads are CLOSED outlines here: the sheet's output contract is
2840        // lines and text, so a filled head is drawn as its border.
2841        for arrow in &drawn.arrows {
2842            let mut closed: Vec<[f64; 3]> = arrow.to_vec();
2843            closed.push(arrow[0]);
2844            lines.push(project_line(&closed));
2845        }
2846
2847        // Every run of one annotation is laid out in the SAME in-plane basis
2848        // (the layout's `right` / `up`), so the first run carries it — read
2849        // rather than re-derived, because the basis is the kernel's. A FRAMED
2850        // symbol — an FCF's cells, a datum's box — is then ONE unit about the
2851        // annotation's anchor: flattening rotates the frame and its cells
2852        // together, so the cells keep their order and their spacing.
2853        let unit = drawn
2854            .texts
2855            .first()
2856            .filter(|_| !drawn.frames.is_empty())
2857            .map(|run| Unit {
2858                anchor: drawn.text_anchor,
2859                right: run.right,
2860                up: run.up,
2861                cap: run.height,
2862            });
2863        // A point of a FLATTENED piece: its offset from the anchor measured
2864        // in the layout's own in-plane basis, laid straight onto the paper at
2865        // sheet scale — the anchor's PROJECTED position kept, everything
2866        // about it turned flat and back to its unforeshortened size.
2867        let flat_about = |anchor: [f64; 3], right3: [f64; 3], up3: [f64; 3], p: [f64; 3]| -> [f64; 2] {
2868            let d = sub(p, anchor);
2869            let a = project(anchor);
2870            [a[0] + dot(d, right3) * placed.scale, a[1] - dot(d, up3) * placed.scale]
2871        };
2872
2873        // An explode step draws NO label, on a sheet as in the 3D view (owner
2874        // 2026-10-26: "I don't want to see the exploded labels at all";
2875        // 2026-10-27, on a placed view: "Exploding a part should not result
2876        // in any additional text being displayed"). The layout gives every
2877        // row one text run as its fallback; the 3D overlay never reads the
2878        // runs (its chip pass skips the kind) and the PDF's 3D model leaves
2879        // the row out (`pdf3d::drawable`), so the sheet was the one consumer
2880        // that drew it. The step's dashed trace line stays: it is the row's
2881        // own `showTraceLine`, and the viewport draws it too.
2882        // (The layout itself gives neither step a fallback run any more; this
2883        // keeps the sheet honest should one ever come back. A hide step is
2884        // the same: it draws nothing.)
2885        let explode = matches!(row.geometry, brep_kernel::PmiGeometry::Explode { .. } | brep_kernel::PmiGeometry::Hide { .. });
2886        let texts: Vec<SheetText> = drawn
2887            .texts
2888            .iter()
2889            .filter(|run| !explode && !run.text.trim().is_empty())
2890            .map(|run| {
2891                let cap = run.height * placed.scale;
2892                if flatten {
2893                    // Reading left to right at the run's sheet-scale size,
2894                    // about its own anchor — or about the unit's, when it is
2895                    // one cell of a framed symbol that turns as a whole.
2896                    let anchor = match unit {
2897                        Some(unit) => flat_about(unit.anchor, unit.right, unit.up, run.anchor),
2898                        None => project(run.anchor),
2899                    };
2900                    return SheetText::flat(run.text.clone(), anchor, cap);
2901                }
2902                // The paper image of one cap height along a unit direction.
2903                let image = |v: [f64; 3]| -> [f64; 2] {
2904                    [dot(v, frame.right) * cap, -dot(v, frame.up) * cap]
2905                };
2906                let mut right = image(run.right);
2907                // A plane seen from BEHIND mirrors its geometry — that is
2908                // what a projection does — but never its text: negating the
2909                // reading direction spans the very same parallelogram, so the
2910                // box stays where it lies and the glyphs still read forward.
2911                if dot(cross(run.right, run.up), frame.forward) > 0.0 {
2912                    right = [-right[0], -right[1]];
2913                }
2914                SheetText::new(run.text.clone(), project(run.anchor), right, image(run.up))
2915            })
2916            .collect();
2917
2918        // The frames follow their unit; everything else — leaders, dimension
2919        // and extension lines, arrowheads — is projected either way.
2920        let frames: Vec<Vec<[f64; 2]>> = match (flatten, unit) {
2921            (true, Some(unit)) => drawn
2922                .frames
2923                .iter()
2924                .map(|polyline| {
2925                    polyline
2926                        .iter()
2927                        .map(|p| flat_about(unit.anchor, unit.right, unit.up, *p))
2928                        .collect()
2929                })
2930                .collect(),
2931            _ => drawn.frames.iter().map(project_line).collect(),
2932        };
2933        // A framed symbol's outline is exempt from the line breaking (it
2934        // would erase itself) and instead becomes a box of its own, which is
2935        // what re-attaches the leader to the flattened frame's nearest edge.
2936        let mut boxes: Vec<Box2> = texts.iter().map(Box2::of_text).collect();
2937        if let Some(unit) = unit {
2938            let scaled = unit.cap * placed.scale;
2939            let (right, up) = if flatten {
2940                ([scaled, 0.0], [0.0, -scaled])
2941            } else {
2942                let image = |v: [f64; 3]| [dot(v, frame.right) * scaled, -dot(v, frame.up) * scaled];
2943                (image(unit.right), image(unit.up))
2944            };
2945            if let Some(box2) = unit.box_of(&drawn.frames, project(unit.anchor), right, up) {
2946                boxes.push(box2);
2947            }
2948        }
2949        let mut lines = break_for_text(lines, &boxes);
2950        lines.extend(frames);
2951
2952        out.push(AnnotationDrawing {
2953            id: row.id.clone(),
2954            kind: row.kind.clone(),
2955            text: row.text.clone(),
2956            lines,
2957            texts,
2958            note: if !plane_is_edge_on(row, frame.forward) {
2959                String::new()
2960            } else if flatten {
2961                format!(
2962                    "annotation plane edge-on to '{}': its geometry projects to a line, its text is flattened onto the sheet",
2963                    view.name
2964                )
2965            } else {
2966                format!(
2967                    "annotation plane edge-on to '{}': it and its text project to a line",
2968                    view.name
2969                )
2970            },
2971        });
2972    }
2973    out
2974}
2975
2976/// A FRAMED symbol — an FCF's row of cells, a datum's lettered box — as one
2977/// piece: the annotation's anchor and the layout's own in-plane basis, with
2978/// the cap height its sizes are measured in. The frame and its cells flatten
2979/// together about `anchor`, which is what keeps the cells in order and
2980/// evenly spaced whatever the annotation plane does to the view.
2981#[derive(Debug, Clone, Copy)]
2982struct Unit {
2983    anchor: [f64; 3],
2984    right: [f64; 3],
2985    up: [f64; 3],
2986    cap: f64,
2987}
2988
2989impl Unit {
2990    /// The box the unit's outline occupies, measured in the layout's own
2991    /// basis about the anchor and mapped to paper through the basis it was
2992    /// DRAWN with — so an oblique plane with the toggle off gives the
2993    /// projected parallelogram and not its bounding rectangle. No clearance:
2994    /// a leader is meant to TOUCH the frame.
2995    fn box_of(
2996        &self,
2997        frames: &[Vec<[f64; 3]>],
2998        anchor: [f64; 2],
2999        right: [f64; 2],
3000        up: [f64; 2],
3001    ) -> Option<Box2> {
3002        if self.cap <= 0.0 {
3003            return None;
3004        }
3005        let mut lo = [f64::INFINITY; 2];
3006        let mut hi = [f64::NEG_INFINITY; 2];
3007        for polyline in frames {
3008            for p in polyline {
3009                let d = sub(*p, self.anchor);
3010                let local = [dot(d, self.right) / self.cap, dot(d, self.up) / self.cap];
3011                for axis in 0..2 {
3012                    lo[axis] = lo[axis].min(local[axis]);
3013                    hi[axis] = hi[axis].max(local[axis]);
3014                }
3015            }
3016        }
3017        if lo[0] > hi[0] {
3018            return None;
3019        }
3020        let mid = [(lo[0] + hi[0]) * 0.5, (lo[1] + hi[1]) * 0.5];
3021        Some(Box2 {
3022            centre: [
3023                anchor[0] + mid[0] * right[0] + mid[1] * up[0],
3024                anchor[1] + mid[0] * right[1] + mid[1] * up[1],
3025            ],
3026            right,
3027            up,
3028            half: [(hi[0] - lo[0]) * 0.5, (hi[1] - lo[1]) * 0.5],
3029        })
3030    }
3031}
3032
3033
3034
3035