Skip to main content

brep_kernel/feature_pipeline/pmi/
mod.rs

1//! PMI — Product and Manufacturing Information: the document's `pmi` block
2//! (views that own annotations), the annotation type table with its schemas
3//! and selection predicates, and the history tail that resolves every
4//! annotation against the just-built scene into a typed [`PmiReport`].
5//!
6//! # The `pmi` block
7//!
8//! `{ views: [{ id, name, camera?, display, annotations: [...] }], idCounter }`
9//! on the history request, round-tripped through the saved document and
10//! ABSENT on every document without PMI (so those files re-serialize
11//! byte-identically). A **view** is a named camera snapshot plus display
12//! state (text size, wireframe, section; what it hides is its hide steps) plus an
13//! ordered list of annotations; a saved view maps to an AP242
14//! `DRAUGHTING_MODEL` + `CAMERA_MODEL_D3` on export and is the unit a future
15//! drawing sheet places. What a view hides is its **hide steps** (`hide`
16//! annotations naming solids / components, tracked like explode steps; the
17//! solids hidden at capture are its baseline step): [`PmiView::hides`] is the one
18//! rule every consumer reads, and the report lists the outcome per view.
19//!
20//! An **annotation** is `{ type, enabled, inputParams, labelWorld? }`: its
21//! params follow a kernel schema exactly like a feature's or an assembly
22//! constraint's (`inputParams.id` is its id, `{SHORT}{n}` minted from the
23//! block's counter), so the app's dialog engine draws every annotation form
24//! from [`pmi_schema_catalogue`] and nothing is hand-written. Geometry is
25//! referenced by kernel entity NAME (faces / edges, `{solid}@x,y,z` vertices
26//! in WORLD coordinates, D/P frame names) — plain and component-owned
27//! geometry alike — so a rebuilt model re-resolves every value and a renamed
28//! or deleted entity puts the annotation into an error status without ever
29//! aborting the view or the run.
30//!
31//! Every drawn annotation has an **annotation plane**: its optional `plane`
32//! reference names a planar face or a reference plane the annotation lies
33//! IN (label projected onto it, drags stay in it, the dimension / extension
34//! lines and frames drawn in it, the AP242 `ANNOTATION_PLANE` placed on it);
35//! left empty, the annotation aligns to the view camera. A picked plane must
36//! be parallel to what it carries — a linear dimension's direction, an
37//! angle's or a circle's plane — or the annotation reports an error rather
38//! than a foreshortened value. Drawing sheets will show, per sheet view, the
39//! annotations whose plane is parallel to the view.
40//!
41//! # The tail
42//!
43//! `finish_history_run` runs after the wire-harness tail on every run and
44//! resolves EVERY view's annotations (a few name lookups each) into a
45//! [`PmiReport`]: per annotation the status, the display text (value +
46//! tolerance block, kernel-formatted so the viewport and the STEP file agree),
47//! the measured value, the resolved analytic geometry the presentation is laid
48//! out from ([`layout`]) and the label position (stored, or a default derived
49//! from the geometry). The report rides `HistoryResult.pmi` (never the JSON
50//! ABI) and the render crate's scene report across the runner seam. Nothing
51//! here touches the incremental feature cache: PMI is annotation state, not
52//! history, and a label drag never re-executes a feature.
53//!
54//! # Measurement contracts (kernel queries only)
55//!
56//! Every value is read from the exact BREP through `crate::assembly_resolve`
57//! (planes, carrier lines, circles, axes, points) — never from tessellation.
58//! Linear: point–point, point–line (perpendicular), line–line (carrier lines:
59//! parallel spacing or closest points), point–plane, parallel plane spacing,
60//! single straight edge length, optional X/Y/Z component. Radial: cylinder /
61//! sphere / circular edge radius from the face metadata. Angle: the two
62//! elements' directions folded to acute / obtuse / reflex, optionally
63//! reversed. Hole callout: the owning Hole feature's parameters. Datum letters
64//! are unique per part; a feature control frame's datum references must name
65//! defined datums.
66
67pub mod anchor;
68pub mod annotations;
69pub mod font;
70pub mod layout;
71pub mod resolve;
72pub mod weld_symbol;
73mod plugin;
74pub use plugin::{PluginAnnotationOutput, PluginAnnotationReplay};
75
76use serde::{Deserialize, Serialize};
77use serde_json::Value;
78use std::collections::BTreeMap;
79
80use crate::feature_pipeline::{Env, HistoryRequest, SceneMap};
81
82pub use anchor::{
83    balloon_head, nearest_displayed_point, nearest_displayed_point_on_edge, nearest_point_on_edge, nearest_point_on_solid,
84    pose_apply, pose_unapply, BalloonAnchor, BalloonAnchorMode, HalfSpace, HeadScope, PmiPose, SolidPoses,
85};
86pub use annotations::{pmi_schema_catalogue, pmi_type, PmiTypeDef, PMI_TYPES};
87
88// ===========================================================================
89// The persisted block
90// ===========================================================================
91
92/// The document's `pmi` block. Loading it folds every view's legacy
93/// `display.hidden` list into that view's baseline hide step (see
94/// [`PmiDisplay`]), so every reader — the run, the parts library, STEP
95/// export, plugins, the 3D PDF — sees one representation.
96#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
97#[serde(from = "PmiStateWire")]
98pub struct PmiState {
99    #[serde(default)]
100    pub views: Vec<PmiView>,
101    /// Mints every view AND annotation id (`VIEW{n}`, `DIM{n}`, …); monotonic,
102    /// never reused, re-seeded from the largest numeric suffix on load.
103    #[serde(default, rename = "idCounter")]
104    pub id_counter: u64,
105}
106
107/// [`PmiState`] as stored, before the legacy hidden lists are folded in.
108#[derive(Deserialize)]
109struct PmiStateWire {
110    #[serde(default)]
111    views: Vec<PmiView>,
112    #[serde(default, rename = "idCounter")]
113    id_counter: u64,
114}
115
116impl From<PmiStateWire> for PmiState {
117    fn from(wire: PmiStateWire) -> Self {
118        let mut state = PmiState { views: wire.views, id_counter: wire.id_counter };
119        for index in 0..state.views.len() {
120            let legacy = std::mem::take(&mut state.views[index].display.legacy_hidden);
121            if legacy.is_empty() {
122                continue;
123            }
124            let mut names = state.views[index].baseline_hidden();
125            for name in legacy {
126                if !names.contains(&name) {
127                    names.push(name);
128                }
129            }
130            let id = state.views[index].id.clone();
131            state.set_view_baseline(&id, &names);
132        }
133        state
134    }
135}
136
137/// A PMI view: a camera snapshot, display state and the annotations it owns.
138#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
139pub struct PmiView {
140    pub id: String,
141    #[serde(default)]
142    pub name: String,
143    #[serde(default, skip_serializing_if = "Option::is_none")]
144    pub camera: Option<PmiCamera>,
145    #[serde(default)]
146    pub display: PmiDisplay,
147    #[serde(default)]
148    pub annotations: Vec<PmiAnnotation>,
149}
150
151/// The camera snapshot: eye / target / up / projection / viewport size — the
152/// render crate's `ViewCamera` minus near/far, which are a per-frame depth
153/// window and never persisted. Applying a snapshot under another viewport
154/// aspect refits the frustum, preserving the apparent size at the target.
155#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
156pub struct PmiCamera {
157    pub eye: [f64; 3],
158    pub target: [f64; 3],
159    pub up: [f64; 3],
160    pub projection: PmiProjection,
161    /// `[width, height]` of the viewport the snapshot was taken in (CSS px).
162    #[serde(default = "default_viewport")]
163    pub viewport: [f64; 2],
164}
165
166fn default_viewport() -> [f64; 2] {
167    [1280.0, 800.0]
168}
169
170impl PmiCamera {
171    /// The unit viewing direction (eye → target).
172    pub fn view_direction(&self) -> [f64; 3] {
173        let d = [
174            self.target[0] - self.eye[0],
175            self.target[1] - self.eye[1],
176            self.target[2] - self.eye[2],
177        ];
178        let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
179        if len < 1e-12 {
180            [0.0, 0.0, -1.0]
181        } else {
182            [d[0] / len, d[1] / len, d[2] / len]
183        }
184    }
185}
186
187#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
188#[serde(tag = "kind", rename_all = "camelCase")]
189pub enum PmiProjection {
190    Orthographic {
191        #[serde(rename = "halfHeight")]
192        half_height: f64,
193    },
194    Perspective {
195        #[serde(rename = "fovYDeg")]
196        fov_y_deg: f64,
197    },
198}
199
200/// Per-view display state.
201#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
202pub struct PmiDisplay {
203    /// Label text size in points, clamped to `[1, 288]`.
204    #[serde(default = "default_text_size", rename = "textSizePt")]
205    pub text_size_pt: f64,
206    #[serde(default)]
207    pub wireframe: bool,
208    /// The pre-2026-11-05 captured baseline (`display.hidden`), read and never
209    /// written: loading a [`PmiState`] folds it into the view's baseline
210    /// **hide step** ([`PmiAnnotation::is_baseline_hide`]), so what a view
211    /// hides has one representation, its hide steps ([`PmiView::hides`]).
212    #[serde(default, rename = "hidden", skip_serializing)]
213    legacy_hidden: Vec<String>,
214    #[serde(default, skip_serializing_if = "Option::is_none")]
215    pub section: Option<PmiSection>,
216}
217
218impl PmiDisplay {
219    /// A view's display state: what it hides lives in its hide steps.
220    pub fn new(text_size_pt: f64, wireframe: bool, section: Option<PmiSection>) -> Self {
221        Self { text_size_pt, wireframe, legacy_hidden: Vec::new(), section }
222    }
223}
224
225/// A display-only half-space through `origin` plus an offset along the normal.
226///
227/// `origin` (and, for the `View` axis, `normal`) is frozen from the captured
228/// camera when the section is set, so re-capturing the camera does not move
229/// the cut. A section saved before they existed reads the camera instead.
230/// The `Plane` axis takes both from `plane`, a planar face or reference plane
231/// the run resolves each time (see [`PmiViewReport::section_plane`]).
232#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
233pub struct PmiSection {
234    pub axis: String,
235    pub offset: f64,
236    #[serde(default)]
237    pub flip: bool,
238    #[serde(default, skip_serializing_if = "Option::is_none")]
239    pub origin: Option<[f64; 3]>,
240    #[serde(default, skip_serializing_if = "Option::is_none")]
241    pub normal: Option<[f64; 3]>,
242    #[serde(default, skip_serializing_if = "Option::is_none")]
243    pub plane: Option<String>,
244    /// Solids and components the cut leaves whole (shafts, fasteners): a
245    /// solid's scene name, or a component id standing for all its solids.
246    #[serde(default, skip_serializing_if = "Vec::is_empty")]
247    pub exclude: Vec<String>,
248    /// Further cutting planes. Material is removed only where EVERY plane
249    /// removes it: one more plane makes a half section (a quarter cut away),
250    /// two more a corner cut away. Each is an axis through the section's
251    /// origin, offset along its normal.
252    #[serde(default, skip_serializing_if = "Vec::is_empty")]
253    pub planes: Vec<PmiSectionPlane>,
254}
255
256/// One further plane of a [`PmiSection`]: `X`, `Y`, `Z` or `View` (the
257/// captured camera's direction, frozen in `normal` when set), `offset` along
258/// it from the section's origin, `flip` keeping the other side.
259#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
260pub struct PmiSectionPlane {
261    pub axis: String,
262    #[serde(default)]
263    pub offset: f64,
264    #[serde(default)]
265    pub flip: bool,
266    #[serde(default, skip_serializing_if = "Option::is_none")]
267    pub normal: Option<[f64; 3]>,
268}
269
270impl PmiSectionPlane {
271    /// The unflipped normal: the axis's, else (`View`) the frozen one, else
272    /// the camera's view direction. `None` for an unknown axis.
273    pub fn axis_normal(&self, camera: Option<&PmiCamera>) -> Option<[f64; 3]> {
274        match self.axis.as_str() {
275            "X" => Some([1., 0., 0.]),
276            "Y" => Some([0., 1., 0.]),
277            "Z" => Some([0., 0., 1.]),
278            "View" => self.normal.or_else(|| camera.map(PmiCamera::view_direction)),
279            _ => None,
280        }
281    }
282}
283/// Whether a SOLID / COMPONENT list entry names `solid`: the solid itself,
284/// or a component it belongs to (`ACOMP1` covers `ACOMP1:Part` and a nested
285/// `ACOMP1:ACOMP2:Part`; a prefix of a longer name, `ACOMP1` for
286/// `ACOMP10:Part`, is not the name). The rule a section's **Not cut** list
287/// and a view's hide steps share.
288pub fn entry_names_solid(entry: &str, solid: &str) -> bool {
289    let entry = entry.trim();
290    !entry.is_empty() && (solid == entry || solid.strip_prefix(entry).is_some_and(|rest| rest.starts_with(':')))
291}
292
293impl PmiSection {
294    /// Whether the solid named `solid` is left uncut: it is listed, or it
295    /// belongs to a listed component (`ACOMP1` covers `ACOMP1:Part` and a
296    /// nested `ACOMP1:ACOMP2:Part`).
297    pub fn excludes(&self, solid: &str) -> bool {
298        self.exclude.iter().any(|entry| entry_names_solid(entry, solid))
299    }
300
301    /// The unflipped normal: the axis's, else (`View`) the frozen one, else
302    /// the camera's view direction.
303    pub fn axis_normal(&self, camera: Option<&PmiCamera>) -> Option<[f64; 3]> {
304        match self.axis.as_str() {
305            "X" => Some([1., 0., 0.]),
306            "Y" => Some([0., 1., 0.]),
307            "Z" => Some([0., 0., 1.]),
308            "Plane" => self.normal,
309            _ => self.normal.or_else(|| camera.map(PmiCamera::view_direction)),
310        }
311    }
312
313    /// Fill a missing `origin` / `View` normal from `camera`, so the plane
314    /// stops depending on it.
315    pub fn freeze(&mut self, camera: Option<&PmiCamera>) {
316        if self.axis == "Plane" {
317            // Resolved from `plane` on every run, never from the camera.
318            self.origin = None;
319            self.normal = None;
320            return;
321        }
322        self.plane = None;
323        let Some(camera) = camera else { return };
324        for plane in &mut self.planes {
325            if plane.axis == "View" {
326                plane.normal.get_or_insert(camera.view_direction());
327            } else {
328                plane.normal = None;
329            }
330        }
331        self.origin.get_or_insert(camera.target);
332        if self.axis == "View" {
333            self.normal.get_or_insert(camera.view_direction());
334        } else {
335            self.normal = None;
336        }
337    }
338}
339impl PmiView {
340    pub fn section_plane(&self) -> Option<([f64; 3], [f64; 3])> {
341        let section = self.display.section.as_ref()?;
342        let camera = self.camera.as_ref();
343        let mut normal = section.axis_normal(camera)?;
344        let origin = section.origin.or_else(|| camera.filter(|_| section.axis != "Plane").map(|c| c.target))?;
345        let point = std::array::from_fn(|i| origin[i] + normal[i] * section.offset);
346        if section.flip {
347            normal = normal.map(|v| -v);
348        }
349        Some((point, normal))
350    }
351
352    /// [`Self::section_plane`], taking a `Plane` section's plane from the
353    /// view's last report (the document stores only the reference's name).
354    pub fn section_plane_in(&self, report: Option<&PmiViewReport>) -> Option<([f64; 3], [f64; 3])> {
355        match self.display.section.as_ref() {
356            Some(section) if section.axis == "Plane" => report.and_then(|report| report.section_plane),
357            _ => self.section_plane(),
358        }
359    }
360
361    /// Every cutting plane of the view's section, `(point, kept-side
362    /// normal)`, the first being [`Self::section_plane_in`]'s: empty without
363    /// a section (or when its first plane does not resolve). A further plane
364    /// goes through the section's origin (else the camera target, else the
365    /// first plane's point) plus its offset; an unknown axis is skipped.
366    pub fn section_planes_in(&self, report: Option<&PmiViewReport>) -> Vec<([f64; 3], [f64; 3])> {
367        self.section_plane_in(report).map_or_else(Vec::new, |first| self.with_further_planes(first))
368    }
369
370    /// [`Self::section_planes_in`] from [`Self::section_plane`] (a `Plane`
371    /// section resolved into the view itself, as the run does).
372    pub fn section_planes(&self) -> Vec<([f64; 3], [f64; 3])> {
373        self.section_plane().map_or_else(Vec::new, |first| self.with_further_planes(first))
374    }
375
376    fn with_further_planes(&self, first: ([f64; 3], [f64; 3])) -> Vec<([f64; 3], [f64; 3])> {
377        let mut planes = vec![first];
378        let Some(section) = self.display.section.as_ref() else { return planes };
379        let camera = self.camera.as_ref();
380        let origin = section.origin.or_else(|| camera.filter(|_| section.axis != "Plane").map(|c| c.target)).unwrap_or(first.0);
381        for plane in &section.planes {
382            let Some(mut normal) = plane.axis_normal(camera) else { continue };
383            let point = std::array::from_fn(|i| origin[i] + normal[i] * plane.offset);
384            if plane.flip {
385                normal = normal.map(|v| -v);
386            }
387            planes.push((point, normal));
388        }
389        planes
390    }
391}
392
393/// The `hide` step param marking a view's **baseline** step: the solids
394/// hidden when the view was captured (or a generated instructions step's
395/// not-yet-placed parts, or a pre-2026-11-05 `display.hidden` list). A name
396/// in it that no longer exists is skipped, not an error.
397pub const HIDE_BASELINE_PARAM: &str = "baseline";
398
399/// The id a view's baseline hide step is given: `HID-{view id}`, unique (one
400/// baseline per view) and derived, so making one never advances the
401/// document's id counter and every id minted after it stays what it was.
402pub fn baseline_hide_id(view_id: &str) -> String {
403    format!("{}-{view_id}", annotations::hide::DEF.short_name)
404}
405
406impl PmiAnnotation {
407    /// A `hide` step `id` naming `targets`; `baseline` marks the view's
408    /// captured baseline ([`HIDE_BASELINE_PARAM`]).
409    pub fn hide_step(id: &str, targets: &[String], baseline: bool) -> Self {
410        let mut params = serde_json::json!({ "id": id, "targets": targets });
411        if baseline {
412            params[HIDE_BASELINE_PARAM] = Value::Bool(true);
413        }
414        Self {
415            kind: annotations::hide::DEF.type_id.to_string(),
416            enabled: true,
417            params,
418            persistent_data: Value::Null,
419            plugin_replay: None,
420            label_world: None,
421        }
422    }
423
424    /// Whether this is a view's baseline hide step.
425    pub fn is_baseline_hide(&self) -> bool {
426        self.kind == annotations::hide::DEF.type_id && self.flag(HIDE_BASELINE_PARAM)
427    }
428}
429
430impl PmiView {
431    /// Whether this view hides the solid named `solid`: an ENABLED hide step
432    /// (its baseline among them) names it or a component it belongs to
433    /// ([`entry_names_solid`]). Names only, no run needed: the viewport
434    /// applies it the moment a step is added, edited, removed or undone, and
435    /// the sheets, the 3D PDF and the instructions pictures read the same
436    /// answer.
437    pub fn hides(&self, solid: &str) -> bool {
438        self.hide_targets().any(|entry| entry_names_solid(entry, solid))
439    }
440
441    /// The targets of the view's baseline hide step(s), in order.
442    pub fn baseline_hidden(&self) -> Vec<String> {
443        self.annotations.iter().filter(|a| a.is_baseline_hide()).flat_map(|a| a.references("targets")).collect()
444    }
445
446    /// Every target of the view's enabled hide steps, in step order.
447    pub fn hide_targets(&self) -> impl Iterator<Item = &str> {
448        self.annotations
449            .iter()
450            .filter(|annotation| annotation.enabled && annotation.kind == annotations::hide::DEF.type_id)
451            .flat_map(|annotation| match annotation.params.get("targets") {
452                Some(Value::String(name)) => std::slice::from_ref(name).iter().map(String::as_str).collect::<Vec<_>>(),
453                Some(Value::Array(items)) => items.iter().filter_map(Value::as_str).collect(),
454                _ => Vec::new(),
455            })
456            .map(str::trim)
457            .filter(|name| !name.is_empty())
458    }
459}
460
461fn default_text_size() -> f64 {
462    12.0
463}
464
465impl Default for PmiDisplay {
466    fn default() -> Self {
467        Self {
468            text_size_pt: default_text_size(),
469            wireframe: false,
470            legacy_hidden: Vec::new(),
471            section: None,
472        }
473    }
474}
475
476/// The text size clamp: `[1, 288]` points.
477pub fn clamp_text_size(size: f64) -> f64 {
478    if !size.is_finite() {
479        return default_text_size();
480    }
481    size.clamp(1.0, 288.0)
482}
483
484/// One annotation: schema-driven params keyed by its `type`.
485#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
486pub struct PmiAnnotation {
487    #[serde(rename = "type")]
488    pub kind: String,
489    #[serde(default = "default_true")]
490    pub enabled: bool,
491    #[serde(default, rename = "inputParams")]
492    pub params: Value,
493    #[serde(default, rename = "persistentData", skip_serializing_if = "Value::is_null")]
494    pub persistent_data: Value,
495    /// Last accepted callback transition. Replays use its prior input, never saved geometry.
496    #[serde(default, rename = "pluginReplay", skip_serializing_if = "Option::is_none")]
497    pub plugin_replay: Option<PluginAnnotationReplay>,
498    /// The draggable label's world anchor. Absent until the user moves it —
499    /// the report then carries a default derived from the geometry.
500    #[serde(default, rename = "labelWorld", skip_serializing_if = "Option::is_none")]
501    pub label_world: Option<[f64; 3]>,
502}
503
504fn is_false(value: &bool) -> bool { !value }
505
506fn default_true() -> bool {
507    true
508}
509
510impl PmiAnnotation {
511    /// `inputParams.id` (empty when absent).
512    pub fn id(&self) -> &str {
513        self.params
514            .get("id")
515            .and_then(Value::as_str)
516            .unwrap_or("")
517    }
518
519    /// A string param, trimmed (`""` when absent or not a string).
520    pub fn text(&self, key: &str) -> &str {
521        self.params
522            .get(key)
523            .and_then(Value::as_str)
524            .map(str::trim)
525            .unwrap_or("")
526    }
527
528    /// A boolean param (`false` when absent).
529    pub fn flag(&self, key: &str) -> bool {
530        self.params
531            .get(key)
532            .and_then(Value::as_bool)
533            .unwrap_or(false)
534    }
535
536    /// A numeric param: a JSON number, or a string evaluated as an expression
537    /// against the document's variable sheet. `default` when absent / empty.
538    pub fn number(&self, key: &str, env: &Env, default: f64) -> Result<f64, String> {
539        match self.params.get(key) {
540            None | Some(Value::Null) => Ok(default),
541            Some(Value::Number(number)) => Ok(number.as_f64().unwrap_or(default)),
542            Some(Value::Bool(flag)) => Ok(if *flag { 1.0 } else { 0.0 }),
543            Some(Value::String(source)) => {
544                let source = source.trim();
545                if source.is_empty() {
546                    return Ok(default);
547                }
548                env.eval(source)
549                    .map_err(|error| format!("{key}: {error}"))
550            }
551            Some(other) => Err(format!("{key}: expected a number, got {other}")),
552        }
553    }
554
555    /// The `plane` reference (a planar face / reference plane name), when
556    /// the annotation is laid out in a picked plane rather than the view.
557    pub fn plane_ref(&self) -> Option<&str> {
558        let name = self.text("plane").trim();
559        (!name.is_empty()).then_some(name)
560    }
561
562    /// A reference param as a name list: a string, or an array of strings
563    /// (empty strings dropped).
564    pub fn references(&self, key: &str) -> Vec<String> {
565        match self.params.get(key) {
566            Some(Value::String(name)) => {
567                let name = name.trim();
568                if name.is_empty() {
569                    Vec::new()
570                } else {
571                    vec![name.to_string()]
572                }
573            }
574            Some(Value::Array(items)) => items
575                .iter()
576                .filter_map(Value::as_str)
577                .map(str::trim)
578                .filter(|name| !name.is_empty())
579                .map(String::from)
580                .collect(),
581            _ => Vec::new(),
582        }
583    }
584}
585
586impl PmiState {
587    /// Replace view `view_id`'s baseline hide step with one naming `names`
588    /// (none when empty), keeping the old step's id and place. False when
589    /// nothing changed or there is no such view.
590    pub fn set_view_baseline(&mut self, view_id: &str, names: &[String]) -> bool {
591        let Some(view) = self.find_view(view_id) else { return false };
592        if view.baseline_hidden() == names && view.annotations.iter().filter(|a| a.is_baseline_hide()).count() <= 1 {
593            return false;
594        }
595        let at = view.annotations.iter().position(PmiAnnotation::is_baseline_hide);
596        let kept_id = at.map(|at| view.annotations[at].id().to_string()).filter(|id| !id.is_empty());
597        let id = kept_id.unwrap_or_else(|| baseline_hide_id(view_id));
598        let view = self.find_view_mut(view_id).expect("found above");
599        view.annotations.retain(|a| !a.is_baseline_hide());
600        if !names.is_empty() {
601            let step = PmiAnnotation::hide_step(&id, names, true);
602            let at = at.unwrap_or(view.annotations.len()).min(view.annotations.len());
603            view.annotations.insert(at, step);
604        }
605        true
606    }
607
608    /// Hide `names` in view `view_id` as a new hide step (the viewport's
609    /// hide while the view is active): only the names the view does not hide
610    /// yet. The new step's id, or `None` when nothing new is hidden.
611    pub fn hide_in_view(&mut self, view_id: &str, names: &[String]) -> Option<String> {
612        let view = self.find_view(view_id)?;
613        let mut targets: Vec<String> = Vec::new();
614        for name in names {
615            if !view.hides(name) && !targets.contains(name) {
616                targets.push(name.clone());
617            }
618        }
619        if targets.is_empty() {
620            return None;
621        }
622        let id = self.next_id(annotations::hide::DEF.short_name);
623        self.find_view_mut(view_id)?.annotations.push(PmiAnnotation::hide_step(&id, &targets, false));
624        Some(id)
625    }
626
627    /// Show `names` in view `view_id` (the viewport's show while the view is
628    /// active): every enabled hide step drops them; a step target naming a
629    /// whole component one of them belongs to becomes that component's other
630    /// solids (from `solids`, the scene's names); a step left with no target
631    /// goes. True when a step changed.
632    pub fn show_in_view(&mut self, view_id: &str, names: &[String], solids: &[String]) -> bool {
633        let Some(view) = self.find_view_mut(view_id) else { return false };
634        let shown = |solid: &str| names.iter().any(|name| name == solid);
635        let mut changed = false;
636        let mut emptied: Vec<usize> = Vec::new();
637        for (index, annotation) in view.annotations.iter_mut().enumerate() {
638            if !annotation.enabled || annotation.kind != annotations::hide::DEF.type_id {
639                continue;
640            }
641            let targets = annotation.references("targets");
642            if !targets.iter().any(|entry| names.iter().any(|name| entry_names_solid(entry, name))) {
643                continue;
644            }
645            let mut kept: Vec<String> = Vec::new();
646            for entry in targets {
647                if !names.iter().any(|name| entry_names_solid(&entry, name)) {
648                    kept.push(entry);
649                    continue;
650                }
651                for solid in solids.iter().filter(|solid| entry_names_solid(&entry, solid) && !shown(solid)) {
652                    if !kept.contains(solid) {
653                        kept.push(solid.clone());
654                    }
655                }
656            }
657            changed = true;
658            if kept.is_empty() {
659                emptied.push(index);
660            } else {
661                annotation.params["targets"] = serde_json::json!(kept);
662            }
663        }
664        for index in emptied.into_iter().rev() {
665            view.annotations.remove(index);
666        }
667        changed
668    }
669
670    /// Make view `view_id` hide exactly `names` among `solids` (MCP
671    /// `pmi_set_view_display`'s `hidden`): what it hides beyond them is shown
672    /// ([`Self::show_in_view`]), and what it does not hide yet joins its
673    /// baseline step. True when a step changed.
674    pub fn set_view_hidden(&mut self, view_id: &str, names: &[String], solids: &[String]) -> bool {
675        let Some(view) = self.find_view(view_id) else { return false };
676        let extra: Vec<String> = solids.iter().filter(|solid| view.hides(solid) && !names.contains(solid)).cloned().collect();
677        let mut changed = !extra.is_empty() && self.show_in_view(view_id, &extra, solids);
678        let view = self.find_view(view_id).expect("found above");
679        let mut baseline = view.baseline_hidden();
680        let missing: Vec<String> = names.iter().filter(|name| !view.hides(name)).cloned().collect();
681        if !missing.is_empty() {
682            if view.annotations.iter().any(|step| step.is_baseline_hide() && !step.enabled) {
683                // A disabled baseline is not hiding its targets. Keep that
684                // authored state and add only the explicitly requested hides.
685                changed |= self.hide_in_view(view_id, &missing).is_some();
686            } else {
687                baseline.extend(missing);
688                changed |= self.set_view_baseline(view_id, &baseline);
689            }
690        }
691        changed
692    }
693
694    /// Mint the next id with `prefix` (`VIEW` → `VIEW3`). The counter is
695    /// re-seeded first from the largest numeric suffix already in the block,
696    /// so an edited or merged document never hands out a colliding id.
697    pub fn next_id(&mut self, prefix: &str) -> String {
698        let seen = self.max_numeric_suffix();
699        if seen > self.id_counter {
700            self.id_counter = seen;
701        }
702        loop {
703            self.id_counter += 1;
704            let candidate = format!("{prefix}{}", self.id_counter);
705            if self.find_view(&candidate).is_none() && self.find_annotation(&candidate).is_none() {
706                return candidate;
707            }
708        }
709    }
710
711    fn max_numeric_suffix(&self) -> u64 {
712        let mut best = 0u64;
713        let mut consider = |id: &str| {
714            let digits = id
715                .bytes()
716                .rev()
717                .take_while(u8::is_ascii_digit)
718                .count();
719            if digits > 0 {
720                if let Ok(value) = id[id.len() - digits..].parse::<u64>() {
721                    best = best.max(value);
722                }
723            }
724        };
725        for view in &self.views {
726            consider(&view.id);
727            for annotation in &view.annotations {
728                consider(annotation.id());
729            }
730        }
731        best
732    }
733
734    pub fn find_view(&self, id: &str) -> Option<&PmiView> {
735        self.views.iter().find(|view| view.id == id)
736    }
737
738    pub fn find_view_mut(&mut self, id: &str) -> Option<&mut PmiView> {
739        self.views.iter_mut().find(|view| view.id == id)
740    }
741
742    /// The annotation with `id` and its owning view.
743    pub fn find_annotation(&self, id: &str) -> Option<(&PmiView, &PmiAnnotation)> {
744        self.views.iter().find_map(|view| {
745            view.annotations
746                .iter()
747                .find(|annotation| annotation.id() == id)
748                .map(|annotation| (view, annotation))
749        })
750    }
751
752    /// The owning view id and index of annotation `id`.
753    pub fn locate_annotation(&self, id: &str) -> Option<(usize, usize)> {
754        self.views.iter().enumerate().find_map(|(view_index, view)| {
755            view.annotations
756                .iter()
757                .position(|annotation| annotation.id() == id)
758                .map(|index| (view_index, index))
759        })
760    }
761
762    pub fn find_annotation_mut(&mut self, id: &str) -> Option<&mut PmiAnnotation> {
763        self.views.iter_mut().find_map(|view| {
764            view.annotations
765                .iter_mut()
766                .find(|annotation| annotation.id() == id)
767        })
768    }
769
770    /// Every datum letter defined in the part (any view), in definition
771    /// order, with the defining annotation's id — the part-level datum
772    /// registry a feature control frame validates its references against.
773    pub fn datum_letters(&self) -> Vec<(String, String)> {
774        let mut out = Vec::new();
775        for view in &self.views {
776            for annotation in &view.annotations {
777                if annotation.kind == annotations::datum::DEF.type_id {
778                    let letter = annotation.text("letter").to_uppercase();
779                    if !letter.is_empty() {
780                        out.push((letter, annotation.id().to_string()));
781                    }
782                }
783            }
784        }
785        out
786    }
787
788    /// The next unused datum letter: A–Z skipping I, O and Q (ASME Y14.5),
789    /// then AA, AB, … (`None` only past ZZ).
790    pub fn next_datum_letter(&self) -> Option<String> {
791        let used: Vec<String> = self.datum_letters().into_iter().map(|(l, _)| l).collect();
792        let alphabet: Vec<char> = ('A'..='Z').filter(|c| !matches!(c, 'I' | 'O' | 'Q')).collect();
793        for letter in &alphabet {
794            let candidate = letter.to_string();
795            if !used.contains(&candidate) {
796                return Some(candidate);
797            }
798        }
799        for first in &alphabet {
800            for second in &alphabet {
801                let candidate = format!("{first}{second}");
802                if !used.contains(&candidate) {
803                    return Some(candidate);
804                }
805            }
806        }
807        None
808    }
809
810    /// Whether the block carries anything worth persisting.
811    pub fn is_empty(&self) -> bool {
812        self.views.is_empty() && self.id_counter == 0
813    }
814}
815
816// ===========================================================================
817// The resolved report
818// ===========================================================================
819
820/// The tail's resolution of every view's annotations.
821#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
822pub struct PmiReport {
823    pub views: Vec<PmiViewReport>,
824}
825
826impl PmiReport {
827    pub fn view(&self, id: &str) -> Option<&PmiViewReport> {
828        self.views.iter().find(|view| view.id == id)
829    }
830
831    pub fn annotation(&self, id: &str) -> Option<&PmiAnnotationReport> {
832        self.views
833            .iter()
834            .find_map(|view| view.annotations.iter().find(|a| a.id == id))
835    }
836
837    pub fn annotation_mut(&mut self, id: &str) -> Option<&mut PmiAnnotationReport> {
838        self.views
839            .iter_mut()
840            .find_map(|view| view.annotations.iter_mut().find(|a| a.id == id))
841    }
842}
843
844#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
845pub struct PmiViewReport {
846    pub id: String,
847    pub annotations: Vec<PmiAnnotationReport>,
848    /// A `Plane` section's cutting plane `(point, kept-side normal)`, resolved
849    /// from its reference by this run.
850    #[serde(default, rename = "sectionPlane", skip_serializing_if = "Option::is_none")]
851    pub section_plane: Option<([f64; 3], [f64; 3])>,
852    /// Why a `Plane` section's reference did not resolve (no cut is shown).
853    #[serde(default, rename = "sectionError", skip_serializing_if = "String::is_empty")]
854    pub section_error: String,
855    /// The scene solids the view hides ([`PmiView::hides`] over this run's
856    /// scene: the captured baseline plus its enabled hide steps), sorted.
857    /// Absent when it hides nothing.
858    #[serde(default, skip_serializing_if = "Vec::is_empty")]
859    pub hidden: Vec<String>,
860}
861
862#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
863#[serde(rename_all = "kebab-case")]
864pub enum PmiStatus {
865    /// Resolved: `text` / `value` / `geometry` are live.
866    Ok,
867    /// An unresolved anchor, a dangling datum reference, an unsupported
868    /// pairing …: `message` says which. The annotation stays listed.
869    Error,
870}
871
872/// One resolved annotation.
873#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
874pub struct PmiAnnotationReport {
875    /// Successful provider output only; errors must preserve saved input data.
876    #[serde(default, rename = "persistentData", skip_serializing_if = "Option::is_none")]
877    pub persistent_data: Option<Value>,
878    #[serde(default, rename = "pluginReplay", skip_serializing_if = "Option::is_none")]
879    pub plugin_replay: Option<PluginAnnotationReplay>,
880    pub id: String,
881    #[serde(rename = "type")]
882    pub kind: String,
883    pub enabled: bool,
884    pub status: PmiStatus,
885    #[serde(default)]
886    pub message: String,
887    /// The display text (value + tolerance block, note / leader text, hole
888    /// callout, datum letter, FCF cells joined).
889    #[serde(default)]
890    pub text: String,
891    /// The measured value (length in model units, angle in degrees).
892    #[serde(default, skip_serializing_if = "Option::is_none")]
893    pub value: Option<f64>,
894    /// `"mm"` / `"deg"` / `""`.
895    #[serde(default)]
896    pub unit: String,
897    /// The scene entity names the annotation resolved (for hover
898    /// highlighting and the STEP shape aspects), in reference order.
899    #[serde(default)]
900    pub references: Vec<String>,
901    /// The label anchor: the stored `labelWorld`, else the geometry's default
902    /// — projected onto the annotation plane when one is picked.
903    #[serde(rename = "labelWorld")]
904    pub label_world: [f64; 3],
905    /// The picked annotation plane; `None` aligns to the view camera.
906    #[serde(default, skip_serializing_if = "Option::is_none")]
907    pub plane: Option<PmiPlane>,
908    pub geometry: PmiGeometry,
909    /// A weld callout's standard weld symbol (absent for the text style, a
910    /// weld kind drawn as text, and every other type): what every consumer
911    /// draws in place of the text leader ([`weld_symbol::present_row`]).
912    #[serde(default, rename = "weldSymbol", skip_serializing_if = "Option::is_none")]
913    pub weld_symbol: Option<weld_symbol::WeldSymbol>,
914}
915
916/// A resolved annotation plane: the plane the annotation lies in (its
917/// `plane` reference — a planar face or a reference plane), `normal`
918/// oriented toward the view's captured camera, `x_axis` the in-plane text
919/// direction (the camera's right projected into the plane). The viewport
920/// overlay and the AP242 `ANNOTATION_PLANE` both lay the annotation out in
921/// this frame.
922#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
923pub struct PmiPlane {
924    pub origin: [f64; 3],
925    pub normal: [f64; 3],
926    #[serde(rename = "xAxis")]
927    pub x_axis: [f64; 3],
928}
929
930impl PmiPlane {
931    /// `point` projected onto the plane along its normal.
932    pub fn project(&self, point: [f64; 3]) -> [f64; 3] {
933        let n = self.normal;
934        let d = (point[0] - self.origin[0]) * n[0] + (point[1] - self.origin[1]) * n[1] + (point[2] - self.origin[2]) * n[2];
935        [point[0] - n[0] * d, point[1] - n[1] * d, point[2] - n[2] * d]
936    }
937
938    /// The in-plane up direction (`normal × x_axis`).
939    pub fn y_axis(&self) -> [f64; 3] {
940        let n = self.normal;
941        let x = self.x_axis;
942        [n[1] * x[2] - n[2] * x[1], n[2] * x[0] - n[0] * x[2], n[0] * x[1] - n[1] * x[0]]
943    }
944
945    /// The ray `origin + t·dir` hit on the plane, if not parallel.
946    pub fn hit(&self, origin: [f64; 3], dir: [f64; 3]) -> Option<[f64; 3]> {
947        let n = self.normal;
948        let denominator = dir[0] * n[0] + dir[1] * n[1] + dir[2] * n[2];
949        if denominator.abs() < 1e-12 {
950            return None;
951        }
952        let diff = [self.origin[0] - origin[0], self.origin[1] - origin[1], self.origin[2] - origin[2]];
953        let t = (diff[0] * n[0] + diff[1] * n[1] + diff[2] * n[2]) / denominator;
954        Some([origin[0] + dir[0] * t, origin[1] + dir[1] * t, origin[2] + dir[2] * t])
955    }
956}
957
958/// The analytic geometry an annotation resolved to — what the presentation
959/// ([`layout`]) and the STEP semantic export are built from.
960#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
961#[serde(tag = "kind", rename_all = "camelCase")]
962pub enum PmiGeometry {
963    None,
964    /// Measured from `a` to `b` (world). `component` names the X/Y/Z axis
965    /// when the dimension is an aligned component, else `None`.
966    Linear {
967        a: [f64; 3],
968        b: [f64; 3],
969        #[serde(default, skip_serializing_if = "Option::is_none")]
970        component: Option<char>,
971    },
972    Radial {
973        center: [f64; 3],
974        axis: [f64; 3],
975        radius: f64,
976        diameter: bool,
977        sphere: bool,
978    },
979    /// The arc sweeps `degrees` from `dir_a` about `axis` (right-handed) at
980    /// `vertex`.
981    Angular {
982        vertex: [f64; 3],
983        #[serde(rename = "dirA")]
984        dir_a: [f64; 3],
985        #[serde(rename = "dirB")]
986        dir_b: [f64; 3],
987        axis: [f64; 3],
988        degrees: f64,
989    },
990    Leader {
991        targets: Vec<[f64; 3]>,
992        dot: bool,
993        #[serde(default, skip_serializing_if = "is_false")]
994        balloon: bool,
995        /// A balloon's head derivation recipe (`None` on a plain leader): the
996        /// viewport re-derives `targets[0]` from a dragged bubble with it.
997        #[serde(default, skip_serializing_if = "Option::is_none")]
998        anchor: Option<BalloonAnchor>,
999    },
1000    Note {
1001        position: [f64; 3],
1002    },
1003    Hole {
1004        anchor: [f64; 3],
1005        normal: [f64; 3],
1006    },
1007    /// Display-only: keep `solids` out of the view while it is active. Draws
1008    /// nothing (no chip, no text, no line).
1009    Hide {
1010        solids: Vec<String>,
1011    },
1012    /// Display-only: pose `solids` by the delta while the view is active.
1013    Explode {
1014        solids: Vec<String>,
1015        translate: [f64; 3],
1016        #[serde(rename = "rotateDeg")]
1017        rotate_deg: [f64; 3],
1018        scale: [f64; 3],
1019        /// The rotation / scale pivot: the targets' aggregate bbox center.
1020        center: [f64; 3],
1021        trace: bool,
1022    },
1023    Datum {
1024        anchor: [f64; 3],
1025        normal: [f64; 3],
1026        letter: String,
1027    },
1028    Fcf {
1029        anchor: [f64; 3],
1030        normal: [f64; 3],
1031        frame: FcfFrame,
1032    },
1033    /// Centre crosses on round features, the dashes reaching `extension`
1034    /// (model units) past each circle.
1035    CenterMark {
1036        marks: Vec<CenterCircle>,
1037        extension: f64,
1038    },
1039    /// A chain line from `a` to `b` (its extension already included).
1040    CenterLine {
1041        a: [f64; 3],
1042        b: [f64; 3],
1043    },
1044}
1045
1046/// One centre mark: the circle it marks. `axis` is the circle's normal, or
1047/// zero for a sphere (its mark lies in the model's XY plane, or in a picked
1048/// annotation plane). A cylinder or cone face is marked at the end its axis
1049/// points to, `depth` the face's length back along the axis to its other
1050/// end: the layout draws the mark on whichever end faces the viewer (zero
1051/// for an edge's or a sphere's mark).
1052///
1053/// `x_dir` fixes the cross in the model: one arm runs along it, the other
1054/// along `axis × x_dir`. It is a unit vector in the circle's plane (for a
1055/// sphere, the direction the layout projects into the mark's plane), taken
1056/// from the annotation's orientation reference or, without one, the model X
1057/// axis (Y where X is along the circle's axis). Zero (a row resolved before
1058/// the field existed) applies the same default in the layout; the camera
1059/// never turns the cross.
1060#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1061pub struct CenterCircle {
1062    pub center: [f64; 3],
1063    pub axis: [f64; 3],
1064    pub radius: f64,
1065    #[serde(default, skip_serializing_if = "is_zero")]
1066    pub depth: f64,
1067    #[serde(default, rename = "xDir", skip_serializing_if = "is_zero_vector")]
1068    pub x_dir: [f64; 3],
1069}
1070
1071fn is_zero_vector(value: &[f64; 3]) -> bool {
1072    value.iter().all(|c| *c == 0.0)
1073}
1074
1075fn is_zero(value: &f64) -> bool {
1076    *value == 0.0
1077}
1078
1079/// The cells of a feature control frame.
1080#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1081pub struct FcfFrame {
1082    /// The characteristic id (`flatness`, `position`, …).
1083    pub characteristic: String,
1084    /// Its Unicode symbol (the glyph key).
1085    pub symbol: String,
1086    /// The tolerance cell text (`⌀0.1 Ⓜ`).
1087    pub zone: String,
1088    /// The datum reference cells (`A`, `B Ⓜ`).
1089    pub datums: Vec<String>,
1090}
1091
1092// ===========================================================================
1093// Value formatting (shared by the viewport and the STEP presentation)
1094// ===========================================================================
1095
1096/// The tolerance block of a dimension: `tolMode` none / symmetric / deviation
1097/// / limits with `tolUpper` / `tolLower`.
1098#[derive(Debug, Clone, Copy, PartialEq)]
1099pub struct ToleranceBlock {
1100    pub mode: ToleranceMode,
1101    pub upper: f64,
1102    pub lower: f64,
1103}
1104
1105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1106pub enum ToleranceMode {
1107    None,
1108    Symmetric,
1109    Deviation,
1110    Limits,
1111}
1112
1113impl ToleranceMode {
1114    pub fn parse(text: &str) -> Self {
1115        match text.trim().to_ascii_lowercase().as_str() {
1116            "symmetric" => ToleranceMode::Symmetric,
1117            "deviation" => ToleranceMode::Deviation,
1118            "limits" => ToleranceMode::Limits,
1119            _ => ToleranceMode::None,
1120        }
1121    }
1122
1123    pub fn as_str(self) -> &'static str {
1124        match self {
1125            ToleranceMode::None => "none",
1126            ToleranceMode::Symmetric => "symmetric",
1127            ToleranceMode::Deviation => "deviation",
1128            ToleranceMode::Limits => "limits",
1129        }
1130    }
1131}
1132
1133impl ToleranceBlock {
1134    /// Read the block off an annotation's params.
1135    pub fn read(annotation: &PmiAnnotation, env: &Env) -> Result<Self, String> {
1136        Ok(Self {
1137            mode: ToleranceMode::parse(annotation.text("tolMode")),
1138            upper: annotation.number("tolUpper", env, 0.0)?.abs(),
1139            lower: annotation.number("tolLower", env, 0.0)?.abs(),
1140        })
1141    }
1142
1143    /// The signed bounds as offsets from the nominal (`lower ≤ 0 ≤ upper`),
1144    /// `None` when the mode carries no tolerance.
1145    pub fn bounds(&self) -> Option<(f64, f64)> {
1146        match self.mode {
1147            ToleranceMode::None => None,
1148            ToleranceMode::Symmetric => Some((-self.upper, self.upper)),
1149            ToleranceMode::Deviation | ToleranceMode::Limits => Some((-self.lower, self.upper)),
1150        }
1151    }
1152}
1153
1154/// `value` with `decimals` places (`0..=8`), no exponent.
1155pub fn format_number(value: f64, decimals: usize) -> String {
1156    let decimals = decimals.min(8);
1157    let text = format!("{:.*}", decimals, value);
1158    // `-0.000` reads as a sign error on a dimension.
1159    if text.starts_with('-') && text[1..].bytes().all(|b| b == b'0' || b == b'.') {
1160        text[1..].to_string()
1161    } else {
1162        text
1163    }
1164}
1165
1166/// The dimension text: `prefix` (`⌀` / `R` / `""`) + the nominal (+ the
1167/// tolerance block) + `suffix` (`°` / `""`); a reference dimension is
1168/// parenthesized and shows no tolerance.
1169pub fn format_dimension(
1170    value: f64,
1171    decimals: usize,
1172    tolerance: &ToleranceBlock,
1173    is_reference: bool,
1174    prefix: &str,
1175    suffix: &str,
1176) -> String {
1177    let nominal = format!("{prefix}{}{suffix}", format_number(value, decimals));
1178    if is_reference {
1179        return format!("({nominal})");
1180    }
1181    match tolerance.mode {
1182        ToleranceMode::None => nominal,
1183        ToleranceMode::Symmetric => format!(
1184            "{nominal} \u{00B1}{}{suffix}",
1185            format_number(tolerance.upper, decimals)
1186        ),
1187        ToleranceMode::Deviation => format!(
1188            "{nominal} +{}{suffix}/\u{2212}{}{suffix}",
1189            format_number(tolerance.upper, decimals),
1190            format_number(tolerance.lower, decimals)
1191        ),
1192        ToleranceMode::Limits => format!(
1193            "{prefix}{}{suffix} / {prefix}{}{suffix}",
1194            format_number(value + tolerance.upper, decimals),
1195            format_number(value - tolerance.lower, decimals)
1196        ),
1197    }
1198}
1199
1200// ===========================================================================
1201// The history tail
1202// ===========================================================================
1203
1204/// What the annotation resolvers read: the live scene, the request (hole
1205/// features for callouts, the datum registry) and the expression sheet.
1206pub struct PmiContext<'a> {
1207    pub scene: &'a SceneMap,
1208    pub request: &'a HistoryRequest,
1209    pub env: &'a Env,
1210    /// The PMI block being resolved, its `Plane` sections already resolved.
1211    pub state: &'a PmiState,
1212    /// The part-level datum registry (letter → annotation id).
1213    pub datums: BTreeMap<String, String>,
1214}
1215
1216/// The outcome of one annotation's resolver.
1217pub struct Resolved {
1218    pub text: String,
1219    pub value: Option<f64>,
1220    pub unit: &'static str,
1221    pub references: Vec<String>,
1222    pub geometry: PmiGeometry,
1223    /// The default label anchor when the annotation stores none.
1224    pub default_label: [f64; 3],
1225}
1226
1227/// Resolve every view's annotations against `scene`. `None` when the request
1228/// carries no `pmi` block (a document without PMI reports nothing).
1229pub(crate) fn finish_history_run(
1230    request: &HistoryRequest,
1231    scene: &SceneMap,
1232    env: &Env,
1233) -> Option<PmiReport> {
1234    let state = request.pmi.as_ref()?;
1235    Some(resolve_state(state, scene, request, env))
1236}
1237
1238/// Resolve `state` (the tail's body, callable on any scene).
1239pub fn resolve_state(
1240    state: &PmiState,
1241    scene: &SceneMap,
1242    request: &HistoryRequest,
1243    env: &Env,
1244) -> PmiReport {
1245    // The datum registry: first definition of a letter wins; a duplicate is
1246    // reported on the later annotation by the datum resolver.
1247    let mut datums: BTreeMap<String, String> = BTreeMap::new();
1248    for (letter, id) in state.datum_letters() {
1249        datums.entry(letter).or_insert(id);
1250    }
1251    // A section on a picked plane resolves against this scene; the
1252    // annotations (balloons included) then see it as a fixed plane.
1253    let mut state = state.clone();
1254    let mut section_errors: BTreeMap<String, String> = BTreeMap::new();
1255    for view in &mut state.views {
1256        if let Err(error) = resolve_section_plane(view, scene) {
1257            section_errors.insert(view.id.clone(), error);
1258        }
1259    }
1260    let state = &state;
1261    let context = PmiContext {
1262        scene,
1263        request,
1264        env,
1265        state,
1266        datums,
1267    };
1268    PmiReport {
1269        views: state
1270            .views
1271            .iter()
1272            .map(|view| {
1273                let section = section_half_space(view);
1274                let exempt = |reference: &str| {
1275                    let section = view.display.section.as_ref();
1276                    section.is_some_and(|section| reference_solid(scene, reference).is_some_and(|solid| section.excludes(&solid)))
1277                };
1278                let mut hidden: Vec<String> = scene.solids.keys().filter(|name| view.hides(name)).cloned().collect();
1279                hidden.sort();
1280                PmiViewReport {
1281                    section_plane: view.display.section.as_ref().filter(|s| s.axis == "Plane").and_then(|_| view.section_plane()),
1282                    section_error: section_errors.remove(&view.id).unwrap_or_default(),
1283                    hidden,
1284                    id: view.id.clone(),
1285                    annotations: view
1286                        .annotations
1287                        .iter()
1288                        .map(|annotation| {
1289                            let report = resolve_annotation(annotation, &context, view.camera.as_ref());
1290                            match &section {
1291                                Some(section) => sectioned_away(report, section, &exempt),
1292                                None => report,
1293                            }
1294                        })
1295                        .collect(),
1296                }
1297            })
1298            .collect(),
1299    }
1300}
1301
1302/// Fill a `Plane` section's origin and normal from its reference: a planar
1303/// face or a reference plane (datum or sketch plane) of `scene`.
1304fn resolve_section_plane(view: &mut PmiView, scene: &SceneMap) -> Result<(), String> {
1305    let Some(section) = view.display.section.as_mut().filter(|s| s.axis == "Plane") else {
1306        return Ok(());
1307    };
1308    let name = section.plane.clone().unwrap_or_default();
1309    if name.trim().is_empty() {
1310        return Err("pick a planar face or a datum plane to cut on".into());
1311    }
1312    match resolve::resolve_reference(scene, &name) {
1313        Ok(crate::SelectionGeometry::Plane { origin, normal }) => {
1314            section.origin = Some(resolve::a3(origin));
1315            section.normal = Some(resolve::a3(normal));
1316            Ok(())
1317        }
1318        Ok(_) => Err(format!("section plane '{name}' is not planar: pick a planar face or a datum plane")),
1319        Err(error) => Err(format!("section plane '{name}': {error}")),
1320    }
1321}
1322
1323/// The half-space a sectioned view keeps, for checking where its
1324/// annotations land. `None` without a section, and for a view that explodes
1325/// anything: its annotations measure the modeling pose while the cut is made
1326/// on the exploded display, so the two cannot be compared.
1327fn section_half_space(view: &PmiView) -> Option<anchor::HalfSpace> {
1328    if view.annotations.iter().any(|a| a.enabled && a.kind == "explode") {
1329        return None;
1330    }
1331    anchor::HalfSpace::of(&view.section_planes())
1332}
1333
1334/// A resolved annotation whose measured points lie on the side the view's
1335/// section removes would be drawn on nothing; it is reported as an error,
1336/// its chip kept where its label is, the way a balloon on a removed part is.
1337/// Balloons check their own anchors, radial and angular annotations measure
1338/// through their centre or vertex (often off the part), and notes float.
1339/// A point on a solid the section leaves whole (`exempt`, by reference) is
1340/// drawn whatever side it is on.
1341fn sectioned_away(mut report: PmiAnnotationReport, section: &anchor::HalfSpace, exempt: &dyn Fn(&str) -> bool) -> PmiAnnotationReport {
1342    if report.status != PmiStatus::Ok {
1343        return report;
1344    }
1345    let points: Vec<[f64; 3]> = match &report.geometry {
1346        PmiGeometry::Linear { a, b, component: None } => vec![*a, *b],
1347        // An aligned dimension's second point is the projected corner, not geometry.
1348        PmiGeometry::Linear { a, component: Some(_), .. } => vec![*a],
1349        PmiGeometry::Leader { targets, balloon: false, .. } => targets.clone(),
1350        PmiGeometry::Hole { anchor, .. } | PmiGeometry::Datum { anchor, .. } | PmiGeometry::Fcf { anchor, .. } => vec![*anchor],
1351        _ => return report,
1352    };
1353    // Each point's own reference where they pair one to one (a dimension's
1354    // two targets, a leader's targets); otherwise all of them must be exempt.
1355    let references = &report.references;
1356    let point_exempt = |index: usize| match references.len() == points.len() {
1357        true => exempt(&references[index]),
1358        false => !references.is_empty() && references.iter().all(|reference| exempt(reference)),
1359    };
1360    if points.iter().enumerate().all(|(index, point)| point_exempt(index) || section.keeps(*point, 1e-6)) {
1361        return report;
1362    }
1363    report.status = PmiStatus::Error;
1364    report.message = "it is on geometry the section removes in this view: move the section, Reverse it, or re-attach the annotation".into();
1365    report.text = String::new();
1366    report.value = None;
1367    report.geometry = PmiGeometry::None;
1368    report.plane = None;
1369    report
1370}
1371
1372/// The scene name of the solid a reference lies on: a vertex ref's solid, a
1373/// face's or an edge's owner, or the solid itself.
1374fn reference_solid(scene: &SceneMap, reference: &str) -> Option<String> {
1375    let reference = reference.trim();
1376    if let Some((solid, _)) = reference.split_once('@') {
1377        return Some(solid.to_string());
1378    }
1379    let handle = scene
1380        .resolve_face(reference)
1381        .map(|face| face.handle)
1382        .or_else(|| scene.resolve_edge(reference).map(|edge| edge.handle))
1383        .or_else(|| scene.resolve_solid(reference))?;
1384    scene.solids.iter().find(|(_, h)| **h == handle).map(|(name, _)| name.clone())
1385}
1386
1387/// Resolve one annotation through its type's resolver into a report row:
1388/// the type's measurement, then its annotation plane (`camera` orients the
1389/// plane toward the view; `None` for a view without a camera).
1390pub fn resolve_annotation(
1391    annotation: &PmiAnnotation,
1392    context: &PmiContext<'_>,
1393    camera: Option<&PmiCamera>,
1394) -> PmiAnnotationReport {
1395    let mut persistent_data = None;
1396    let mut plugin_replay = None;
1397    let outcome = match pmi_type(&annotation.kind) {
1398        None if annotation.kind.contains('/') && !annotation.enabled => Ok(Resolved {
1399            text: String::new(), value: None, unit: "", references: Vec::new(),
1400            geometry: PmiGeometry::None, default_label: annotation.label_world.unwrap_or([0.; 3]),
1401        }),
1402        Some(def) => (def.resolve)(annotation, context),
1403        None if annotation.kind.contains('/') => plugin::resolve(annotation, context).map(|(resolved, data, replay)| {
1404            persistent_data = Some(data);
1405            plugin_replay = Some(replay);
1406            resolved
1407        }),
1408        None => Err(format!("unknown PMI annotation type '{}'", annotation.kind)),
1409    }
1410    .and_then(|resolved| {
1411        let plane = annotation_plane(annotation, context, camera, &resolved.geometry)?;
1412        Ok((resolved, plane))
1413    });
1414    match outcome {
1415        Ok((resolved, plane)) => {
1416            let label = annotation.label_world.unwrap_or(resolved.default_label);
1417            // A symbol that cannot be built leaves the row its text leader.
1418            let weld_symbol = (annotation.kind == annotations::weld_callout::DEF.type_id)
1419                .then(|| annotations::weld_callout::symbol(annotation, context).ok().flatten())
1420                .flatten();
1421            PmiAnnotationReport {
1422                persistent_data,
1423                plugin_replay,
1424                id: annotation.id().to_string(),
1425                kind: annotation.kind.clone(),
1426                enabled: annotation.enabled,
1427                status: PmiStatus::Ok,
1428                message: String::new(),
1429                text: resolved.text,
1430                value: resolved.value,
1431                unit: resolved.unit.to_string(),
1432                references: resolved.references,
1433                label_world: plane.map_or(label, |plane| plane.project(label)),
1434                plane,
1435                geometry: resolved.geometry,
1436                weld_symbol,
1437            }
1438        }
1439        Err(message) => PmiAnnotationReport {
1440            persistent_data: None,
1441            plugin_replay: None,
1442            id: annotation.id().to_string(),
1443            kind: annotation.kind.clone(),
1444            enabled: annotation.enabled,
1445            status: PmiStatus::Error,
1446            message,
1447            text: String::new(),
1448            value: None,
1449            unit: String::new(),
1450            references: Vec::new(),
1451            // A refused balloon's chip sits beside its occurrence, where the
1452            // bubble would have been, not at the origin.
1453            label_world: annotation
1454                .label_world
1455                .or_else(|| (annotation.kind == "balloon").then(|| annotations::balloon::error_bubble(annotation, context)).flatten())
1456                .unwrap_or([0.0; 3]),
1457            plane: None,
1458            geometry: PmiGeometry::None,
1459            weld_symbol: None,
1460        },
1461    }
1462}
1463
1464/// Resolve an annotation's `plane` reference into its [`PmiPlane`]. The
1465/// reference must be a planar face or a reference plane, and the plane must
1466/// be parallel to what it carries — a linear dimension's direction, an
1467/// angle's plane, a circle's plane — since a dimension line drawn in a
1468/// non-parallel plane would be foreshortened and misstate the value. The
1469/// normal faces the view's camera and the text direction follows the
1470/// camera's right. `Ok(None)` when the annotation aligns to the view.
1471fn annotation_plane(
1472    annotation: &PmiAnnotation,
1473    context: &PmiContext<'_>,
1474    camera: Option<&PmiCamera>,
1475    geometry: &PmiGeometry,
1476) -> Result<Option<PmiPlane>, String> {
1477    use crate::SelectionGeometry;
1478    use resolve::{a3, perpendicular_in_plane, v3};
1479    let Some(name) = annotation.plane_ref() else {
1480        return Ok(None);
1481    };
1482    let (origin, normal) = match resolve::resolve_reference(context.scene, name)? {
1483        SelectionGeometry::Plane { origin, normal } => (origin, normal),
1484        _ => return Err(format!("annotation plane '{name}' must be a planar face or a reference plane")),
1485    };
1486    let mut normal = normal
1487        .normalized()
1488        .map_err(|_| format!("annotation plane '{name}' has no normal"))?;
1489    // sin of the largest tolerated tilt (~0.06°).
1490    const PARALLEL: f64 = 1e-3;
1491    match geometry {
1492        PmiGeometry::Linear { a, b, .. } => {
1493            let span = v3(*b).sub(v3(*a));
1494            if span.length() > 1e-9 && span.normalized().map(|d| d.dot(normal).abs()).unwrap_or(0.0) > PARALLEL {
1495                return Err(format!("annotation plane '{name}' is not parallel to the measured direction"));
1496            }
1497        }
1498        PmiGeometry::Angular { axis, .. } => {
1499            if v3(*axis).cross(normal).length() > PARALLEL {
1500                return Err(format!("annotation plane '{name}' is not parallel to the angle's plane"));
1501            }
1502        }
1503        PmiGeometry::Radial { axis, sphere: false, .. } => {
1504            if v3(*axis).cross(normal).length() > PARALLEL {
1505                return Err(format!("annotation plane '{name}' is not parallel to the circle's plane"));
1506            }
1507        }
1508        PmiGeometry::CenterMark { marks, .. } => {
1509            if marks.iter().any(|mark| v3(mark.axis).length() > 1e-12 && v3(mark.axis).cross(normal).length() > PARALLEL) {
1510                return Err(format!("annotation plane '{name}' is not parallel to the marked circle's plane"));
1511            }
1512        }
1513        PmiGeometry::CenterLine { a, b } => {
1514            let span = v3(*b).sub(v3(*a));
1515            if span.length() > 1e-9 && span.normalized().map(|d| d.dot(normal).abs()).unwrap_or(0.0) > PARALLEL {
1516                return Err(format!("annotation plane '{name}' is not parallel to the centerline"));
1517            }
1518        }
1519        _ => {}
1520    }
1521    let x_axis = match camera {
1522        Some(camera) => {
1523            let view = v3(camera.view_direction());
1524            if normal.dot(view) > 0.0 {
1525                normal = normal.scale(-1.0);
1526            }
1527            perpendicular_in_plane(normal, view.cross(v3(camera.up)))
1528        }
1529        None => perpendicular_in_plane(normal, crate::Vec3::new(1.0, 0.0, 0.0)),
1530    };
1531    Ok(Some(PmiPlane {
1532        origin: a3(origin),
1533        normal: a3(normal),
1534        x_axis: a3(x_axis),
1535    }))
1536}
1537