BREP_render 0.4.0

BREP Rust rendering engine: kernel-fed scene store + wgpu renderer (headless artifact, desktop window, and wasm canvas shells).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
//! PMI — the engine half of the PMI workbench: the document's `pmi` block
//! (checkpointed edits + re-run, like `wire_harness_ops`), the ACTIVE view
//! (applied camera / visibility / wireframe / explode poses, restored
//! exactly on deactivate), annotation CRUD, the coalesced label drag, and the
//! reference picker's PMI flavour.
//!
//! Persisted vs engine memory: the `pmi` block (views, annotations, label
//! positions) lives in the document and rides its undo stack; WHICH view is
//! active and WHICH annotation's form is open are engine memory — a mode,
//! not model state — so a rerun, a save or an undo never churns on them.
//!
//! A label drag is the one high-frequency PMI edit: it writes the block with
//! a coalesced checkpoint (`pmi:label:{id}` — one undo step per drag) and
//! NEVER re-runs the history: the cached report's label position is patched
//! locally and the overlay re-baked. Every other mutation (a view capture,
//! an annotation add / edit / remove) is its own undo step followed by a
//! re-run, whose tail re-resolves the annotations.

use super::*;
use brep_kernel::{
    PmiAnnotation, PmiCamera, PmiDisplay, PmiGeometry, PmiProjection, PmiReport, PmiState,
    PmiStatus, PmiView,
};
use crate::view::Projection;

/// The modeling state remembered while the PMI workbench is active.
#[derive(Debug, Clone)]
pub struct PmiModelingSnapshot {
    pub camera_json: String,
    pub hidden: Vec<String>,
    pub wireframe: bool,
}

/// A patch the panel applies to one view's name / display state.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct PmiViewPatch {
    pub name: Option<String>,
    pub text_size_pt: Option<f64>,
    pub wireframe: Option<bool>,
    pub hidden: Option<Vec<String>>,
}

/// `{solid}@x,y,z` in WORLD coordinates (the PMI vertex-ref convention).
pub fn world_vertex_ref(solid: &str, position: [f64; 3]) -> String {
    let trim = |v: f64| {
        let rounded = (v * 1e9).round() / 1e9;
        let trimmed = crate::formatting::compact_decimal(rounded, 9);
        if trimmed == "-0" || trimmed.is_empty() { "0".to_string() } else { trimmed }
    };
    format!("{solid}@{},{},{}", trim(position[0]), trim(position[1]), trim(position[2]))
}

impl EngineState {
    // --- read surface ------------------------------------------------------

    /// The document's `pmi` block as typed state (the default — no views —
    /// when the document carries none).
    pub fn pmi_state(&self) -> PmiState {
        self.history
            .pmi_block()
            .and_then(|block| serde_json::from_value(block.clone()).ok())
            .unwrap_or_default()
    }

    /// The PMI report of the last APPLIED run.
    pub fn pmi_report(&self) -> Option<&PmiReport> {
        self.pmi_report.as_ref()
    }

    pub fn pmi_active_view(&self) -> Option<&str> {
        self.pmi_active_view.as_deref()
    }

    pub fn pmi_open_annotation(&self) -> Option<&str> {
        self.pmi_open_annotation.as_deref()
    }

    /// Whether the PMI workbench remembered a modeling state (it is "entered").
    pub fn pmi_workbench_entered(&self) -> bool {
        self.pmi_modeling.is_some()
    }

    /// The `__brepPmi` verifier global: the block, the report, the active
    /// view, the open annotation and the datum letters, as one object.
    pub fn pmi_state_json(&self) -> String {
        let state = self.pmi_state();
        serde_json::json!({
            "views": state.views,
            "idCounter": state.id_counter,
            "activeView": self.pmi_active_view,
            "openAnnotation": self.pmi_open_annotation,
            "entered": self.pmi_modeling.is_some(),
            "datums": state.datum_letters(),
            "report": self.pmi_report,
        })
        .to_string()
    }

    // --- block writes --------------------------------------------------------

