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            object.insert("id".into(), serde_json::Value::String(id.clone()));
1007            if type_id == "datum" {
1008                let letter = object.get("letter").and_then(serde_json::Value::as_str).unwrap_or("").trim().to_string();
1009                if letter.is_empty() {
1010                    if let Some(next) = state.next_datum_letter() {
1011                        object.insert("letter".into(), serde_json::Value::String(next));
1012                    }
1013                }
1014            }
1015        }
1016        let view = state.find_view_mut(&view_id).ok_or_else(|| format!("no PMI view '{view_id}'"))?;
1017        view.annotations.push(PmiAnnotation {
1018            plugin_replay: None,
1019            persistent_data: serde_json::Value::Null,
1020            kind: type_id.to_string(),
1021            enabled: true,
1022            params,
1023            label_world: None,
1024        });
1025        self.open_pmi_annotation(id.clone());
1026        self.write_pmi_state(state);
1027        Ok(id)
1028    }
1029
1030    /// Replace an annotation's params (a form edit). Re-runs.
1031    pub fn pmi_update_annotation(&mut self, id: &str, params_json: &str) -> Result<(), String> {
1032        if self.pmi_state().find_annotation(id).is_some_and(|(_, a)| a.kind.contains('/')) {
1033            let params = serde_json::from_str(params_json).map_err(|e| format!("annotation params: {e}"))?;
1034            return self.plugin_update_annotation(id, params).map(|_| ());
1035        }
1036        self.pmi_update_annotation_no_rerun(id, params_json)?;
1037        self.rerun_history();
1038        Ok(())
1039    }
1040
1041    /// The fold half of [`Self::pmi_update_annotation`] (checkpointed, no
1042    /// re-run) — the reference picker's commit uses it before its shared
1043    /// end tail re-runs.
1044    pub(crate) fn pmi_update_annotation_no_rerun(&mut self, id: &str, params_json: &str) -> Result<(), String> {
1045        let mut state = self.pmi_state();
1046        let annotation = state.find_annotation_mut(id).ok_or_else(|| format!("no PMI annotation '{id}'"))?;
1047        if annotation.kind.contains('/') {
1048            return Err("plugin annotation edits require the worker transaction path".into());
1049        }
1050        let mut params: serde_json::Value =
1051            serde_json::from_str(params_json).map_err(|error| format!("annotation params: {error}"))?;
1052        if let Some(object) = params.as_object_mut() {
1053            object.insert("id".into(), serde_json::Value::String(id.to_string()));
1054        }
1055        annotation.params = params;
1056        let block = serde_json::to_value(&state).ok();
1057        self.history.set_pmi_block(block, Some(&format!("pmi:params:{id}")));
1058        Ok(())
1059    }
1060
1061    pub fn pmi_remove_annotation(&mut self, id: &str) -> Result<(), String> {
1062        if self.pmi_state().find_annotation(id).is_some_and(|(_, a)| a.kind.contains('/')) {
1063            return self.plugin_delete_annotation(id).map(|_| ());
1064        }
1065        let mut state = self.pmi_state();
1066        let Some((view_index, index)) = state.locate_annotation(id) else {
1067            return Err(format!("no PMI annotation '{id}'"));
1068        };
1069        state.views[view_index].annotations.remove(index);
1070        if self.pmi_open_annotation.as_deref() == Some(id) {
1071            self.pmi_open_annotation = None;
1072        }
1073        self.write_pmi_state(state);
1074        Ok(())
1075    }
1076
1077    pub fn pmi_set_annotation_enabled(&mut self, id: &str, enabled: bool) -> Result<(), String> {
1078        if self.pmi_state().find_annotation(id).is_some_and(|(_, a)| a.kind.contains('/')) {
1079            return self.plugin_set_annotation_enabled(id, enabled).map(|_| ());
1080        }
1081        let mut state = self.pmi_state();
1082        let annotation = state.find_annotation_mut(id).ok_or_else(|| format!("no PMI annotation '{id}'"))?;
1083        if annotation.enabled == enabled {
1084            return Ok(());
1085        }
1086        annotation.enabled = enabled;
1087        self.write_pmi_state(state);
1088        Ok(())
1089    }
1090
1091    /// Move an annotation to `index` within its view.
1092    pub fn pmi_move_annotation(&mut self, id: &str, index: usize) -> Result<(), String> {
1093        let mut state = self.pmi_state();
1094        let Some((view_index, from)) = state.locate_annotation(id) else {
1095            return Err(format!("no PMI annotation '{id}'"));
1096        };
1097        let annotations = &mut state.views[view_index].annotations;
1098        let annotation = annotations.remove(from);
1099        let to = index.min(annotations.len());
1100        annotations.insert(to, annotation);
1101        self.write_pmi_state(state);
1102        Ok(())
1103    }
1104
1105    /// Move an annotation to another view (append).
1106    pub fn pmi_move_annotation_to_view(&mut self, id: &str, view_id: &str) -> Result<(), String> {
1107        let mut state = self.pmi_state();
1108        let Some((view_index, from)) = state.locate_annotation(id) else {
1109            return Err(format!("no PMI annotation '{id}'"));
1110        };
1111        if state.find_view(view_id).is_none() {
1112            return Err(format!("no PMI view '{view_id}'"));
1113        }
1114        let annotation = state.views[view_index].annotations.remove(from);
1115        state.find_view_mut(view_id).expect("checked").annotations.push(annotation);
1116        self.write_pmi_state(state);
1117        Ok(())
1118    }
1119
1120    /// Open one annotation's form (engine memory; `None` closes). Opening an
1121    /// annotation of another view activates that view. An open COUNTS
1122    /// (`Self::open_pmi_annotation`) — including a re-open of the annotation
1123    /// already open, which is a viewport label double click on the form the user
1124    /// cannot see; an id that resolves to no annotation opens nothing and
1125    /// counts nothing.
1126    pub fn pmi_set_annotation_open(&mut self, id: Option<&str>) {
1127        match id {
1128            Some(id) => {
1129                let state = self.pmi_state();
1130                if let Some((view, _)) = state.find_annotation(id) {
1131                    let view_id = view.id.clone();
1132                    if self.pmi_active_view.as_deref() != Some(view_id.as_str()) {
1133                        let _ = self.pmi_activate_view(&view_id);
1134                    }
1135                    self.open_pmi_annotation(id.to_string());
1136                }
1137            }
1138            None => {
1139                if self.pmi_open_annotation.as_deref() == Some(self.transform_armed_feature().as_str()) { self.disarm_transform(); }
1140                self.pmi_open_annotation = None;
1141            },
1142        }
1143        self.refresh_pmi_overlay();
1144    }
1145
1146    // --- labels -----------------------------------------------------------------
1147
1148    /// Move an annotation's label (world). Coalesced per annotation into ONE
1149    /// undo step, and NEVER a re-run: the cached report is patched in place
1150    /// and the overlay re-baked. A balloon's arrow head is re-derived from
1151    /// the moved bubble (`Self::pmi_reproject_balloon_head`).
1152    pub fn pmi_set_label_world(&mut self, id: &str, world: [f64; 3]) -> Result<(), String> {
1153        let mut state = self.pmi_state();
1154        let annotation = state.find_annotation_mut(id).ok_or_else(|| format!("no PMI annotation '{id}'"))?;
1155        annotation.label_world = Some(world);
1156        let block = serde_json::to_value(&state).ok();
1157        self.history.set_pmi_block(block, Some(&format!("pmi:label:{id}")));
1158        if let Some(report) = self.pmi_report.as_mut() {
1159            if let Some(row) = report.annotation_mut(id) {
1160                row.label_world = world;
1161                if let PmiGeometry::Note { position } = &mut row.geometry {
1162                    *position = world;
1163                }
1164            }
1165        }
1166        self.pmi_reproject_balloon_head(id);
1167        self.refresh_pmi_overlay();
1168        Ok(())
1169    }
1170
1171    /// Re-derive a balloon's arrow head from its row's bubble through the
1172    /// recipe the kernel put on its leader (the same projection the resolver
1173    /// ran, on the exact-solid clones the scene holds), and patch the cached
1174    /// report. The head is derived, never stored, so no document edit and no
1175    /// run: the next run resolves the same head from the stored bubble. A
1176    /// solid the scene does not hold yet is asked of the runner; the head is
1177    /// re-derived when the reply lands ([`Self::pmi_refresh_stale_balloon`]),
1178    /// which for the Inline runner is before this returns. Any other
1179    /// annotation is left alone.
1180    pub(crate) fn pmi_reproject_balloon_head(&mut self, id: &str) {
1181        if let Some(missing) = self.pmi_balloon_head_now(id) {
1182            self.pmi_balloon_stale = Some(id.to_string());
1183            self.request_exact_solids(missing.iter().map(String::as_str));
1184            self.pmi_refresh_stale_balloon();
1185        }
1186    }
1187
1188    /// Retry the balloon whose re-projection waited on a topology reply.
1189    pub(crate) fn pmi_refresh_stale_balloon(&mut self) {
1190        let Some(id) = self.pmi_balloon_stale.take() else {
1191            return;
1192        };
1193        if self.pmi_balloon_head_now(&id).is_some() {
1194            // Still waiting (a background runner's reply is on its way).
1195            self.pmi_balloon_stale = Some(id);
1196        } else {
1197            self.refresh_pmi_overlay();
1198        }
1199    }
1200
1201    /// One re-projection attempt: `None` when done (or not a balloon), else
1202    /// the occurrence solids the scene does not hold.
1203    pub(super) fn pmi_balloon_head_now(&mut self, id: &str) -> Option<Vec<String>> {
1204        let (mut anchor, bubble) = self
1205            .pmi_report
1206            .as_ref()
1207            .and_then(|report| report.annotation(id))
1208            .and_then(|row| match &row.geometry {
1209                PmiGeometry::Leader { balloon: true, anchor: Some(anchor), .. } => Some((anchor.clone(), row.label_world)),
1210                _ => None,
1211            })?;
1212        anchor.camera = Some(self.snapshot_camera());
1213        let mut missing = Vec::new();
1214        let head = brep_kernel::pmi_balloon_head(&anchor, bubble, |name| self.scene.exact_solid(name), &mut missing);
1215        if !missing.is_empty() {
1216            return Some(missing);
1217        }
1218        // A fixed (vertex) anchor answers `None`: the head never moves. A
1219        // projection error keeps the kernel's head rather than a wrong one.
1220        if let Ok(Some(head)) = head {
1221            if let Some(row) = self.pmi_report.as_mut().and_then(|report| report.annotation_mut(id)) {
1222                if let PmiGeometry::Leader { targets, anchor: recipe, .. } = &mut row.geometry {
1223                    *recipe = Some(anchor);
1224                    if let Some(first) = targets.first_mut() {
1225                        *first = head;
1226                    }
1227                }
1228            }
1229        }
1230        None
1231    }
1232
1233    /// Drag an annotation's label to the pointer: the new position is where
1234    /// the pick ray crosses the plane through the current label perpendicular
1235    /// to the viewing direction (so a drag never changes the label's depth).
1236    pub fn pmi_label_drag_to(&mut self, id: &str, x: f64, y: f64) {
1237        // Part-way through explode playback the chip is drawn where its body
1238        // is now: the drag runs there, and is stored back in the run's frame.
1239        let playback = self.explode_playback_poses();
1240        let Some((current, plane)) = self
1241            .pmi_report
1242            .as_ref()
1243            .and_then(|r| r.annotation(id))
1244            .map(|r| (playback.as_ref().map_or(r.label_world, |poses| poses.shown(r, r.label_world)), r.plane))
1245        else {
1246            return;
1247        };
1248        let ray = self.camera.pick_ray(x, y);
1249        // In a picked annotation plane the label stays ON that plane; a
1250        // view-aligned label moves in the view-parallel plane through its
1251        // current position.
1252        let plane = plane.unwrap_or_else(|| {
1253            let (_, _, view) = self.camera.basis();
1254            brep_kernel::PmiPlane {
1255                origin: current,
1256                normal: view,
1257                x_axis: [0.0; 3],
1258            }
1259        });
1260        let Some(world) = plane.hit(ray.origin, ray.dir) else {
1261            return;
1262        };
1263        let world = match (&playback, self.pmi_report.as_ref().and_then(|r| r.annotation(id))) {
1264            (Some(poses), Some(row)) => poses.full(row, world),
1265            _ => world,
1266        };
1267        let _ = self.pmi_set_label_world(id, world);
1268    }
1269
1270    /// A label drag ended: the next drag is a fresh undo step.
1271    pub fn pmi_label_drag_end(&mut self) {
1272        self.history.break_coalescing();
1273    }
1274
1275    /// Hover a label: highlight the annotation's referenced geometry.
1276    pub fn pmi_hover(&mut self, id: &str) {
1277        self.pmi_label_hover_active = true;
1278        if self.pmi_hovered.as_deref() == Some(id) {
1279            return;
1280        }
1281        let references: Vec<String> = self
1282            .pmi_report
1283            .as_ref()
1284            .and_then(|report| report.annotation(id))
1285            .map(|row| row.references.clone())
1286            .unwrap_or_default();
1287        let mut solids: Vec<String> = Vec::new();
1288        let mut faces: Vec<String> = Vec::new();
1289        let mut edges: Vec<String> = Vec::new();
1290        for reference in &references {
1291            if let Some(at) = reference.find('@') {
1292                solids.push(reference[..at].to_string());
1293            } else if self.scene_has_face(reference) {
1294                faces.push(reference.clone());
1295            } else if self.scene_has_edge(reference) {
1296                edges.push(reference.clone());
1297            } else if self.scene.solid(reference).is_some() {
1298                solids.push(reference.clone());
1299            } else {
1300                let prefix = format!("{reference}:");
1301                solids.extend(self.scene.solids().iter().filter(|s| s.name.starts_with(&prefix)).map(|s| s.name.clone()));
1302            }
1303        }
1304        self.clear_hover();
1305        self.emphasis.hovered_solids.extend(solids);
1306        self.emphasis.hovered_faces.extend(faces);
1307        self.emphasis.hovered_edges.extend(edges);
1308        self.emphasis.generation = self.emphasis.generation.wrapping_add(1);
1309        self.pmi_hovered = Some(id.to_string());
1310        self.dirty = true;
1311    }
1312
1313    pub fn pmi_hover_end(&mut self) {
1314        if self.pmi_hovered.take().is_some() {
1315            self.clear_hover();
1316            self.dirty = true;
1317        }
1318    }
1319
1320    /// Consume the one-frame "a PMI label is hovering elements" flag (the
1321    /// viewport's scene-hover pass yields while set).
1322    pub fn take_pmi_label_hover(&mut self) -> bool {
1323        std::mem::take(&mut self.pmi_label_hover_active)
1324    }
1325
1326    /// A label was clicked: SELECT that annotation, as its tree row's single
1327    /// click does — the label carries the accent and nothing opens.
1328    pub fn pmi_label_clicked(&mut self, id: &str) {
1329        self.pmi_select_annotation(id);
1330    }
1331
1332    /// A label was double-clicked: open that annotation's form, as its tree
1333    /// row's double click does.
1334    pub fn pmi_label_double_clicked(&mut self, id: &str) {
1335        self.pmi_set_annotation_open(Some(id));
1336    }
1337
1338    /// SELECT an annotation without opening it — the PMI tree's single click.
1339    /// Its view activates when it is not the active one, as opening does, so
1340    /// the selected label is on screen to carry the selection accent. Returns
1341    /// false, changing nothing, for an id that names no annotation.
1342    pub fn pmi_select_annotation(&mut self, id: &str) -> bool {
1343        let state = self.pmi_state();
1344        let Some((view, _)) = state.find_annotation(id) else {
1345            return false;
1346        };
1347        if self.pmi_active_view.as_deref() != Some(view.id.as_str()) {
1348            let _ = self.pmi_activate_view(&view.id);
1349        }
1350        self.pmi_selected_view = None;
1351        self.pmi_selected_annotation = Some(id.to_string());
1352        self.refresh_pmi_overlay();
1353        true
1354    }
1355
1356    /// SELECT a view without activating it — the PMI tree's single click on a
1357    /// view row. The camera, visibility and wireframe stay as they are: a
1358    /// double click (which opens the view's dialog) or the row's On toggle is
1359    /// what activates. A selected annotation gives up the selection. Returns
1360    /// false, changing nothing, for an id that names no view.
1361    pub fn pmi_select_view(&mut self, id: &str) -> bool {
1362        if self.pmi_state().find_view(id).is_none() {
1363            return false;
1364        }
1365        if self.pmi_selected_annotation.take().is_some() {
1366            self.refresh_pmi_overlay();
1367        }
1368        self.pmi_selected_view = Some(id.to_string());
1369        self.dirty = true;
1370        true
1371    }
1372
1373    // --- reference picker ---------------------------------------------------------
1374
1375    /// Enter reference-selection mode for annotation `id`'s field at `path`.
1376    pub fn begin_ref_select_for_pmi(
1377        &mut self,
1378        id: &str,
1379        path: Vec<String>,
1380        label: String,
1381        filter: Vec<String>,
1382        multiple: bool,
1383        seed_names: Vec<String>,
1384    ) {
1385        let restore_index = self.history.rollback();
1386        self.selection_filter = SelectionFilter::from_ref_filter(&filter);
1387        self.ref_select = Some(RefSelectState {
1388            feature_id: id.to_string(),
1389            path,
1390            label,
1391            filter,
1392            multiple,
1393            names: seed_names,
1394            restore_index,
1395            target: RefSelectTarget::Pmi,
1396            picks: 0,
1397            claimed: false,
1398            finish_requested: false,
1399        });
1400        self.sync_ref_select_emphasis();
1401    }
1402
1403    // --- explode editing before the pick commits ------------------------------
1404
1405    /// The names an open explode step is about to move: the reference pick
1406    /// running on its `targets` field while one runs (the picker holds the
1407    /// part until Done commits it), else the step's committed targets.
1408    fn explode_target_names(&self, id: &str, annotation: &PmiAnnotation) -> Vec<String> {
1409        if let Some(field) = self.ref_select_field() {
1410            if field.target == RefSelectTarget::Pmi && field.subject == id && field.path == ["targets"] {
1411                return field.names;
1412            }
1413        }
1414        annotation.references("targets")
1415    }
1416
1417    /// The world bbox centre of the scene solids `names` name: a solid by its
1418    /// name, a component by every solid inside it (`ACOMP2` → `ACOMP2:…`).
1419    /// `None` when none of them is in the scene.
1420    fn scene_names_center(&self, names: &[String]) -> Option<[f64; 3]> {
1421        let mut low = [f64::INFINITY; 3];
1422        let mut high = [f64::NEG_INFINITY; 3];
1423        let mut any = false;
1424        for name in names {
1425            let prefix = format!("{name}:");
1426            for solid in self.scene.solids() {
1427                if solid.name == *name || solid.name.starts_with(&prefix) {
1428                    for axis in 0..3 {
1429                        low[axis] = low[axis].min(solid.bbox.min[axis]);
1430                        high[axis] = high[axis].max(solid.bbox.max[axis]);
1431                    }
1432                    any = true;
1433                }
1434            }
1435        }
1436        any.then(|| std::array::from_fn(|axis| (low[axis] + high[axis]) * 0.5))
1437    }
1438
1439    /// Where an open explode step's gizmo stands BEFORE the kernel has laid
1440    /// the step out — the owner (2026-10-26) picked a part for a new explode
1441    /// and saw no transform controls: a reference pick commits at Done, and
1442    /// until then the step had nothing to stand on. This is the centre of
1443    /// what the step is about to move (the running pick's names, else its
1444    /// committed targets), the same bbox centre the kernel's layout uses.
1445    /// `None` with nothing to move yet, or when the step is not in the
1446    /// active view. Once the run lays the step out, the report's centre is
1447    /// the one the gizmo and a drag use.
1448    pub(super) fn pmi_explode_live_center(&self, id: &str) -> Option<[f64; 3]> {
1449        let state = self.pmi_state_shared();
1450        let (view, annotation) = state.find_annotation(id)?;
1451        if annotation.kind != "explode" || self.pmi_active_view.as_deref() != Some(view.id.as_str()) {
1452            return None;
1453        }
1454        let names = self.explode_target_names(id, annotation);
1455        self.scene_names_center(&names)
1456    }
1457
1458    /// Commit a finished PMI ref-select into the annotation's params (fold
1459    /// only — the caller's shared tail re-runs).
1460    pub(crate) fn pmi_commit_refs(&mut self, id: &str, path: &[String], names: &[String], multiple: bool) {
1461        if self.pmi_state().find_view(id).is_some() {
1462            match path.first().map(String::as_str) {
1463                Some("sectionExclude") => self.pmi_commit_section_exclude(id, names),
1464                _ => self.pmi_commit_section_plane(id, names.first().map(String::as_str).unwrap_or("")),
1465            }
1466            self.history.break_coalescing();
1467            return;
1468        }
1469        let state = self.pmi_state();
1470        let Some((_, annotation)) = state.find_annotation(id) else {
1471            self.push_notice(format!("unknown PMI annotation '{id}'"));
1472            return;
1473        };
1474        let mut params = annotation.params.clone();
1475        let value = if multiple {
1476            serde_json::Value::Array(names.iter().cloned().map(serde_json::Value::String).collect())
1477        } else {
1478            serde_json::Value::String(names.first().cloned().unwrap_or_default())
1479        };
1480        super::selection_ux::set_json_at(&mut params, path, value);
1481        if let Err(error) = self.pmi_update_annotation_no_rerun(id, &params.to_string()) {
1482            self.push_notice(format!("PMI update failed: {error}"));
1483        }
1484        // A pick is a discrete change (it ends with Finish): the next edit of
1485        // the same annotation's params is its own undo step, so picking an
1486        // anchor and then clearing it in the form undo one at a time.
1487        self.history.break_coalescing();
1488    }
1489
1490    /// Commit a view form's **Section plane** pick (fold only, like
1491    /// [`Self::pmi_commit_refs`]): picking a face or plane makes the section
1492    /// cut on it — the section turns on with the `Plane` normal.
1493    fn pmi_commit_section_plane(&mut self, id: &str, name: &str) {
1494        let mut state = self.pmi_state();
1495        let Some(view) = state.find_view_mut(id) else { return };
1496        let section = view.display.section.get_or_insert_with(|| brep_kernel::feature_pipeline::pmi::PmiSection {
1497            axis: "Plane".into(),
1498            offset: 0.,
1499            flip: false,
1500            origin: None,
1501            normal: None,
1502            plane: None,
1503            exclude: Vec::new(),
1504            planes: Vec::new(),
1505        });
1506        section.axis = "Plane".into();
1507        section.plane = Some(name.trim().to_string()).filter(|name| !name.is_empty());
1508        section.freeze(None);
1509        let block = serde_json::to_value(&state).ok();
1510        // Its own undo step, not folded into the form's edits before it.
1511        self.history.break_coalescing();
1512        self.history.set_pmi_block(block, Some(&format!("pmi:view:{id}")));
1513    }
1514
1515    /// Commit a view form's **Not cut** picks (fold only, like
1516    /// [`Self::pmi_commit_section_plane`]): the solids and components the
1517    /// section leaves whole. Nothing to commit on a view without a section.
1518    fn pmi_commit_section_exclude(&mut self, id: &str, names: &[String]) {
1519        let mut state = self.pmi_state();
1520        let Some(section) = state.find_view_mut(id).and_then(|view| view.display.section.as_mut()) else { return };
1521        section.exclude = names.iter().map(|name| name.trim().to_string()).filter(|name| !name.is_empty()).collect();
1522        let block = serde_json::to_value(&state).ok();
1523        self.history.break_coalescing();
1524        self.history.set_pmi_block(block, Some(&format!("pmi:view:{id}")));
1525    }
1526
1527    // --- import -------------------------------------------------------------------
1528
1529    /// Merge a file's lifted PMI (`read_step_pmi`) into the document beside
1530    /// the import that added its geometry: views append with fresh ids, the
1531    /// import's undo checkpoint covers both (no second checkpoint).
1532    pub(crate) fn pmi_merge_imported(&mut self, lifted: PmiState) {
1533        let mut state = self.pmi_state();
1534        for view in lifted.views {
1535            let id = state.next_id("VIEW");
1536            let mut annotations = Vec::with_capacity(view.annotations.len());
1537            for mut annotation in view.annotations {
1538                let prefix = brep_kernel::pmi_type(&annotation.kind).map(|def| def.short_name).unwrap_or("PMI");
1539                let fresh = state.next_id(prefix);
1540                if let Some(object) = annotation.params.as_object_mut() {
1541                    object.insert("id".into(), serde_json::Value::String(fresh));
1542                }
1543                annotations.push(annotation);
1544            }
1545            state.views.push(PmiView {
1546                id,
1547                name: view.name,
1548                camera: view.camera,
1549                display: view.display,
1550                annotations,
1551            });
1552        }
1553        let block = serde_json::to_value(&state).ok();
1554        self.history.set_pmi_block_no_undo(block);
1555        self.rerun_history();
1556    }
1557}
1558
1559/// Pose a display in place: `p' = R((p − c) ∘ s) + c + t` on the mesh, the
1560/// edge polylines and the vertices; normals rotate; the bbox is rebuilt.
1561/// `p ↦ R((p − c) ∘ s) + c + t` as a column-major 4×4, its rotation read off
1562/// the very rotation the vertices are turned by.
1563fn pose_matrix(center: [f64; 3], translate: [f64; 3], rotate: &dyn Fn([f64; 3]) -> [f64; 3], scale: [f64; 3]) -> [f32; 16] {
1564    let columns = [rotate([1.0, 0.0, 0.0]), rotate([0.0, 1.0, 0.0]), rotate([0.0, 0.0, 1.0])];
1565    let linear: [[f64; 3]; 3] = std::array::from_fn(|j| columns[j].map(|v| v * scale[j]));
1566    let shifted: [f64; 3] = std::array::from_fn(|i| center[i] + translate[i] - (0..3).map(|j| linear[j][i] * center[j]).sum::<f64>());
1567    let mut m = [0.0f32; 16];
1568    for j in 0..3 {
1569        for i in 0..3 {
1570            m[j * 4 + i] = linear[j][i] as f32;
1571        }
1572    }
1573    m[12] = shifted[0] as f32;
1574    m[13] = shifted[1] as f32;
1575    m[14] = shifted[2] as f32;
1576    m[15] = 1.0;
1577    m
1578}
1579
1580/// `a · b`, column-major 4×4.
1581use crate::view::mat4_mul_column_major as mat4_mul;
1582
1583/// Put a posed display's geometry back to its original's, copying into the
1584/// buffers it already holds: what a pose moves (positions, normals, edge
1585/// polylines, vertices, the box) and the revisions it set.
1586fn reset_posed_geometry(display: &mut crate::scene::SolidDisplay, original: &crate::scene::SolidDisplay) {
1587    display.mesh.positions.clone_from(&original.mesh.positions);
1588    display.mesh.normals.clone_from(&original.mesh.normals);
1589    if display.edges.len() == original.edges.len() {
1590        for (edge, from) in display.edges.iter_mut().zip(&original.edges) {
1591            edge.polyline.clone_from(&from.polyline);
1592        }
1593    } else {
1594        display.edges.clone_from(&original.edges);
1595    }
1596    display.vertices.clone_from(&original.vertices);
1597    display.bbox = original.bbox;
1598    display.revision = original.revision;
1599    display.shape_revision = original.shape_revision;
1600    display.pose = original.pose;
1601}
1602
1603pub(super) fn transform_display(
1604    display: &mut crate::scene::SolidDisplay,
1605    center: [f64; 3],
1606    translate: [f64; 3],
1607    rotate_deg: [f64; 3],
1608    scale: [f64; 3],
1609) {
1610    // The same mesh posed: the renderer rewrites its positions in the buffers
1611    // it holds (`sync_scene`'s pose path) instead of rebuilding the solid on
1612    // every frame an exploded view animates (l500: p95 81 ms a frame). A
1613    // section clip, which changes the mesh, resets this itself.
1614    // The kernel's explode rotation is in degrees (as every `rotationEuler`;
1615    // its balloon anchors convert the same way); the rotation takes radians.
1616    let rotate_rad = rotate_deg.map(f64::to_radians);
1617    let rotate = |v: [f64; 3]| super::rotate_euler_xyz_f64(v, rotate_rad);
1618    // The pose as a matrix over the shape's own geometry: this one, composed
1619    // with any pose already on it. A display moved some other way (a drag)
1620    // has no shape geometry to compose over, and keeps none.
1621    let step = pose_matrix(center, translate, &rotate, scale);
1622    display.pose = if display.shape_revision == 0 {
1623        Some(step)
1624    } else {
1625        display.pose.map(|before| mat4_mul(&step, &before))
1626    };
1627    if display.shape_revision == 0 {
1628        display.shape_revision = display.revision;
1629    }
1630    display.revision = crate::scene::next_revision();
1631    let pose = |p: [f64; 3]| -> [f64; 3] {
1632        let local = [(p[0] - center[0]) * scale[0], (p[1] - center[1]) * scale[1], (p[2] - center[2]) * scale[2]];
1633        let rotated = rotate(local);
1634        [rotated[0] + center[0] + translate[0], rotated[1] + center[1] + translate[1], rotated[2] + center[2] + translate[2]]
1635    };
1636    let mut bbox = crate::camera::Aabb::empty();
1637    for position in &mut display.mesh.positions {
1638        let posed = pose([position[0] as f64, position[1] as f64, position[2] as f64]);
1639        *position = [posed[0] as f32, posed[1] as f32, posed[2] as f32];
1640        bbox.expand(posed);
1641    }
1642    for normal in &mut display.mesh.normals {
1643        let rotated = rotate(std::array::from_fn(|i| normal[i] as f64 / scale[i]));
1644        let length = rotated.iter().map(|v| v * v).sum::<f64>().sqrt().max(1e-20);
1645        *normal = rotated.map(|v| (v / length) as f32);
1646    }
1647    for edge in &mut display.edges {
1648        for point in &mut edge.polyline {
1649            let posed = pose([point[0] as f64, point[1] as f64, point[2] as f64]);
1650            *point = [posed[0] as f32, posed[1] as f32, posed[2] as f32];
1651            bbox.expand(posed);
1652        }
1653    }
1654    for vertex in &mut display.vertices {
1655        vertex.position = pose(vertex.position);
1656        bbox.expand(vertex.position);
1657    }
1658    if !bbox.is_empty() {
1659        display.bbox = bbox;
1660    }
1661}
1662