BREP_app 0.1.0

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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
//! Sketch panel (S1) — the engine-native sketcher's entry point + mode bar.
//!
//! Two thin surfaces over [`EngineState`] (the single brain — it owns the sketch
//! edit; this panel only triggers its methods and reads it back):
//!
//! * The SIDE-PANEL entry point ([`SketchPanel::show`], drawn only when NOT in
//!   sketch mode): a "New Sketch" row that starts an engine-native sketch on a
//!   base plane (XY / XZ / YZ) via [`EngineState::new_sketch`] and enters sketch
//!   mode on it.
//! * The sketch-mode TOP BAR ([`SketchPanel::show_mode_bar`], drawn while
//!   [`EngineState::sketch_mode`]): the sketch title + the DOF status readout +
//!   Finish / Cancel → [`EngineState::exit_sketch_mode`]. Finish commits the
//!   edited doc back to the feature; Cancel discards it (deleting a brand-new
//!   sketch).
//!
//! Enter/exit rolls the model to the step before the sketch and orients the
//! camera onto the plane — all handled by the engine; the shell just keeps the
//! 3D viewport visible as the sketching surface.

use super::action_rail::{action_rail, ActionItem};
use super::toolbar_button;
use crate::panels::tree::{self, TreeRow};
use brep_render::engine_state::{EngineState, SketchEntityRow};
use eframe::egui;
use std::collections::HashMap;

/// The sketch panel's transient UI state (the sketch itself lives in the engine).
#[derive(Default)]
pub struct SketchPanel {
    /// Per-frame context-rail widget rects (verifier).
    ctx_hits: HashMap<String, egui::Rect>,
    /// Collapse state for the entity-list sections (default open = false).
    curves_collapsed: bool,
    points_collapsed: bool,
    constraints_collapsed: bool,
    /// Solver Settings section starts COLLAPSED (advanced/rarely-touched).
    solver_collapsed: bool,
}

impl SketchPanel {
    pub fn new() -> Self {
        Self {
            // Solver Settings is advanced — start it collapsed.
            solver_collapsed: true,
            ..Self::default()
        }
    }

