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