    /// Write `state` as the document's block (checkpointed) and re-run the
    /// history so the tail resolves it. An empty block is removed so a part
    /// that never had PMI saves byte-identically.
    fn write_pmi_state(&mut self, state: PmiState) -> String {
        let block = if state.is_empty() { None } else { serde_json::to_value(&state).ok() };
        self.history.set_pmi_block(block, None);
        self.rerun_history()
    }

    // --- views ---------------------------------------------------------------

    /// The current camera as a snapshot.
    fn snapshot_camera(&self) -> PmiCamera {
        let camera = &self.camera;
        PmiCamera {
            eye: camera.eye,
            target: camera.target,
            up: camera.up,
            projection: match camera.projection {
                Projection::Orthographic { half_height } => PmiProjection::Orthographic { half_height },
                Projection::Perspective { fov_y_deg } => PmiProjection::Perspective { fov_y_deg },
            },
            viewport: [camera.width, camera.height],
        }
    }

    /// The names of the solids currently hidden in the scene.
    fn hidden_solid_names(&self) -> Vec<String> {
        self.scene
            .solids()
            .iter()
            .filter(|solid| !solid.visible)
            .map(|solid| solid.name.clone())
            .collect()
    }

    /// Capture a view: the current camera, hidden objects and wireframe
    /// setting, named `name` (or `View N`). The new view becomes active.
    pub fn pmi_capture_view(&mut self, name: Option<&str>) -> String {
        let mut state = self.pmi_state();
        let id = state.next_id("VIEW");
        let name = name
            .map(str::trim)
            .filter(|n| !n.is_empty())
            .map(String::from)
            .unwrap_or_else(|| format!("View {}", state.views.len() + 1));
        // The capture reads the MODELING state: if another view is active its
        // applied state is what is on screen, so deactivate first (restores)
        // — a view captures what the user set up, not another view's snapshot.
        let was_active = self.pmi_active_view.is_some();
        if was_active {
            self.pmi_deactivate_view();
        }
        self.pmi_remember_modeling();
        state.views.push(PmiView {
            id: id.clone(),
            name,
            camera: Some(self.snapshot_camera()),
            display: PmiDisplay {
                text_size_pt: 12.0,
                wireframe: self.settings.wireframe,
                hidden: self.hidden_solid_names(),
            },
            annotations: Vec::new(),
        });
        self.write_pmi_state(state);
        let _ = self.pmi_activate_view(&id);
        id
    }

    pub fn pmi_rename_view(&mut self, id: &str, name: &str) -> Result<(), String> {
        let mut state = self.pmi_state();
        let view = state.find_view_mut(id).ok_or_else(|| format!("no PMI view '{id}'"))?;
        let name = name.trim();
        if name.is_empty() {
            return Err("a view needs a name".into());
        }
        view.name = name.to_string();
        self.write_pmi_state(state);
        Ok(())
    }

    /// Delete a view (and its annotations). An active view deactivates first.
    pub fn pmi_delete_view(&mut self, id: &str) -> Result<(), String> {
        let mut state = self.pmi_state();
        let before = state.views.len();
        if self.pmi_active_view.as_deref() == Some(id) {
            self.pmi_deactivate_view();
        }
        state.views.retain(|view| view.id != id);
        if state.views.len() == before {
            return Err(format!("no PMI view '{id}'"));
        }
        if let Some(open) = &self.pmi_open_annotation {
            if state.find_annotation(open).is_none() {
                self.pmi_open_annotation = None;
            }
        }
        self.write_pmi_state(state);
        Ok(())
    }

    /// Re-capture a view's camera from the current camera (the explicit
    /// Update Camera action — orbiting never rewrites a snapshot silently).
    pub fn pmi_update_view_camera(&mut self, id: &str) -> Result<(), String> {
        let mut state = self.pmi_state();
        let camera = self.snapshot_camera();
        let view = state.find_view_mut(id).ok_or_else(|| format!("no PMI view '{id}'"))?;
        view.camera = Some(camera);
        self.write_pmi_state(state);
        Ok(())
    }

