Skip to main content

brep_render/engine_state/
box_select.rs

1//! BOX selection in the 3D view (Shift+left-drag): [`crate::box_pick`]'s
2//! visible entities, through the bottom selection filter, into the selection.
3
4use super::*;
5use crate::box_pick::{box_pick, ScreenBox};
6
7/// What a box drag does to the selection.
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum BoxSelectMode {
10    /// Shift+drag: the box's entities become the selection.
11    Replace,
12    /// Primary+Shift+drag: they are added.
13    Add,
14    /// Alt/Option+Shift+drag: they are removed.
15    Remove,
16}
17
18impl EngineState {
19    /// The candidates a box from `start` to `end` (viewport CSS px) takes —
20    /// all of ONE kind, the coarsest it caught among those the filter admits
21    /// (component > solid > face > edge > vertex) — WINDOW (left to right, fully inside) or CROSSING
22    /// (right to left, touching), visible entities only. With the filter's
23    /// COMPONENT lane on, an entity of an assembly component is taken as its
24    /// component (window: every member solid inside).
25    pub fn box_candidates(&self, start: (f64, f64), end: (f64, f64)) -> Vec<pick::PickCandidate> {
26        let rect = ScreenBox::from_drag(start, end);
27        let kinds = self.selection_filter.enabled_kinds();
28        let component_on = self.selection_filter.component;
29        if kinds.is_empty() && !component_on {
30            return Vec::new();
31        }
32        let raw = box_pick(&self.scene, &self.camera, rect, &self.pick_options());
33        let mut out: Vec<pick::PickCandidate> = Vec::new();
34        for candidate in &raw {
35            if component_on && self.hit_owning_component(candidate).is_some() {
36                continue;
37            }
38            if self.candidate_admitted(&kinds, candidate) {
39                out.push(candidate.clone());
40            }
41        }
42        if component_on {
43            let components = if rect.crossing() {
44                self.component_candidates(&raw)
45            } else {
46                let taken: std::collections::HashSet<&str> = raw
47                    .iter()
48                    .filter(|c| c.kind == pick::PickKind::Solid)
49                    .map(|c| c.name.as_str())
50                    .collect();
51                self.component_candidates(&raw)
52                    .into_iter()
53                    .filter(|component| {
54                        let members = self.component_member_solids(&component.name);
55                        !members.is_empty() && members.iter().all(|m| taken.contains(m.as_str()))
56                    })
57                    .collect()
58            };
59            out.extend(components);
60        }
61        // ONE KIND per box (master/owner 2026-11-27): with several kinds
62        // admitted, only the COARSEST the box caught — the Ctrl/Cmd+A rule —
63        // so a crossing over a cube is the solid, not the solid with its
64        // faces, edges and vertices. A held letter or a narrowed bottom
65        // filter picks a finer kind.
66        match SELECT_ALL_ORDER.iter().copied().find(|k| out.iter().any(|c| c.kind == *k)) {
67            Some(kind) => out.into_iter().filter(|c| c.kind == kind).collect(),
68            None => out,
69        }
70    }
71
72    /// Apply a box drag to the selection (see [`BoxSelectMode`]). Returns how
73    /// many entities the box took.
74    pub fn box_select(&mut self, start: (f64, f64), end: (f64, f64), mode: BoxSelectMode) -> usize {
75        let candidates = self.box_candidates(start, end);
76        // Say what it took (as select-all does). Nothing caught says nothing.
77        if let Some(first) = candidates.first() {
78            let verb = if mode == BoxSelectMode::Remove { "Removed" } else { "Selected" };
79            let what = kind_count_phrase(first.kind, candidates.len());
80            self.push_notice_as(NoticeSeverity::Info, format!("{verb} {what}"));
81        }
82        if mode == BoxSelectMode::Replace {
83            self.clear_selection();
84        }
85        for candidate in &candidates {
86            let selected = self.candidate_is_selected(candidate);
87            let wanted = mode != BoxSelectMode::Remove;
88            if selected != wanted {
89                self.toggle_candidate(candidate);
90            }
91        }
92        self.dirty = true;
93        candidates.len()
94    }
95}
96
97/// The kind select-all / invert act on: the coarsest kind the filter admits
98/// that has a visible entity, COMPONENT > SOLID > FACE > EDGE > VERTEX.
99const SELECT_ALL_ORDER: [pick::PickKind; 5] = [
100    pick::PickKind::Component,
101    pick::PickKind::Solid,
102    pick::PickKind::Face,
103    pick::PickKind::Edge,
104    pick::PickKind::Vertex,
105];
106
107impl EngineState {
108    /// Every VISIBLE entity of the current filter type (primary+A): the
109    /// coarsest kind the selection filter — or a held letter — admits that
110    /// has anything on screen (components, else solids, faces, edges,
111    /// vertices). `invert` (primary+I) flips the selection within that kind
112    /// instead: the visible ones not selected become selected and the
113    /// selected ones are dropped. Replaces the selection of every other kind
114    /// either way. Returns how many entities are selected of that kind after.
115    pub fn select_all_visible(&mut self, invert: bool) -> usize {
116        let (w, h) = (self.camera.width, self.camera.height);
117        let all = self.box_candidates((w, 0.0), (0.0, h));
118        let Some(kind) = SELECT_ALL_ORDER.iter().copied().find(|k| all.iter().any(|c| c.kind == *k)) else {
119            if !invert {
120                self.clear_selection();
121            }
122            return 0;
123        };
124        let of_kind: Vec<pick::PickCandidate> = all.into_iter().filter(|c| c.kind == kind).collect();
125        let selected: Vec<bool> = of_kind.iter().map(|c| self.candidate_is_selected(c)).collect();
126        self.clear_selection();
127        let mut count = 0;
128        for (candidate, was) in of_kind.iter().zip(selected) {
129            if !invert || !was {
130                if !self.candidate_is_selected(candidate) {
131                    self.toggle_candidate(candidate);
132                }
133                count += 1;
134            }
135        }
136        self.dirty = true;
137        // Say what it took (master 2026-11-26): the status readout.
138        self.push_notice_as(NoticeSeverity::Info, format!("Selected {}", kind_count_phrase(kind, count)));
139        count
140    }
141}
142
143impl EngineState {
144    /// Primary+A while a MULTIPLE reference field is picking: every visible
145    /// entity of the coarsest kind the field admits goes into its running
146    /// list (de-duplicated, named as a click would name it). Returns how many
147    /// it offered; 0 for a single field or none picking.
148    pub fn ref_select_all_visible(&mut self) -> usize {
149        if !self.ref_select.as_ref().is_some_and(|state| state.multiple) {
150            return 0;
151        }
152        let (w, h) = (self.camera.width, self.camera.height);
153        let all = self.box_candidates((w, 0.0), (0.0, h));
154        let Some(kind) = SELECT_ALL_ORDER.iter().copied().find(|k| all.iter().any(|c| c.kind == *k)) else {
155            return 0;
156        };
157        let of_kind: Vec<pick::PickCandidate> = all.into_iter().filter(|c| c.kind == kind).collect();
158        for candidate in &of_kind {
159            self.ref_select_take_candidate(candidate);
160        }
161        self.dirty = true;
162        of_kind.len()
163    }
164}
165
166impl EngineState {
167    /// The LIVE box preview (owner 2026-11-26): while a box is dragged the
168    /// pointer's own hover highlight is off and the hover emphasis lights
169    /// exactly what releasing the box here would take — the same
170    /// [`Self::box_candidates`] the release applies. Returns how many.
171    pub fn hover_box_preview(&mut self, start: (f64, f64), end: (f64, f64)) -> usize {
172        use crate::pick::PickKind;
173        let candidates = self.box_candidates(start, end);
174        let had_datums = !self.emphasis.hovered_datums.is_empty();
175        self.emphasis.hovered_solids.clear();
176        self.emphasis.hovered_faces.clear();
177        self.emphasis.hovered_edges.clear();
178        self.emphasis.hovered_vertices.clear();
179        self.emphasis.hovered_datums.clear();
180        for candidate in &candidates {
181            match candidate.kind {
182                PickKind::Solid => {
183                    self.emphasis.hovered_solids.insert(self.candidate_solid_name(candidate));
184                }
185                PickKind::Face => {
186                    self.emphasis.hovered_faces.insert(candidate.name.clone());
187                }
188                PickKind::Edge => {
189                    self.emphasis.hovered_edges.insert(candidate.name.clone());
190                }
191                PickKind::Vertex => self.emphasis.hovered_vertices.push(crate::style::VertexRef {
192                    solid: candidate.solid.clone(),
193                    position: candidate.position,
194                }),
195                PickKind::Plane => {
196                    self.emphasis.hovered_datums.insert(candidate.name.clone());
197                }
198                PickKind::Component => {
199                    for member in self.component_member_solids(&candidate.name) {
200                        self.emphasis.hovered_solids.insert(member);
201                    }
202                }
203            }
204        }
205        self.emphasis.generation = self.emphasis.generation.wrapping_add(1);
206        self.dirty = true;
207        if had_datums {
208            self.refresh_construction_datums();
209        }
210        candidates.len()
211    }
212}
213
214/// "1 solid", "3 faces", "8 vertices": the count of one pick kind in words.
215pub(crate) fn kind_count_phrase(kind: pick::PickKind, count: usize) -> String {
216    let (one, many) = match kind {
217        pick::PickKind::Component => ("component", "components"),
218        pick::PickKind::Solid => ("solid", "solids"),
219        pick::PickKind::Face => ("face", "faces"),
220        pick::PickKind::Edge => ("edge", "edges"),
221        pick::PickKind::Vertex => ("vertex", "vertices"),
222        pick::PickKind::Plane => ("plane", "planes"),
223    };
224    format!("{count} {}", if count == 1 { one } else { many })
225}
226