    /// The sketch-mode bar (drawn as its own top panel while
    /// [`EngineState::sketch_mode`]): the sketch title + DOF readout + Finish /
    /// Cancel. Called from the shell right after the toolbar so it reserves a strip
    /// below it, keeping the viewport as the sketching surface.
    pub fn show_mode_bar(&mut self, ui: &mut egui::Ui, state: &mut EngineState) {
        egui::containers::panel::Panel::top("sketch-mode-bar")
            .resizable(false)
            .show(ui, |ui| {
                ui.add_space(3.0);
                // Row 1: sketch title + DOF + selection count + undo/redo. NOTE:
                // Finish/Cancel now live in the top-right mode-exit card, and the
                // selection-driven constraint ACTIONS in the shared context rail
                // (right side) — this strip is just the drawing toolbar + status.
                ui.horizontal_wrapped(|ui| {
                    let id = state.sketch_edit_feature_id().unwrap_or("").to_string();
                    ui.label(egui::RichText::new(format!("Sketch: {id}")).strong());
                    ui.separator();
                    if let Some(session) = state.sketch_edit_session() {
                        dof_readout(ui, &session.diagnostics);
                    }
                    ui.separator();
                    ui.label(
                        egui::RichText::new(format!("{} selected", state.sketch_selection_count()))
                            .weak(),
                    );
                    ui.separator();
                    // Per-session undo/redo (S6a). The keyboard path (Ctrl+Z /
                    // Ctrl+Shift+Z / Ctrl+Y) is handled by the shell's shortcut
                    // router. Glyphs U+21B6 / U+21B7 — the glyphs from the previous app.
                    if toolbar_button::button_enabled(ui, state.sketch_can_undo(), "\u{21b6}", "Undo (Ctrl+Z)")
                        .clicked()
                    {
                        state.sketch_undo();
                    }
                    if toolbar_button::button_enabled(ui, state.sketch_can_redo(), "\u{21b7}", "Redo (Ctrl+Y)")
                        .clicked()
                    {
                        state.sketch_redo();
                    }
                    ui.separator();
                    // Camera lock (on by default): hold the view flat to the sketch
                    // plane and allow only panning. Toggling it back on re-faces the
                    // camera to the plane; off frees orbiting.
                    let mut locked = state.sketch_camera_locked();
                    if ui
                        .checkbox(&mut locked, "Lock to sketch")
                        .on_hover_text(
                            "Face the sketch plane and pan only. Uncheck to orbit; \
                             re-check to snap back flat.",
                        )
                        .changed()
                    {
                        state.toggle_sketch_camera_lock();
                    }
                });
                ui.add_space(3.0);

                // Row 2: the primitive draw tools (S3). The active one is
                // highlighted; clicking arms it via the engine. `Select` is the S2
                // selection mode (no active tool).
                ui.horizontal_wrapped(|ui| {
                    let active = state.sketch_active_tool().unwrap_or("select").to_string();
                    // Each draw tool shows its EXACT glyph from the previous app; the human label
                    // lives in the hover tooltip (`tip`). The `tool` id + `tip` +
                    // set-tool behavior are unchanged — only the displayed glyph.
                    for (tool, glyph, tip) in [
                        ("select", "\u{1F446}", "Select / drag entities"),
                        ("point", "\u{2316}", "Place a point"),
                        ("line", "/", "Draw connected line segments (Esc ends)"),
                        ("rect", "\u{2610}", "Draw a rectangle (two opposite corners)"),
                        ("circle", "\u{25EF}", "Draw a circle (center, then radius)"),
                        ("arc", "\u{25E0}", "Draw an arc (center, start, end)"),
                        ("bezier", "\u{223F}", "Bezier — end, ctrl, ctrl, end"),
                        ("handdraw", "\u{270D}", "Freehand (auto line/circle/arc)"),
                        ("trim", "\u{2702}", "Trim curve"),
                        ("pickEdges", "\u{26D3}", "Link external edge"),
                    ] {
                        let selected = active.as_str() == tool;
                        if toolbar_button::toggle(ui, selected, glyph, tip).clicked() {
                            state.sketch_set_tool(Some(tool));
                        }
                    }
                    let pending = state.sketch_pending_len();
                    if pending > 0 {
                        ui.separator();
                        ui.label(
                            egui::RichText::new(format!("{pending} placed"))
                                .weak()
                                .italics(),
                        );
                    }
                });
                ui.add_space(3.0);
            });
    }