    /// Re-capture a view's hidden set from the scene (the explicit Update
    /// Visibility action).
    pub fn pmi_update_view_visibility(&mut self, id: &str) -> Result<(), String> {
        let hidden = self.hidden_solid_names();
        self.pmi_set_view_display(id, &PmiViewPatch { hidden: Some(hidden), ..Default::default() })
    }

    /// Patch a view's name / display state. The active view re-applies.
    pub fn pmi_set_view_display(&mut self, id: &str, patch: &PmiViewPatch) -> Result<(), String> {
        let mut state = self.pmi_state();
        let view = state.find_view_mut(id).ok_or_else(|| format!("no PMI view '{id}'"))?;
        if let Some(name) = &patch.name {
            let name = name.trim();
            if name.is_empty() {
                return Err("a view needs a name".into());
            }
            view.name = name.to_string();
        }
        if let Some(size) = patch.text_size_pt {
            view.display.text_size_pt = brep_kernel::clamp_text_size(size);
        }
        if let Some(wireframe) = patch.wireframe {
            view.display.wireframe = wireframe;
        }
        if let Some(hidden) = &patch.hidden {
            view.display.hidden = hidden.clone();
        }
        let display = view.display.clone();
        self.write_pmi_state(state);
        if self.pmi_active_view.as_deref() == Some(id) {
            self.apply_view_display(&display);
        }
        Ok(())
    }

    /// Remember the modeling state: what is on screen while NO view is
    /// active is the modeling state (hiding a body in the workbench before
    /// capturing is a modeling change, not a view's), so it is re-snapshotted
    /// whenever an activation starts from no active view; while a view is
    /// active the snapshot is kept (switching views restores to it).
    fn pmi_remember_modeling(&mut self) {
        if self.pmi_active_view.is_none() || self.pmi_modeling.is_none() {
            self.pmi_modeling = Some(PmiModelingSnapshot {
                camera_json: self.camera_state_json(),
                hidden: self.hidden_solid_names(),
                wireframe: self.settings.wireframe,
            });
        }
    }

    /// Entering the PMI workbench: remember the modeling camera, visibility
    /// and wireframe so a view activation can be undone exactly.
    pub fn pmi_enter_workbench(&mut self) {
        self.pmi_remember_modeling();
    }

    /// Leaving the PMI workbench: deactivate the view (restoring the modeling
    /// state) and forget the snapshot.
    pub fn pmi_leave_workbench(&mut self) {
        self.pmi_deactivate_view();
        self.pmi_modeling = None;
        self.pmi_open_annotation = None;
        self.refresh_pmi_overlay();
    }

    fn apply_view_display(&mut self, display: &PmiDisplay) {
        let names: Vec<String> = self.scene.solids().iter().map(|s| s.name.clone()).collect();
        for name in names {
            let visible = !display.hidden.contains(&name);
            self.scene.set_visible(&name, visible);
        }
        if self.settings.wireframe != display.wireframe {
            self.settings.wireframe = display.wireframe;
            self.settings_generation = self.settings_generation.wrapping_add(1);
        }
        self.dirty = true;
    }

    /// Activate a view: apply its camera (refit to the live viewport), hidden
    /// names, wireframe and explode poses; its annotations become the drawn
    /// and editable set.
    pub fn pmi_activate_view(&mut self, id: &str) -> Result<(), String> {
        let state = self.pmi_state();
        let view = state.find_view(id).ok_or_else(|| format!("no PMI view '{id}'"))?.clone();
        if self.pmi_active_view.as_deref() != Some(id) {
            // Switching views keeps the snapshot: deactivating restores the
            // modeling state, and the new view starts from it.
            let keep = self.pmi_active_view.is_some();
            self.pmi_deactivate_view();
            if !keep {
                self.pmi_remember_modeling();
            }
        }
        if self.pmi_modeling.is_none() {
            self.pmi_remember_modeling();
        }
        self.pmi_active_view = Some(id.to_string());
        if let Some(camera) = &view.camera {
            let (kind, scale) = match camera.projection {
                PmiProjection::Orthographic { half_height } => ("orthographic", half_height),
                PmiProjection::Perspective { fov_y_deg } => ("perspective", fov_y_deg),
            };
            let json = serde_json::json!({
                "kind": kind, "eye": camera.eye, "target": camera.target, "up": camera.up, "scale": scale,
            })
            .to_string();
            let _ = self.apply_camera_state_json(&json);
            self.controls_sync_after_camera_apply();
        }
        self.apply_view_display(&view.display);
        self.pmi_apply_explode();
        if let Some(open) = &self.pmi_open_annotation {
            if !view.annotations.iter().any(|a| a.id() == open) {
                self.pmi_open_annotation = None;
            }
        }
        self.refresh_pmi_overlay();
        Ok(())
    }

