Skip to main content

brep_render/engine_state/
selection_ux.rs

1use super::*;
2
3/// The geometry selection [`EngineState::select_feature`] made, kept beside the
4/// feature id so the feature reads as selected exactly as long as that
5/// selection stands.
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub(crate) struct FeatureSelection {
8    solids: crate::style::OrderedNames,
9    faces: crate::style::OrderedNames,
10    edges: crate::style::OrderedNames,
11    datums: crate::style::OrderedNames,
12}
13
14impl FeatureSelection {
15    fn of(emphasis: &crate::style::Emphasis) -> Self {
16        Self {
17            solids: emphasis.selected_solids.clone(),
18            faces: emphasis.selected_faces.clone(),
19            edges: emphasis.selected_edges.clone(),
20            datums: emphasis.selected_datums.clone(),
21        }
22    }
23}
24
25/// The active reference pick as a FORM sees it (see
26/// [`EngineState::ref_select_field`]): the subject whose field is being
27/// filled, the field's path, and the running list.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct RefSelectField {
30    /// The feature / constraint / annotation / sheet-object id the field
31    /// belongs to.
32    pub subject: String,
33    /// The field's JSON path (`["targetSolid"]`, `["boolean","targets"]`).
34    pub path: Vec<String>,
35    /// Whether the field takes a list.
36    pub multiple: bool,
37    /// The picked names so far.
38    pub names: Vec<String>,
39    /// Picks since the field was activated (see `RefSelectState::picks`).
40    pub picks: usize,
41    /// Which commit lane the pick belongs to.
42    pub target: RefSelectTarget,
43}
44
45impl EngineState {
46    /// Clear the current SELECTION (Esc): drop all selected solids/faces/edges/
47    /// vertices (hover is left untouched). Bumps the emphasis generation + marks
48    /// dirty only when something was actually cleared. Returns whether it changed.
49    pub fn clear_selection(&mut self) -> bool {
50        // The Work part's context selection clears with the rest.
51        let had_context = self.select_context(None);
52        // The viewport-selected CONSTRAINT (label click) clears with the rest.
53        let had_constraint = self.selected_constraint.is_some();
54        self.constraint_deselect();
55        // …and so do the tree selections that have no geometry of their own: a
56        // feature (whose geometry clears below), a PMI annotation and a sheet
57        // object.
58        let had_feature = self.selected_feature.take().is_some();
59        let had_pmi_annotation = self.pmi_selected_annotation.take().is_some();
60        if had_pmi_annotation {
61            self.refresh_pmi_overlay();
62        }
63        let had_pmi = self.pmi_selected_view.take().is_some() || had_pmi_annotation;
64        let had_sheet = self.sheet_selected_object.take().is_some();
65        let had_datums = !self.emphasis.selected_datums.is_empty();
66        let had = had_context
67            || had_constraint
68            || had_feature
69            || had_pmi
70            || had_sheet
71            || !self.emphasis.selected_solids.is_empty()
72            || !self.emphasis.selected_faces.is_empty()
73            || !self.emphasis.selected_edges.is_empty()
74            || !self.emphasis.selected_vertices.is_empty()
75            || had_datums;
76        if had {
77            self.emphasis.selected_solids.clear();
78            self.emphasis.selected_faces.clear();
79            self.emphasis.selected_edges.clear();
80            self.emphasis.selected_vertices.clear();
81            self.emphasis.selected_datums.clear();
82            self.emphasis.generation = self.emphasis.generation.wrapping_add(1);
83            self.dirty = true;
84        }
85        // A cleared datum drops its selection accent — re-feed the datum planes so
86        // the highlight disappears immediately (no re-run needed).
87        if had_datums {
88            self.refresh_construction_datums();
89        }
90        had
91    }
92
93    /// REPLACE the whole selection with these named entities — the write twin of
94    /// [`Self::selection_json`], and the only way to put a MULTI-entity selection
95    /// back the way it was (`select_by_name` takes one name and clears the rest).
96    ///
97    /// Names are taken as given, IN THE ORDER GIVEN: this is the write twin of a
98    /// pick order, so a selection saved from `selection_json` and put back here
99    /// seeds exactly what it seeded before. An unknown name simply highlights
100    /// nothing, the same as a stale name after a rebuild. VERTICES are not
101    /// addressable here —
102    /// they have no kernel name and emphasis keys them by position
103    /// ([`Self::select_vertex_by_position`]) — so a saved selection's vertices do
104    /// not come back through this call.
105    pub fn set_selection(
106        &mut self,
107        solids: &[String],
108        faces: &[String],
109        edges: &[String],
110        datums: &[String],
111    ) {
112        let had_datums = !self.emphasis.selected_datums.is_empty();
113        self.emphasis.selected_solids = solids.iter().cloned().collect();
114        self.emphasis.selected_faces = faces.iter().cloned().collect();
115        self.emphasis.selected_edges = edges.iter().cloned().collect();
116        self.emphasis.selected_datums = datums.iter().cloned().collect();
117        self.emphasis.selected_vertices.clear();
118        self.emphasis.generation = self.emphasis.generation.wrapping_add(1);
119        self.dirty = true;
120        if had_datums || !datums.is_empty() {
121            self.refresh_construction_datums();
122        }
123    }
124
125    /// SELECT a feature, as the history tree's single click does: the feature
126    /// becomes the selected one and the geometry it contributed to the model on
127    /// screen becomes the viewport selection, replacing whatever was selected.
128    ///
129    /// What a feature "contributed" is read from the last run, first match wins:
130    /// the FACES it created that are still in the scene (a fillet's blends, a
131    /// hole's bore — a feature later rewritten by another keeps its own faces);
132    /// else the SOLIDS it was the last to write (a boolean, which makes no face
133    /// of its own); else its own sketch or datum frames. A feature past the
134    /// rollback has built nothing, so it selects with an empty geometry
135    /// selection — the tree row still shows it.
136    ///
137    /// Returns false, changing nothing, when `id` is not a feature.
138    pub fn select_feature(&mut self, id: &str) -> bool {
139        if self.history.index_of(id).is_none() {
140            return false;
141        }
142        let in_scene_faces: Vec<String> = self
143            .scene
144            .solids()
145            .iter()
146            .flat_map(|solid| solid.faces.iter().map(|face| face.name.clone()))
147            .filter(|name| self.entity_origin.get(name).map(String::as_str) == Some(id))
148            .collect();
149        let mut solids: Vec<String> = Vec::new();
150        let mut datums: Vec<String> = Vec::new();
151        if in_scene_faces.is_empty() {
152            solids = self
153                .scene
154                .solids()
155                .iter()
156                .filter(|solid| {
157                    self.provenance.get(&solid.name).map(String::as_str) == Some(id)
158                        || solid.name == id
159                })
160                .map(|solid| solid.name.clone())
161                .collect();
162        }
163        if in_scene_faces.is_empty() && solids.is_empty() {
164            datums = self
165                .construction_frames
166                .iter()
167                .map(|(name, _)| name)
168                .filter(|name| {
169                    self.datum_feature_for_name(name)
170                        .is_some_and(|(feature, _)| feature == id)
171                })
172                .cloned()
173                .collect();
174        }
175        self.set_selection(&solids, &in_scene_faces, &[], &datums);
176        self.selected_feature = Some((id.to_string(), FeatureSelection::of(&self.emphasis)));
177        true
178    }
179
180    /// The feature selected through [`Self::select_feature`], while the
181    /// geometry selection it made still stands and the feature still exists.
182    /// Any other selection — a viewport pick, Esc, Clear, a Scene-tree row —
183    /// replaces that geometry and so reads as the feature being deselected.
184    pub fn selected_feature(&self) -> Option<&str> {
185        let (id, made) = self.selected_feature.as_ref()?;
186        (self.history.index_of(id).is_some() && *made == FeatureSelection::of(&self.emphasis)
187            && self.emphasis.selected_vertices.is_empty())
188        .then_some(id.as_str())
189    }
190
191    /// Select the top-priority pick under CSS-pixel `(x, y)` that the SELECTION
192    /// FILTER admits — replacing the current selection (a plain viewport click).
193    /// A miss (or a click when the filter admits nothing) clears the selection.
194    /// Marks dirty when the selection changed; returns whether something was
195    /// selected. The by-kind honoring lives in [`select_filtered_at`](Self::select_filtered_at) in the
196    /// appended selection-filter impl block (kept separate so concurrent edits to
197    /// this primary block don't conflict).
198    pub fn select_top_at(&mut self, x: f64, y: f64) -> bool {
199        self.select_filtered_at(x, y)
200    }
201
202    /// The current SELECTION (not hover) as JSON
203    /// `{ solids:[..], faces:[..], edges:[..], vertices: n }` — lets a UI / the
204    /// headed verifier read selection state (e.g. assert Esc cleared it).
205    ///
206    /// Each array is in PICK ORDER, oldest first ([`OrderedNames`](crate::style::OrderedNames)): the first name in `faces` is the face that was picked
207    /// first, and a face toggled off and on again is last. That is the order
208    /// every seeder reads — the assembly constraint's `elements` (whose first
209    /// element is the Distance BASE face), the context bar's reference pre-fill,
210    /// a boolean's target/tool, a fillet's edge list — so the same picks seed the
211    /// same feature in every process. Order is per BUCKET: a face and an edge
212    /// picked in either order still list under `faces` and `edges`, and a seeder
213    /// that takes both reads them in ITS OWN kind order (the field's
214    /// `selectionFilter`), which is fixed by the schema.
215    pub fn selection_json(&self) -> String {
216        self.selection_value().to_string()
217    }
218
219    /// [`Self::selection_json`] as a JSON value.
220    pub fn selection_value(&self) -> serde_json::Value {
221        let solids: Vec<&String> = self.emphasis.selected_solids.iter().collect();
222        let faces: Vec<&String> = self.emphasis.selected_faces.iter().collect();
223        let edges: Vec<&String> = self.emphasis.selected_edges.iter().collect();
224        let datums: Vec<&String> = self.emphasis.selected_datums.iter().collect();
225        serde_json::json!({
226            "solids": solids,
227            "faces": faces,
228            "edges": edges,
229            "datums": datums,
230            "vertices": self.emphasis.selected_vertices.len(),
231        })
232    }
233
234    // --- Reference-selection widget (the engine-native picker, #42) --------
235    //
236    // A feature-dialog reference field activates this MODAL: the UI hides the
237    // rest of itself and shows only the widget's list + Finish/Cancel; the engine
238    // rolls to the pre-feature "before" state, highlights the running selection
239    // (via `emphasis`), and each click in the viewport type-constrained-picks a
240    // name into the list. Finish writes the names into the feature params (via
241    // the same `update_feature_params` path) and restores; Cancel discards. The
242    // list of names is the whole state — no event-on-object wiring.
243
244    /// True while the reference-selection modal is active (the shell hides the
245    /// rest of the UI and the viewport routes clicks to picking).
246    pub fn ref_select_active(&self) -> bool {
247        self.ref_select.is_some()
248    }
249
250    /// Enter reference-selection mode for feature `feature_id`'s param at `path`.
251    /// Seeds the running list from `seed_names` (the field's current value), rolls
252    /// the model to the pre-feature "before" state (the step just before the
253    /// edited feature ran), and highlights the seeded names. `filter` constrains
254    /// the pick kind (`["SOLID"]`, `["FACE"]`, …); `multiple` allows a list.
255    pub fn begin_ref_select(
256        &mut self,
257        feature_id: &str,
258        path: Vec<String>,
259        label: String,
260        filter: Vec<String>,
261        multiple: bool,
262        seed_names: Vec<String>,
263    ) {
264        let restore_index = self.history.rollback();
265        // "Before" = the step just before the edited feature ran, so the user
266        // picks against the correct geometry. Clamp at 0 for the first feature.
267        let before = self
268            .history
269            .index_of(feature_id)
270            .map(|i| i.saturating_sub(1))
271            .unwrap_or(restore_index);
272        // Constrain the GLOBAL selection filter to exactly the kinds this field
273        // permits: this drives BOTH click-picking (`ref_select_click`) AND
274        // hover-highlighting (`hover_at`, which reads `selection_filter`), so only
275        // the allowed kinds highlight/select while the picker is active. An
276        // absent/construction-only field filter maps to all-enabled (see
277        // `from_ref_filter`). Restored to the all-enabled default on finish/cancel
278        // (`end_ref_select`).
279        self.selection_filter = SelectionFilter::from_ref_filter(&filter);
280        self.ref_select = Some(RefSelectState {
281            feature_id: feature_id.to_string(),
282            path,
283            label,
284            filter,
285            multiple,
286            names: seed_names,
287            restore_index,
288            target: RefSelectTarget::Feature,
289            picks: 0,
290            claimed: false,
291            finish_requested: false,
292        });
293        // Roll to the before-state (re-runs + marks dirty), then light up the seed.
294        self.history.set_rollback(before);
295        self.rerun_history();
296        self.sync_ref_select_emphasis();
297    }
298
299    /// Enter a POINT pick for the vec3 field of feature `feature_id` whose pick
300    /// button is `button_path` (the field's path with
301    /// [`super::POINT_PICK_SUFFIX`] on its last key): the same roll and the
302    /// same type-constrained pick as [`Self::begin_ref_select`], single-valued
303    /// and unseeded, committed by [`Self::finish_ref_select`] as a point (see
304    /// [`RefSelectTarget::PointPick`]).
305    pub fn begin_point_pick(&mut self, feature_id: &str, button_path: Vec<String>, label: String, filter: Vec<String>) {
306        self.begin_ref_select(feature_id, button_path, label, filter, false, Vec::new());
307        if let Some(state) = self.ref_select.as_mut() {
308            state.target = RefSelectTarget::PointPick;
309        }
310    }
311
312    /// The point a picked `name` puts a vec3 field of the feature at `index`
313    /// on, resolved against the scene BEFORE that feature — the prefix the
314    /// pick was made on, replayed like the default pivot's (warm).
315    fn point_pick_value(&self, index: usize, name: &str) -> Result<[f64; 3], String> {
316        let request = self.history.request_before(index).ok_or("the feature has no history before it")?;
317        let request: HistoryRequest = serde_json::from_value(request).map_err(|error| error.to_string())?;
318        let _trace = crate::run_trace::span("point_pick_value");
319        let result = self.execute_plugin_history(&request);
320        brep_kernel::face_transform_reference_point(&result.results, name)
321    }
322
323    /// The running list of picked names (empty when not active) — the modal UI
324    /// reads this back to draw its one-per-line list.
325    pub fn ref_select_names(&self) -> Vec<String> {
326        self.ref_select
327            .as_ref()
328            .map(|r| r.names.clone())
329            .unwrap_or_default()
330    }
331
332    /// The active field's label (for the modal heading), or empty.
333    pub fn ref_select_label(&self) -> String {
334        self.ref_select
335            .as_ref()
336            .map(|r| r.label.clone())
337            .unwrap_or_default()
338    }
339
340    /// A one-line summary of the active field for the modal heading:
341    /// `"Tool solids (SOLID, multiple)"`.
342    pub fn ref_select_prompt(&self) -> String {
343        match &self.ref_select {
344            Some(r) if r.target == RefSelectTarget::Sheet => format!(
345                "{} (sheet anchor{})",
346                r.label,
347                if r.multiple { "s" } else { "" }
348            ),
349            Some(r) => format!(
350                "{} ({}{})",
351                r.label,
352                r.filter.join("/"),
353                if r.multiple { ", multiple" } else { "" }
354            ),
355            None => String::new(),
356        }
357    }
358
359    /// A viewport click while active: type-constrained-pick the nearest allowed
360    /// hit under CSS-pixel `(x, y)` and add its name to the running list (single
361    /// fields replace; multiple fields append, de-duplicated). Re-lights the
362    /// highlight. No-op on a miss / an empty (unnamed) hit.
363    pub fn ref_select_click(&mut self, x: f64, y: f64) {
364        let Some(state) = self.ref_select.as_ref() else {
365            return;
366        };
367        let filter = state.filter.clone();
368        let target = state.target;
369        // A SHEET pick is an anchor on the paper, never a 3D hit: the sheet
370        // viewport feeds `ref_select_pick_sheet_anchor` instead.
371        if target == RefSelectTarget::Sheet {
372            return;
373        }
374        // A Work part's CONTEXT is not the part's to reference: say so, and
375        // say what to do instead, rather than store a name its kernel cannot
376        // resolve. (An instructions pick names the ghosts in that layer on
377        // purpose: `pick_candidates_at` lists them for it.)
378        let instructions_pick = matches!(target, RefSelectTarget::Instructions { .. });
379        if let Some(hit) = self.context_hit_at(x, y).filter(|_| !instructions_pick) {
380            self.push_notice(format!(
381                "'{}' is another part of the assembly: a feature cannot reference it (it would not follow that part). \
382                 Make a datum on it, or copy its edges into a sketch, and use that.",
383                hit.solid
384            ));
385            return;
386        }
387        // The field's RAW kind strings drive the pick (`pick_top_at` reads
388        // `DATUM` as an alias of `PLANE`), so a `["PLANE","FACE"]` sketchPlane
389        // field now picks a construction plane through the ORDINARY candidate
390        // list — including one sitting under a face, which the geometry-miss
391        // fallback below could never reach.
392        //
393        // The click takes the TOP row of the same list the field's pick list
394        // shows, so a field that admits COMPONENT (an assembly pattern's seed
395        // components) takes the component owning the geometry under the
396        // cursor: the raw pick never holds a COMPONENT row of its own.
397        match self.ref_select_candidates_at(x, y).into_iter().next() {
398            Some(hit) => self.ref_select_take_candidate(&hit),
399            None => self.ref_select_take_miss(x, y, &filter),
400        }
401    }
402
403    /// The candidates a reference pick may take under CSS-pixel `(x, y)`, for
404    /// the PICK LIST the viewport opens on a dwelled (or Alt) click while a
405    /// reference field is picking: the raw list
406    /// ([`pick_candidates_at`](Self::pick_candidates_at)) admitted by the
407    /// field's OWN kind strings — the same admission
408    /// [`ref_select_click`](Self::ref_select_click) applies — in the shared
409    /// pick-list order. A plain click takes the top admitted row by kind, so
410    /// with a `["SOLID","FACE","SKETCH"]` field the face always wins it and the
411    /// solid behind that face is reachable only through this list. Empty when
412    /// no field is picking, for a sheet pick (anchors are on the paper), and
413    /// when a Work part's context is in front (the click refuses that too).
414    pub fn ref_select_candidates_at(&self, x: f64, y: f64) -> Vec<pick::PickCandidate> {
415        let Some(state) = self.ref_select.as_ref() else {
416            return Vec::new();
417        };
418        if state.target == RefSelectTarget::Sheet {
419            return Vec::new();
420        }
421        let instructions_pick = matches!(state.target, RefSelectTarget::Instructions { .. });
422        if !instructions_pick && self.context_hit_at(x, y).is_some() {
423            return Vec::new();
424        }
425        let filter = &state.filter;
426        let raw = self.pick_candidates_at(x, y);
427        let mut out: Vec<pick::PickCandidate> = raw
428            .iter()
429            .filter(|c| filter.is_empty() || self.candidate_admitted(filter, c))
430            .cloned()
431            .collect();
432        // A field that admits COMPONENT lists the component owning any hit
433        // (ranked last, so a SOLID or FACE the field also admits keeps the
434        // plain click). An empty filter admits every raw kind already.
435        if filter.iter().any(|k| k.eq_ignore_ascii_case("COMPONENT")) {
436            out.extend(self.component_candidates(&raw));
437            super::plane_pick::sort_pick_candidates(&mut out);
438        }
439        out
440    }
441
442    /// Whether `candidate` is already in the running reference list — the pick
443    /// list's per-row selected state while a reference field is picking.
444    pub fn ref_select_has_candidate(&self, candidate: &pick::PickCandidate) -> bool {
445        let Some(state) = self.ref_select.as_ref() else {
446            return false;
447        };
448        !candidate.name.trim().is_empty() && state.names.iter().any(|n| n == &candidate.name)
449    }
450
451    /// Take ONE candidate into the running reference list — what a plain click
452    /// does with its top hit, and what a pick-list row does with its own. The
453    /// candidate resolves to a name exactly as the click's did (a plane only by
454    /// a resolved D/P frame name, a vertex as a coordinate ref for the targets
455    /// that read one, a spline anchor as its owning port); single fields
456    /// replace, multiple fields append, de-duplicated. No-op while no field is
457    /// picking, for a sheet pick, and for a hit that resolves to no name.
458    pub fn ref_select_take_candidate(&mut self, hit: &pick::PickCandidate) {
459        let Some(target) = self.ref_select.as_ref().map(|state| state.target) else {
460            return;
461        };
462        if target == RefSelectTarget::Sheet {
463            return;
464        }
465        // A spline anchor attaches to a PORT: whatever part of a port's drawn
466        // sheet was hit (its line, its base vertex, the sheet itself), the
467        // pick resolves to the OWNING sheet, which is keyed by the port id;
468        // anything that is not a port is refused with a notice.
469        if let RefSelectTarget::SplineAnchor { .. } = target {
470            let owner = if hit.solid.trim().is_empty() { hit.name.clone() } else { hit.solid.clone() };
471            if !self.is_port_id(&owner) {
472                self.push_notice(format!("'{owner}' is not a port — pick a port to attach the anchor"));
473                return;
474            }
475            let state = self.ref_select.as_mut().expect("active by guard above");
476            state.names = vec![owner];
477            state.picks += 1;
478            self.sync_ref_select_emphasis();
479            return;
480        }
481        let picked = match hit {
482            hit if hit.kind == pick::PickKind::Plane => {
483                // Accept ONLY a resolved D/P frame name, the same guard the
484                // fallback applies — a stray widget-fed plane never lands in a
485                // reference field.
486                if self.datum_feature_for_name(&hit.name).is_none() {
487                    return;
488                }
489                hit.name.clone()
490            }
491            hit if !hit.name.trim().is_empty() => hit.name.clone(),
492            hit => {
493                // A vertex pick carries no kernel name. For an ASSEMBLY CONSTRAINT
494                // field that accepts VERTEX, build the `{solidName}@x,y,z` ref with
495                // COMPONENT-LOCAL coordinates (world pick · owning-component
496                // pose⁻¹ — the lane-E selection contract; the kernel resolver snaps
497                // to the nearest topology vertex). Everything else stays a no-op.
498                if !matches!(hit.kind, pick::PickKind::Vertex) {
499                    return;
500                }
501                match target {
502                    RefSelectTarget::AssemblyConstraint => {
503                        match self.component_vertex_ref(&hit.solid, hit.position) {
504                            Some(vertex_ref) => vertex_ref,
505                            None => return, // not component geometry — constraints reject it anyway
506                        }
507                    }
508                    // PMI resolves against the world-posed resident solids, so
509                    // its vertex refs carry WORLD coordinates.
510                    RefSelectTarget::Pmi => super::pmi_ops::world_vertex_ref(&hit.solid, hit.position),
511                    // A connection point's seat resolves against the finished
512                    // part, which is the same world-posed scene, so its vertex
513                    // refs take the same form and the kernel reads them with
514                    // the same helper.
515                    RefSelectTarget::PortPoint { .. } => {
516                        super::pmi_ops::world_vertex_ref(&hit.solid, hit.position)
517                    }
518                    // A point pick resolves against the modeling scene before
519                    // the feature, whose solids are in world coordinates.
520                    RefSelectTarget::PointPick => super::pmi_ops::world_vertex_ref(&hit.solid, hit.position),
521                    // A mount's origin pick resolves against the same scene.
522                    RefSelectTarget::Mount { .. } => super::pmi_ops::world_vertex_ref(&hit.solid, hit.position),
523                    _ => return,
524                }
525            }
526        };
527        self.ref_select_add_name(picked);
528    }
529
530    /// A reference click that hit NO admitted candidate: only a plane field can
531    /// still take something, through the datum widget pick.
532    fn ref_select_take_miss(&mut self, x: f64, y: f64, filter: &[String]) {
533        // TOTAL MISS. The plane CARDS are candidates above and they are
534        // the same set `datum_pick` tests, so in the app this arm is
535        // unreachable for a plane field; it is kept as a second line of
536        // defense for the tested `["PLANE","FACE"]` sketchPlane flow (and
537        // it is the ONLY path that would reach a datum AXIS, were one ever
538        // fed). Accept ONLY a resolved D/P frame name
539        // (`datum_feature_for_name`, mirroring `select_datum`'s guard) so an
540        // AXIS name — which `datum_pick` may also return — never lands in a
541        // plane field.
542        let admits_plane = filter
543            .iter()
544            .any(|k| k.eq_ignore_ascii_case("PLANE") || k.eq_ignore_ascii_case("DATUM"));
545        if !admits_plane {
546            return;
547        }
548        let name = self.datum_pick(x, y);
549        if name.is_empty() || self.datum_feature_for_name(&name).is_none() {
550            return;
551        }
552        self.ref_select_add_name(name);
553    }
554
555    /// Feed a picked NAME into the running list — what [`Self::ref_select_click`]
556    /// does after its pick (single fields replace; multiple fields append,
557    /// de-duplicated), for a caller that already holds the name (a test, an
558    /// automation driver). No-op while no selection is running.
559    pub fn ref_select_add_name(&mut self, name: String) {
560        let Some(state) = self.ref_select.as_mut() else {
561            return;
562        };
563        if state.multiple {
564            if !state.names.iter().any(|n| n == &name) {
565                state.names.push(name);
566            }
567        } else {
568            state.names = vec![name];
569        }
570        state.picks += 1;
571        self.sync_ref_select_emphasis();
572    }
573
574    /// Remove the name at `index` from the running list (the modal's per-line X).
575    pub fn ref_select_remove(&mut self, index: usize) {
576        if let Some(state) = self.ref_select.as_mut() {
577            if index < state.names.len() {
578                state.names.remove(index);
579            }
580        }
581        self.sync_ref_select_emphasis();
582    }
583
584    /// Finish: write the running names into the edited feature's params at the
585    /// field path, restore the rolled-to step, clear the highlight, and re-run so
586    /// the feature rebuilds with the chosen references.
587    pub fn finish_ref_select(&mut self) {
588        let Some(state) = self.ref_select.take() else {
589            return;
590        };
591        // An ASSEMBLY CONSTRAINT field commits through the constraint update
592        // lane (kernel session + document fold), not feature params; the shared
593        // end tail below still restores the roll + re-runs (which re-solves).
594        if state.target == RefSelectTarget::AssemblyConstraint {
595            self.assembly_commit_constraint_refs(
596                &state.feature_id,
597                &state.path,
598                &state.names,
599                state.multiple,
600            );
601            self.end_ref_select(state.restore_index);
602            return;
603        }
604        // A PMI annotation field commits into the document's pmi block (no
605        // history feature is involved); the shared tail restores + re-runs,
606        // which resolves the annotation against the fresh scene.
607        if state.target == RefSelectTarget::Pmi {
608            if let Some((_, annotation)) = self.pmi_state().find_annotation(&state.feature_id) {
609                if annotation.kind.contains('/') {
610                    let mut params = annotation.params.clone();
611                    let value = if state.multiple { serde_json::json!(state.names) }
612                        else { serde_json::json!(state.names.first().cloned().unwrap_or_default()) };
613                    set_json_at(&mut params, &state.path, value);
614                    // Clear picking state before the transaction captures selection/revision.
615                    // PMI never rolled the history; a second rerun would invalidate the worker reply.
616                    let _ = self.emphasis.apply_json("{}");
617                    self.selection_filter = SelectionFilter::default();
618                    if let Err(error) = self.plugin_update_annotation(&state.feature_id, params) {
619                        self.push_notice(format!("PMI update failed: {error}"));
620                    }
621                    self.dirty = true;
622                    return;
623                }
624            }
625            self.pmi_commit_refs(&state.feature_id, &state.path, &state.names, state.multiple);
626            self.end_ref_select(state.restore_index);
627            return;
628        }
629        // A CAM record's field commits into the `cam` block; nothing rolled
630        // and no run is needed, so the tail is the highlight and the filter
631        // going back to their defaults.
632        if state.target == RefSelectTarget::Cam {
633            let _ = self.emphasis.apply_json("{}");
634            self.selection_filter = SelectionFilter::default();
635            if let Err(error) = self.cam_commit_refs(&state.path, &state.names, state.multiple) {
636                self.push_notice(format!("CAM: {error}"));
637            }
638            self.dirty = true;
639            return;
640        }
641        // An INSTRUCTIONS step's occurrence field commits into the
642        // instructions block (one undo step through `instructions_edit`);
643        // nothing rolled and no run is needed, so the tail is the highlight
644        // and the filter going back to their defaults.
645        if let RefSelectTarget::Instructions { field } = state.target {
646            let _ = self.emphasis.apply_json("{}");
647            self.clear_ghost_lights();
648            self.selection_filter = SelectionFilter::default();
649            if let Some(solid) = state.names.first() {
650                if let Err(error) = self.instructions_commit_ref(&state.feature_id, field, solid) {
651                    self.push_notice(format!("Instructions: {error}"));
652                }
653            }
654            self.dirty = true;
655            return;
656        }
657        // A SHEET object's field commits into the `sheets` block, and a sheet
658        // edit never re-runs the history — so its tail is its own: no roll to
659        // restore, no rebuild, just the modal gone.
660        if state.target == RefSelectTarget::Sheet {
661            if let Err(error) =
662                self.sheet_commit_refs(&state.feature_id, &state.path, &state.names, state.multiple)
663            {
664                self.push_notice(format!("Sheets: {error}"));
665            }
666            self.dirty = true;
667            return;
668        }
669        // A CONNECTION POINT's reference commits into the `ports` block (no
670        // history feature is involved, and nothing was rolled). The shared
671        // tail re-runs, which is what re-seats the point on what was picked.
672        if let RefSelectTarget::PortPoint { field } = state.target {
673            self.ports_commit_ref(
674                &state.feature_id,
675                field,
676                state.names.first().map(String::as_str).unwrap_or_default(),
677            );
678            self.end_ref_select(state.restore_index);
679            return;
680        }
681        // A MOUNT helper's pick becomes numbers in the `mount` block (one undo
682        // step); nothing rolled, and the shared tail re-runs.
683        if let RefSelectTarget::Mount { pick } = state.target {
684            self.mount_commit_pick(pick, state.names.first().map(String::as_str));
685            self.end_ref_select(state.restore_index);
686            return;
687        }
688        // A SPLINE ANCHOR attachment commits through the anchor lane (the
689        // persistent spline document), then the shared tail restores + re-runs.
690        if let RefSelectTarget::SplineAnchor { index } = state.target {
691            if let Some(port) = state.names.first() {
692                self.attach_spline_anchor_no_rerun(&state.feature_id, index, port);
693            }
694            self.end_ref_select(state.restore_index);
695            return;
696        }
697        // A motion-study CLIP's parts commit into the `simulation` block
698        // through the study patch lane; nothing rolled and nothing re-runs,
699        // so the tail is the CAM one: highlight and filter back to default.
700        // A REPLACE REPAIR pick is handed to the replace dialog, which runs
701        // the repair (one undo step, nested assemblies included); nothing
702        // rolled, so the tail is the highlight and the filter going back.
703        if state.target == RefSelectTarget::ReplaceRepair {
704            let _ = self.emphasis.apply_json("{}");
705            self.selection_filter = SelectionFilter::default();
706            let old_ref = state.path.first().cloned().unwrap_or_default();
707            self.replace_repair_pick = state.names.into_iter().next().map(|pick| (state.feature_id, old_ref, pick));
708            self.dirty = true;
709            return;
710        }
711        // A vec3 field's POINT pick: the one pick becomes three numbers at the
712        // field's own path (the button's path without its suffix). A pick that
713        // does not resolve says why and leaves the stored value as it was.
714        if state.target == RefSelectTarget::PointPick {
715            let mut field_path = state.path.clone();
716            if let Some(last) = field_path.last_mut() {
717                if let Some(stem) = last.strip_suffix(super::POINT_PICK_SUFFIX) {
718                    *last = stem.to_string();
719                }
720            }
721            if let (Some(index), Some(name)) = (self.history.index_of(&state.feature_id), state.names.first()) {
722                match self.point_pick_value(index, name) {
723                    Ok(point) => {
724                        let mut params = self.history.feature_params(index).unwrap_or_else(|| serde_json::json!({}));
725                        set_json_at(&mut params, &field_path, serde_json::json!(point));
726                        self.stamp_face_transform_pivot(index, &mut params);
727                        self.history.set_feature_params(index, params);
728                    }
729                    Err(error) => self.push_notice(format!("{}: {error}", state.label)),
730                }
731            }
732            self.end_ref_select(state.restore_index);
733            return;
734        }
735        if state.target == RefSelectTarget::Simulation {
736            let _ = self.emphasis.apply_json("{}");
737            self.selection_filter = SelectionFilter::default();
738            if let Err(error) = self.simulation_commit_refs(&state.feature_id, &state.path, &state.names) {
739                self.push_notice(format!("Simulation: {error}"));
740            }
741            self.dirty = true;
742            return;
743        }
744        if let Some(index) = self.history.index_of(&state.feature_id) {
745            let mut params = self
746                .history
747                .feature_params(index)
748                .unwrap_or_else(|| serde_json::json!({}));
749            let value = if state.multiple {
750                serde_json::Value::Array(
751                    state
752                        .names
753                        .iter()
754                        .cloned()
755                        .map(serde_json::Value::String)
756                        .collect(),
757                )
758            } else {
759                serde_json::Value::String(state.names.first().cloned().unwrap_or_default())
760            };
761            set_json_at(&mut params, &state.path, value);
762            self.stamp_face_transform_pivot(index, &mut params);
763            self.history.set_feature_params(index, params);
764        }
765        self.end_ref_select(state.restore_index);
766    }
767
768    /// The ghosts a running instructions pick lights whole (`Self::sync_ref_select_emphasis`).
769    pub fn ref_select_ghosts_lit(&self) -> Vec<String> {
770        self.context_pick_lit.clone()
771    }
772
773    /// Put the ghosts' lights out (a pick ending).
774    fn clear_ghost_lights(&mut self) {
775        if !self.context_pick_lit.is_empty() {
776            self.context_pick_lit.clear();
777            self.sync_context_highlight();
778        }
779    }
780
781    /// Cancel: discard the running selection, clear the highlight, restore the
782    /// rolled-to step, and re-run (no param change).
783    pub fn cancel_ref_select(&mut self) {
784        if let Some(state) = self.ref_select.take() {
785            if state.target == RefSelectTarget::Sheet {
786                // Nothing rolled and nothing was highlighted: just close.
787                self.dirty = true;
788                return;
789            }
790            self.end_ref_select(state.restore_index);
791        }
792    }
793
794    /// Whether the active picker is picking ANCHORS on a drawing sheet — the
795    /// sheet viewport routes its clicks to [`Self::ref_select_pick_sheet_anchor`]
796    /// and the modal's hint speaks of the paper rather than the 3D view.
797    pub fn ref_select_is_sheet(&self) -> bool {
798        self.ref_select.as_ref().is_some_and(|state| state.target == RefSelectTarget::Sheet)
799    }
800
801    /// Whether the active pick belongs to a FORM FIELD — a feature's, an
802    /// assembly constraint's, a PMI annotation's or a sheet object's reference
803    /// row. Such a pick is drawn by the field itself, the way other CAD
804    /// applications keep the dialog up and the selection box focused: the
805    /// field lists the picks, its button ends them, and the rest of the UI
806    /// stays. The other targets (a connection point's seat, a spline anchor's
807    /// port) are opened from list rows that have no field, so they keep the
808    /// top-right card and the shell steps everything else aside for them —
809    /// [`Self::ref_select_modal`].
810    pub fn ref_select_in_form(&self) -> bool {
811        self.ref_select.as_ref().is_some_and(|state| {
812            matches!(
813                state.target,
814                RefSelectTarget::Feature
815                    | RefSelectTarget::AssemblyConstraint
816                    | RefSelectTarget::Pmi
817                    | RefSelectTarget::Sheet
818                    | RefSelectTarget::Cam
819                    | RefSelectTarget::Instructions { .. }
820                    | RefSelectTarget::Simulation
821                    | RefSelectTarget::ReplaceRepair
822                    | RefSelectTarget::PointPick
823            )
824        })
825    }
826
827    /// Whether a pick is up that takes the shell over (the dock folds away and
828    /// the top-right card is the picker): an active pick that is NOT a form
829    /// field's. The shell's "special mode" question.
830    pub fn ref_select_modal(&self) -> bool {
831        self.ref_select_active() && !self.ref_select_in_form()
832    }
833
834    /// The active pick as its form sees it — who it is for, which field, what
835    /// it holds — or `None` while no pick is up. A form draws the field whose
836    /// `subject` and `path` match as the FOCUSED one.
837    pub fn ref_select_field(&self) -> Option<RefSelectField> {
838        self.ref_select.as_ref().map(|state| RefSelectField {
839            subject: state.feature_id.clone(),
840            path: state.path.clone(),
841            multiple: state.multiple,
842            names: state.names.clone(),
843            picks: state.picks,
844            target: state.target,
845        })
846    }
847
848    /// The pick's form drew it this frame. Called by the form's consumer every
849    /// frame it draws the focused field; read back by the shell through
850    /// [`Self::ref_select_take_claim`].
851    pub fn ref_select_claim(&mut self) {
852        if let Some(state) = self.ref_select.as_mut() {
853            state.claimed = true;
854        }
855    }
856
857    /// Ask for the running pick to finish at the end of the frame (see
858    /// `RefSelectState::finish_requested`); the shell's settle step does it.
859    pub fn ref_select_request_finish(&mut self) {
860        if let Some(state) = self.ref_select.as_mut() {
861            state.finish_requested = true;
862        }
863    }
864
865    /// Whether [`Self::ref_select_request_finish`] was called on the running
866    /// pick.
867    pub fn ref_select_finish_requested(&self) -> bool {
868        self.ref_select.as_ref().is_some_and(|state| state.finish_requested)
869    }
870
871    /// Whether the pick was claimed since the last call — and reset, so each
872    /// frame answers for itself. `true` while no pick is up, so the shell's
873    /// "finish an unclaimed in-form pick" never fires on nothing.
874    pub fn ref_select_take_claim(&mut self) -> bool {
875        match self.ref_select.as_mut() {
876            Some(state) => std::mem::replace(&mut state.claimed, false),
877            None => true,
878        }
879    }
880
881    /// Restore the rolled-to step + clear emphasis + re-run + reset the selection
882    /// filter to the all-enabled default (shared Finish/Cancel tail).
883    ///
884    /// Resetting to the DEFAULT (not a saved "prior" filter) is deliberate: the
885    /// spec baseline out of ref-select is "all kinds enabled", and `begin_ref_select`
886    /// overwrites `ref_select` without routing through here, so a stashed prior
887    /// could be a stale already-constrained filter. Living in this shared tail also
888    /// means a stray `finish_ref_select()` while inactive (early return on `take`)
889    /// never clobbers the filter.
890    fn end_ref_select(&mut self, restore_index: usize) {
891        let _ = self.emphasis.apply_json("{}");
892        self.clear_ghost_lights();
893        // The rerun below marks the frame only when it lands, which on the
894        // background runner is later; the cleared highlight is shown now.
895        self.dirty = true;
896        self.selection_filter = SelectionFilter::default();
897        self.history.set_rollback(restore_index);
898        self.rerun_history();
899    }
900
901    /// Drive the selection highlight (`emphasis`) from the running name list so
902    /// picks light up in the viewport. A field may allow SEVERAL kinds at once
903    /// (e.g. `FACE`/`EDGE`), and a pick can be any of them, so every picked name is
904    /// fed to EVERY name-based bucket the filter permits — a name only ever matches
905    /// its own kind's entities (edge names carry the `|…[n]` topology form, faces do
906    /// not), so the cross-listing is harmless and each pick highlights correctly.
907    /// (The old code bucketed ALL names by `filter.first()` only, so an EDGE pick
908    /// under a `FACE`-first filter landed in `faces`, matched nothing, and never
909    /// showed.) VERTEX picks are position-keyed, not name-keyed, so they can't be
910    /// emphasized from a name list here.
911    pub(crate) fn sync_ref_select_emphasis(&mut self) {
912        // A sheet pick names paper anchors, not scene entities: the 3D
913        // highlight is not its to drive (the paper draws its own picks).
914        if self.ref_select_is_sheet() {
915            return;
916        }
917        let json = match &self.ref_select {
918            Some(state) => {
919                let names = serde_json::json!(state.names);
920                let mut selected = serde_json::Map::new();
921                for kind in &state.filter {
922                    // Case-INSENSITIVE match, mirroring `SelectionFilter::set` (which
923                    // pick-filtering uses via `from_ref_filter`). Without this, a
924                    // schema that spelled a kind non-canonically (e.g. `"Edge"`) would
925                    // let the user PICK that kind but silently skip its seed HIGHLIGHT
926                    // here — a lenient-pick / strict-highlight split. VERTEX is inert:
927                    // vertex picks carry no kernel name, so `ref_select_click` never
928                    // records one in `names` (empty-name early-return), so there is
929                    // nothing to highlight by name.
930                    let bucket = match kind.to_ascii_uppercase().as_str() {
931                        "FACE" => "faces",
932                        "EDGE" => "edges",
933                        "SOLID" => "solids",
934                        "PLANE" | "DATUM" => "datums",
935                        _ => continue, // VERTEX (never name-seeded) / unknown
936                    };
937                    selected.entry(bucket.to_string()).or_insert_with(|| names.clone());
938                }
939                // A COMPONENT pick names the component (`ACOMP3`): it lights
940                // through its member solids, as the selection's promotion does.
941                if state.filter.iter().any(|k| k.eq_ignore_ascii_case("COMPONENT")) {
942                    let mut solids: Vec<serde_json::Value> = selected
943                        .get("solids")
944                        .and_then(|v| v.as_array().cloned())
945                        .unwrap_or_default();
946                    for name in &state.names {
947                        for member in self.component_member_solids(name) {
948                            let member = serde_json::Value::String(member);
949                            if !solids.contains(&member) {
950                                solids.push(member);
951                            }
952                        }
953                    }
954                    if !solids.is_empty() {
955                        selected.insert("solids".to_string(), serde_json::Value::Array(solids));
956                    }
957                }
958                // No highlightable kind in the filter → fall back to solids (the
959                // prior default) so at least solid-name picks still light up.
960                if selected.is_empty() {
961                    selected.insert("solids".to_string(), names);
962                }
963                serde_json::json!({ "selected": selected }).to_string()
964            }
965            None => "{}".to_string(),
966        };
967        let _ = self.emphasis.apply_json(&json);
968        // An instructions pick's names can be GHOSTS (the parts earlier steps
969        // placed, drawn in the context layer with their solid hidden): those
970        // light through the context highlight, whole.
971        let ghosts: Vec<String> = match &self.ref_select {
972            Some(state) if matches!(state.target, RefSelectTarget::Instructions { .. }) => {
973                state.names.iter().filter(|name| self.context_scene.solid(name).is_some()).cloned().collect()
974            }
975            _ => Vec::new(),
976        };
977        if self.context_pick_lit != ghosts {
978            self.context_pick_lit = ghosts;
979            self.sync_context_highlight();
980        }
981        // A picked construction PLANE/DATUM highlights through the datum-plane
982        // WIDGET, whose accent is baked at feed time (`refresh_construction_datums`
983        // reads `emphasis.selected_datums`) — so a plain `apply_json` does not
984        // re-color it. Re-feed here so a datum pick lights up (and un-lights on
985        // remove) in the modal. Harmless for non-datum fields (no datum selected →
986        // an ordinary calm-color re-feed).
987        self.refresh_construction_datums();
988        self.dirty = true;
989    }
990}
991
992/// Write `value` into `root` at `path` (object-key chain), auto-vivifying
993/// intermediate objects — the engine-side twin of the form's nested setter, used
994/// to commit a reference field's picked names back into the feature params.
995pub(crate) fn set_json_at(root: &mut serde_json::Value, path: &[String], value: serde_json::Value) {
996    if path.is_empty() {
997        *root = value;
998        return;
999    }
1000    if !root.is_object() {
1001        *root = serde_json::Value::Object(serde_json::Map::new());
1002    }
1003    let mut cur = root;
1004    for seg in &path[..path.len() - 1] {
1005        let obj = cur.as_object_mut().expect("object by construction");
1006        cur = obj
1007            .entry(seg.clone())
1008            .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
1009        if !cur.is_object() {
1010            *cur = serde_json::Value::Object(serde_json::Map::new());
1011        }
1012    }
1013    cur.as_object_mut()
1014        .expect("object by construction")
1015        .insert(path[path.len() - 1].clone(), value);
1016}
1017
1018impl EngineState {
1019    /// The ONE candidate under CSS-pixel `(x, y)` that the hover highlight lights
1020    /// and a plain click takes: the filter-admitted candidate FIRST IN THE
1021    /// RAYCAST by depth, the shared kind order breaking ties inside the nearest
1022    /// depth layer (`front_layer_winner`).
1023    /// `None` on a miss, or when the filter admits nothing.
1024    ///
1025    /// Built from [`candidates_filtered_at`](Self::candidates_filtered_at), so
1026    /// what the pointer promises is drawn from exactly the set the PICK LIST
1027    /// offers — one selection rule over one list, never a second pick with its
1028    /// own admission rules. The list's own ordering is untouched.
1029    ///
1030    /// The layer band is the camera's world-per-pixel times the picker's
1031    /// [`EDGE_PICK_PX`](crate::pick::EDGE_PICK_PX): the same 6 px neighbourhood
1032    /// the picker already accepts *laterally* for an edge or a vertex, applied in
1033    /// depth. It is a screen-space quantity, so it tracks zoom and model scale
1034    /// without a unit of its own. (A face seen at a grazing angle changes depth
1035    /// faster than that across 6 px, so its bounding edge can fall outside the
1036    /// band and lose to the face — click nearer the edge, or dwell for the list.)
1037    ///
1038    /// COMPONENT promotion mirrors
1039    /// [`select_filtered_at`](Self::select_filtered_at): with the filter's
1040    /// COMPONENT lane on, a winner that is component geometry answers as its
1041    /// owning COMPONENT, so the highlight lights the same whole component the
1042    /// click would select.
1043    pub fn nearest_candidate_at(&self, x: f64, y: f64) -> Option<pick::PickCandidate> {
1044        let candidates = self.candidates_filtered_at(x, y);
1045        let band = self.camera.world_per_pixel() * crate::pick::EDGE_PICK_PX;
1046        let winner = super::plane_pick::front_layer_winner(&candidates, band)?;
1047        if self.selection_filter.component && winner.kind != pick::PickKind::Component {
1048            if let Some(owner) = self.hit_owning_component(winner) {
1049                // The COMPONENT row for that owner is already in the list (the
1050                // builder appends one per owning component), carrying its
1051                // nearest member hit — reuse it rather than synthesizing one.
1052                if let Some(entry) = candidates
1053                    .iter()
1054                    .find(|c| c.kind == pick::PickKind::Component && c.name == owner)
1055                {
1056                    return Some(entry.clone());
1057                }
1058            }
1059        }
1060        Some(winner.clone())
1061    }
1062
1063    /// Hover-highlight the candidate under CSS-pixel `(x, y)` that a plain click
1064    /// would take — the NEAREST admitted hit by depth
1065    /// ([`nearest_candidate_at`](Self::nearest_candidate_at)) — setting it
1066    /// HOVERED in `emphasis` (the renderer tints it). A miss — or a filter
1067    /// admitting nothing — clears the hover. No-ops (returns `false`, no dirty)
1068    /// when the hovered entity is unchanged, so a stationary pointer over the
1069    /// same face doesn't re-render every frame. Returns whether the hover state
1070    /// changed — the signal the viewport's dwell clock restarts on, so "how long
1071    /// has THIS highlight been showing" is answered without a second pick.
1072    ///
1073    /// The highlight is the promise the click keeps: both resolve through the one
1074    /// query above, so what lights up is what a plain click selects.
1075    pub fn hover_at(&mut self, x: f64, y: f64) -> bool {
1076        // A Work part's context face in front lights as context hover; for
1077        // the sketch pickEdges tool, the context edge it would copy.
1078        let context = if self.sketch_active_tool() == Some("pickEdges") {
1079            self.context_edge_at(x, y)
1080        } else {
1081            self.context_hit_at(x, y)
1082        };
1083        let context_changed = self.hover_context(context);
1084        let changed = match self.nearest_candidate_at(x, y) {
1085            Some(hit) => {
1086                if self.hover_is(&hit) {
1087                    false // unchanged — keep the frame clean.
1088                } else {
1089                    self.set_hover_to_candidate(&hit);
1090                    true
1091                }
1092            }
1093            None => self.clear_hover(),
1094        };
1095        changed || context_changed
1096    }
1097
1098    /// Whether ANY hover highlight is lit right now. The viewport's dwell clock
1099    /// runs only over a lit highlight (there is nothing to open a list about over
1100    /// empty space), and this is the cheap read of that.
1101    pub fn hover_is_lit(&self) -> bool {
1102        !self.emphasis.hovered_solids.is_empty()
1103            || !self.emphasis.hovered_faces.is_empty()
1104            || !self.emphasis.hovered_edges.is_empty()
1105            || !self.emphasis.hovered_vertices.is_empty()
1106            || !self.emphasis.hovered_datums.is_empty()
1107    }
1108
1109    /// Clear the hover highlight (pointer moved to empty space / off the
1110    /// viewport). Bumps the emphasis generation + marks dirty only when a hover
1111    /// was actually lit. Returns whether it changed. (Distinct from
1112    /// [`clear_selection`](Self::clear_selection), which leaves hover alone.)
1113    pub fn clear_hover(&mut self) -> bool {
1114        let had_datums = !self.emphasis.hovered_datums.is_empty();
1115        let had = !self.emphasis.hovered_solids.is_empty()
1116            || !self.emphasis.hovered_faces.is_empty()
1117            || !self.emphasis.hovered_edges.is_empty()
1118            || !self.emphasis.hovered_vertices.is_empty()
1119            || had_datums;
1120        if had {
1121            self.emphasis.hovered_solids.clear();
1122            self.emphasis.hovered_faces.clear();
1123            self.emphasis.hovered_edges.clear();
1124            self.emphasis.hovered_vertices.clear();
1125            self.emphasis.hovered_datums.clear();
1126            self.emphasis.generation = self.emphasis.generation.wrapping_add(1);
1127            self.dirty = true;
1128        }
1129        // A hovered plane's accent is baked into the datum feed, so dropping the
1130        // hover needs a re-feed to un-light it (the datum twin of the selection
1131        // re-feed in `clear_selection`).
1132        if had_datums {
1133            self.refresh_construction_datums();
1134        }
1135        had
1136    }
1137
1138    /// The current HOVER (not selection) as JSON
1139    /// `{ solids:[..], faces:[..], edges:[..], vertices: n }` — the hover twin of
1140    /// [`selection_json`](Self::selection_json) so a UI / the headed verifier can
1141    /// assert that moving the pointer over a face lit the hover emphasis.
1142    pub fn hovered_json(&self) -> String {
1143        let solids: Vec<&String> = self.emphasis.hovered_solids.iter().collect();
1144        let faces: Vec<&String> = self.emphasis.hovered_faces.iter().collect();
1145        let edges: Vec<&String> = self.emphasis.hovered_edges.iter().collect();
1146        let datums: Vec<&String> = self.emphasis.hovered_datums.iter().collect();
1147        serde_json::json!({
1148            "solids": solids,
1149            "faces": faces,
1150            "edges": edges,
1151            "datums": datums,
1152            "vertices": self.emphasis.hovered_vertices.len(),
1153        })
1154        .to_string()
1155    }
1156
1157    /// TOGGLE the admitted pick under CSS-pixel `(x, y)` — the NEAREST by depth,
1158    /// the one the hover highlight is showing — in the current
1159    /// selection (a **Ctrl/Cmd+click**): add it if absent, remove it if present,
1160    /// leaving the rest of the selection intact (unlike [`select_top_at`](Self::select_top_at), which
1161    /// REPLACES). With the COMPONENT filter on, a hit on component geometry
1162    /// toggles the whole component (all member solids as one unit). A miss — or
1163    /// a filter admitting nothing — leaves the selection untouched (additive
1164    /// mode never clears). Returns whether a hit was toggled.
1165    pub fn select_toggle_at(&mut self, x: f64, y: f64) -> bool {
1166        // The SAME hit the hover highlight is showing
1167        // ([`nearest_candidate_at`](Self::nearest_candidate_at)) — a modifier
1168        // changes whether the pick replaces or adds, never WHICH entity it is,
1169        // so the highlight stays the promise. Its COMPONENT promotion carries
1170        // the whole component through as one unit, which is what
1171        // [`toggle_candidate`](Self::toggle_candidate) toggles for a COMPONENT
1172        // row, and it answers `None` when the filter admits nothing.
1173        match self.nearest_candidate_at(x, y) {
1174            Some(hit) => {
1175                self.toggle_candidate(&hit);
1176                true
1177            }
1178            None => false,
1179        }
1180    }
1181
1182    /// The RANKED, filter-respecting candidates under CSS-pixel `(x, y)` as JSON
1183    /// `[{kind, name, solid, depth}]` — the "candidates under the cursor" list
1184    /// (feeds the pick-list popup + the headed verifier).
1185    ///
1186    /// Sorted category-major in the pick-list order (VERTEX > EDGE > FACE >
1187    /// PLANE > SOLID > COMPONENT), nearest (smallest depth) first within each
1188    /// category — see [`candidates_filtered_at`](Self::candidates_filtered_at).
1189    pub fn candidates_at(&self, x: f64, y: f64) -> String {
1190        let list = self.candidates_filtered_at(x, y);
1191        let out: Vec<serde_json::Value> = list
1192            .iter()
1193            .map(|c| {
1194                serde_json::json!({
1195                    "kind": self.candidate_kind_label(c),
1196                    "name": c.name,
1197                    "solid": c.solid,
1198                    "depth": c.depth,
1199                })
1200            })
1201            .collect();
1202        serde_json::Value::Array(out).to_string()
1203    }
1204
1205    /// What a REGULAR (non-dwelling) viewport click at CSS-pixel `(x, y)` takes,
1206    /// as one JSON `{kind, name, solid, depth}` — the same shape a row of
1207    /// [`candidates_at`](Self::candidates_at) carries — or `null` on a miss.
1208    ///
1209    /// The automation bridge reads this to answer "would a click here reach the
1210    /// entity I named": since the trigger moved, the top ROW of the list and what
1211    /// a plain click resolves to are no longer the same question, and a script
1212    /// that guesses wrong picks the wrong thing silently.
1213    pub fn nearest_candidate_json(&self, x: f64, y: f64) -> String {
1214        match self.nearest_candidate_at(x, y) {
1215            Some(c) => serde_json::json!({
1216                "kind": self.candidate_kind_label(&c),
1217                "name": c.name,
1218                "solid": c.solid,
1219                "depth": c.depth,
1220            })
1221            .to_string(),
1222            None => "null".to_string(),
1223        }
1224    }
1225
1226    /// One COMPONENT candidate per assembly component owning any of the `raw`
1227    /// hits (name = component id), carrying its NEAREST member hit's
1228    /// depth/position (raw hits are kind-major, so all are scanned). A PLANE
1229    /// hit owns no component. Shared by the pick list
1230    /// ([`candidates_filtered_at`](Self::candidates_filtered_at)) and a
1231    /// reference field that admits COMPONENT
1232    /// ([`ref_select_candidates_at`](Self::ref_select_candidates_at)).
1233    pub(super) fn component_candidates(&self, raw: &[pick::PickCandidate]) -> Vec<pick::PickCandidate> {
1234        let mut components: Vec<pick::PickCandidate> = Vec::new();
1235        for hit in raw {
1236            let Some(owner) = self.hit_owning_component(hit) else {
1237                continue;
1238            };
1239            match components.iter_mut().find(|c| c.name == owner) {
1240                Some(entry) => {
1241                    if hit.depth < entry.depth {
1242                        entry.depth = hit.depth;
1243                        entry.position = hit.position;
1244                    }
1245                }
1246                None => components.push(pick::PickCandidate {
1247                    kind: pick::PickKind::Component,
1248                    name: owner,
1249                    solid: String::new(),
1250                    depth: hit.depth,
1251                    screen_dist: hit.screen_dist,
1252                    position: hit.position,
1253                }),
1254            }
1255        }
1256        components
1257    }
1258
1259    /// The same ranked, filter-respecting candidate list as typed values (the
1260    /// in-process egui pick-list popup consumes these directly, then re-hovers /
1261    /// selects a chosen one via [`hover_candidate`](Self::hover_candidate) /
1262    /// [`select_candidate`](Self::select_candidate) /
1263    /// [`toggle_candidate`](Self::toggle_candidate)). EMPTY when the filter admits
1264    /// nothing (not the `pick_filtered` "empty filter = any" case).
1265    ///
1266    /// The raw list is [`pick_candidates_at`](Self::pick_candidates_at), so
1267    /// construction PLANE cards are ordinary entries here — a plane under other
1268    /// geometry is listed (right after the faces) instead of being reachable only
1269    /// on a geometry miss.
1270    ///
1271    /// With the filter's COMPONENT lane on, one COMPONENT entry per owning
1272    /// assembly component of ANY raw hit is appended (name = component id, depth
1273    /// = the component's nearest hit) — a raw hit of a filtered-OFF kind still
1274    /// reaches its owning component, mirroring `select_filtered_at`'s
1275    /// component-only promotion (a PLANE hit owns no component). The final list is
1276    /// sorted category-major in the pick-list order
1277    /// (VERTEX > EDGE > FACE > PLANE > SOLID > COMPONENT), nearest first within
1278    /// each category.
1279    pub fn candidates_filtered_at(&self, x: f64, y: f64) -> Vec<pick::PickCandidate> {
1280        let kinds = self.selection_filter.enabled_kinds();
1281        let component_on = self.selection_filter.component;
1282        if kinds.is_empty() && !component_on {
1283            return Vec::new();
1284        }
1285        let raw = self.pick_candidates_at(x, y);
1286        let mut out: Vec<pick::PickCandidate> = raw
1287            .iter()
1288            .filter(|c| self.candidate_admitted(&kinds, c))
1289            .cloned()
1290            .collect();
1291        if component_on {
1292            out.extend(self.component_candidates(&raw));
1293        }
1294        // Category-major (PickKind's discriminant order IS the pick-list order),
1295        // nearest first within a category — the shared ordering every pick path
1296        // uses, so the appended COMPONENT rows land in the same sort.
1297        super::plane_pick::sort_pick_candidates(&mut out);
1298        out
1299    }
1300
1301    /// Whether a candidate is CURRENTLY selected (drives the pick-list popup's
1302    /// per-row selected state so click-toggling reads back visually).
1303    pub fn candidate_is_selected(&self, candidate: &pick::PickCandidate) -> bool {
1304        use crate::pick::PickKind;
1305        match candidate.kind {
1306            PickKind::Solid => self
1307                .emphasis
1308                .selected_solids
1309                .contains(&self.candidate_solid_name(candidate)),
1310            PickKind::Face => self.emphasis.selected_faces.contains(&candidate.name),
1311            PickKind::Edge => self.emphasis.selected_edges.contains(&candidate.name),
1312            PickKind::Vertex => self
1313                .emphasis
1314                .selected_vertices
1315                .iter()
1316                .any(|v| Self::vertex_ref_matches(v, candidate)),
1317            PickKind::Plane => self.emphasis.selected_datums.contains(&candidate.name),
1318            PickKind::Component => {
1319                let members = self.component_member_solids(&candidate.name);
1320                !members.is_empty()
1321                    && members
1322                        .iter()
1323                        .all(|m| self.emphasis.selected_solids.contains(m))
1324            }
1325        }
1326    }
1327
1328    /// Hover a SPECIFIC candidate (the popup entry the pointer is over) — sets it
1329    /// HOVERED in `emphasis`, replacing any prior hover.
1330    pub fn hover_candidate(&mut self, candidate: &pick::PickCandidate) {
1331        self.set_hover_to_candidate(candidate);
1332    }
1333
1334    /// REPLACE the selection with a specific candidate (a plain click on a popup
1335    /// entry) — reuses the same bucketing as a plain viewport click.
1336    pub fn select_candidate(&mut self, candidate: &pick::PickCandidate) {
1337        self.set_selection_to_candidate(candidate);
1338    }
1339
1340    /// TOGGLE a specific candidate in the selection (a Ctrl/Cmd+click on a popup
1341    /// entry, or the [`select_toggle_at`](Self::select_toggle_at) hit): add if
1342    /// absent, remove if present. Returns whether it is NOW selected (`true` =
1343    /// added, `false` = removed). Bumps the emphasis generation + marks dirty.
1344    pub fn toggle_candidate(&mut self, candidate: &pick::PickCandidate) -> bool {
1345        use crate::pick::PickKind;
1346        let now_selected = match candidate.kind {
1347            PickKind::Solid => {
1348                let name = self.candidate_solid_name(candidate);
1349                if self.emphasis.selected_solids.remove(&name) {
1350                    false
1351                } else {
1352                    self.emphasis.selected_solids.insert(name);
1353                    true
1354                }
1355            }
1356            PickKind::Face => {
1357                if self.emphasis.selected_faces.remove(&candidate.name) {
1358                    false
1359                } else {
1360                    self.emphasis.selected_faces.insert(candidate.name.clone());
1361                    true
1362                }
1363            }
1364            PickKind::Edge => {
1365                if self.emphasis.selected_edges.remove(&candidate.name) {
1366                    false
1367                } else {
1368                    self.emphasis.selected_edges.insert(candidate.name.clone());
1369                    true
1370                }
1371            }
1372            PickKind::Vertex => {
1373                if let Some(index) = self
1374                    .emphasis
1375                    .selected_vertices
1376                    .iter()
1377                    .position(|v| Self::vertex_ref_matches(v, candidate))
1378                {
1379                    self.emphasis.selected_vertices.remove(index);
1380                    false
1381                } else {
1382                    self.emphasis.selected_vertices.push(crate::style::VertexRef {
1383                        solid: candidate.solid.clone(),
1384                        position: candidate.position,
1385                    });
1386                    true
1387                }
1388            }
1389            PickKind::Plane => {
1390                // A construction PLANE toggles by FRAME NAME, the datum bucket the
1391                // Scene-tree row / `select_datum` fill.
1392                if self.emphasis.selected_datums.remove(&candidate.name) {
1393                    false
1394                } else {
1395                    self.emphasis.selected_datums.insert(candidate.name.clone());
1396                    true
1397                }
1398            }
1399            PickKind::Component => {
1400                // The whole component toggles as ONE unit (member solids), the
1401                // same rule as the Ctrl/Cmd+click COMPONENT promotion.
1402                let was_selected = self.candidate_is_selected(candidate);
1403                self.toggle_component_selection(&candidate.name);
1404                !was_selected
1405            }
1406        };
1407        self.emphasis.generation = self.emphasis.generation.wrapping_add(1);
1408        self.dirty = true;
1409        // A plane's accent is baked into the datum feed, so a toggled plane only
1410        // lights / un-lights after a re-feed.
1411        if candidate.kind == PickKind::Plane {
1412            self.refresh_construction_datums();
1413        }
1414        now_selected
1415    }
1416
1417    /// Set the hover emphasis to exactly one candidate (bucketed by kind), the
1418    /// hover twin of `set_selection_to_candidate`.
1419    fn set_hover_to_candidate(&mut self, candidate: &pick::PickCandidate) {
1420        use crate::pick::PickKind;
1421        // A hovered PLANE's accent lives in the datum FEED, so the re-feed below
1422        // is needed both when a plane becomes hovered and when one stops being.
1423        let touches_datums =
1424            !self.emphasis.hovered_datums.is_empty() || candidate.kind == PickKind::Plane;
1425        self.emphasis.hovered_solids.clear();
1426        self.emphasis.hovered_faces.clear();
1427        self.emphasis.hovered_edges.clear();
1428        self.emphasis.hovered_vertices.clear();
1429        self.emphasis.hovered_datums.clear();
1430        match candidate.kind {
1431            PickKind::Solid => {
1432                self.emphasis
1433                    .hovered_solids
1434                    .insert(self.candidate_solid_name(candidate));
1435            }
1436            PickKind::Face => {
1437                self.emphasis.hovered_faces.insert(candidate.name.clone());
1438            }
1439            PickKind::Edge => {
1440                self.emphasis.hovered_edges.insert(candidate.name.clone());
1441            }
1442            PickKind::Vertex => {
1443                self.emphasis.hovered_vertices.push(crate::style::VertexRef {
1444                    solid: candidate.solid.clone(),
1445                    position: candidate.position,
1446                });
1447            }
1448            PickKind::Plane => {
1449                self.emphasis.hovered_datums.insert(candidate.name.clone());
1450            }
1451            PickKind::Component => {
1452                // Hovering a COMPONENT entry lights every member solid.
1453                for member in self.component_member_solids(&candidate.name) {
1454                    self.emphasis.hovered_solids.insert(member);
1455                }
1456            }
1457        }
1458        self.emphasis.generation = self.emphasis.generation.wrapping_add(1);
1459        self.dirty = true;
1460        if touches_datums {
1461            self.refresh_construction_datums();
1462        }
1463    }
1464
1465    /// Whether the CURRENT hover is exactly this one candidate (the `hover_at`
1466    /// early-out) — a single hovered entity that matches `candidate` (for a
1467    /// COMPONENT candidate: exactly its member-solid set). `pub(super)` so the
1468    /// Scene-tree row hover (`scene_query.rs`) shares the same identity test for
1469    /// its dedupe + its "only clear what the tree lit" rule.
1470    pub(super) fn hover_is(&self, candidate: &pick::PickCandidate) -> bool {
1471        use crate::pick::PickKind;
1472        if candidate.kind == PickKind::Component {
1473            let members = self.component_member_solids(&candidate.name);
1474            return !members.is_empty()
1475                && self.emphasis.hovered_faces.is_empty()
1476                && self.emphasis.hovered_edges.is_empty()
1477                && self.emphasis.hovered_vertices.is_empty()
1478                && self.emphasis.hovered_datums.is_empty()
1479                && self.emphasis.hovered_solids.len() == members.len()
1480                && members.iter().all(|m| self.emphasis.hovered_solids.contains(m));
1481        }
1482        let total = self.emphasis.hovered_solids.len()
1483            + self.emphasis.hovered_faces.len()
1484            + self.emphasis.hovered_edges.len()
1485            + self.emphasis.hovered_vertices.len()
1486            + self.emphasis.hovered_datums.len();
1487        if total != 1 {
1488            return false;
1489        }
1490        match candidate.kind {
1491            PickKind::Solid => self
1492                .emphasis
1493                .hovered_solids
1494                .contains(&self.candidate_solid_name(candidate)),
1495            PickKind::Face => self.emphasis.hovered_faces.contains(&candidate.name),
1496            PickKind::Edge => self.emphasis.hovered_edges.contains(&candidate.name),
1497            PickKind::Vertex => self
1498                .emphasis
1499                .hovered_vertices
1500                .iter()
1501                .any(|v| Self::vertex_ref_matches(v, candidate)),
1502            PickKind::Plane => self.emphasis.hovered_datums.contains(&candidate.name),
1503            PickKind::Component => false, // handled by the early return above
1504        }
1505    }
1506
1507    /// The scene name a SOLID candidate resolves to (its owning `solid`, falling
1508    /// back to `name` when the pick didn't carry one) — the same rule
1509    /// `set_selection_to_candidate` uses.
1510    fn candidate_solid_name(&self, candidate: &pick::PickCandidate) -> String {
1511        if candidate.solid.is_empty() {
1512            candidate.name.clone()
1513        } else {
1514            candidate.solid.clone()
1515        }
1516    }
1517
1518    /// Vertex identity: same owning solid + position within the emphasis match
1519    /// tolerance (vertices carry no kernel name, so they resolve by solid+pos).
1520    fn vertex_ref_matches(v: &crate::style::VertexRef, candidate: &pick::PickCandidate) -> bool {
1521        const TOL: f64 = 1e-4;
1522        v.solid == candidate.solid
1523            && (v.position[0] - candidate.position[0]).abs() <= TOL
1524            && (v.position[1] - candidate.position[1]).abs() <= TOL
1525            && (v.position[2] - candidate.position[2]).abs() <= TOL
1526    }
1527}
1528
1529// ---------------------------------------------------------------------------
1530// Sketch display (S0) — read-only overlay of a solved SketchSession.
1531//
1532// Additive, self-contained: a solved sketch is fed to the general `set_overlay`
1533// channel as the named groups `sketch-geometry` (lines) and `sketch-points`
1534// (billboarded points), colored by solver mobility. No interaction (the tools /
1535// picking / dimensions of later slices live elsewhere); this block only pushes /
1536// clears the display geometry.
1537// ---------------------------------------------------------------------------
1538impl EngineState {
1539    /// Display a solved [`crate::sketch::SketchSession`] as a read-only overlay.
1540    /// The plane geometry is tessellated to world space and pushed via
1541    /// [`set_overlay_json`](Self::set_overlay_json); construction dashes are sized
1542    /// against the LIVE camera so they stay screen-constant.
1543    pub fn set_sketch_overlay(&mut self, session: &crate::sketch::SketchSession) {
1544        let world_per_pixel = self.camera.world_per_pixel();
1545        let json = session.overlay_json(world_per_pixel);
1546        // The overlay channel accepts our exact `{groups:[…]}` shape; a parse
1547        // failure would be a programming error in the tessellator, so drop it.
1548        let _ = self.set_overlay_json(&json);
1549        // The dimension leaders ride in their own `sketch-dim-leaders` group (S5).
1550        let _ = self.set_overlay_json(&session.dim_leaders_overlay_json(world_per_pixel));
1551        // The geometric-constraint glyphs ride in `sketch-constraint-glyphs` (S6c).
1552        let _ = self.set_overlay_json(&session.constraint_glyphs_overlay_json(world_per_pixel));
1553        // The zoom this screen-constant sizing was baked at, so the per-frame
1554        // `ensure_sketch_overlay_current` re-bakes it when the camera zooms.
1555        self.sketch_overlay_wpp = if world_per_pixel > 0.0 {
1556            world_per_pixel
1557        } else {
1558            f64::MIN_POSITIVE
1559        };
1560    }
1561
1562    /// Remove the sketch overlay groups (feeding empty same-named groups upserts
1563    /// them to empty, which the overlay channel treats as a removal — other
1564    /// overlay groups are left untouched).
1565    pub fn clear_sketch_overlay(&mut self) {
1566        let _ = self.set_overlay_json(
1567            "{\"groups\":[{\"name\":\"sketch-geometry\"},{\"name\":\"sketch-points\"},{\"name\":\"sketch-preview\"},{\"name\":\"sketch-dim-leaders\"},{\"name\":\"sketch-constraint-glyphs\"}]}",
1568        );
1569        self.sketch_overlay_wpp = 0.0;
1570    }
1571}
1572