BREP_app 0.2.1

The BREP CAD application: an eframe (egui + wgpu) host that draws the brep-render 3D engine into an egui frame — native + wasm from one codebase.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! Interference results window (assemblies build-spec §9) — the floating
//! window behind the Assembly workbench's `∩` toolbar button.
//!
//! Follows the pinned Info-window idiom: a movable + resizable
//! [`egui::Window`] drawn at ctx level, owning its own state (the last
//! [`InterferenceReport`]). The check itself lives in the ENGINE
//! ([`EngineState::interference_check`] — main-side, non-destructive,
//! bbox-prefiltered); this panel only renders the report:
//!
//! * a row per INTERFERING pair — `ACOMP1 × ACOMP3 — 12.4 mm³` — clicking it
//!   selects/highlights BOTH components (emphasis over their member solids);
//!   a hidden participant is noted on its row (it still participated —
//!   interference is a physical question);
//! * a green all-clear line when nothing interferes (a PASS state, shown
//!   positively);
//! * explicit `unverified` (boolean refused) and `skipped` (budget / no
//!   geometry) sections — nothing is ever dropped silently;
//! * a Re-run button.
//!
//! Colors come from the ONE assembly status map
//! ([`brep_render::assembly_status`]) and volumes from the ONE measurement
//! formatter ([`super::info_windows::num`]) — no re-rolled styling.

use brep_render::assembly_status;
use brep_render::engine_state::{EngineState, InterferencePair, InterferenceReport};
use eframe::egui;
use serde_json::Value;
use std::collections::HashMap;

/// The row/line label of one interfering pair: `A × B — 12.4 mm³`, with a
/// `(hidden: …)` note when a participant is currently invisible.
fn pair_label(pair: &InterferencePair) -> String {
    let mut label = format!(
        "{} \u{00d7} {} \u{2014} {} mm\u{00b3}",
        pair.a,
        pair.b,
        super::info_windows::num(pair.volume)
    );
    let hidden: Vec<&str> = [
        pair.a_hidden.then_some(pair.a.as_str()),
        pair.b_hidden.then_some(pair.b.as_str()),
    ]
    .into_iter()
    .flatten()
    .collect();
    if !hidden.is_empty() {
        label.push_str(&format!(" (hidden: {})", hidden.join(", ")));
    }
    label
}

/// An [`egui::Color32`] off the shared status palette.
fn status_color(status: &str) -> egui::Color32 {
    let [r, g, b] = assembly_status::status_color_rgb(status);
    egui::Color32::from_rgb(r, g, b)
}

/// The shell-owned interference results window. Opened (and run) by the
/// Assembly workbench's toolbar button; re-run from its own button. Owns the
/// last report — the engine holds no window state.
#[derive(Default)]
pub struct InterferenceWindow {
    open: bool,
    report: Option<InterferenceReport>,
    /// Per-frame interactive-widget screen rects for the headed verifier.
    hits: HashMap<String, egui::Rect>,
}

impl InterferenceWindow {
    pub fn new() -> Self {
        Self::default()
    }

    /// The toolbar entry point: run the check NOW and show the window.
    pub fn open_and_run(&mut self, state: &mut EngineState) {
        self.report = Some(state.interference_check());
        self.open = true;
    }

    /// Draw the window (if open) at ctx level, like the Info windows.
    pub fn show(&mut self, ctx: &egui::Context, state: &mut EngineState) {
        self.hits.clear();
        if !self.open {
            return;
        }
        let mut open = true;
        egui::Window::new("Interference")
            .id(egui::Id::new("brep-interference-window"))
            .open(&mut open)
            .movable(true)
            .resizable(true)
            .default_size([360.0, 320.0])
            .default_pos([860.0, 80.0])
            .show(ctx, |ui| {
                egui::ScrollArea::vertical()
                    .auto_shrink([false, false])
                    .show(ui, |ui| self.body(ui, state));
            });
        self.open = open;
    }

    fn body(&mut self, ui: &mut egui::Ui, state: &mut EngineState) {
        // Header: the summary + Re-run.
        ui.horizontal(|ui| {
            let rerun = ui.button("Re-run");
            self.hits.insert("interference:rerun".into(), rerun.rect);
            if rerun.clicked() {
                self.report = Some(state.interference_check());
            }
            if let Some(report) = &self.report {
                ui.weak(format!(
                    "{} components \u{00b7} {} pairs \u{00b7} {} boolean{}",
                    report.component_count,
                    report.pair_total,
                    report.booleans_run,
                    if report.booleans_run == 1 { "" } else { "s" }
                ));
            }
        });
        ui.separator();

        let Some(report) = self.report.clone() else {
            ui.weak("Run the check from the toolbar.");
            return;
        };
        if report.component_count < 2 {
            ui.weak("Needs at least two components.");
            return;
        }

        if report.pairs.is_empty() {
            // The PASS state, shown positively (green — the shared palette's
            // `satisfied`). Refusals/skips below still temper it.
            ui.colored_label(
                status_color("satisfied"),
                format!(
                    "\u{2713} No interference \u{2014} {} pair{} checked",
                    report.pair_total,
                    if report.pair_total == 1 { "" } else { "s" }
                ),
            );
        } else {
            for pair in &report.pairs {
                // A clickable row: selecting it highlights BOTH participants
                // (emphasis over the union of their member solids).
                let row = ui.selectable_label(
                    false,
                    egui::RichText::new(pair_label(pair)).color(status_color("error")),
                );
                self.hits
                    .insert(format!("interference:pair:{}x{}", pair.a, pair.b), row.rect);
                if row.clicked() {
                    state.select_components(&[pair.a.clone(), pair.b.clone()]);
                }
            }
        }

        // Never-silent sections: boolean refusals and skipped work.
        if !report.unverified.is_empty() {
            ui.add_space(4.0);
            ui.label("Not verified (boolean refused):");
            for line in &report.unverified {
                ui.colored_label(status_color("unsupported-selection"), line);
            }
        }
        if !report.skipped.is_empty() {
            ui.add_space(4.0);
            ui.label("Not checked:");
            for line in &report.skipped {
                ui.weak(line);
            }
        }
    }