    /// The in-sketch CONTEXT actions — the selection-driven constraint palette
    /// (applicable constraints + Fix/Unfix + ◐ construction + 🧹 cleanup + 🗑
    /// delete) — rendered through the SAME shared rail as the modeling context
    /// bar ([`super::action_rail`]), so both look and behave identically. The
    /// shell draws it into the top-right overlay, below the mode-exit card. No-op
    /// unless a sketch is being edited AND something is selected.
    pub fn context_card(&mut self, ui: &mut egui::Ui, state: &mut EngineState) {
        self.ctx_hits.clear();
        if !state.sketch_mode() || state.sketch_selection_count() == 0 {
            return;
        }

        let actions = state.sketch_applicable_constraints();
        let grounded = state.sketch_selection_all_grounded();
        let construction = state.sketch_selection_all_construction();

        let mut items: Vec<ActionItem> = Vec::new();
        for action in &actions {
            items.push(ActionItem::new(
                format!("constraint:{}", action.symbol),
                format!("{} {}", action.symbol, action.label),
                action.label.clone(),
            ));
        }
        if let Some(all_grounded) = grounded {
            let (label, tip) = if all_grounded {
                ("Unfix", "Remove the ground constraint")
            } else {
                ("Fix", "Ground (fix) the selected points")
            };
            items.push(ActionItem::new("fix", label, tip));
        }
        if let Some(all_construction) = construction {
            let tip = if all_construction {
                "Convert to regular geometry"
            } else {
                "Convert to construction geometry"
            };
            items.push(ActionItem::new("construction", "◐ Construction", tip));
        }
        items.push(ActionItem::new(
            "cleanup",
            "🧹 Clean",
            "Remove unused points",
        ));
        items.push(ActionItem::new(
            "delete",
            "🗑 Delete",
            "Delete the selected entities (Del / Backspace)",
        ));

        let subtitle = format!("{} selected", state.sketch_selection_count());
        let clicked = egui::Frame::popup(ui.style())
            .show(ui, |ui| {
                action_rail(
                    ui,
                    Some("Sketch actions"),
                    Some(&subtitle),
                    &items,
                    &mut self.ctx_hits,
                )
            })
            .inner;

        match clicked.as_deref() {
            Some(key) if key.starts_with("constraint:") => {
                state.sketch_add_constraint(&key["constraint:".len()..]);
            }
            Some("fix") => {
                state.sketch_toggle_ground();
            }
            Some("construction") => {
                state.sketch_toggle_construction();
            }
            Some("cleanup") => {
                state.sketch_cleanup_unused_points();
            }
            Some("delete") => {
                state.sketch_delete_selection();
            }
            _ => {}
        }
    }

    /// The sketch-mode LEFT panel: Curves / Points / Constraints as selectable,
    /// deletable, hover-synced rows (the port of the previous app's list sidebar).
    /// Drawn only while editing a sketch; a click selects (Ctrl/Cmd adds), a row
    /// hover highlights the entity on the canvas, and the ✕ deletes it.
    pub fn show_entity_lists(&mut self, ui: &mut egui::Ui, state: &mut EngineState) {
        egui::ScrollArea::vertical().show(ui, |ui| {
            ui.add_space(4.0);
            // Snapshot the rows first (immutable borrow), then render with `&mut
            // state` so per-row select/hover can call back into the engine.
            let curves = state.sketch_geometry_rows();
            let points = state.sketch_point_rows();
            let constraints = state.sketch_constraint_rows();
            entity_section(ui, &mut self.curves_collapsed, state, "Curves", "geometry", curves);
            entity_section(ui, &mut self.points_collapsed, state, "Points", "point", points);
            entity_section(
                ui,
                &mut self.constraints_collapsed,
                state,
                "Constraints",
                "constraint",
                constraints,
            );

            ui.add_space(6.0);
            solver_settings_section(ui, &mut self.solver_collapsed, state);
        });
    }