    /// Deactivate the active view: restore the explode poses, the modeling
    /// visibility, wireframe and camera. A no-op without an active view.
    pub fn pmi_deactivate_view(&mut self) {
        if self.pmi_active_view.take().is_none() {
            return;
        }
        self.pmi_restore_explode();
        if let Some(snapshot) = self.pmi_modeling.clone() {
            let names: Vec<String> = self.scene.solids().iter().map(|s| s.name.clone()).collect();
            for name in names {
                let visible = !snapshot.hidden.contains(&name);
                self.scene.set_visible(&name, visible);
            }
            if self.settings.wireframe != snapshot.wireframe {
                self.settings.wireframe = snapshot.wireframe;
                self.settings_generation = self.settings_generation.wrapping_add(1);
            }
            let _ = self.apply_camera_state_json(&snapshot.camera_json);
            self.controls_sync_after_camera_apply();
        }
        self.pmi_open_annotation = None;
        self.dirty = true;
        self.refresh_pmi_overlay();
    }

    /// Keep the arcball controls in step with a camera written wholesale.
    fn controls_sync_after_camera_apply(&mut self) {
        // The controls read the camera each frame (orbit deltas are applied
        // onto `self.camera`), so writing the camera is enough; a fresh depth
        // fit happens on the next render. Nothing else to sync.
        self.dirty = true;
    }

    // --- explode (display-only poses) -----------------------------------------

    /// Pose the active view's explode targets on the CURRENT displays,
    /// keeping the un-posed copies for the restore.
    pub(crate) fn pmi_apply_explode(&mut self) {
        self.pmi_restore_explode();
        let Some(active) = self.pmi_active_view.clone() else {
            return;
        };
        let Some(report) = self.pmi_report.as_ref() else {
            return;
        };
        let Some(view) = report.view(&active) else {
            return;
        };
        let poses: Vec<(Vec<String>, [f64; 3], [f64; 3], [f64; 3], [f64; 3])> = view
            .annotations
            .iter()
            .filter(|row| row.enabled && row.status == PmiStatus::Ok)
            .filter_map(|row| match &row.geometry {
                PmiGeometry::Explode { solids, translate, rotate_deg, scale, center, .. } => {
                    Some((solids.clone(), *translate, *rotate_deg, *scale, *center))
                }
                _ => None,
            })
            .collect();
        for (solids, translate, rotate_deg, scale, center) in poses {
            for name in solids {
                let Some(display) = self.scene.solid(&name) else { continue };
                self.pmi_explode_originals
                    .entry(name.clone())
                    .or_insert_with(|| display.clone());
                if let Some(display) = self.scene.solid_mut(&name) {
                    transform_display(display, center, translate, rotate_deg, scale);
                }
            }
        }
        if !self.pmi_explode_originals.is_empty() {
            self.dirty = true;
        }
    }

    /// Put every exploded display back exactly.
    pub(crate) fn pmi_restore_explode(&mut self) {
        let originals = std::mem::take(&mut self.pmi_explode_originals);
        for (name, original) in originals {
            if let Some(display) = self.scene.solid_mut(&name) {
                *display = original;
            }
        }
        self.dirty = true;
    }