    /// The window's logical state for the headed verifier
    /// (`__brepInterference`): `{open, report: {…} | null}`.
    #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
    pub fn state_json(&self) -> String {
        let report = self.report.as_ref().map(|report| {
            serde_json::json!({
                "componentCount": report.component_count,
                "pairTotal": report.pair_total,
                "booleansRun": report.booleans_run,
                "pairs": report
                    .pairs
                    .iter()
                    .map(|pair| {
                        serde_json::json!({
                            "a": pair.a,
                            "b": pair.b,
                            "volume": pair.volume,
                            "aHidden": pair.a_hidden,
                            "bHidden": pair.b_hidden,
                            "label": pair_label(pair),
                        })
                    })
                    .collect::<Vec<_>>(),
                "skipped": report.skipped,
                "unverified": report.unverified,
            })
        });
        serde_json::json!({
            "open": self.open,
            "report": report.unwrap_or(Value::Null),
        })
        .to_string()
    }

    /// Per-frame widget rects (`interference:rerun`, `interference:pair:AxB`)
    /// for the headed verifier.
    #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
    pub fn hits_json(&self) -> String {
        let mut map = serde_json::Map::new();
        for (key, rect) in &self.hits {
            map.insert(
                key.clone(),
                serde_json::json!([rect.min.x, rect.min.y, rect.width(), rect.height()]),
            );
        }
        Value::Object(map).to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use brep_render::engine_state::ComponentInsert;

    /// A one-cube part document (10 mm cube `Part` — the insert-flow payload).
    fn part_document() -> String {
        serde_json::json!({
            "expressions": "",
            "configurator": {},
            "features": [{
                "type": "P.CU",
                "inputParams": {
                    "id": "Part",
                    "sizeX": 10.0, "sizeY": 10.0, "sizeZ": 10.0,
                    "transform": {
                        "position": [0.0, 0.0, 0.0],
                        "rotationEuler": [0.0, 0.0, 0.0],
                        "scale": [1.0, 1.0, 1.0]
                    },
                    "boolean": { "targets": [], "operation": "NONE" }
                },
                "persistentData": {}
            }]
        })
        .to_string()
    }

    /// Two 10 mm cube instances via the REAL insert flow, the second moved to
    /// `translate` (the assembly_ops test idiom).
    fn two_cube_state(translate: [f64; 3]) -> EngineState {
        brep_render::brep_kernel::clear_history_cache();
        let mut state = EngineState::new();
        state
            .insert_component(ComponentInsert::New {
                name: "cube",
                source_key: "cube",
                source_signature: "sig-1",
                document_json: &part_document(),
            })
            .expect("insert 1");
        state
            .insert_component(ComponentInsert::Existing { part_name: "cube" })
            .expect("insert 2");
        let mut params = state
            .history
            .feature_params(state.history.index_of("ACOMP2").unwrap())
            .unwrap();
        params["transform"]["translate"] = serde_json::json!(translate);
        state
            .update_feature_params("ACOMP2", &params.to_string())
            .expect("move ACOMP2");
        state
    }

    /// One headless egui frame of the window (the panel test idiom).
    fn run_frame(
        ctx: &egui::Context,
        window: &mut InterferenceWindow,
        state: &mut EngineState,
        events: Vec<egui::Event>,
    ) {
        let raw = egui::RawInput {
            screen_rect: Some(egui::Rect::from_min_size(
                egui::pos2(0.0, 0.0),
                egui::vec2(1280.0, 800.0),
            )),
            events,
            ..Default::default()
        };
        let _ = ctx.run_ui(raw, |ui| {
            let _ = ui; // the window draws at ctx level
            window.show(ctx, state);
        });
    }

    /// Left-click at `pos`: hover frame + press frame, then a release frame
    /// (the assembly-structure `click_at` idiom).
    fn click_at(
        ctx: &egui::Context,
        window: &mut InterferenceWindow,
        state: &mut EngineState,
        pos: egui::Pos2,
    ) {
        run_frame(
            ctx,
            window,
            state,
            vec![
                egui::Event::PointerMoved(pos),
                egui::Event::PointerButton {
                    pos,
                    button: egui::PointerButton::Primary,
                    pressed: true,
                    modifiers: egui::Modifiers::default(),
                },
            ],
        );
        run_frame(
            ctx,
            window,
            state,
            vec![egui::Event::PointerButton {
                pos,
                button: egui::PointerButton::Primary,
                pressed: false,
                modifiers: egui::Modifiers::default(),
            }],
        );
    }

    #[test]
    fn labels_read_pair_volume_and_hidden_note() {
        let pair = |hidden: (bool, bool)| InterferencePair {
            a: "ACOMP1".into(),
            b: "ACOMP3".into(),
            volume: 12.4,
            a_hidden: hidden.0,
            b_hidden: hidden.1,
        };
        assert_eq!(
            pair_label(&pair((false, false))),
            "ACOMP1 \u{00d7} ACOMP3 \u{2014} 12.4 mm\u{00b3}"
        );
        assert_eq!(
            pair_label(&pair((false, true))),
            "ACOMP1 \u{00d7} ACOMP3 \u{2014} 12.4 mm\u{00b3} (hidden: ACOMP3)"
        );
        assert_eq!(
            pair_label(&pair((true, true))),
            "ACOMP1 \u{00d7} ACOMP3 \u{2014} 12.4 mm\u{00b3} (hidden: ACOMP1, ACOMP3)"
        );
    }

    /// The toolbar entry point runs the ENGINE check and the published state
    /// carries the interfering pair with its exact volume; the all-clear case
    /// publishes an empty pair list over the same report shape.
    #[test]
    fn open_and_run_publishes_the_report() {
        let mut state = two_cube_state([5.0, 0.0, 0.0]);
        let mut window = InterferenceWindow::new();
        assert_eq!(
            serde_json::from_str::<Value>(&window.state_json()).unwrap()["report"],
            Value::Null,
            "no report before the first run"
        );
        window.open_and_run(&mut state);
        let published: Value = serde_json::from_str(&window.state_json()).unwrap();
        assert_eq!(published["open"], true);
        let report = &published["report"];
        assert_eq!(report["componentCount"], 2);
        assert_eq!(report["pairTotal"], 1);
        assert_eq!(report["pairs"][0]["a"], "ACOMP1");
        assert_eq!(report["pairs"][0]["b"], "ACOMP2");
        assert!((report["pairs"][0]["volume"].as_f64().unwrap() - 500.0).abs() < 1e-6);
        assert_eq!(
            report["pairs"][0]["label"],
            "ACOMP1 \u{00d7} ACOMP2 \u{2014} 500 mm\u{00b3}"
        );

        // All-clear: separated cubes → empty pairs, pass state.
        let mut state = two_cube_state([40.0, 0.0, 0.0]);
        let mut window = InterferenceWindow::new();
        window.open_and_run(&mut state);
        let published: Value = serde_json::from_str(&window.state_json()).unwrap();
        assert_eq!(published["report"]["pairs"], serde_json::json!([]));
        assert_eq!(published["report"]["booleansRun"], 0, "prefiltered");
    }

    /// Clicking a pair row selects BOTH participants (emphasis over the union
    /// of their member solids) through a real egui click.
    #[test]
    fn pair_row_click_selects_both_components() {
        let ctx = egui::Context::default();
        let mut state = two_cube_state([5.0, 0.0, 0.0]);
        let mut window = InterferenceWindow::new();
        window.open_and_run(&mut state);

        // Two settle frames: the window's first-frame placement may still be
        // constrained/sized; read the rects only once the layout is stable.
        run_frame(&ctx, &mut window, &mut state, vec![]);
        run_frame(&ctx, &mut window, &mut state, vec![]);
        let row = *window
            .hits
            .get("interference:pair:ACOMP1xACOMP2")
            .expect("pair row rect");
        click_at(&ctx, &mut window, &mut state, row.center());
        assert!(
            state.emphasis.selected_solids.contains("ACOMP1:Part")
                && state.emphasis.selected_solids.contains("ACOMP2:Part"),
            "row click highlights BOTH participants"
        );
    }

    /// The Re-run button reflects engine changes: hide a participant, re-run,
    /// and the pair is flagged hidden in the published state.
    #[test]
    fn rerun_picks_up_hidden_participants() {
        let ctx = egui::Context::default();
        let mut state = two_cube_state([5.0, 0.0, 0.0]);
        let mut window = InterferenceWindow::new();
        window.open_and_run(&mut state);
        assert!(state.scene.set_visible("ACOMP2:Part", false));

        run_frame(&ctx, &mut window, &mut state, vec![]);
        run_frame(&ctx, &mut window, &mut state, vec![]);
        let rerun = *window.hits.get("interference:rerun").expect("rerun rect");
        click_at(&ctx, &mut window, &mut state, rerun.center());
        let published: Value = serde_json::from_str(&window.state_json()).unwrap();
        let pair = &published["report"]["pairs"][0];
        assert_eq!(pair["bHidden"], true, "hidden participant flagged: {pair}");
        assert!(
            pair["label"].as_str().unwrap().contains("(hidden: ACOMP2)"),
            "{pair}"
        );
    }
}