    /// Verification mirror (wasm): the live sketch-mode state + the active session's
    /// solve summary, so the headed verifier can assert enter/exit (screenshots read
    /// black headless).
    #[cfg(target_arch = "wasm32")]
    pub fn published_json(&self, state: &EngineState) -> String {
        let session = state.sketch_edit_session();
        // S5 editable dimensions: the per-constraint labels (id/value/valueExpr/mode)
        // + a count, so the headless verifier can assert dims render + edit.
        let dim_labels: Vec<serde_json::Value> =
            serde_json::from_str(&state.sketch_dimension_labels_json()).unwrap_or_default();
        let dimensions: Vec<serde_json::Value> = dim_labels
            .iter()
            .map(|l| {
                serde_json::json!({
                    "id": l["id"],
                    "text": l["text"],
                    "value": l["value"],
                    "valueExpr": l["valueExpr"],
                    "mode": l["mode"],
                })
            })
            .collect();
        serde_json::json!({
            "sketchMode": state.sketch_mode(),
            "featureId": state.sketch_edit_feature_id(),
            "dof": session.map(|s| s.diagnostics.dof),
            "status": session.map(|s| s.diagnostics.status.clone()),
            "conflicting": session.map(|s| s.diagnostics.conflicting),
            "points": session.map(|s| s.doc.points.len()),
            "geometries": session.map(|s| s.doc.geometries.len()),
            "constraints": session.map(|s| s.doc.constraints.len()),
            // S2 picking state (the headless verifier asserts hover/selection).
            "hovered": session.and_then(|s| s.hovered.clone()),
            "selectionCount": state.sketch_selection_count(),
            // Constraint selection (select + delete): how many selected refs are
            // constraints, so the verifier can assert a constraint pick + delete.
            "selectedConstraintCount": state.sketch_selected_constraint_count(),
            // S3a draw-tool state (the verifier asserts tool selection + that draws
            // landed): the active tool + the doc's point/geometry counts + the
            // in-progress click buffer length.
            "tool": state.sketch_active_tool(),
            "cameraLocked": state.sketch_camera_locked(),
            "pointCount": session.map(|s| s.doc.points.len()),
            "geometryCount": session.map(|s| s.doc.geometries.len()),
            "pendingLen": state.sketch_pending_len(),
            // S4 constraint palette: the active doc's constraint count + the ordered
            // list of applicable-constraint symbols for the live selection (the
            // headless verifier asserts the palette + that additions landed).
            "constraintCount": state.sketch_constraint_count(),
            "applicableConstraints": state
                .sketch_applicable_constraints()
                .iter()
                .map(|a| a.symbol.clone())
                .collect::<Vec<_>>(),
            // S5 editable dimensions.
            "dimensionCount": dimensions.len(),
            "dimensions": dimensions,
            // S6a per-session sketch undo/redo (the verifier asserts a draw is
            // undoable and that redo is available after an undo).
            "canUndo": state.sketch_can_undo(),
            "canRedo": state.sketch_can_redo(),
            // S6b-2 pickEdges: the number of linked external-reference edges (the
            // verifier asserts a link landed and round-trips a commit + re-enter).
            "externalRefCount": state.sketch_external_ref_count(),
            // S6b-3 handdraw: the live freehand stroke sample count (the verifier
            // asserts a stroke captures while dragging, then clears + emits on end).
            "handdrawPoints": state.sketch_handdraw_len(),
        })
        .to_string()
    }
}

/// The DOF status readout — a colored dot + label, ported from the previous
/// sketcher's DOF readout. Red = conflicting, yellow = over-constrained, blue =
/// under-constrained (`N` DOF), green = fully constrained.
fn dof_readout(ui: &mut egui::Ui, diag: &brep_render::sketch::SketchDiagnostics) {
    let (color, label): (egui::Color32, String) = if diag.conflicting {
        (
            egui::Color32::from_rgb(0xff, 0x5c, 0x5c),
            "Conflicting constraints".to_string(),
        )
    } else if diag.status == "over" || diag.redundant > 0 {
        let label = if diag.dof > 0 {
            format!(
                "Over-constrained ({} redundant, {} DOF)",
                diag.redundant, diag.dof
            )
        } else {
            format!("Over-constrained ({} redundant)", diag.redundant)
        };
        (egui::Color32::from_rgb(0xff, 0xcf, 0x5c), label)
    } else if diag.status == "under" || diag.dof > 0 {
        (
            egui::Color32::from_rgb(0x4a, 0xa3, 0xff),
            format!("Under-constrained — {} DOF", diag.dof),
        )
    } else {
        (
            egui::Color32::from_rgb(0x7e, 0xe0, 0xa6),
            "Fully constrained".to_string(),
        )
    };

    ui.horizontal(|ui| {
        let (rect, _) = ui.allocate_exact_size(egui::vec2(12.0, 12.0), egui::Sense::hover());
        ui.painter().circle_filled(rect.center(), 5.0, color);
        ui.label(egui::RichText::new(label).strong());
    });
}