    /// Post-apply tail (`finish_apply`): the displays are fresh, so re-pose
    /// the active view's explode targets and re-bake the overlay.
    pub(crate) fn pmi_after_apply(&mut self) {
        // Normally already un-posed by `apply_run_output` (before the scene
        // reconcile); the parse-error branch of a rerun reaches here with the
        // poses still applied, so restore rather than forget them.
        self.pmi_restore_explode();
        if let Some(active) = self.pmi_active_view.clone() {
            // A view that vanished (undo of its capture) deactivates.
            let exists = self.pmi_state().find_view(&active).is_some();
            if !exists {
                self.pmi_active_view = None;
                self.pmi_open_annotation = None;
            } else {
                self.pmi_apply_explode();
            }
        }
        if let Some(open) = &self.pmi_open_annotation {
            if self.pmi_state().find_annotation(open).is_none() {
                self.pmi_open_annotation = None;
            }
        }
        self.refresh_pmi_overlay();
    }

    // --- annotations -----------------------------------------------------------

    /// Add an annotation of `type_id` to view `view_id` (the active view when
    /// `None`) with `params_json` (the schema params; `id` is minted). A datum
    /// with no letter gets the next unused one. Returns the id; the new
    /// annotation's form opens.
    pub fn pmi_add_annotation(
        &mut self,
        view_id: Option<&str>,
        type_id: &str,
        params_json: &str,
    ) -> Result<String, String> {
        let def = brep_kernel::pmi_type(type_id).ok_or_else(|| format!("unknown PMI annotation type '{type_id}'"))?;
        let mut state = self.pmi_state();
        let view_id = view_id
            .map(String::from)
            .or_else(|| self.pmi_active_view.clone())
            .ok_or_else(|| "no active PMI view — capture or activate a view first".to_string())?;
        let id = state.next_id(def.short_name);
        let mut params: serde_json::Value = serde_json::from_str(params_json).unwrap_or_else(|_| serde_json::json!({}));
        if !params.is_object() {
            params = serde_json::json!({});
        }
        // Schema defaults under the given params.
        let schema = (def.schema)();
        if let (Some(fields), Some(object)) = (
            schema.get("inputParamsSchema").and_then(serde_json::Value::as_object),
            params.as_object_mut(),
        ) {
            for (key, spec) in fields {
                if !object.contains_key(key) {
                    if let Some(default) = spec.get("default_value") {
                        if !default.is_null() {
                            object.insert(key.clone(), default.clone());
                        }
                    }
                }
            }
            object.insert("id".into(), serde_json::Value::String(id.clone()));
            if type_id == "datum" {
                let letter = object.get("letter").and_then(serde_json::Value::as_str).unwrap_or("").trim().to_string();
                if letter.is_empty() {
                    if let Some(next) = state.next_datum_letter() {
                        object.insert("letter".into(), serde_json::Value::String(next));
                    }
                }
            }
        }
        let view = state.find_view_mut(&view_id).ok_or_else(|| format!("no PMI view '{view_id}'"))?;
        view.annotations.push(PmiAnnotation {
            kind: type_id.to_string(),
            enabled: true,
            params,
            label_world: None,
        });
        self.pmi_open_annotation = Some(id.clone());
        self.write_pmi_state(state);
        Ok(id)
    }

    /// Replace an annotation's params (a form edit). Re-runs.
    pub fn pmi_update_annotation(&mut self, id: &str, params_json: &str) -> Result<(), String> {
        self.pmi_update_annotation_no_rerun(id, params_json)?;
        self.rerun_history();
        Ok(())
    }

    /// The fold half of [`Self::pmi_update_annotation`] (checkpointed, no
    /// re-run) — the reference picker's commit uses it before its shared
    /// end tail re-runs.
    pub(crate) fn pmi_update_annotation_no_rerun(&mut self, id: &str, params_json: &str) -> Result<(), String> {
        let mut state = self.pmi_state();
        let annotation = state.find_annotation_mut(id).ok_or_else(|| format!("no PMI annotation '{id}'"))?;
        let mut params: serde_json::Value =
            serde_json::from_str(params_json).map_err(|error| format!("annotation params: {error}"))?;
        if let Some(object) = params.as_object_mut() {
            object.insert("id".into(), serde_json::Value::String(id.to_string()));
        }
        annotation.params = params;
        let block = serde_json::to_value(&state).ok();
        self.history.set_pmi_block(block, Some(&format!("pmi:params:{id}")));
        Ok(())
    }

