Skip to main content

brep_render/engine_state/
pmi_ops.rs

1//! PMI — the engine half of the PMI workbench: the document's `pmi` block
2//! (checkpointed edits + re-run, like `wire_harness_ops`), the ACTIVE view
3//! (applied camera / visibility / wireframe / explode poses, restored
4//! exactly on deactivate), annotation CRUD, the coalesced label drag, and the
5//! reference picker's PMI flavour.
6//!
7//! Persisted vs engine memory: the `pmi` block (views, annotations, label
8//! positions) lives in the document and rides its undo stack; WHICH view is
9//! active and WHICH annotation's form is open are engine memory — a mode,
10//! not model state — so a rerun, a save or an undo never churns on them.
11//!
12//! A label drag is the one high-frequency PMI edit: it writes the block with
13//! a coalesced checkpoint (`pmi:label:{id}` — one undo step per drag) and
14//! NEVER re-runs the history: the cached report's label position is patched
15//! locally and the overlay re-baked. Every other mutation (a view capture,
16//! an annotation add / edit / remove) is its own undo step followed by a
17//! re-run, whose tail re-resolves the annotations.
18
19use super::*;
20use brep_kernel::{
21    PmiAnnotation, PmiCamera, PmiDisplay, PmiGeometry, PmiProjection, PmiReport, PmiState,
22    PmiStatus, PmiView,
23};
24use crate::view::Projection;
25
26/// The modeling state remembered while the PMI workbench is active.
27#[derive(Debug, Clone)]
28pub struct PmiModelingSnapshot {
29    pub camera_json: String,
30    pub hidden: Vec<String>,
31    pub wireframe: bool,
32}
33
34/// A patch the panel applies to one view's name / display state.
35#[derive(Debug, Default, Clone, PartialEq)]
36pub struct PmiViewPatch {
37    pub name: Option<String>,
38    pub text_size_pt: Option<f64>,
39    pub wireframe: Option<bool>,
40    pub hidden: Option<Vec<String>>,
41    pub section: Option<Option<brep_kernel::feature_pipeline::pmi::PmiSection>>,
42}
43
44/// The **PMI view** dialog's schema — what a view's own form edits: its name,
45/// the text size its labels draw at and whether it shows the model in
46/// wireframe, plus the two re-capture actions its row menu also offers. Shaped
47/// like every other object schema so the shared form view draws it;
48/// [`EngineState::pmi_update_view`] applies what it edits.
49pub fn pmi_view_schema() -> serde_json::Value {
50    serde_json::json!({
51        "type": "pmiView",
52        "shortName": "VIEW",
53        "longName": "PMI view",
54        "inputParamsSchema": {
55            "name": { "type": "string", "label": "Name", "default_value": "View 1" },
56            "textSizePt": { "type": "number", "label": "Text size (pt)", "default_value": brep_kernel::PmiDisplay::default().text_size_pt },
57            "wireframe": { "type": "boolean", "label": "Wireframe", "default_value": false },
58            "sectionEnabled": { "type": "boolean", "label": "Section view", "default_value": false },
59            "sectionAxis": { "type": "options", "label": "Section normal", "options": ["View", "X", "Y", "Z", "Plane"], "default_value": "View" },
60            "sectionPlane": {
61                "type": "reference_selection", "label": "Section plane", "selectionFilter": ["FACE", "PLANE"], "multiple": false,
62                "minSelections": 0, "maxSelections": 1, "default_value": null,
63                "hint": "A planar face, datum plane or sketch plane to cut on (Section normal: Plane); the offset moves the cut along its normal"
64            },
65            "sectionOffset": { "type": "number", "label": "Section offset (mm)", "default_value": 0.0 },
66            "sectionFlip": { "type": "boolean", "label": "Reverse section", "default_value": false },
67            "halfAxis": {
68                "type": "options", "label": "Half section", "options": ["None", "View", "X", "Y", "Z"], "default_value": "None",
69                "hint": "A second plane through the section's origin: material is removed only where both planes remove it (a quarter cut away)"
70            },
71            "halfOffset": { "type": "number", "label": "Half section offset (mm)", "default_value": 0.0 },
72            "halfFlip": { "type": "boolean", "label": "Reverse half section", "default_value": false },
73            "sectionExclude": {
74                "type": "reference_selection", "label": "Not cut", "selectionFilter": ["SOLID", "COMPONENT"], "multiple": true,
75                "minSelections": 0, "maxSelections": 64, "default_value": [],
76                "hint": "Solids or components the section leaves whole, such as shafts and fasteners"
77            },
78            "updateCamera": { "type": "button", "label": "Update camera from the viewport" },
79            "hideSelected": { "type": "button", "label": "Hide the selected bodies in this view" }
80        }
81    })
82}
83
84/// The further planes a view's section edit asks for: a whole `sectionPlanes`
85/// list replaces them, then the form's `half*` rows set (or, `None`, drop)
86/// the first; what neither names is kept. A frozen `View` normal is kept for
87/// a plane that stays `View`.
88fn section_planes_from(
89    params: &serde_json::Value,
90    prior: Option<&brep_kernel::feature_pipeline::pmi::PmiSection>,
91) -> Result<Vec<brep_kernel::feature_pipeline::pmi::PmiSectionPlane>, String> {
92    use brep_kernel::feature_pipeline::pmi::PmiSectionPlane;
93    let prior_planes = prior.map(|s| s.planes.clone()).unwrap_or_default();
94    let valid = |plane: &PmiSectionPlane| ["View", "X", "Y", "Z"].contains(&plane.axis.as_str()) && plane.offset.is_finite();
95    let mut planes = match params.get("sectionPlanes") {
96        Some(serde_json::Value::Null) => Vec::new(),
97        Some(list) => {
98            let planes: Vec<PmiSectionPlane> = serde_json::from_value(list.clone()).map_err(|e| format!("invalid section planes: {e}"))?;
99            if !planes.iter().all(valid) {
100                return Err("invalid section plane".into());
101            }
102            planes
103        }
104        None => prior_planes,
105    };
106    if let Some(axis) = params.get("halfAxis").and_then(serde_json::Value::as_str) {
107        if axis == "None" {
108            if !planes.is_empty() {
109                planes.remove(0);
110            }
111        } else {
112            let before = planes.first();
113            let plane = PmiSectionPlane {
114                axis: axis.to_string(),
115                offset: params.get("halfOffset").and_then(serde_json::Value::as_f64).or(before.map(|p| p.offset)).unwrap_or(0.),
116                flip: params.get("halfFlip").and_then(serde_json::Value::as_bool).or(before.map(|p| p.flip)).unwrap_or(false),
117                normal: before.filter(|p| p.axis == axis).and_then(|p| p.normal),
118            };
119            if !valid(&plane) {
120                return Err("invalid section plane".into());
121            }
122            match planes.first_mut() {
123                Some(first) => *first = plane,
124                None => planes.push(plane),
125            }
126        }
127    }
128    // A View plane with no normal takes the captured direction in `freeze`.
129    Ok(planes)
130}
131
132/// A view's current values in [`pmi_view_schema`]'s shape — the form's seed.
133pub fn pmi_view_params(view: &brep_kernel::PmiView) -> serde_json::Value {
134    serde_json::json!({
135        "name": view.name,
136        "textSizePt": view.display.text_size_pt,
137        "wireframe": view.display.wireframe,
138        "sectionEnabled": view.display.section.is_some(),
139        "sectionAxis": view.display.section.as_ref().map(|s| s.axis.as_str()).unwrap_or("View"),
140        "sectionOffset": view.display.section.as_ref().map(|s| s.offset).unwrap_or(0.),
141        "sectionFlip": view.display.section.as_ref().is_some_and(|s| s.flip),
142        "sectionPlane": view.display.section.as_ref().and_then(|s| s.plane.as_deref()).unwrap_or(""),
143        "sectionExclude": view.display.section.as_ref().map(|s| s.exclude.clone()).unwrap_or_default(),
144        "halfAxis": view.display.section.as_ref().and_then(|s| s.planes.first()).map(|p| p.axis.as_str()).unwrap_or("None"),
145        "halfOffset": view.display.section.as_ref().and_then(|s| s.planes.first()).map(|p| p.offset).unwrap_or(0.),
146        "halfFlip": view.display.section.as_ref().and_then(|s| s.planes.first()).is_some_and(|p| p.flip),
147    })
148}
149
150/// `{solid}@x,y,z` in WORLD coordinates (the PMI vertex-ref convention).
151pub fn world_vertex_ref(solid: &str, position: [f64; 3]) -> String {
152    let trim = |v: f64| {
153        let rounded = (v * 1e9).round() / 1e9;
154        let trimmed = crate::formatting::compact_decimal(rounded, 9);
155        if trimmed == "-0" || trimmed.is_empty() { "0".to_string() } else { trimmed }
156    };
157    format!("{solid}@{},{},{}", trim(position[0]), trim(position[1]), trim(position[2]))
158}
159
160impl EngineState {
161    // --- read surface ------------------------------------------------------
162
163    /// The document's `pmi` block as typed state (the default — no views —
164    /// when the document carries none).
165    pub fn pmi_state(&self) -> PmiState {
166        self.history
167            .pmi_block()
168            .and_then(|block| serde_json::from_value(block.clone()).ok())
169            .unwrap_or_default()
170    }
171
172    /// [`Self::pmi_state`] parsed once per history revision and shared: what
173    /// a frame reads (an animation frame's section check and overlay), where
174    /// parsing the whole block each time cost ~14 ms a parse on a 500-step
175    /// view.
176    pub fn pmi_state_shared(&self) -> std::rc::Rc<PmiState> {
177        let revision = self.history.revision();
178        if let Some((at, state)) = self.pmi_state_cache.borrow().as_ref() {
179            if *at == revision {
180                return state.clone();
181            }
182        }
183        let state = std::rc::Rc::new(self.pmi_state());
184        *self.pmi_state_cache.borrow_mut() = Some((revision, state.clone()));
185        state
186    }
187
188    /// The PMI report of the last APPLIED run.
189    pub fn pmi_report(&self) -> Option<&PmiReport> {
190        self.pmi_report.as_ref()
191    }
192
193    pub fn pmi_active_view(&self) -> Option<&str> {
194        self.pmi_active_view.as_deref()
195    }
196
197    pub fn pmi_open_annotation(&self) -> Option<&str> {
198        self.pmi_open_annotation.as_deref()
199    }
200
201    /// The view whose dialog the PMI pane shows, if one is open.
202    pub fn pmi_open_view(&self) -> Option<&str> {
203        self.pmi_open_view.as_deref()
204    }
205
206    /// How many PMI dialogs — annotation or view — this engine has OPENED. The
207    /// app's dialog door reads it beside the open subject so a re-open of the
208    /// dialog already open is still an open (the id alone does not move).
209    /// Monotonic and never reset; a CLOSE does not count.
210    pub fn pmi_dialog_opens(&self) -> u64 {
211        self.pmi_dialog_opens
212    }
213
214    /// **The PMI half of the dialog door's counter.** Open `id`'s form and
215    /// count the open. EVERY path that opens an annotation form goes through
216    /// here — the panel's `+`, its row Edit and double-click, the viewport
217    /// label double click, the automation add — so the door has one signal to watch
218    /// and a re-open of the same annotation still reads as an open. Assigning
219    /// `pmi_open_annotation = Some(..)` anywhere else is the bug this exists to
220    /// prevent: the form would open with its pane still behind another tab.
221    ///
222    /// An open annotation is the selected one too — the dialog is about it —
223    /// and it replaces an open VIEW dialog, since the pane shows one dialog.
224    fn open_pmi_annotation(&mut self, id: String) {
225        self.pmi_open_view = None;
226        self.pmi_selected_view = None;
227        self.pmi_selected_annotation = Some(id.clone());
228        self.pmi_open_annotation = Some(id);
229        self.pmi_dialog_opens = self.pmi_dialog_opens.wrapping_add(1);
230    }
231
232    /// The view half of [`Self::open_pmi_annotation`]: open view `id`'s dialog,
233    /// closing an open annotation's, select the view and count the open.
234    fn open_pmi_view(&mut self, id: String) {
235        self.pmi_open_annotation = None;
236        if self.pmi_selected_annotation.take().is_some() {
237            self.refresh_pmi_overlay();
238        }
239        self.pmi_selected_view = Some(id.clone());
240        self.pmi_open_view = Some(id);
241        self.pmi_dialog_opens = self.pmi_dialog_opens.wrapping_add(1);
242    }
243
244    /// The annotation selected in the PMI tree (or opened), while it exists.
245    /// Asked every frame (the tree's highlight), so it reads the shared parse.
246    pub fn pmi_selected_annotation(&self) -> Option<&str> {
247        let id = self.pmi_selected_annotation.as_deref()?;
248        self.pmi_state_shared().find_annotation(id).is_some().then_some(id)
249    }
250
251    /// The view selected in the PMI tree (or opened), while it exists.
252    pub fn pmi_selected_view(&self) -> Option<&str> {
253        let id = self.pmi_selected_view.as_deref()?;
254        self.pmi_state_shared().find_view(id).is_some().then_some(id)
255    }
256
257    /// Whether the PMI workbench remembered a modeling state (it is "entered").
258    pub fn pmi_workbench_entered(&self) -> bool {
259        self.pmi_modeling.is_some()
260    }
261
262    /// The `__brepPmi` verifier global: the block, the report, the active
263    /// view, the open annotation and the datum letters, as one object.
264    pub fn pmi_state_json(&self) -> String {
265        self.pmi_state_value().to_string()
266    }
267
268    /// [`Self::pmi_state_json`] as a JSON value.
269    pub fn pmi_state_value(&self) -> serde_json::Value {
270        let state = self.pmi_state();
271        serde_json::json!({
272            "views": state.views,
273            "idCounter": state.id_counter,
274            "activeView": self.pmi_active_view,
275            "openAnnotation": self.pmi_open_annotation,
276            "openView": self.pmi_open_view,
277            "selectedAnnotation": self.pmi_selected_annotation(),
278            "selectedView": self.pmi_selected_view(),
279            "entered": self.pmi_modeling.is_some(),
280            "datums": state.datum_letters(),
281            "report": self.pmi_report,
282        })
283    }
284
285    // --- block writes --------------------------------------------------------
286
287    /// Write `state` as the document's block (checkpointed) and re-run the
288    /// history so the tail resolves it. An empty block is removed so a part
289    /// that never had PMI saves byte-identically.
290    pub(super) fn write_pmi_state(&mut self, state: PmiState) -> String {
291        let block = if state.is_empty() { None } else { serde_json::to_value(&state).ok() };
292        self.history.set_pmi_block(block, None);
293        self.rerun_history()
294    }
295
296    // --- views ---------------------------------------------------------------
297
298    /// The current camera as a snapshot.
299    pub(super) fn snapshot_camera(&self) -> PmiCamera {
300        let camera = &self.camera;
301        PmiCamera {
302            eye: camera.eye,
303            target: camera.target,
304            up: camera.up,
305            projection: match camera.projection {
306                Projection::Orthographic { half_height } => PmiProjection::Orthographic { half_height },
307                Projection::Perspective { fov_y_deg } => PmiProjection::Perspective { fov_y_deg },
308            },
309            viewport: [camera.width, camera.height],
310        }
311    }
312
313    /// The names of the solids currently hidden in the scene.
314    fn hidden_solid_names(&self) -> Vec<String> {
315        // A committed sketch's visibility is its own (`hidden_sketches`),
316        // never a view's: a sketch name is no solid a hide step resolves.
317        self.scene
318            .solids()
319            .iter()
320            .filter(|solid| !solid.visible && !solid.is_sketch)
321            .map(|solid| solid.name.clone())
322            .collect()
323    }
324
325    /// Capture a view: the current camera, hidden objects (its baseline hide
326    /// step) and wireframe setting, named `name` (or `View N`). The new view
327    /// becomes active.
328    pub fn pmi_capture_view(&mut self, name: Option<&str>) -> String {
329        let mut state = self.pmi_state();
330        let id = state.next_id("VIEW");
331        let name = name
332            .map(str::trim)
333            .filter(|n| !n.is_empty())
334            .map(String::from)
335            .unwrap_or_else(|| format!("View {}", state.views.len() + 1));
336        // The capture reads the MODELING visibility and wireframe: if another
337        // view is active its hides, wireframe and explode poses are what is on
338        // screen, so deactivate first (restores) — a view's baseline is what
339        // the user set up, not another view's display. The CAMERA is the one
340        // on screen all the same: a view stays active while the user goes on
341        // working and orbiting, and Capture means "this camera". It is read
342        // before the restore and given to the new view; the remembered
343        // modeling camera stays the one from before any view was active, as
344        // it does across a switch between views.
345        let live_camera = self.pmi_active_view.is_some().then(|| self.snapshot_camera());
346        if live_camera.is_some() {
347            self.pmi_deactivate_view();
348        }
349        self.pmi_remember_modeling();
350        let camera = live_camera.unwrap_or_else(|| self.snapshot_camera());
351        state.views.push(PmiView {
352            id: id.clone(),
353            name,
354            camera: Some(camera),
355            display: PmiDisplay::new(12.0, self.settings.wireframe, None),
356            annotations: Vec::new(),
357        });
358        state.set_view_baseline(&id, &self.hidden_solid_names());
359        self.write_pmi_state(state);
360        let _ = self.pmi_activate_view(&id);
361        id
362    }
363
364    pub fn pmi_rename_view(&mut self, id: &str, name: &str) -> Result<(), String> {
365        let mut state = self.pmi_state();
366        let view = state.find_view_mut(id).ok_or_else(|| format!("no PMI view '{id}'"))?;
367        let name = name.trim();
368        if name.is_empty() {
369            return Err("a view needs a name".into());
370        }
371        view.name = name.to_string();
372        self.write_pmi_state(state);
373        Ok(())
374    }
375
376    /// Delete a view (and its annotations). An active view deactivates first.
377    pub fn pmi_delete_view(&mut self, id: &str) -> Result<(), String> {
378        let mut state = self.pmi_state();
379        let before = state.views.len();
380        if self.pmi_active_view.as_deref() == Some(id) {
381            self.pmi_deactivate_view();
382        }
383        state.views.retain(|view| view.id != id);
384        if state.views.len() == before {
385            return Err(format!("no PMI view '{id}'"));
386        }
387        if let Some(open) = &self.pmi_open_annotation {
388            if state.find_annotation(open).is_none() {
389                self.pmi_open_annotation = None;
390            }
391        }
392        if self.pmi_open_view.as_deref() == Some(id) {
393            self.pmi_open_view = None;
394        }
395        self.write_pmi_state(state);
396        Ok(())
397    }
398
399    /// Re-capture a view's camera from the current camera (the explicit
400    /// Update Camera action — orbiting never rewrites a snapshot silently).
401    pub fn pmi_update_view_camera(&mut self, id: &str) -> Result<(), String> {
402        // A step's view: the capture is the step's author camera, kept
403        // through the step edits that regenerate a generated one. The step
404        // stays shown as the user had it (the capture rebuilds the views,
405        // which puts every view away).
406        if let Some(step) = self.instructions_step_of_view(id) {
407            let shown = self.instructions_shown_step().as_deref() == Some(step.as_str());
408            self.instructions_capture_camera(&step)?;
409            if shown {
410                self.instructions_show_step(&step)?;
411            }
412            return Ok(());
413        }
414        let mut state = self.pmi_state();
415        let camera = self.snapshot_camera();
416        let view = state.find_view_mut(id).ok_or_else(|| format!("no PMI view '{id}'"))?;
417        // A section saved before its plane was stored is anchored on the OLD
418        // camera first, so the cut stays where it was.
419        if let Some(section) = view.display.section.as_mut() {
420            section.freeze(view.camera.as_ref());
421        }
422        view.camera = Some(camera);
423        self.write_pmi_state(state);
424        Ok(())
425    }
426
427    /// Hide the selection in view `view_id` (the active view when `None`) as
428    /// a new **hide step** — a `hide` annotation naming the selected
429    /// components (whole placements, a part inside a sub-assembly by its
430    /// occurrence path, as an explode step names them) and any other
431    /// selected solids — tracked, listed, edited and undone like an explode
432    /// step. The step's form opens. Refused with nothing selected.
433    pub fn pmi_hide_selected(&mut self, view_id: Option<&str>) -> Result<String, String> {
434        let mut targets = self.selected_occurrences();
435        for solid in &self.emphasis.selected_solids {
436            if !targets.iter().any(|target| brep_kernel::entry_names_solid(target, solid)) {
437                targets.push(solid.clone());
438            }
439        }
440        if targets.is_empty() {
441            return Err("select the solids or components to hide".into());
442        }
443        let params = serde_json::json!({ "targets": targets }).to_string();
444        self.pmi_add_annotation(view_id, "hide", &params)
445    }
446
447    /// Patch a view's name / display state. The active view re-applies.
448    pub fn pmi_set_view_display(&mut self, id: &str, patch: &PmiViewPatch) -> Result<(), String> {
449        self.patch_pmi_view(id, patch, None)
450    }
451
452    /// Apply an edited **PMI view** form ([`pmi_view_schema`]'s params). Only
453    /// the fields that differ from the view are written, and a run of edits to
454    /// one view is ONE undo step — the form writes on every keystroke of the
455    /// name, the way an annotation's form does.
456    pub fn pmi_update_view(&mut self, id: &str, params_json: &str) -> Result<(), String> {
457        let params: serde_json::Value =
458            serde_json::from_str(params_json).map_err(|error| format!("view params: {error}"))?;
459        let state = self.pmi_state();
460        let view = state.find_view(id).ok_or_else(|| format!("no PMI view '{id}'"))?;
461        let name = params
462            .get("name")
463            .and_then(serde_json::Value::as_str)
464            .filter(|name| *name != view.name)
465            .map(String::from);
466        let text_size_pt = params
467            .get("textSizePt")
468            .and_then(serde_json::Value::as_f64)
469            .filter(|size| *size != view.display.text_size_pt);
470        let wireframe = params
471            .get("wireframe")
472            .and_then(serde_json::Value::as_bool)
473            .filter(|on| *on != view.display.wireframe);
474        let section = if params.get("sectionEnabled").is_some() {
475            let section = if params["sectionEnabled"].as_bool().unwrap_or(false) {
476                let axis = params["sectionAxis"].as_str().unwrap_or("View");
477                let offset = params["sectionOffset"].as_f64().unwrap_or(0.);
478                if !["View", "X", "Y", "Z", "Plane"].contains(&axis) || !offset.is_finite() { return Err("invalid section plane".into()); }
479                // The plane keeps the anchor it was set on: a re-captured
480                // camera must not move the cut. A newly chosen View axis takes
481                // the captured direction.
482                let prior = view.display.section.as_ref();
483                let mut section = brep_kernel::feature_pipeline::pmi::PmiSection {
484                    axis: axis.into(),
485                    offset,
486                    flip: params["sectionFlip"].as_bool().unwrap_or(false),
487                    origin: prior.and_then(|s| s.origin),
488                    normal: prior.filter(|s| s.axis == axis).and_then(|s| s.normal),
489                    // The picked face or plane (`Plane`): the run resolves it.
490                    plane: match params.get("sectionPlane") {
491                        Some(serde_json::Value::String(name)) => Some(name.trim().to_string()).filter(|name| !name.is_empty()),
492                        Some(serde_json::Value::Null) => None,
493                        _ => prior.and_then(|s| s.plane.clone()),
494                    },
495                    exclude: match params.get("sectionExclude") {
496                        Some(serde_json::Value::Array(names)) => names
497                            .iter()
498                            .filter_map(serde_json::Value::as_str)
499                            .map(|name| name.trim().to_string())
500                            .filter(|name| !name.is_empty())
501                            .collect(),
502                        Some(serde_json::Value::Null) => Vec::new(),
503                        _ => prior.map(|s| s.exclude.clone()).unwrap_or_default(),
504                    },
505                    planes: section_planes_from(&params, prior)?,
506                };
507                section.freeze(view.camera.as_ref());
508                Some(section)
509            } else { None };
510            (section != view.display.section).then_some(section)
511        } else { None };
512        if name.is_none() && text_size_pt.is_none() && wireframe.is_none() && section.is_none() {
513            return Ok(());
514        }
515        let patch = PmiViewPatch { name, text_size_pt, wireframe, hidden: None, section };
516        self.patch_pmi_view(id, &patch, Some(&format!("pmi:view:{id}")))
517    }
518
519    /// Set view `id`'s section the way its form's section rows do, as ONE
520    /// undo step: `enabled` turns it on or off, and each field left `None`
521    /// keeps what the section has (or the form's default: `View`, offset 0,
522    /// not reversed, no plane, nothing left whole, no further planes).
523    /// `planes` replaces the further planes (a half or corner cut away;
524    /// empty: none). The plane is anchored as the form anchors it
525    /// ([`Self::pmi_update_view`]).
526    #[allow(clippy::too_many_arguments)]
527    pub fn pmi_set_view_section(
528        &mut self,
529        id: &str,
530        enabled: bool,
531        axis: Option<&str>,
532        offset: Option<f64>,
533        flip: Option<bool>,
534        plane: Option<&str>,
535        exclude: Option<Vec<String>>,
536        planes: Option<Vec<brep_kernel::feature_pipeline::pmi::PmiSectionPlane>>,
537    ) -> Result<(), String> {
538        let state = self.pmi_state();
539        let view = state.find_view(id).ok_or_else(|| format!("no PMI view '{id}'"))?;
540        let prior = view.display.section.as_ref();
541        // A plane named with no axis cuts on that plane, as picking one in
542        // the form does.
543        let axis = axis.or_else(|| plane.filter(|plane| !plane.trim().is_empty()).map(|_| "Plane"));
544        let mut params = serde_json::json!({
545            "sectionEnabled": enabled,
546            "sectionAxis": axis.map(str::to_string).or_else(|| prior.map(|s| s.axis.clone())).unwrap_or_else(|| "View".into()),
547            "sectionOffset": offset.or_else(|| prior.map(|s| s.offset)).unwrap_or(0.),
548            "sectionFlip": flip.or_else(|| prior.map(|s| s.flip)).unwrap_or(false),
549        });
550        if let Some(plane) = plane {
551            params["sectionPlane"] = plane.into();
552        }
553        if let Some(exclude) = exclude {
554            params["sectionExclude"] = exclude.into();
555        }
556        if let Some(planes) = planes {
557            params["sectionPlanes"] = serde_json::to_value(planes).map_err(|e| e.to_string())?;
558        }
559        self.history.break_coalescing();
560        let result = self.pmi_update_view(id, &params.to_string());
561        self.history.break_coalescing();
562        result
563    }
564
565    /// Open view `id`'s dialog (`None` closes it). Opening activates the view,
566    /// as opening one of its annotations does: the dialog describes what is on
567    /// screen. An id that names no view opens nothing and counts nothing.
568    pub fn pmi_set_view_open(&mut self, id: Option<&str>) {
569        match id {
570            Some(id) => {
571                if self.pmi_state().find_view(id).is_none() {
572                    return;
573                }
574                if self.pmi_active_view.as_deref() != Some(id) {
575                    let _ = self.pmi_activate_view(id);
576                }
577                self.open_pmi_view(id.to_string());
578            }
579            None => self.pmi_open_view = None,
580        }
581        self.refresh_pmi_overlay();
582    }
583
584    fn patch_pmi_view(&mut self, id: &str, patch: &PmiViewPatch, coalesce_key: Option<&str>) -> Result<(), String> {
585        let mut state = self.pmi_state();
586        let view = state.find_view_mut(id).ok_or_else(|| format!("no PMI view '{id}'"))?;
587        if let Some(name) = &patch.name {
588            let name = name.trim();
589            if name.is_empty() {
590                return Err("a view needs a name".into());
591            }
592            view.name = name.to_string();
593        }
594        if let Some(size) = patch.text_size_pt {
595            view.display.text_size_pt = brep_kernel::clamp_text_size(size);
596        }
597        if let Some(wireframe) = patch.wireframe {
598            view.display.wireframe = wireframe;
599        }
600        if let Some(section) = &patch.section { view.display.section = section.clone(); }
601        if let Some(hidden) = &patch.hidden {
602            let solids = self.view_hideable_names();
603            state.set_view_hidden(id, hidden, &solids);
604        }
605        let view = state.find_view(id).expect("patched above").clone();
606        let block = if state.is_empty() { None } else { serde_json::to_value(&state).ok() };
607        self.history.set_pmi_block(block, coalesce_key);
608        self.rerun_history();
609        if self.pmi_active_view.as_deref() == Some(id) {
610            self.apply_view_display(&view);
611        }
612        Ok(())
613    }
614
615    /// The scene's solid names a view's hide step can name (committed
616    /// sketches excluded: their visibility is `hidden_sketches`).
617    fn view_hideable_names(&self) -> Vec<String> {
618        self.scene.solids().iter().filter(|solid| !solid.is_sketch).map(|solid| solid.name.clone()).collect()
619    }
620
621    /// **A viewport hide or show while a view is active is an edit of that
622    /// view** (one undo step): hiding adds a hide step naming what was not
623    /// hidden yet, showing drops the names from its hide steps (a hidden
624    /// component keeps its other solids hidden). The view then re-applies,
625    /// so leaving and re-entering it shows the same thing, and its sheets,
626    /// 3D PDF and report agree. Names that are no scene solid are ignored.
627    /// False when nothing changed.
628    pub(crate) fn pmi_record_visibility(&mut self, view_id: &str, names: &[String], visible: bool) -> bool {
629        let solids = self.view_hideable_names();
630        let names: Vec<String> = names.iter().filter(|name| solids.contains(name)).cloned().collect();
631        if names.is_empty() {
632            return false;
633        }
634        let mut state = self.pmi_state();
635        let changed = if visible {
636            state.show_in_view(view_id, &names, &solids)
637        } else {
638            state.hide_in_view(view_id, &names).is_some()
639        };
640        if !changed {
641            return false;
642        }
643        let Some(view) = state.find_view(view_id).cloned() else { return false };
644        self.write_pmi_state(state);
645        if self.pmi_active_view.as_deref() == Some(view_id) {
646            self.apply_view_display(&view);
647            self.refresh_pmi_overlay();
648        }
649        true
650    }
651
652    /// Remember the modeling state: what is on screen while NO view is
653    /// active is the modeling state (hiding a body in the workbench before
654    /// capturing is a modeling change, not a view's), so it is re-snapshotted
655    /// whenever an activation starts from no active view; while a view is
656    /// active the snapshot is kept (switching views restores to it).
657    fn pmi_remember_modeling(&mut self) {
658        if self.pmi_active_view.is_none() || self.pmi_modeling.is_none() {
659            self.pmi_modeling = Some(PmiModelingSnapshot {
660                camera_json: self.camera_state_json(),
661                hidden: self.hidden_solid_names(),
662                wireframe: self.settings.wireframe,
663            });
664        }
665    }
666
667    /// Entering the PMI workbench: remember the modeling camera, visibility
668    /// and wireframe so a view activation can be undone exactly.
669    pub fn pmi_enter_workbench(&mut self) {
670        self.pmi_remember_modeling();
671    }
672
673    /// Leaving the PMI workbench: deactivate the view (restoring the modeling
674    /// state), close its dialogs, and forget the snapshot. An open SHEET is
675    /// not this workbench's to close — sheets are the Drawing workbench's, and
676    /// the shell closes the paper when a workbench hides the Sheets pane.
677    pub fn pmi_leave_workbench(&mut self) {
678        self.pmi_deactivate_view();
679        self.pmi_modeling = None;
680        self.pmi_open_annotation = None;
681        self.pmi_open_view = None;
682        self.refresh_pmi_overlay();
683    }
684
685    /// Apply a view's visibility and wireframe: a solid is hidden when the
686    /// view `hides` it — its captured baseline or one of its hide steps
687    /// (`PmiView::hides`, by name, so a step just added, edited, removed or
688    /// undone takes effect without waiting on a run).
689    fn apply_view_display(&mut self, view: &PmiView) {
690        let display = &view.display;
691        let names: Vec<String> = self.scene.solids().iter().map(|s| s.name.clone()).collect();
692        for name in names {
693            let hidden = view.hides(&name);
694            if let Some(original) = self.pmi_explode_originals.get_mut(&name).filter(|original| original.visible == hidden) {
695                original.visible = !hidden;
696                self.pmi_unposed_visibility += 1;
697            }
698            if hidden {
699                // Hidden by the view: restoring the section must not show it.
700                self.pmi_section_hidden.retain(|hidden| *hidden != name);
701                self.scene.set_visible(&name, false);
702            } else if !self.pmi_section_hidden.contains(&name) {
703                // A solid the section removes whole stays hidden.
704                self.scene.set_visible(&name, true);
705            }
706        }
707        if self.settings.wireframe != display.wireframe {
708            self.settings.wireframe = display.wireframe;
709            self.settings_generation = self.settings_generation.wrapping_add(1);
710        }
711        self.dirty = true;
712    }
713
714    /// Activate a view: apply its camera (refit to the live viewport), hidden
715    /// names, wireframe and explode poses; its annotations become the drawn
716    /// and editable set.
717    pub fn pmi_activate_view(&mut self, id: &str) -> Result<(), String> {
718        let state = self.pmi_state();
719        let view = state.find_view(id).ok_or_else(|| format!("no PMI view '{id}'"))?.clone();
720        if self.pmi_active_view.as_deref() != Some(id) {
721            // Switching views keeps the snapshot: deactivating restores the
722            // modeling state, and the new view starts from it.
723            let keep = self.pmi_active_view.is_some();
724            self.pmi_deactivate_view();
725            if !keep {
726                self.pmi_remember_modeling();
727            }
728        }
729        if self.pmi_modeling.is_none() {
730            self.pmi_remember_modeling();
731        }
732        if self.pmi_active_view.as_deref() != Some(id) {
733            // A view activated afresh shows every explode step at full.
734            self.explode_playback = Default::default();
735        }
736        self.pmi_active_view = Some(id.to_string());
737        if let Some(camera) = &view.camera {
738            let (kind, scale) = match camera.projection {
739                PmiProjection::Orthographic { half_height } => ("orthographic", half_height),
740                PmiProjection::Perspective { fov_y_deg } => ("perspective", fov_y_deg),
741            };
742            let json = serde_json::json!({
743                "kind": kind, "eye": camera.eye, "target": camera.target, "up": camera.up, "scale": scale,
744            })
745            .to_string();
746            let _ = self.apply_camera_state_json(&json);
747            self.controls_sync_after_camera_apply();
748        }
749        self.apply_view_display(&view);
750        self.pmi_apply_explode();
751        self.instructions_refresh_ghosts();
752        if let Some(open) = &self.pmi_open_annotation {
753            if !view.annotations.iter().any(|a| a.id() == open) {
754                self.pmi_open_annotation = None;
755            }
756        }
757        self.refresh_pmi_overlay();
758        Ok(())
759    }
760
761    /// Deactivate the active view: restore the explode poses, the modeling
762    /// visibility, wireframe and camera. A no-op without an active view.
763    pub fn pmi_deactivate_view(&mut self) {
764        if self.pmi_active_view.take().is_none() {
765            return;
766        }
767        // Instructions' ghosts go before the modeling visibility comes back.
768        self.instructions_refresh_ghosts();
769        if self.pmi_state().find_annotation(&self.transform_armed_feature()).is_some() { self.disarm_transform(); }
770        self.pmi_restore_explode();
771        if let Some(snapshot) = self.pmi_modeling.clone() {
772            let names: Vec<String> = self.scene.solids().iter().map(|s| s.name.clone()).collect();
773            for name in names {
774                let visible = !snapshot.hidden.contains(&name);
775                self.scene.set_visible(&name, visible);
776            }
777            if self.settings.wireframe != snapshot.wireframe {
778                self.settings.wireframe = snapshot.wireframe;
779                self.settings_generation = self.settings_generation.wrapping_add(1);
780            }
781            let _ = self.apply_camera_state_json(&snapshot.camera_json);
782            self.controls_sync_after_camera_apply();
783        }
784        self.pmi_open_annotation = None;
785        self.dirty = true;
786        self.refresh_pmi_overlay();
787    }
788
789    /// Keep the arcball controls in step with a camera written wholesale.
790    pub(super) fn controls_sync_after_camera_apply(&mut self) {
791        // The controls read the camera each frame (orbit deltas are applied
792        // onto `self.camera`), so writing the camera is enough; a fresh depth
793        // fit happens on the next render. Nothing else to sync.
794        self.dirty = true;
795    }
796
797    // --- explode (display-only poses) -----------------------------------------
798
799    /// Pose the active view's explode targets on the CURRENT displays,
800    /// keeping the un-posed copies for the restore.
801    pub(crate) fn pmi_apply_explode(&mut self) {
802        let Some(active) = self.pmi_active_view.clone() else {
803            self.pmi_restore_explode();
804            return;
805        };
806        let report = self.pmi_report.as_ref().and_then(|report| report.view(&active));
807        let state = self.pmi_state_shared();
808        let view = state.find_view(&active);
809        // Every plane of the section: material goes only where all remove it.
810        let planes = view.map(|v| v.section_planes_in(report)).unwrap_or_default();
811        let section = (!planes.is_empty()).then_some(());
812        let exclude = view.and_then(|v| v.display.section.clone());
813        let poses: Vec<(Vec<String>, [f64; 3], [f64; 3], [f64; 3], [f64; 3])> = report
814            .map(|view| {
815                view.annotations
816                    .iter()
817                    .filter(|row| row.enabled && row.status == PmiStatus::Ok)
818                    .filter(|row| matches!(row.geometry, PmiGeometry::Explode { .. }))
819                    .enumerate()
820                    // Each step at its playback fraction (`exploded_ops`; 1 unless animating).
821                    .filter_map(|(step, row)| match super::exploded_ops::explode_at(&row.geometry, self.explode_fraction(step)) {
822                        PmiGeometry::Explode { solids, translate, rotate_deg, scale, center, .. } => {
823                            Some((solids, translate, rotate_deg, scale, center))
824                        }
825                        _ => None,
826                    })
827                    .collect()
828            })
829            .unwrap_or_default();
830        // An instructions step's insertion: its arrowed parts on their way home.
831        let mut poses = poses;
832        poses.extend(self.instructions_insertion_poses());
833        if section.is_none() && self.pmi_section_hidden.is_empty() && !self.pmi_explode_originals.is_empty() {
834            // Posed again (an animation frame): a display already posed is
835            // reset from its original's geometry, copied into the buffers it
836            // holds, rather than restored and cloned whole again (every frame,
837            // every moving solid: ~500 on a deep l500 view). A section changes
838            // the meshes themselves, so a sectioned view takes the full way.
839            let wanted: std::collections::HashSet<&String> = poses.iter().flat_map(|pose| pose.0.iter()).collect();
840            let stale: Vec<String> = self.pmi_explode_originals.keys().filter(|name| !wanted.contains(name)).cloned().collect();
841            for name in stale {
842                if let (Some(original), Some(display)) = (self.pmi_explode_originals.remove(&name), self.scene.solid_mut(&name)) {
843                    *display = original;
844                }
845            }
846            for name in wanted {
847                match self.pmi_explode_originals.get(name) {
848                    Some(original) => {
849                        if let Some(display) = self.scene.solid_mut(name) {
850                            reset_posed_geometry(display, original);
851                        }
852                    }
853                    None => {
854                        if let Some(display) = self.scene.solid(name) {
855                            self.pmi_explode_originals.insert(name.clone(), display.clone());
856                        }
857                    }
858                }
859            }
860        } else {
861            self.pmi_restore_explode();
862            for (solids, ..) in &poses {
863                for name in solids {
864                    let Some(display) = self.scene.solid(name) else { continue };
865                    self.pmi_explode_originals.entry(name.clone()).or_insert_with(|| display.clone());
866                }
867            }
868        }
869        for (solids, translate, rotate_deg, scale, center) in poses {
870            for name in solids {
871                if let Some(display) = self.scene.solid_mut(&name) {
872                    transform_display(display, center, translate, rotate_deg, scale);
873                }
874            }
875        }
876        if section.is_some() {
877            use super::pmi_section::{side_of_all, Side};
878            // A solid wholly on the kept side is left exactly as it is (no
879            // copy, no new revision: the GPU keeps its buffers); one wholly
880            // removed is hidden, which keeps its revision too, and its
881            // un-hidden original is kept so sheets and the 3D PDF still draw
882            // it. Only what the plane crosses is clipped, capped and
883            // re-uploaded.
884            // A solid the section excludes (a shaft, a fastener) stays whole.
885            let names: Vec<(String, Side)> = self
886                .scene
887                .solids()
888                .iter()
889                .map(|s| (s.name.clone(), if exclude.as_ref().is_some_and(|cut| cut.excludes(&s.name)) { Side::Kept } else { side_of_all(s, &planes) }))
890                .collect();
891            for (name, side) in names {
892                match side {
893                    Side::Kept => {}
894                    Side::Removed => {
895                        if let Some(display) = self.scene.solid(&name).filter(|display| display.visible) {
896                            self.pmi_explode_originals.entry(name.clone()).or_insert_with(|| display.clone());
897                            self.scene.set_visible(&name, false);
898                            self.pmi_section_hidden.push(name);
899                        }
900                    }
901                    Side::Cut => {
902                        if let Some(display) = self.scene.solid(&name) { self.pmi_explode_originals.entry(name.clone()).or_insert_with(|| display.clone()); }
903                        if let Some(display) = self.scene.solid_mut(&name) { super::pmi_section::clip_display_all(display, &planes); }
904                    }
905                }
906            }
907        }
908        if !self.pmi_explode_originals.is_empty() || !self.pmi_section_hidden.is_empty() {
909            self.dirty = true;
910        }
911    }
912
913    /// Put every exploded display back exactly.
914    pub(crate) fn pmi_restore_explode(&mut self) {
915        for name in std::mem::take(&mut self.pmi_section_hidden) {
916            self.scene.set_visible(&name, true);
917        }
918        let originals = std::mem::take(&mut self.pmi_explode_originals);
919        for (name, original) in originals {
920            if let Some(display) = self.scene.solid_mut(&name) {
921                *display = original;
922            }
923        }
924        self.dirty = true;
925    }
926
927    /// Post-apply tail (`finish_apply`): the displays are fresh, so re-pose
928    /// the active view's explode targets and re-bake the overlay.
929    pub(crate) fn pmi_after_apply(&mut self) {
930        // The fresh report resolved every balloon's head from its stored bubble.
931        self.pmi_balloon_stale = None;
932        // Normally already un-posed by `apply_run_output` (before the scene
933        // reconcile); the parse-error branch of a rerun reaches here with the
934        // poses still applied, so restore rather than forget them.
935        self.pmi_restore_explode();
936        if let Some(active) = self.pmi_active_view.clone() {
937            // A view that vanished (undo of its capture) deactivates.
938            let view = self.pmi_state().find_view(&active).cloned();
939            match view {
940                None => {
941                    self.pmi_active_view = None;
942                    self.pmi_open_annotation = None;
943                }
944                Some(view) => {
945                    // The view's hide steps may have changed with this run
946                    // (added, edited, removed, suppressed, undone): the
947                    // displays take the view's visibility again, then its poses.
948                    self.apply_view_display(&view);
949                    self.pmi_apply_explode();
950                }
951            }
952        }
953        self.instructions_refresh_ghosts();
954        if let Some(open) = &self.pmi_open_annotation {
955            if self.pmi_state().find_annotation(open).is_none() {
956                self.pmi_open_annotation = None;
957            }
958        }
959        // A view dialog whose view went away (undo of its capture) closes.
960        if let Some(open) = &self.pmi_open_view {
961            if self.pmi_state().find_view(open).is_none() {
962                self.pmi_open_view = None;
963            }
964        }
965        self.refresh_pmi_overlay();
966    }
967
968    // --- annotations -----------------------------------------------------------
969
970    /// Add an annotation of `type_id` to view `view_id` (the active view when
971    /// `None`) with `params_json` (the schema params; `id` is minted). A datum
972    /// with no letter gets the next unused one. Returns the id; the new
973    /// annotation's form opens.
974    pub fn pmi_add_annotation(
975        &mut self,
976        view_id: Option<&str>,
977        type_id: &str,
978        params_json: &str,
979    ) -> Result<String, String> {
980        let def = brep_kernel::pmi_type(type_id).ok_or_else(|| format!("unknown PMI annotation type '{type_id}'"))?;
981        let mut state = self.pmi_state();
982        let view_id = view_id
983            .map(String::from)
984            .or_else(|| self.pmi_active_view.clone())
985            .ok_or_else(|| "no active PMI view — capture or activate a view first".to_string())?;
986        let id = state.next_id(def.short_name);
987        let mut params: serde_json::Value = serde_json::from_str(params_json).unwrap_or_else(|_| serde_json::json!({}));
988        if !params.is_object() {
989            params = serde_json::json!({});
990        }
991        // Schema defaults under the given params.
992        let schema = (def.schema)();
993        if let (Some(fields), Some(object)) = (
994            schema.get("inputParamsSchema").and_then(serde_json::Value::as_object),
995            params.as_object_mut(),
996        ) {
997            for (key, spec) in fields {
998                if !object.contains_key(key) {
999                    if let Some(default) = spec.get("default_value") {
1000                        if !default.is_null() {
1001                            object.insert(key.clone(), default.clone());
1002                        }
1003                    }
1004                }
1005            }
1006            crate::pmi_weld_symbol::seed_defaults(type_id, object);
1007            object.insert("id".into(), serde_json::Value::String(id.clone()));
1008            if type_id == "datum" {
1009                let letter = object.get("letter").and_then(serde_json::Value::as_str).unwrap_or("").trim().to_string();
1010                if letter.is_empty() {
1011                    if let Some(next) = state.next_datum_letter() {
1012                        object.insert("letter".into(), serde_json::Value::String(next));
1013                    }
1014                }
1015            }
1016        }
1017        let view = state.find_view_mut(&view_id).ok_or_else(|| format!("no PMI view '{view_id}'"))?;
1018        view.annotations.push(PmiAnnotation {
1019            plugin_replay: None,
1020            persistent_data: serde_json::Value::Null,
1021            kind: type_id.to_string(),
1022            enabled: true,
1023            params,
1024            label_world: None,
1025        });
1026        self.open_pmi_annotation(id.clone());
1027        self.write_pmi_state(state);
1028        Ok(id)
1029    }
1030
1031    /// Replace an annotation's params (a form edit). Re-runs.
1032    pub fn pmi_update_annotation(&mut self, id: &str, params_json: &str) -> Result<(), String> {
1033        if self.pmi_state().find_annotation(id).is_some_and(|(_, a)| a.kind.contains('/')) {
1034            let params = serde_json::from_str(params_json).map_err(|e| format!("annotation params: {e}"))?;
1035            return self.plugin_update_annotation(id, params).map(|_| ());
1036        }
1037        self.pmi_update_annotation_no_rerun(id, params_json)?;
1038        self.rerun_history();
1039        Ok(())
1040    }
1041
1042    /// The fold half of [`Self::pmi_update_annotation`] (checkpointed, no
1043    /// re-run) — the reference picker's commit uses it before its shared
1044    /// end tail re-runs.
1045    pub(crate) fn pmi_update_annotation_no_rerun(&mut self, id: &str, params_json: &str) -> Result<(), String> {
1046        let mut state = self.pmi_state();
1047        let annotation = state.find_annotation_mut(id).ok_or_else(|| format!("no PMI annotation '{id}'"))?;
1048        if annotation.kind.contains('/') {
1049            return Err("plugin annotation edits require the worker transaction path".into());
1050        }
1051        let mut params: serde_json::Value =
1052            serde_json::from_str(params_json).map_err(|error| format!("annotation params: {error}"))?;
1053        if let Some(object) = params.as_object_mut() {
1054            object.insert("id".into(), serde_json::Value::String(id.to_string()));
1055        }
1056        annotation.params = params;
1057        let block = serde_json::to_value(&state).ok();
1058        self.history.set_pmi_block(block, Some(&format!("pmi:params:{id}")));
1059        Ok(())
1060    }
1061
1062    pub fn pmi_remove_annotation(&mut self, id: &str) -> Result<(), String> {
1063        if self.pmi_state().find_annotation(id).is_some_and(|(_, a)| a.kind.contains('/')) {
1064            return self.plugin_delete_annotation(id).map(|_| ());
1065        }
1066        let mut state = self.pmi_state();
1067        let Some((view_index, index)) = state.locate_annotation(id) else {
1068            return Err(format!("no PMI annotation '{id}'"));
1069        };
1070        state.views[view_index].annotations.remove(index);
1071        if self.pmi_open_annotation.as_deref() == Some(id) {
1072            self.pmi_open_annotation = None;
1073        }
1074        self.write_pmi_state(state);
1075        Ok(())
1076    }
1077
1078    pub fn pmi_set_annotation_enabled(&mut self, id: &str, enabled: bool) -> Result<(), String> {
1079        if self.pmi_state().find_annotation(id).is_some_and(|(_, a)| a.kind.contains('/')) {
1080            return self.plugin_set_annotation_enabled(id, enabled).map(|_| ());
1081        }
1082        let mut state = self.pmi_state();
1083        let annotation = state.find_annotation_mut(id).ok_or_else(|| format!("no PMI annotation '{id}'"))?;
1084        if annotation.enabled == enabled {
1085            return Ok(());
1086        }
1087        annotation.enabled = enabled;
1088        self.write_pmi_state(state);
1089        Ok(())
1090    }
1091
1092    /// Move an annotation to `index` within its view.
1093    pub fn pmi_move_annotation(&mut self, id: &str, index: usize) -> Result<(), String> {
1094        let mut state = self.pmi_state();
1095        let Some((view_index, from)) = state.locate_annotation(id) else {
1096            return Err(format!("no PMI annotation '{id}'"));
1097        };
1098        let annotations = &mut state.views[view_index].annotations;
1099        let annotation = annotations.remove(from);
1100        let to = index.min(annotations.len());
1101        annotations.insert(to, annotation);
1102        self.write_pmi_state(state);
1103        Ok(())
1104    }
1105
1106    /// Move an annotation to another view (append).
1107    pub fn pmi_move_annotation_to_view(&mut self, id: &str, view_id: &str) -> Result<(), String> {
1108        let mut state = self.pmi_state();
1109        let Some((view_index, from)) = state.locate_annotation(id) else {
1110            return Err(format!("no PMI annotation '{id}'"));
1111        };
1112        if state.find_view(view_id).is_none() {
1113            return Err(format!("no PMI view '{view_id}'"));
1114        }
1115        let annotation = state.views[view_index].annotations.remove(from);
1116        state.find_view_mut(view_id).expect("checked").annotations.push(annotation);
1117        self.write_pmi_state(state);
1118        Ok(())
1119    }
1120
1121    /// Open one annotation's form (engine memory; `None` closes). Opening an
1122    /// annotation of another view activates that view. An open COUNTS
1123    /// (`Self::open_pmi_annotation`) — including a re-open of the annotation
1124    /// already open, which is a viewport label double click on the form the user
1125    /// cannot see; an id that resolves to no annotation opens nothing and
1126    /// counts nothing.
1127    pub fn pmi_set_annotation_open(&mut self, id: Option<&str>) {
1128        match id {
1129            Some(id) => {
1130                let state = self.pmi_state();
1131                if let Some((view, _)) = state.find_annotation(id) {
1132                    let view_id = view.id.clone();
1133                    if self.pmi_active_view.as_deref() != Some(view_id.as_str()) {
1134                        let _ = self.pmi_activate_view(&view_id);
1135                    }
1136                    self.open_pmi_annotation(id.to_string());
1137                }
1138            }
1139            None => {
1140                if self.pmi_open_annotation.as_deref() == Some(self.transform_armed_feature().as_str()) { self.disarm_transform(); }
1141                self.pmi_open_annotation = None;
1142            },
1143        }
1144        self.refresh_pmi_overlay();
1145    }
1146
1147    // --- labels -----------------------------------------------------------------
1148
1149    /// Move an annotation's label (world). Coalesced per annotation into ONE
1150    /// undo step, and NEVER a re-run: the cached report is patched in place
1151    /// and the overlay re-baked. A balloon's arrow head is re-derived from
1152    /// the moved bubble (`Self::pmi_reproject_balloon_head`).
1153    pub fn pmi_set_label_world(&mut self, id: &str, world: [f64; 3]) -> Result<(), String> {
1154        let mut state = self.pmi_state();
1155        let annotation = state.find_annotation_mut(id).ok_or_else(|| format!("no PMI annotation '{id}'"))?;
1156        annotation.label_world = Some(world);
1157        let block = serde_json::to_value(&state).ok();
1158        self.history.set_pmi_block(block, Some(&format!("pmi:label:{id}")));
1159        if let Some(report) = self.pmi_report.as_mut() {
1160            if let Some(row) = report.annotation_mut(id) {
1161                row.label_world = world;
1162                if let PmiGeometry::Note { position } = &mut row.geometry {
1163                    *position = world;
1164                }
1165            }
1166        }
1167        self.pmi_reproject_balloon_head(id);
1168        self.refresh_pmi_overlay();
1169        Ok(())
1170    }
1171
1172    /// Re-derive a balloon's arrow head from its row's bubble through the
1173    /// recipe the kernel put on its leader (the same projection the resolver
1174    /// ran, on the exact-solid clones the scene holds), and patch the cached
1175    /// report. The head is derived, never stored, so no document edit and no
1176    /// run: the next run resolves the same head from the stored bubble. A
1177    /// solid the scene does not hold yet is asked of the runner; the head is
1178    /// re-derived when the reply lands ([`Self::pmi_refresh_stale_balloon`]),
1179    /// which for the Inline runner is before this returns. Any other
1180    /// annotation is left alone.
1181    pub(crate) fn pmi_reproject_balloon_head(&mut self, id: &str) {
1182        if let Some(missing) = self.pmi_balloon_head_now(id) {
1183            self.pmi_balloon_stale = Some(id.to_string());
1184            self.request_exact_solids(missing.iter().map(String::as_str));
1185            self.pmi_refresh_stale_balloon();
1186        }
1187    }
1188
1189    /// Retry the balloon whose re-projection waited on a topology reply.
1190    pub(crate) fn pmi_refresh_stale_balloon(&mut self) {
1191        let Some(id) = self.pmi_balloon_stale.take() else {
1192            return;
1193        };
1194        if self.pmi_balloon_head_now(&id).is_some() {
1195            // Still waiting (a background runner's reply is on its way).
1196            self.pmi_balloon_stale = Some(id);
1197        } else {
1198            self.refresh_pmi_overlay();
1199        }
1200    }
1201
1202    /// One re-projection attempt: `None` when done (or not a balloon), else
1203    /// the occurrence solids the scene does not hold.
1204    pub(super) fn pmi_balloon_head_now(&mut self, id: &str) -> Option<Vec<String>> {
1205        let (mut anchor, bubble) = self
1206            .pmi_report
1207            .as_ref()
1208            .and_then(|report| report.annotation(id))
1209            .and_then(|row| match &row.geometry {
1210                PmiGeometry::Leader { balloon: true, anchor: Some(anchor), .. } => Some((anchor.clone(), row.label_world)),
1211                _ => None,
1212            })?;
1213        anchor.camera = Some(self.snapshot_camera());
1214        let mut missing = Vec::new();
1215        let head = brep_kernel::pmi_balloon_head(&anchor, bubble, |name| self.scene.exact_solid(name), &mut missing);
1216        if !missing.is_empty() {
1217            return Some(missing);
1218        }
1219        // A fixed (vertex) anchor answers `None`: the head never moves. A
1220        // projection error keeps the kernel's head rather than a wrong one.
1221        if let Ok(Some(head)) = head {
1222            if let Some(row) = self.pmi_report.as_mut().and_then(|report| report.annotation_mut(id)) {
1223                if let PmiGeometry::Leader { targets, anchor: recipe, .. } = &mut row.geometry {
1224                    *recipe = Some(anchor);
1225                    if let Some(first) = targets.first_mut() {
1226                        *first = head;
1227                    }
1228                }
1229            }
1230        }
1231        None
1232    }
1233
1234    /// Drag an annotation's label to the pointer: the new position is where
1235    /// the pick ray crosses the plane through the current label perpendicular
1236    /// to the viewing direction (so a drag never changes the label's depth).
1237    pub fn pmi_label_drag_to(&mut self, id: &str, x: f64, y: f64) {
1238        // Part-way through explode playback the chip is drawn where its body
1239        // is now: the drag runs there, and is stored back in the run's frame.
1240        let playback = self.explode_playback_poses();
1241        let Some((current, plane)) = self
1242            .pmi_report
1243            .as_ref()
1244            .and_then(|r| r.annotation(id))
1245            .map(|r| (playback.as_ref().map_or(r.label_world, |poses| poses.shown(r, r.label_world)), r.plane))
1246        else {
1247            return;
1248        };
1249        let ray = self.camera.pick_ray(x, y);
1250        // In a picked annotation plane the label stays ON that plane; a
1251        // view-aligned label moves in the view-parallel plane through its
1252        // current position.
1253        let plane = plane.unwrap_or_else(|| {
1254            let (_, _, view) = self.camera.basis();
1255            brep_kernel::PmiPlane {
1256                origin: current,
1257                normal: view,
1258                x_axis: [0.0; 3],
1259            }
1260        });
1261        let Some(world) = plane.hit(ray.origin, ray.dir) else {
1262            return;
1263        };
1264        let world = match (&playback, self.pmi_report.as_ref().and_then(|r| r.annotation(id))) {
1265            (Some(poses), Some(row)) => poses.full(row, world),
1266            _ => world,
1267        };
1268        let _ = self.pmi_set_label_world(id, world);
1269    }
1270
1271    /// A label drag ended: the next drag is a fresh undo step.
1272    pub fn pmi_label_drag_end(&mut self) {
1273        self.history.break_coalescing();
1274    }
1275
1276    /// Hover a label: highlight the annotation's referenced geometry.
1277    pub fn pmi_hover(&mut self, id: &str) {
1278        self.pmi_label_hover_active = true;
1279        if self.pmi_hovered.as_deref() == Some(id) {
1280            return;
1281        }
1282        let references: Vec<String> = self
1283            .pmi_report
1284            .as_ref()
1285            .and_then(|report| report.annotation(id))
1286            .map(|row| row.references.clone())
1287            .unwrap_or_default();
1288        let mut solids: Vec<String> = Vec::new();
1289        let mut faces: Vec<String> = Vec::new();
1290        let mut edges: Vec<String> = Vec::new();
1291        for reference in &references {
1292            if let Some(at) = reference.find('@') {
1293                solids.push(reference[..at].to_string());
1294            } else if self.scene_has_face(reference) {
1295                faces.push(reference.clone());
1296            } else if self.scene_has_edge(reference) {
1297                edges.push(reference.clone());
1298            } else if self.scene.solid(reference).is_some() {
1299                solids.push(reference.clone());
1300            } else {
1301                let prefix = format!("{reference}:");
1302                solids.extend(self.scene.solids().iter().filter(|s| s.name.starts_with(&prefix)).map(|s| s.name.clone()));
1303            }
1304        }
1305        self.clear_hover();
1306        self.emphasis.hovered_solids.extend(solids);
1307        self.emphasis.hovered_faces.extend(faces);
1308        self.emphasis.hovered_edges.extend(edges);
1309        self.emphasis.generation = self.emphasis.generation.wrapping_add(1);
1310        self.pmi_hovered = Some(id.to_string());
1311        self.dirty = true;
1312    }
1313
1314    pub fn pmi_hover_end(&mut self) {
1315        if self.pmi_hovered.take().is_some() {
1316            self.clear_hover();
1317            self.dirty = true;
1318        }
1319    }
1320
1321    /// Consume the one-frame "a PMI label is hovering elements" flag (the
1322    /// viewport's scene-hover pass yields while set).
1323    pub fn take_pmi_label_hover(&mut self) -> bool {
1324        std::mem::take(&mut self.pmi_label_hover_active)
1325    }
1326
1327    /// A label was clicked: SELECT that annotation, as its tree row's single
1328    /// click does — the label carries the accent and nothing opens.
1329    pub fn pmi_label_clicked(&mut self, id: &str) {
1330        self.pmi_select_annotation(id);
1331    }
1332
1333    /// A label was double-clicked: open that annotation's form, as its tree
1334    /// row's double click does.
1335    pub fn pmi_label_double_clicked(&mut self, id: &str) {
1336        self.pmi_set_annotation_open(Some(id));
1337    }
1338
1339    /// SELECT an annotation without opening it — the PMI tree's single click.
1340    /// Its view activates when it is not the active one, as opening does, so
1341    /// the selected label is on screen to carry the selection accent. Returns
1342    /// false, changing nothing, for an id that names no annotation.
1343    pub fn pmi_select_annotation(&mut self, id: &str) -> bool {
1344        let state = self.pmi_state();
1345        let Some((view, _)) = state.find_annotation(id) else {
1346            return false;
1347        };
1348        if self.pmi_active_view.as_deref() != Some(view.id.as_str()) {
1349            let _ = self.pmi_activate_view(&view.id);
1350        }
1351        self.pmi_selected_view = None;
1352        self.pmi_selected_annotation = Some(id.to_string());
1353        self.refresh_pmi_overlay();
1354        true
1355    }
1356
1357    /// SELECT a view without activating it — the PMI tree's single click on a
1358    /// view row. The camera, visibility and wireframe stay as they are: a
1359    /// double click (which opens the view's dialog) or the row's On toggle is
1360    /// what activates. A selected annotation gives up the selection. Returns
1361    /// false, changing nothing, for an id that names no view.
1362    pub fn pmi_select_view(&mut self, id: &str) -> bool {
1363        if self.pmi_state().find_view(id).is_none() {
1364            return false;
1365        }
1366        if self.pmi_selected_annotation.take().is_some() {
1367            self.refresh_pmi_overlay();
1368        }
1369        self.pmi_selected_view = Some(id.to_string());
1370        self.dirty = true;
1371        true
1372    }
1373
1374    // --- reference picker ---------------------------------------------------------
1375
1376    /// Enter reference-selection mode for annotation `id`'s field at `path`.
1377    pub fn begin_ref_select_for_pmi(
1378        &mut self,
1379        id: &str,
1380        path: Vec<String>,
1381        label: String,
1382        filter: Vec<String>,
1383        multiple: bool,
1384        seed_names: Vec<String>,
1385    ) {
1386        let restore_index = self.history.rollback();
1387        self.selection_filter = SelectionFilter::from_ref_filter(&filter);
1388        self.ref_select = Some(RefSelectState {
1389            feature_id: id.to_string(),
1390            path,
1391            label,
1392            filter,
1393            multiple,
1394            names: seed_names,
1395            restore_index,
1396            target: RefSelectTarget::Pmi,
1397            picks: 0,
1398            claimed: false,
1399            finish_requested: false,
1400        });
1401        self.sync_ref_select_emphasis();
1402    }
1403
1404    // --- explode editing before the pick commits ------------------------------
1405
1406    /// The names an open explode step is about to move: the reference pick
1407    /// running on its `targets` field while one runs (the picker holds the
1408    /// part until Done commits it), else the step's committed targets.
1409    fn explode_target_names(&self, id: &str, annotation: &PmiAnnotation) -> Vec<String> {
1410        if let Some(field) = self.ref_select_field() {
1411            if field.target == RefSelectTarget::Pmi && field.subject == id && field.path == ["targets"] {
1412                return field.names;
1413            }
1414        }
1415        annotation.references("targets")
1416    }
1417
1418    /// The world bbox centre of the scene solids `names` name: a solid by its
1419    /// name, a component by every solid inside it (`ACOMP2` → `ACOMP2:…`).
1420    /// `None` when none of them is in the scene.
1421    fn scene_names_center(&self, names: &[String]) -> Option<[f64; 3]> {
1422        let mut low = [f64::INFINITY; 3];
1423        let mut high = [f64::NEG_INFINITY; 3];
1424        let mut any = false;
1425        for name in names {
1426            let prefix = format!("{name}:");
1427            for solid in self.scene.solids() {
1428                if solid.name == *name || solid.name.starts_with(&prefix) {
1429                    for axis in 0..3 {
1430                        low[axis] = low[axis].min(solid.bbox.min[axis]);
1431                        high[axis] = high[axis].max(solid.bbox.max[axis]);
1432                    }
1433                    any = true;
1434                }
1435            }
1436        }
1437        any.then(|| std::array::from_fn(|axis| (low[axis] + high[axis]) * 0.5))
1438    }
1439
1440    /// Where an open explode step's gizmo stands BEFORE the kernel has laid
1441    /// the step out — the owner (2026-10-26) picked a part for a new explode
1442    /// and saw no transform controls: a reference pick commits at Done, and
1443    /// until then the step had nothing to stand on. This is the centre of
1444    /// what the step is about to move (the running pick's names, else its
1445    /// committed targets), the same bbox centre the kernel's layout uses.
1446    /// `None` with nothing to move yet, or when the step is not in the
1447    /// active view. Once the run lays the step out, the report's centre is
1448    /// the one the gizmo and a drag use.
1449    pub(super) fn pmi_explode_live_center(&self, id: &str) -> Option<[f64; 3]> {
1450        let state = self.pmi_state_shared();
1451        let (view, annotation) = state.find_annotation(id)?;
1452        if annotation.kind != "explode" || self.pmi_active_view.as_deref() != Some(view.id.as_str()) {
1453            return None;
1454        }
1455        let names = self.explode_target_names(id, annotation);
1456        self.scene_names_center(&names)
1457    }
1458
1459    /// Commit a finished PMI ref-select into the annotation's params (fold
1460    /// only — the caller's shared tail re-runs).
1461    pub(crate) fn pmi_commit_refs(&mut self, id: &str, path: &[String], names: &[String], multiple: bool) {
1462        if self.pmi_state().find_view(id).is_some() {
1463            match path.first().map(String::as_str) {
1464                Some("sectionExclude") => self.pmi_commit_section_exclude(id, names),
1465                _ => self.pmi_commit_section_plane(id, names.first().map(String::as_str).unwrap_or("")),
1466            }
1467            self.history.break_coalescing();
1468            return;
1469        }
1470        let state = self.pmi_state();
1471        let Some((_, annotation)) = state.find_annotation(id) else {
1472            self.push_notice(format!("unknown PMI annotation '{id}'"));
1473            return;
1474        };
1475        let mut params = annotation.params.clone();
1476        let value = if multiple {
1477            serde_json::Value::Array(names.iter().cloned().map(serde_json::Value::String).collect())
1478        } else {
1479            serde_json::Value::String(names.first().cloned().unwrap_or_default())
1480        };
1481        super::selection_ux::set_json_at(&mut params, path, value);
1482        if let Err(error) = self.pmi_update_annotation_no_rerun(id, &params.to_string()) {
1483            self.push_notice(format!("PMI update failed: {error}"));
1484        }
1485        // A pick is a discrete change (it ends with Finish): the next edit of
1486        // the same annotation's params is its own undo step, so picking an
1487        // anchor and then clearing it in the form undo one at a time.
1488        self.history.break_coalescing();
1489    }
1490
1491    /// Commit a view form's **Section plane** pick (fold only, like
1492    /// [`Self::pmi_commit_refs`]): picking a face or plane makes the section
1493    /// cut on it — the section turns on with the `Plane` normal.
1494    fn pmi_commit_section_plane(&mut self, id: &str, name: &str) {
1495        let mut state = self.pmi_state();
1496        let Some(view) = state.find_view_mut(id) else { return };
1497        let section = view.display.section.get_or_insert_with(|| brep_kernel::feature_pipeline::pmi::PmiSection {
1498            axis: "Plane".into(),
1499            offset: 0.,
1500            flip: false,
1501            origin: None,
1502            normal: None,
1503            plane: None,
1504            exclude: Vec::new(),
1505            planes: Vec::new(),
1506        });
1507        section.axis = "Plane".into();
1508        section.plane = Some(name.trim().to_string()).filter(|name| !name.is_empty());
1509        section.freeze(None);
1510        let block = serde_json::to_value(&state).ok();
1511        // Its own undo step, not folded into the form's edits before it.
1512        self.history.break_coalescing();
1513        self.history.set_pmi_block(block, Some(&format!("pmi:view:{id}")));
1514    }
1515
1516    /// Commit a view form's **Not cut** picks (fold only, like
1517    /// [`Self::pmi_commit_section_plane`]): the solids and components the
1518    /// section leaves whole. Nothing to commit on a view without a section.
1519    fn pmi_commit_section_exclude(&mut self, id: &str, names: &[String]) {
1520        let mut state = self.pmi_state();
1521        let Some(section) = state.find_view_mut(id).and_then(|view| view.display.section.as_mut()) else { return };
1522        section.exclude = names.iter().map(|name| name.trim().to_string()).filter(|name| !name.is_empty()).collect();
1523        let block = serde_json::to_value(&state).ok();
1524        self.history.break_coalescing();
1525        self.history.set_pmi_block(block, Some(&format!("pmi:view:{id}")));
1526    }
1527
1528    // --- import -------------------------------------------------------------------
1529
1530    /// Merge a file's lifted PMI (`read_step_pmi`) into the document beside
1531    /// the import that added its geometry: views append with fresh ids, the
1532    /// import's undo checkpoint covers both (no second checkpoint).
1533    pub(crate) fn pmi_merge_imported(&mut self, lifted: PmiState) {
1534        let mut state = self.pmi_state();
1535        for view in lifted.views {
1536            let id = state.next_id("VIEW");
1537            let mut annotations = Vec::with_capacity(view.annotations.len());
1538            for mut annotation in view.annotations {
1539                let prefix = brep_kernel::pmi_type(&annotation.kind).map(|def| def.short_name).unwrap_or("PMI");
1540                let fresh = state.next_id(prefix);
1541                if let Some(object) = annotation.params.as_object_mut() {
1542                    object.insert("id".into(), serde_json::Value::String(fresh));
1543                }
1544                annotations.push(annotation);
1545            }
1546            state.views.push(PmiView {
1547                id,
1548                name: view.name,
1549                camera: view.camera,
1550                display: view.display,
1551                annotations,
1552            });
1553        }
1554        let block = serde_json::to_value(&state).ok();
1555        self.history.set_pmi_block_no_undo(block);
1556        self.rerun_history();
1557    }
1558}
1559
1560/// Pose a display in place: `p' = R((p − c) ∘ s) + c + t` on the mesh, the
1561/// edge polylines and the vertices; normals rotate; the bbox is rebuilt.
1562/// `p ↦ R((p − c) ∘ s) + c + t` as a column-major 4×4, its rotation read off
1563/// the very rotation the vertices are turned by.
1564fn pose_matrix(center: [f64; 3], translate: [f64; 3], rotate: &dyn Fn([f64; 3]) -> [f64; 3], scale: [f64; 3]) -> [f32; 16] {
1565    let columns = [rotate([1.0, 0.0, 0.0]), rotate([0.0, 1.0, 0.0]), rotate([0.0, 0.0, 1.0])];
1566    let linear: [[f64; 3]; 3] = std::array::from_fn(|j| columns[j].map(|v| v * scale[j]));
1567    let shifted: [f64; 3] = std::array::from_fn(|i| center[i] + translate[i] - (0..3).map(|j| linear[j][i] * center[j]).sum::<f64>());
1568    let mut m = [0.0f32; 16];
1569    for j in 0..3 {
1570        for i in 0..3 {
1571            m[j * 4 + i] = linear[j][i] as f32;
1572        }
1573    }
1574    m[12] = shifted[0] as f32;
1575    m[13] = shifted[1] as f32;
1576    m[14] = shifted[2] as f32;
1577    m[15] = 1.0;
1578    m
1579}
1580
1581/// `a · b`, column-major 4×4.
1582use crate::view::mat4_mul_column_major as mat4_mul;
1583
1584/// Put a posed display's geometry back to its original's, copying into the
1585/// buffers it already holds: what a pose moves (positions, normals, edge
1586/// polylines, vertices, the box) and the revisions it set.
1587fn reset_posed_geometry(display: &mut crate::scene::SolidDisplay, original: &crate::scene::SolidDisplay) {
1588    display.mesh.positions.clone_from(&original.mesh.positions);
1589    display.mesh.normals.clone_from(&original.mesh.normals);
1590    if display.edges.len() == original.edges.len() {
1591        for (edge, from) in display.edges.iter_mut().zip(&original.edges) {
1592            edge.polyline.clone_from(&from.polyline);
1593        }
1594    } else {
1595        display.edges.clone_from(&original.edges);
1596    }
1597    display.vertices.clone_from(&original.vertices);
1598    display.bbox = original.bbox;
1599    display.revision = original.revision;
1600    display.shape_revision = original.shape_revision;
1601    display.pose = original.pose;
1602}
1603
1604pub(super) fn transform_display(
1605    display: &mut crate::scene::SolidDisplay,
1606    center: [f64; 3],
1607    translate: [f64; 3],
1608    rotate_deg: [f64; 3],
1609    scale: [f64; 3],
1610) {
1611    // The same mesh posed: the renderer rewrites its positions in the buffers
1612    // it holds (`sync_scene`'s pose path) instead of rebuilding the solid on
1613    // every frame an exploded view animates (l500: p95 81 ms a frame). A
1614    // section clip, which changes the mesh, resets this itself.
1615    // The kernel's explode rotation is in degrees (as every `rotationEuler`;
1616    // its balloon anchors convert the same way); the rotation takes radians.
1617    let rotate_rad = rotate_deg.map(f64::to_radians);
1618    let rotate = |v: [f64; 3]| super::rotate_euler_xyz_f64(v, rotate_rad);
1619    // The pose as a matrix over the shape's own geometry: this one, composed
1620    // with any pose already on it. A display moved some other way (a drag)
1621    // has no shape geometry to compose over, and keeps none.
1622    let step = pose_matrix(center, translate, &rotate, scale);
1623    display.pose = if display.shape_revision == 0 {
1624        Some(step)
1625    } else {
1626        display.pose.map(|before| mat4_mul(&step, &before))
1627    };
1628    if display.shape_revision == 0 {
1629        display.shape_revision = display.revision;
1630    }
1631    display.revision = crate::scene::next_revision();
1632    let pose = |p: [f64; 3]| -> [f64; 3] {
1633        let local = [(p[0] - center[0]) * scale[0], (p[1] - center[1]) * scale[1], (p[2] - center[2]) * scale[2]];
1634        let rotated = rotate(local);
1635        [rotated[0] + center[0] + translate[0], rotated[1] + center[1] + translate[1], rotated[2] + center[2] + translate[2]]
1636    };
1637    let mut bbox = crate::camera::Aabb::empty();
1638    for position in &mut display.mesh.positions {
1639        let posed = pose([position[0] as f64, position[1] as f64, position[2] as f64]);
1640        *position = [posed[0] as f32, posed[1] as f32, posed[2] as f32];
1641        bbox.expand(posed);
1642    }
1643    for normal in &mut display.mesh.normals {
1644        let rotated = rotate(std::array::from_fn(|i| normal[i] as f64 / scale[i]));
1645        let length = rotated.iter().map(|v| v * v).sum::<f64>().sqrt().max(1e-20);
1646        *normal = rotated.map(|v| (v / length) as f32);
1647    }
1648    for edge in &mut display.edges {
1649        for point in &mut edge.polyline {
1650            let posed = pose([point[0] as f64, point[1] as f64, point[2] as f64]);
1651            *point = [posed[0] as f32, posed[1] as f32, posed[2] as f32];
1652            bbox.expand(posed);
1653        }
1654    }
1655    for vertex in &mut display.vertices {
1656        vertex.position = pose(vertex.position);
1657        bbox.expand(vertex.position);
1658    }
1659    if !bbox.is_empty() {
1660        display.bbox = bbox;
1661    }
1662}
1663