Skip to main content

brep_app/panels/
interference.rs

1//! Interference results window — the floating
2//! window behind the Assembly workbench's `∩` toolbar button.
3//!
4//! Follows the pinned Info-window idiom: a movable + resizable
5//! [`egui::Window`] drawn at ctx level, owning its own state (the last
6//! [`InterferenceReport`]). The check itself lives in the ENGINE
7//! ([`EngineState::interference_check`] — main-side, non-destructive,
8//! bbox-prefiltered); this panel only renders the report:
9//!
10//! * a Clearance field (mm, 0 = off): the near-miss threshold for the run;
11//! * a row per INTERFERING pair — `ACOMP1 × ACOMP3 — 12.4 mm³` — clicking it
12//!   selects/highlights BOTH components (emphasis over their member solids)
13//!   and frames them; a hidden participant is noted on its row (it still
14//!   participated — interference is a physical question);
15//! * a row per NEAR MISS — `ACOMP1 × ACOMP2 — 1.5 mm gap` — same click;
16//! * the interference volumes (red) and near-miss gaps (amber) drawn in the
17//!   viewport while the window is open and the report is current;
18//! * a green all-clear line when nothing interferes (a PASS state, shown
19//!   positively);
20//! * explicit `unverified` (boolean refused) and `skipped` (budget / no
21//!   geometry) sections — nothing is ever dropped silently;
22//! * a Re-run button.
23//!
24//! Colors come from the ONE assembly status map
25//! ([`brep_render::assembly_status`]) and volumes from the ONE measurement
26//! formatter (`super::info_windows::num`) — no re-rolled styling.
27
28use crate::ui_kit;
29use crate::automation::hit_keys::HitKeyDoc;
30use brep_render::assembly_status;
31use brep_render::engine_state::{ClearancePair, EngineState, InterferencePair, InterferenceReport};
32use eframe::egui;
33use serde_json::Value;
34use std::collections::HashMap;
35
36/// The row/line label of one interfering pair: `A × B — 12.4 mm³`, with a
37/// `(hidden: …)` note when a participant is currently invisible.
38fn pair_label(pair: &InterferencePair) -> String {
39    let mut label = format!(
40        "{} \u{00d7} {} \u{2014} {} mm\u{00b3}",
41        pair.a,
42        pair.b,
43        super::info_windows::num(pair.volume)
44    );
45    let hidden: Vec<&str> = [
46        pair.a_hidden.then_some(pair.a.as_str()),
47        pair.b_hidden.then_some(pair.b.as_str()),
48    ]
49    .into_iter()
50    .flatten()
51    .collect();
52    if !hidden.is_empty() {
53        label.push_str(&format!(" (hidden: {})", hidden.join(", ")));
54    }
55    label
56}
57
58/// The near-miss row label: `A × B — 1.5 mm gap`, plus the hidden note.
59fn near_label(pair: &ClearancePair) -> String {
60    let mut label = format!(
61        "{} \u{00d7} {} \u{2014} {} mm gap",
62        pair.a,
63        pair.b,
64        super::info_windows::num(pair.distance)
65    );
66    let hidden: Vec<&str> = [
67        pair.a_hidden.then_some(pair.a.as_str()),
68        pair.b_hidden.then_some(pair.b.as_str()),
69    ]
70    .into_iter()
71    .flatten()
72    .collect();
73    if !hidden.is_empty() {
74        label.push_str(&format!(" (hidden: {})", hidden.join(", ")));
75    }
76    label
77}
78
79/// An [`egui::Color32`] off the shared status palette.
80fn status_color(status: &str) -> egui::Color32 {
81    let [r, g, b] = assembly_status::status_color_rgb(status);
82    egui::Color32::from_rgb(r, g, b)
83}
84
85/// The shell-owned interference results window. Opened (and run) by the
86/// Assembly workbench's toolbar button; re-run from its own button. Owns the
87/// last report — the engine holds no window state.
88#[derive(Default)]
89pub struct InterferenceWindow {
90    open: bool,
91    report: Option<InterferenceReport>,
92    /// The near-miss threshold (mm) the next run uses; 0 = off.
93    clearance: f64,
94    /// The model moved since the report was taken: its overlay is cleared
95    /// and the window asks for a re-run.
96    stale: bool,
97    /// Per-frame interactive-widget screen rects for the headed verifier.
98    hits: HashMap<String, egui::Rect>,
99}
100
101impl InterferenceWindow {
102    pub fn new() -> Self {
103        Self::default()
104    }
105
106    /// The toolbar entry point: run the check NOW and show the window.
107    pub fn open_and_run(&mut self, state: &mut EngineState) {
108        self.run(state);
109        self.open = true;
110    }
111
112    /// Run the check at the window's clearance (draws the overlay).
113    fn run(&mut self, state: &mut EngineState) {
114        self.report = Some(state.interference_check_with(self.clearance));
115        self.stale = false;
116    }
117
118    /// Select both participants of a result row and frame them.
119    fn focus_pair(state: &mut EngineState, a: &str, b: &str) {
120        let ids = [a.to_string(), b.to_string()];
121        state.select_components(&ids);
122        state.zoom_to_components(&ids);
123    }
124
125    /// Draw the window (if open) at ctx level, like the Info windows.
126    pub fn show(&mut self, ctx: &egui::Context, state: &mut EngineState) {
127        self.hits.clear();
128        if !self.open {
129            return;
130        }
131        // A rebuild since the run: the drawn volumes no longer match the
132        // model — take them down and ask for a re-run.
133        if !self.stale
134            && self
135                .report
136                .as_ref()
137                .is_some_and(|report| report.generation != state.applied_generation())
138        {
139            self.stale = true;
140            state.clear_interference_overlay();
141        }
142        let mut open = true;
143        egui::Window::new("Interference")
144            .id(egui::Id::new("brep-interference-window"))
145            .open(&mut open)
146            .movable(true)
147            .resizable(true)
148            .default_size([360.0, 320.0])
149            .default_pos(super::below_chrome(ctx, 860.0, 0.0))
150            .show(ctx, |ui| {
151                egui::ScrollArea::vertical()
152                    .auto_shrink([false, false])
153                    .show(ui, |ui| self.body(ui, state));
154            });
155        if !open {
156            self.close(state);
157        }
158    }
159
160    /// Shut the window and take its overlay down (the title-bar ✕).
161    pub fn close(&mut self, state: &mut EngineState) {
162        self.open = false;
163        state.clear_interference_overlay();
164    }
165
166    fn body(&mut self, ui: &mut egui::Ui, state: &mut EngineState) {
167        // Header: the summary + Re-run.
168        ui.horizontal(|ui| {
169            let rerun = ui.add(ui_kit::Button::new("Re-run"));
170            self.hits.insert("interference:rerun".into(), rerun.rect);
171            if rerun.clicked() {
172                self.run(state);
173            }
174            ui.label("Clearance");
175            let clearance = ui.add(
176                egui::DragValue::new(&mut self.clearance)
177                    .range(0.0..=1.0e4)
178                    .speed(0.1)
179                    .suffix(" mm"),
180            );
181            self.hits.insert("interference:clearance".into(), clearance.rect);
182            if let Some(report) = &self.report {
183                ui.weak(format!(
184                    "{} components \u{00b7} {} pairs \u{00b7} {} boolean{}",
185                    report.component_count,
186                    report.pair_total,
187                    report.booleans_run,
188                    if report.booleans_run == 1 { "" } else { "s" }
189                ));
190            }
191        });
192        ui.separator();
193
194        let Some(report) = self.report.clone() else {
195            ui.weak("Run the check from the toolbar.");
196            return;
197        };
198        if report.component_count < 2 {
199            ui.weak("Needs at least two components.");
200            return;
201        }
202        if self.stale {
203            ui.colored_label(
204                status_color("unsupported-selection"),
205                "The model changed \u{2014} Re-run to refresh.",
206            );
207        }
208
209        if report.pairs.is_empty() {
210            // The PASS state, shown positively (green — the shared palette's
211            // `satisfied`). Refusals/skips below still temper it.
212            ui.colored_label(
213                status_color("satisfied"),
214                format!(
215                    "\u{2713} No interference \u{2014} {} pair{} checked",
216                    report.pair_total,
217                    if report.pair_total == 1 { "" } else { "s" }
218                ),
219            );
220        } else {
221            for pair in &report.pairs {
222                // A clickable row: selecting it highlights BOTH participants
223                // (emphasis over the union of their member solids).
224                let row = ui.selectable_label(
225                    false,
226                    crate::theme::data(pair_label(pair)).color(status_color("error")),
227                );
228                self.hits
229                    .insert(format!("interference:pair:{}x{}", pair.a, pair.b), row.rect);
230                if row.clicked() {
231                    Self::focus_pair(state, &pair.a, &pair.b);
232                }
233            }
234        }
235
236        // Near misses (a clearance was set): amber rows, smallest gap first.
237        if report.clearance > 0.0 {
238            ui.add_space(4.0);
239            if report.near_misses.is_empty() {
240                ui.weak(format!(
241                    "No gaps under {} mm",
242                    super::info_windows::num(report.clearance)
243                ));
244            } else {
245                ui.label(format!(
246                    "Clearance under {} mm (gap measured on the display mesh):",
247                    super::info_windows::num(report.clearance)
248                ));
249            }
250            for pair in &report.near_misses {
251                let row = ui.selectable_label(
252                    false,
253                    crate::theme::data(near_label(pair))
254                        .color(status_color("unsupported-selection")),
255                );
256                self.hits
257                    .insert(format!("interference:near:{}x{}", pair.a, pair.b), row.rect);
258                if row.clicked() {
259                    Self::focus_pair(state, &pair.a, &pair.b);
260                }
261            }
262        }
263
264        // Never-silent sections: boolean refusals and skipped work.
265        if !report.unverified.is_empty() {
266            ui.add_space(4.0);
267            ui.label("Not verified (boolean refused):");
268            for line in &report.unverified {
269                ui.colored_label(status_color("unsupported-selection"), crate::theme::data(line));
270            }
271        }
272        if !report.skipped.is_empty() {
273            ui.add_space(4.0);
274            ui.label("Not checked:");
275            for line in &report.skipped {
276                ui.label(crate::theme::data(line).weak());
277            }
278        }
279    }
280
281    /// The window's logical state for the headed verifier
282    /// (`__brepInterference`): `{open, report: {…} | null}`.
283    #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
284    pub fn state_json(&self) -> String {
285        self.state_value().to_string()
286    }
287
288    /// [`Self::state_json`] plus `overlayShown`: whether `state` (the active
289    /// document's engine) currently draws the interference overlay — the
290    /// published blob, so a script can see the overlay follow the window.
291    pub fn state_json_in(&self, state: &EngineState) -> String {
292        let mut value = self.state_value();
293        value["overlayShown"] = Value::Bool(
294            state
295                .widgets
296                .overlay_group_names()
297                .contains(&brep_render::engine_state::INTERFERENCE_OVERLAY_GROUP),
298        );
299        value.to_string()
300    }
301
302    fn state_value(&self) -> Value {
303        let report = self.report.as_ref().map(|report| {
304            serde_json::json!({
305                "componentCount": report.component_count,
306                "pairTotal": report.pair_total,
307                "booleansRun": report.booleans_run,
308                "pairs": report
309                    .pairs
310                    .iter()
311                    .map(|pair| {
312                        serde_json::json!({
313                            "a": pair.a,
314                            "b": pair.b,
315                            "volume": pair.volume,
316                            "aHidden": pair.a_hidden,
317                            "bHidden": pair.b_hidden,
318                            "label": pair_label(pair),
319                        })
320                    })
321                    .collect::<Vec<_>>(),
322                "clearance": report.clearance,
323                "nearMisses": report
324                    .near_misses
325                    .iter()
326                    .map(|pair| {
327                        serde_json::json!({
328                            "a": pair.a,
329                            "b": pair.b,
330                            "distance": pair.distance,
331                            "witness": pair.witness,
332                            "aHidden": pair.a_hidden,
333                            "bHidden": pair.b_hidden,
334                            "label": near_label(pair),
335                        })
336                    })
337                    .collect::<Vec<_>>(),
338                "skipped": report.skipped,
339                "unverified": report.unverified,
340            })
341        });
342        serde_json::json!({
343            "open": self.open,
344            "clearance": self.clearance,
345            "stale": self.stale,
346            "report": report.unwrap_or(Value::Null),
347        })
348    }
349
350    /// Per-frame widget rects (`interference:rerun`, `interference:clearance`,
351    /// `interference:pair:AxB`, `interference:near:AxB`)
352    /// for the headed verifier.
353    #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
354    pub fn hits_json(&self) -> String {
355        crate::automation::hit_rects::hits_json(&self.hits)
356    }
357}
358
359
360/// The hit keys this panel publishes (see `automation::hit_keys`).
361pub static HIT_KEYS: &[HitKeyDoc] = &[
362    HitKeyDoc { panel: "interference", prefix: "interference:rerun", meaning: "rerun the interference check", command: Some("interference_check") },
363    HitKeyDoc { panel: "interference", prefix: "interference:", meaning: "an interference result row", command: None },
364];