    pub fn pmi_remove_annotation(&mut self, id: &str) -> Result<(), String> {
        let mut state = self.pmi_state();
        let Some((view_index, index)) = state.locate_annotation(id) else {
            return Err(format!("no PMI annotation '{id}'"));
        };
        state.views[view_index].annotations.remove(index);
        if self.pmi_open_annotation.as_deref() == Some(id) {
            self.pmi_open_annotation = None;
        }
        self.write_pmi_state(state);
        Ok(())
    }

    pub fn pmi_set_annotation_enabled(&mut self, id: &str, enabled: bool) -> Result<(), String> {
        let mut state = self.pmi_state();
        let annotation = state.find_annotation_mut(id).ok_or_else(|| format!("no PMI annotation '{id}'"))?;
        if annotation.enabled == enabled {
            return Ok(());
        }
        annotation.enabled = enabled;
        self.write_pmi_state(state);
        Ok(())
    }

    /// Move an annotation to `index` within its view.
    pub fn pmi_move_annotation(&mut self, id: &str, index: usize) -> Result<(), String> {
        let mut state = self.pmi_state();
        let Some((view_index, from)) = state.locate_annotation(id) else {
            return Err(format!("no PMI annotation '{id}'"));
        };
        let annotations = &mut state.views[view_index].annotations;
        let annotation = annotations.remove(from);
        let to = index.min(annotations.len());
        annotations.insert(to, annotation);
        self.write_pmi_state(state);
        Ok(())
    }

    /// Move an annotation to another view (append).
    pub fn pmi_move_annotation_to_view(&mut self, id: &str, view_id: &str) -> Result<(), String> {
        let mut state = self.pmi_state();
        let Some((view_index, from)) = state.locate_annotation(id) else {
            return Err(format!("no PMI annotation '{id}'"));
        };
        if state.find_view(view_id).is_none() {
            return Err(format!("no PMI view '{view_id}'"));
        }
        let annotation = state.views[view_index].annotations.remove(from);
        state.find_view_mut(view_id).expect("checked").annotations.push(annotation);
        self.write_pmi_state(state);
        Ok(())
    }

    /// Open one annotation's form (engine memory; `None` closes). Opening an
    /// annotation of another view activates that view.
    pub fn pmi_set_annotation_open(&mut self, id: Option<&str>) {
        match id {
            Some(id) => {
                let state = self.pmi_state();
                if let Some((view, _)) = state.find_annotation(id) {
                    let view_id = view.id.clone();
                    if self.pmi_active_view.as_deref() != Some(view_id.as_str()) {
                        let _ = self.pmi_activate_view(&view_id);
                    }
                    self.pmi_open_annotation = Some(id.to_string());
                }
            }
            None => self.pmi_open_annotation = None,
        }
        self.refresh_pmi_overlay();
    }

    // --- labels -----------------------------------------------------------------

    /// Move an annotation's label (world). Coalesced per annotation into ONE
    /// undo step, and NEVER a re-run: the cached report is patched in place
    /// and the overlay re-baked.
    pub fn pmi_set_label_world(&mut self, id: &str, world: [f64; 3]) -> Result<(), String> {
        let mut state = self.pmi_state();
        let annotation = state.find_annotation_mut(id).ok_or_else(|| format!("no PMI annotation '{id}'"))?;
        annotation.label_world = Some(world);
        let block = serde_json::to_value(&state).ok();
        self.history.set_pmi_block(block, Some(&format!("pmi:label:{id}")));
        if let Some(report) = self.pmi_report.as_mut() {
            if let Some(row) = report.annotation_mut(id) {
                row.label_world = world;
                if let PmiGeometry::Note { position } = &mut row.geometry {
                    *position = world;
                }
            }
        }
        self.refresh_pmi_overlay();
        Ok(())
    }