/// One collapsible entity-list section, rendered with the shared `tree` widget so
/// it matches the Scene tree. A branch header (title + count) over leaf rows; each
/// leaf is a selectable label (Ctrl/Cmd adds), a row hover highlights the entity on
/// the canvas, and a trailing ✕ deletes it via the existing selection-delete path.
fn entity_section(
    ui: &mut egui::Ui,
    collapsed: &mut bool,
    state: &mut EngineState,
    title: &str,
    kind: &'static str,
    rows: Vec<SketchEntityRow>,
) {
    let open = !*collapsed;
    let resp = tree::node(ui, TreeRow::branch(&[], true, open, title), |ui| {
        ui.add_space(6.0);
        ui.label(egui::RichText::new(format!("{}", rows.len())).weak());
    });
    if resp.toggled || resp.label.clicked() {
        *collapsed = !*collapsed;
    }
    if !open {
        return;
    }

    let base = tree::child_guides(&[], true);
    if rows.is_empty() {
        tree::node(ui, TreeRow::leaf(&base, true, ""), |_| {});
        return;
    }

    let n = rows.len();
    let mut to_delete: Option<serde_json::Value> = None;
    for (i, row) in rows.iter().enumerate() {
        let last = i + 1 == n;
        let mut delete_clicked = false;
        let resp = tree::node(
            ui,
            TreeRow::leaf(&base, last, row.label.as_str()).selected(row.selected),
            |ui| {
                if ui.small_button("").on_hover_text("Delete").clicked() {
                    delete_clicked = true;
                }
            },
        );
        if delete_clicked {
            to_delete = Some(row.id.clone());
        } else if resp.label.clicked() {
            let additive = ui.input(|i| i.modifiers.command || i.modifiers.ctrl);
            state.sketch_select_entity(kind, row.id.clone(), additive);
        }
        if resp.label.hovered() {
            state.sketch_hover_entity(kind, row.id.clone());
        }
    }
    // Delete last so it can't invalidate the rows we are still iterating this frame.
    if let Some(id) = to_delete {
        state.sketch_select_entity(kind, id, false);
        state.sketch_delete_selection();
    }
}

/// The Solver Settings section (the port of the previous app's "Solver Settings" sidebar): a
/// couple of the `SolveSketchRequest` knobs (iteration cap + optional tolerance
/// override), plus Reset. Any change re-solves the sketch immediately. Defaults
/// reproduce the historical solve, so an untouched sketch is unaffected.
fn solver_settings_section(ui: &mut egui::Ui, collapsed: &mut bool, state: &mut EngineState) {
    let Some(mut settings) = state.sketch_solver_settings() else {
        return;
    };
    let open = !*collapsed;
    let resp = tree::node(ui, TreeRow::branch(&[], true, open, "Solver Settings"), |_| {});
    if resp.toggled || resp.label.clicked() {
        *collapsed = !*collapsed;
    }
    if !open {
        return;
    }

    let before = settings.clone();
    egui::Frame::group(ui.style()).show(ui, |ui| {
        // Iteration cap (always set; default 1000).
        let mut iters = settings.iterations.unwrap_or(1000);
        ui.horizontal(|ui| {
            ui.label("Max iterations");
            if ui
                .add(egui::DragValue::new(&mut iters).range(50..=20_000).speed(10.0))
                .changed()
            {
                settings.iterations = Some(iters);
            }
        });

        // Optional convergence tolerance override.
        let mut tol_on = settings.tolerance.is_some();
        ui.horizontal(|ui| {
            if ui.checkbox(&mut tol_on, "Override tolerance").changed() {
                settings.tolerance = tol_on.then_some(1e-6);
            }
            if let Some(mut tol) = settings.tolerance {
                if ui
                    .add(
                        egui::DragValue::new(&mut tol)
                            .range(1e-9..=1e-1)
                            .speed(1e-6)
                            .custom_formatter(|v, _| format!("{v:.1e}")),
                    )
                    .changed()
                {
                    settings.tolerance = Some(tol);
                }
            }
        });

        if ui.button("Reset to defaults").clicked() {
            settings = brep_render::sketch::SketchSolverSettings::default();
        }
    });

    if settings != before {
        state.sketch_set_solver_settings(settings);
    }
}