    /// Drag an annotation's label to the pointer: the new position is where
    /// the pick ray crosses the plane through the current label perpendicular
    /// to the viewing direction (so a drag never changes the label's depth).
    pub fn pmi_label_drag_to(&mut self, id: &str, x: f64, y: f64) {
        let Some((current, plane)) = self
            .pmi_report
            .as_ref()
            .and_then(|r| r.annotation(id))
            .map(|r| (r.label_world, r.plane))
        else {
            return;
        };
        let ray = self.camera.pick_ray(x, y);
        // In a picked annotation plane the label stays ON that plane; a
        // view-aligned label moves in the view-parallel plane through its
        // current position.
        let plane = plane.unwrap_or_else(|| {
            let (_, _, view) = self.camera.basis();
            brep_kernel::PmiPlane {
                origin: current,
                normal: view,
                x_axis: [0.0; 3],
            }
        });
        let Some(world) = plane.hit(ray.origin, ray.dir) else {
            return;
        };
        let _ = self.pmi_set_label_world(id, world);
    }

    /// A label drag ended: the next drag is a fresh undo step.
    pub fn pmi_label_drag_end(&mut self) {
        self.history.break_coalescing();
    }

    /// Hover a label: highlight the annotation's referenced geometry.
    pub fn pmi_hover(&mut self, id: &str) {
        self.pmi_label_hover_active = true;
        if self.pmi_hovered.as_deref() == Some(id) {
            return;
        }
        let references: Vec<String> = self
            .pmi_report
            .as_ref()
            .and_then(|report| report.annotation(id))
            .map(|row| row.references.clone())
            .unwrap_or_default();
        let mut solids: Vec<String> = Vec::new();
        let mut faces: Vec<String> = Vec::new();
        let mut edges: Vec<String> = Vec::new();
        for reference in &references {
            if let Some(at) = reference.find('@') {
                solids.push(reference[..at].to_string());
            } else if self.scene_has_face(reference) {
                faces.push(reference.clone());
            } else if self.scene_has_edge(reference) {
                edges.push(reference.clone());
            } else if self.scene.solid(reference).is_some() {
                solids.push(reference.clone());
            } else {
                let prefix = format!("{reference}:");
                solids.extend(self.scene.solids().iter().filter(|s| s.name.starts_with(&prefix)).map(|s| s.name.clone()));
            }
        }
        self.clear_hover();
        self.emphasis.hovered_solids.extend(solids);
        self.emphasis.hovered_faces.extend(faces);
        self.emphasis.hovered_edges.extend(edges);
        self.emphasis.generation = self.emphasis.generation.wrapping_add(1);
        self.pmi_hovered = Some(id.to_string());
        self.dirty = true;
    }

    pub fn pmi_hover_end(&mut self) {
        if self.pmi_hovered.take().is_some() {
            self.clear_hover();
            self.dirty = true;
        }
    }

    /// Consume the one-frame "a PMI label is hovering elements" flag (the
    /// viewport's scene-hover pass yields while set).
    pub fn take_pmi_label_hover(&mut self) -> bool {
        std::mem::take(&mut self.pmi_label_hover_active)
    }

    /// A label was clicked: open that annotation's form.
    pub fn pmi_label_clicked(&mut self, id: &str) {
        self.pmi_set_annotation_open(Some(id));
    }

    // --- reference picker ---------------------------------------------------------

    /// Enter reference-selection mode for annotation `id`'s field at `path`.
    pub fn begin_ref_select_for_pmi(
        &mut self,
        id: &str,
        path: Vec<String>,
        label: String,
        filter: Vec<String>,
        multiple: bool,
        seed_names: Vec<String>,
    ) {
        let restore_index = self.history.rollback();
        self.selection_filter = SelectionFilter::from_ref_filter(&filter);
        self.ref_select = Some(RefSelectState {
            feature_id: id.to_string(),
            path,
            label,
            filter,
            multiple,
            names: seed_names,
            restore_index,
            target: RefSelectTarget::Pmi,
        });
        self.sync_ref_select_emphasis();
    }

    /// Commit a finished PMI ref-select into the annotation's params (fold
    /// only — the caller's shared tail re-runs).
    pub(crate) fn pmi_commit_refs(&mut self, id: &str, path: &[String], names: &[String], multiple: bool) {
        let state = self.pmi_state();
        let Some((_, annotation)) = state.find_annotation(id) else {
            self.push_notice(format!("unknown PMI annotation '{id}'"));
            return;
        };
        let mut params = annotation.params.clone();
        let value = if multiple {
            serde_json::Value::Array(names.iter().cloned().map(serde_json::Value::String).collect())
        } else {
            serde_json::Value::String(names.first().cloned().unwrap_or_default())
        };
        super::selection_ux::set_json_at(&mut params, path, value);
        if let Err(error) = self.pmi_update_annotation_no_rerun(id, &params.to_string()) {
            self.push_notice(format!("PMI update failed: {error}"));
        }
    }

    // --- import -------------------------------------------------------------------

    /// Merge a file's lifted PMI (`read_step_pmi`) into the document beside
    /// the import that added its geometry: views append with fresh ids, the
    /// import's undo checkpoint covers both (no second checkpoint).
    pub(crate) fn pmi_merge_imported(&mut self, lifted: PmiState) {
        let mut state = self.pmi_state();
        for view in lifted.views {
            let id = state.next_id("VIEW");
            let mut annotations = Vec::with_capacity(view.annotations.len());
            for mut annotation in view.annotations {
                let prefix = brep_kernel::pmi_type(&annotation.kind).map(|def| def.short_name).unwrap_or("PMI");
                let fresh = state.next_id(prefix);
                if let Some(object) = annotation.params.as_object_mut() {
                    object.insert("id".into(), serde_json::Value::String(fresh));
                }
                annotations.push(annotation);
            }
            state.views.push(PmiView {
                id,
                name: view.name,
                camera: view.camera,
                display: view.display,
                annotations,
            });
        }
        let block = serde_json::to_value(&state).ok();
        self.history.set_pmi_block_no_undo(block);
        self.rerun_history();
    }
}

/// Pose a display in place: `p' = R((p − c) ∘ s) + c + t` on the mesh, the
/// edge polylines and the vertices; normals rotate; the bbox is rebuilt.
fn transform_display(
    display: &mut crate::scene::SolidDisplay,
    center: [f64; 3],
    translate: [f64; 3],
    rotate_deg: [f64; 3],
    scale: [f64; 3],
) {
    let rotate = |v: [f64; 3]| super::rotate_euler_xyz_f64(v, rotate_deg);
    let pose = |p: [f64; 3]| -> [f64; 3] {
        let local = [(p[0] - center[0]) * scale[0], (p[1] - center[1]) * scale[1], (p[2] - center[2]) * scale[2]];
        let rotated = rotate(local);
        [rotated[0] + center[0] + translate[0], rotated[1] + center[1] + translate[1], rotated[2] + center[2] + translate[2]]
    };
    let mut bbox = crate::camera::Aabb::empty();
    for position in &mut display.mesh.positions {
        let posed = pose([position[0] as f64, position[1] as f64, position[2] as f64]);
        *position = [posed[0] as f32, posed[1] as f32, posed[2] as f32];
        bbox.expand(posed);
    }
    for normal in &mut display.mesh.normals {
        let rotated = rotate([normal[0] as f64, normal[1] as f64, normal[2] as f64]);
        *normal = [rotated[0] as f32, rotated[1] as f32, rotated[2] as f32];
    }
    for edge in &mut display.edges {
        for point in &mut edge.polyline {
            let posed = pose([point[0] as f64, point[1] as f64, point[2] as f64]);
            *point = [posed[0] as f32, posed[1] as f32, posed[2] as f32];
            bbox.expand(posed);
        }
    }
    for vertex in &mut display.vertices {
        vertex.position = pose(vertex.position);
        bbox.expand(vertex.position);
    }
    if !bbox.is_empty() {
        display.bbox = bbox;
    }
}

// BREP private tests: 19802c114ba38bda