Skip to main content

brep_render/
style.rs

1//! Render settings (R14 — the `CADmaterials` semantics: per-kind material
2//! variants, hover color, flat-shading toggle, user-persisted overrides) and
3//! the selection/hover emphasis state (R17/R24 — name-keyed, fed by the host's
4//! `SelectionFilter`). Plain data, shared by the engine core and the wgpu
5//! renderer; JSON in/out at the R3 boundary.
6
7use std::collections::HashSet;
8
9/// sRGB color in 0..1 + alpha.
10pub type Rgba = [f32; 4];
11
12fn hex(hex: u32, alpha: f32) -> Rgba {
13    let [r, g, b] = crate::color::hex_to_srgb_f32(hex);
14    [r, g, b, alpha]
15}
16
17/// Parse `#rrggbb` / `#rgb` / `0xrrggbb` (returns None on anything else).
18pub fn parse_css_hex(value: &str) -> Option<[f32; 3]> {
19    let v = value.trim();
20    let digits = v
21        .strip_prefix('#')
22        .or_else(|| v.strip_prefix("0x"))
23        .or_else(|| v.strip_prefix("0X"))?;
24    let expand = |c: char| c.to_digit(16).map(|d| (d * 17) as f32 / 255.0);
25    match digits.len() {
26        3 => {
27            let mut chars = digits.chars();
28            Some([
29                expand(chars.next()?)?,
30                expand(chars.next()?)?,
31                expand(chars.next()?)?,
32            ])
33        }
34        6 => {
35            let n = u32::from_str_radix(digits, 16).ok()?;
36            Some(crate::color::hex_to_srgb_f32(n))
37        }
38        _ => None,
39    }
40}
41
42/// The sketcher's overlay palette as plain `0xRRGGBB` hex — the ONE place the
43/// default color literals live. [`RenderSettings`] stores each of these as an
44/// editable [`Rgba`] field (defaults derived from here via [`hex`]) and hands the
45/// sketch tessellation/overlay builders a live `SketchColors` view via
46/// [`RenderSettings::sketch_colors`], so the sketch renderer reads its colors from
47/// the display settings just like faces/edges/vertices do — no scattered constants.
48///
49/// The `constraint` green is a deliberate user directive (2026-08-22): CONSTRAINT
50/// annotations (geometric-constraint glyphs + dimension leaders/labels) read in
51/// green so they stand apart from the blue/white sketch GEOMETRY.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub struct SketchColors {
54    /// Movable geometry / point (blue).
55    pub movable: u32,
56    /// Locked geometry / point (near-white).
57    pub locked: u32,
58    /// No-mobility geometry fallback (yellow).
59    pub geometry: u32,
60    /// No-mobility point fallback.
61    pub point: u32,
62    /// Construction point (orange).
63    pub construction_point: u32,
64    /// Heuristic under-constrained point.
65    pub under_constrained_point: u32,
66    /// Selected entity — amber (the transform-gizmo accent); beats hover.
67    pub selected: u32,
68    /// Hovered entity — light blue (brighter than movable).
69    pub hovered: u32,
70    /// Draw-tool rubber-band preview (dim, so it reads as tentative).
71    pub preview: u32,
72    /// Constraint annotations — glyphs + dimension leaders/labels (green).
73    pub constraint: u32,
74    /// A constraint the solver named as part of a CONFLICT — the red of the
75    /// status bar's conflict dot, so the two readouts agree at a glance.
76    pub conflict: u32,
77}
78
79impl Default for SketchColors {
80    fn default() -> Self {
81        // The previous sketcher's theme defaults — the single source of these literals.
82        Self {
83            movable: 0x4aa3ff,
84            locked: 0xe6ebf2,
85            geometry: 0xffff88,
86            point: 0x9ec9ff,
87            construction_point: 0xffa86a,
88            under_constrained_point: 0xffb347,
89            selected: 0xffa500,
90            hovered: 0x7fd0ff,
91            preview: 0x8fa0b8,
92            constraint: 0x4ade80,
93            conflict: 0xff5c5c,
94        }
95    }
96}
97
98/// The GUI chrome theme (panels, windows, toolbar, text) — controls the egui
99/// look, NOT the 3D viewport background (that is the separate `background`
100/// setting). `Auto` follows the OS/system theme (`prefers-color-scheme` on web).
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102pub enum ThemeMode {
103    /// Follow the system's theme preference (falls back to dark when no OS signal).
104    Auto,
105    Light,
106    Dark,
107}
108
109/// How a plain viewport click builds a MULTI-selection (the Settings "Multi-select"
110/// dropdown). Read by the app's viewport click routing — the engine's selection
111/// primitives (`select_candidate` replace / `toggle_candidate` toggle) are
112/// mode-agnostic; this only chooses which one a plain click drives.
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub enum MultiSelectMode {
115    /// A plain click REPLACES the selection; Ctrl/Cmd+click adds/toggles (the
116    /// classic CAD behavior).
117    CtrlClick,
118    /// A plain click TOGGLES the item in the selection (click again to unselect)
119    /// so a multi-selection needs no modifier key; a click on empty space clears.
120    ClickToggles,
121}
122
123impl MultiSelectMode {
124    /// Every mode, in the order the Settings dropdown lists them.
125    pub const ALL: [MultiSelectMode; 2] = [MultiSelectMode::CtrlClick, MultiSelectMode::ClickToggles];
126
127    /// The human label — ALSO the serialized `multiSelect` value (the
128    /// renderQuality pattern: the dropdown and the stored JSON speak the label;
129    /// `apply_json` parses it back tolerantly).
130    pub fn label(&self) -> &'static str {
131        match self {
132            MultiSelectMode::CtrlClick => "Ctrl+Click",
133            MultiSelectMode::ClickToggles => "Click toggles",
134        }
135    }
136}
137
138/// How base face color is chosen per solid.
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140pub enum FaceColorMode {
141    /// The app look: every face gets `face_color` (unless the solid carries a
142    /// metadata override).
143    Uniform,
144    /// The artifact look: stable name-hashed color per solid.
145    HashedBySolid,
146}
147
148/// The viewer's material palette + display toggles. Defaults are the
149/// `CADmaterials` values.
150/// Global toolbar appearance. Missing saved values migrate to Ribbon.
151#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
152pub enum ToolbarStyle {
153    #[default]
154    Ribbon,
155    Classic,
156}
157
158impl ToolbarStyle {
159    pub fn as_str(self) -> &'static str {
160        match self {
161            Self::Ribbon => "Ribbon",
162            Self::Classic => "Classic",
163        }
164    }
165}
166
167#[derive(Debug, Clone, PartialEq)]
168pub struct RenderSettings {
169    /// GUI chrome theme (egui panels/windows/toolbar/text). Defaults to `Auto`,
170    /// following the OS light/dark preference.
171    pub theme: ThemeMode,
172    /// Global UI size scale applied to the whole egui chrome via
173    /// [`egui::Context::set_zoom_factor`]. 1.0 = native size; composes with the
174    /// device pixel ratio. Clamped to `[0.5, 3.0]`.
175    pub ui_scale: f32,
176    /// Skip the startup recovery offer without restoring documents automatically.
177    /// Autosaving remains enabled for the current session.
178    pub disable_recovery_prompt: bool,
179    /// Size multiplier for the floating TEXT LABELS the app overlays on the 3D
180    /// model — the dimension-gizmo value chips (sketch + feature dimensions), the
181    /// assembly-constraint chips, and the transform gizmo's axis letters. 1.0 = the
182    /// base monospace size; the label's glyphs, its measured edit-box width, and its
183    /// chip padding all scale together (see `brep-app`'s `viewport::labels`). A
184    /// MULTIPLIER, not a point size, so labels stay consistent with each other and
185    /// the setting survives a restyle. Clamped to `[0.25, 3.0]`: 0.25 is the
186    /// smallest label that is still a LABEL rather than a smudge — a quarter of the
187    /// 12pt base monospace is a ~3.8pt glyph row inside a ~4.5pt-tall chip, which is
188    /// the point at which the double-click/drag target stops being something a
189    /// pointer can reliably land on (and it composes with `uiScale` + the device
190    /// pixel ratio, so it is not an absolute 3pt on screen). The 3.0 ceiling keeps a
191    /// user from filling the viewport with one label. Independent of
192    /// [`RenderSettings::ui_scale`], which sizes the egui CHROME (panels/toolbar)
193    /// and not the model overlay.
194    pub label_scale: f32,
195    /// Debug overlay: draw the 1px red outline of each gizmo grab handle's hit
196    /// region (arrows/leaders as capsules, balls as circles). Off by default;
197    /// toggled from Settings to inspect exactly where a drag will grab.
198    pub debug_grab_handles: bool,
199    pub background: [f32; 3],
200    pub face_color_mode: FaceColorMode,
201    /// IGNORE the model's own colours when shading (RENDER-ONLY).
202    ///
203    /// Bodies and faces carry a durable `color` metadata attribute — stamped by
204    /// a STEP import, editable in the Info window — and by default it IS the
205    /// shaded colour. Ticking this box makes the viewport fall back to
206    /// [`Self::face_color_mode`] (the uniform or name-hashed colour) as though
207    /// the model carried no colours at all.
208    ///
209    /// It is a DISPLAY switch, not an edit: the metadata store is never touched,
210    /// so unticking it brings every model colour straight back, and a document
211    /// saved with the box ticked still carries all of its colours. Defaults to
212    /// false — a coloured model shows its colours.
213    pub override_model_colors: bool,
214    /// Show the WORKBENCH ACTIONS toolbar — a second strip under the primary
215    /// toolbar with one button per feature the active workbench offers (and, where
216    /// the Constraints panel is shown, one per assembly-constraint type). Chrome
217    /// only: it never changes what the palette or context bar offer. The app
218    /// hides the strip while a sketch is being edited regardless of this flag.
219    pub show_workbench_toolbar: bool,
220    pub toolbar_style: ToolbarStyle,
221    pub face_color: Rgba,
222    pub face_selected_color: Rgba,
223    pub hover_color: Rgba,
224    pub edge_color: Rgba,
225    pub edge_selected_color: Rgba,
226    pub edge_width_px: f32,
227    /// Draw the OCCLUDED portions of edges at all — the second, depth-failing
228    /// edge pass that [`Self::hidden_edge_alpha`] dims.
229    ///
230    /// It is a whole extra pass over every edge buffer in the scene, so turning
231    /// it off is the single largest display saving the viewer has: measured
232    /// 2026-09-11 on a heavy model, frame `draw` fell 33.61 ms -> 24.76 ms
233    /// (-26%). The viewport looks materially different with it off — edges
234    /// behind a face simply are not there — which is why this is a user's
235    /// choice and not a performance default. Defaults to true, the look the
236    /// viewer has always had.
237    ///
238    /// Distinct from setting [`Self::hidden_edge_alpha`] to 0, which also skips
239    /// the pass: the alpha is how DIM the occluded edges are, this is WHETHER
240    /// they are drawn, so a user can A/B the cost without losing their dimness.
241    pub show_occluded_edges: bool,
242    /// Occluded edges render dimmed, not dropped (R17): alpha of the
243    /// depth-failing edge pass. 0 disables the pass, as does
244    /// [`Self::show_occluded_edges`] being false.
245    pub hidden_edge_alpha: f32,
246    pub vertex_color: Rgba,
247    pub vertex_selected_color: Rgba,
248    pub vertex_size_px: f32,
249    pub flat_shading: bool,
250    /// Wireframe display (R14): when true the shaded face-fill pass is skipped so
251    /// only edges draw (the CAD wireframe look; back edges show through). Does
252    /// NOT affect picking (CPU ray-based) or the overlay pass.
253    pub wireframe: bool,
254    /// Draw the shaded FACES (R14 companion): false leaves the model as its
255    /// edges and vertices alone. Independent of [`Self::wireframe`], which
256    /// swaps the shaded fill for the triangle wireframe — with faces off there
257    /// is nothing to swap, so both face passes are skipped.
258    ///
259    /// A DISPLAY switch only: picking is CPU ray-based and unaffected, so a
260    /// hidden face still selects. This exists so a presentation capture (and
261    /// the toolbar's three visibility toggles) can drop a whole class of
262    /// geometry without editing the size settings that describe how the class
263    /// is DRAWN — a zeroed `edgeWidthPx` is not "no edges", it is a
264    /// zero-width edge the user has to restore by remembering the old number.
265    pub show_faces: bool,
266    /// Draw the EDGES (both the visible pass and the dimmed occluded one).
267    /// See [`Self::show_faces`] for why this is not `edgeWidthPx = 0`.
268    pub show_edges: bool,
269    /// Draw the VERTEX points. See [`Self::show_faces`].
270    pub show_vertices: bool,
271    /// World-axis helper (R20): screen length in CSS px; 0 disables.
272    pub axis_length_px: f32,
273    /// On-screen edge length of the always-on corner ViewCube, in CSS px. Drives
274    /// BOTH the rendered mini-camera viewport AND the hit-test corner rect (they
275    /// read the same value), so the cube and its clickable region scale together.
276    /// Defaults to [`ViewCube::DEFAULT_SIZE_PX`], so the cube is unchanged until edited.
277    pub viewcube_size_px: f32,
278    pub pick_double_sided: bool,
279    /// How a plain viewport click builds a multi-selection (see [`MultiSelectMode`]).
280    pub multi_select: MultiSelectMode,
281    /// Tessellation LOD factor (1.0 = the app's "Normal" preset).
282    pub lod_factor: f64,
283    // --- Sketcher overlay palette (managed here like every other display color) ---
284    // Defaults come from `SketchColors::default()` (the single source of the
285    // literals); `sketch_colors()` re-derives a `SketchColors` view for the
286    // tessellation/overlay builders.
287    pub sketch_movable_color: Rgba,
288    pub sketch_locked_color: Rgba,
289    pub sketch_geometry_color: Rgba,
290    pub sketch_point_color: Rgba,
291    pub sketch_construction_point_color: Rgba,
292    pub sketch_under_constrained_point_color: Rgba,
293    pub sketch_selected_color: Rgba,
294    pub sketch_hovered_color: Rgba,
295    pub sketch_preview_color: Rgba,
296    pub sketch_constraint_color: Rgba,
297    pub sketch_conflict_color: Rgba,
298    /// The active UI WORKBENCH id (`"all"` / `"modeling"` / `"sheetMetal"`), a
299    /// plain string (NOT an enum) so the app-side per-file workbench registry
300    /// stays the sole owner of the valid-id set — adding a workbench never touches
301    /// this crate. This is purely a UI FILTER over feature-CREATION: it does not
302    /// affect what the history executes or renders. Default `"modeling"`. An
303    /// unknown stored id is tolerated here and validated app-side (the registry's
304    /// resolver falls back to the default).
305    pub workbench: String,
306    /// Assembly AUTO-SOLVE: when true (the default) every constraint mutation
307    /// re-solves + re-runs immediately; when false the mutation paths only
308    /// update state and the user drives the manual Solve button. Consulted by
309    /// the app's constraint-mutation path.
310    pub assembly_auto_solve: bool,
311    /// Show Constraint Graphics: the render toggle the viewport overlay lane
312    /// consumes — per-constraint leader/label graphics draw only while this is
313    /// on. Owned here so the panel toggle, persistence, and the overlay
314    /// renderer all read ONE flag.
315    pub show_constraint_graphics: bool,
316    /// The BOM's COLUMN CONFIGURATION — the raw text of the Settings panel's
317    /// Assemblies textarea (one `[*]prefix.Field` per line). Stored VERBATIM,
318    /// exactly as the user typed it: parsing, the known-field catalogue and the
319    /// `part.` / `occurrence.` vocabulary all live app-side
320    /// (`panels::bom_columns`), so adding a BOM field never touches this crate
321    /// — the same division of labour that keeps `workbench` a plain string here.
322    ///
323    /// Default EMPTY, which means "the app's shipped default configuration".
324    /// A document that was never configured therefore persists byte-for-byte as
325    /// before, and a later change to the shipped default still reaches every
326    /// user who never overrode it.
327    pub bom_columns: String,
328}
329
330impl Default for RenderSettings {
331    fn default() -> Self {
332        let sk = SketchColors::default();
333        Self {
334            // Default to Auto so the chrome follows the OS light/dark preference
335            // (egui's `ThemePreference::System`; falls back to dark when there is
336            // no OS signal).
337            theme: ThemeMode::Auto,
338            // 1.0 = native UI size (no zoom); scales the whole egui chrome.
339            ui_scale: 1.0,
340            disable_recovery_prompt: false,
341            // 1.0 = the labels' native monospace size (no scaling).
342            label_scale: 1.0,
343            // Debug grab-handle outlines are off by default (a diagnostic aid).
344            debug_grab_handles: false,
345            background: [
346                ((0x0b) as f32) / 255.0,
347                ((0x0d) as f32) / 255.0,
348                ((0x10) as f32) / 255.0,
349            ],
350            face_color_mode: FaceColorMode::Uniform,
351            face_color: hex(0x00009e, 1.0),
352            face_selected_color: hex(0xffc400, 1.0),
353            hover_color: hex(0xfbff00, 1.0),
354            edge_color: hex(0x009dff, 1.0),
355            edge_selected_color: hex(0xff00ff, 1.0),
356            edge_width_px: 2.0,
357            show_occluded_edges: true,
358            hidden_edge_alpha: 0.22,
359            vertex_color: hex(0x4aff03, 1.0),
360            vertex_selected_color: hex(0x00ffff, 1.0),
361            vertex_size_px: 6.0,
362            flat_shading: false,
363            wireframe: false,
364            // Everything visible: the three toggles are a subtractive control.
365            show_faces: true,
366            show_edges: true,
367            show_vertices: true,
368            override_model_colors: false,
369            show_workbench_toolbar: true,
370            toolbar_style: ToolbarStyle::Ribbon,
371            axis_length_px: 46.0,
372            // The corner ViewCube's current on-screen size — the single source of
373            // the literal is `ViewCube::DEFAULT_SIZE_PX`, so the settings default and
374            // the widget default can never drift.
375            viewcube_size_px: brep_gizmos::view_cube::ViewCube::DEFAULT_SIZE_PX,
376            pick_double_sided: true,
377            multi_select: MultiSelectMode::ClickToggles,
378            lod_factor: 1.0,
379            // Sketch palette: derive each Rgba from the ONE source of the literals
380            // (`SketchColors::default`) so nothing changes visually until edited.
381            sketch_movable_color: hex(sk.movable, 1.0),
382            sketch_locked_color: hex(sk.locked, 1.0),
383            sketch_geometry_color: hex(sk.geometry, 1.0),
384            sketch_point_color: hex(sk.point, 1.0),
385            sketch_construction_point_color: hex(sk.construction_point, 1.0),
386            sketch_under_constrained_point_color: hex(sk.under_constrained_point, 1.0),
387            sketch_selected_color: hex(sk.selected, 1.0),
388            sketch_hovered_color: hex(sk.hovered, 1.0),
389            sketch_preview_color: hex(sk.preview, 1.0),
390            sketch_constraint_color: hex(sk.constraint, 1.0),
391            sketch_conflict_color: hex(sk.conflict, 1.0),
392            // Default workbench: general Modeling.
393            workbench: "modeling".to_string(),
394            // Assembly: auto-solve every constraint mutation; constraint
395            // graphics shown while a document has constraints.
396            assembly_auto_solve: true,
397            show_constraint_graphics: true,
398            // Empty = the app's shipped BOM column configuration.
399            bom_columns: String::new(),
400        }
401    }
402}
403
404impl RenderSettings {
405    /// The artifact-corpus preset: byte-faithful to the slice-1 artifact look
406    /// (per-solid hashed colors, 0x101418 background, 1.6px edges in
407    /// 0x0d1030, no hidden-edge pass, no vertices, no axes).
408    pub fn artifact() -> Self {
409        Self {
410            background: [
411                ((0x10) as f32) / 255.0,
412                ((0x14) as f32) / 255.0,
413                ((0x18) as f32) / 255.0,
414            ],
415            face_color_mode: FaceColorMode::HashedBySolid,
416            edge_color: hex(0x0d1030, 1.0),
417            edge_width_px: 1.6,
418            hidden_edge_alpha: 0.0,
419            vertex_size_px: 0.0,
420            axis_length_px: 0.0,
421            ..Self::default()
422        }
423    }
424
425    /// Apply a partial JSON override (R3 settings entrypoint). Unknown keys
426    /// are ignored; colors are CSS hex strings.
427    pub fn apply_json(&mut self, json: &str) -> Result<(), String> {
428        let value: serde_json::Value =
429            serde_json::from_str(json).map_err(|error| format!("settings parse: {error}"))?;
430        let color = |key: &str, target: &mut Rgba| {
431            if let Some(v) = value.get(key).and_then(|v| v.as_str()) {
432                if let Some(rgb) = parse_css_hex(v) {
433                    target[0] = rgb[0];
434                    target[1] = rgb[1];
435                    target[2] = rgb[2];
436                }
437            }
438        };
439        color("faceColor", &mut self.face_color);
440        color("faceSelectedColor", &mut self.face_selected_color);
441        color("hoverColor", &mut self.hover_color);
442        color("edgeColor", &mut self.edge_color);
443        color("edgeSelectedColor", &mut self.edge_selected_color);
444        color("vertexColor", &mut self.vertex_color);
445        color("vertexSelectedColor", &mut self.vertex_selected_color);
446        // Sketcher overlay palette (same CSS-hex shape as the face/edge/vertex colors).
447        color("sketchMovableColor", &mut self.sketch_movable_color);
448        color("sketchLockedColor", &mut self.sketch_locked_color);
449        color("sketchGeometryColor", &mut self.sketch_geometry_color);
450        color("sketchPointColor", &mut self.sketch_point_color);
451        color("sketchConstructionPointColor", &mut self.sketch_construction_point_color);
452        color("sketchUnderConstrainedPointColor", &mut self.sketch_under_constrained_point_color);
453        color("sketchSelectedColor", &mut self.sketch_selected_color);
454        color("sketchHoveredColor", &mut self.sketch_hovered_color);
455        color("sketchPreviewColor", &mut self.sketch_preview_color);
456        color("sketchConstraintColor", &mut self.sketch_constraint_color);
457        color("sketchConflictColor", &mut self.sketch_conflict_color);
458        if let Some(v) = value.get("background").and_then(|v| v.as_str()) {
459            if let Some(rgb) = parse_css_hex(v) {
460                self.background = rgb;
461            }
462        }
463        if let Some(v) = value.get("edgeWidthPx").and_then(|v| v.as_f64()) {
464            self.edge_width_px = (v as f32).clamp(0.0, 32.0);
465        }
466        if let Some(v) = value.get("vertexSizePx").and_then(|v| v.as_f64()) {
467            self.vertex_size_px = (v as f32).clamp(0.0, 64.0);
468        }
469        if let Some(v) = value.get("showOccludedEdges").and_then(|v| v.as_bool()) {
470            self.show_occluded_edges = v;
471        }
472        if let Some(v) = value.get("hiddenEdgeAlpha").and_then(|v| v.as_f64()) {
473            self.hidden_edge_alpha = (v as f32).clamp(0.0, 1.0);
474        }
475        if let Some(v) = value.get("faceColorMode").and_then(|v| v.as_str()) {
476            match v.trim().to_ascii_lowercase().as_str() {
477                "hashedbysolid" | "hashed" => self.face_color_mode = FaceColorMode::HashedBySolid,
478                "uniform" => self.face_color_mode = FaceColorMode::Uniform,
479                _ => {}
480            }
481        }
482        if let Some(v) = value.get("theme").and_then(|v| v.as_str()) {
483            match v.trim().to_ascii_lowercase().as_str() {
484                "auto" => self.theme = ThemeMode::Auto,
485                "light" => self.theme = ThemeMode::Light,
486                "dark" => self.theme = ThemeMode::Dark,
487                _ => {}
488            }
489        }
490        if let Some(v) = value.get("uiScale").and_then(|v| v.as_f64()) {
491            self.ui_scale = (v as f32).clamp(0.5, 3.0);
492        }
493        if let Some(v) = value.get("disableRecoveryPrompt").and_then(|v| v.as_bool()) {
494            self.disable_recovery_prompt = v;
495        }
496        // Model-overlay label size. Clamped to the SAME [0.25, 3.0] domain the
497        // settings slider offers, so a persisted value never silently re-clamps on
498        // reload (the `viewcubeSizePx` rule).
499        if let Some(v) = value.get("labelScale").and_then(|v| v.as_f64()) {
500            self.label_scale = (v as f32).clamp(0.25, 3.0);
501        }
502        if let Some(v) = value.get("debugGrabHandles").and_then(|v| v.as_bool()) {
503            self.debug_grab_handles = v;
504        }
505        if let Some(v) = value.get("flatShading").and_then(|v| v.as_bool()) {
506            self.flat_shading = v;
507        }
508        if let Some(v) = value.get("wireframe").and_then(|v| v.as_bool()) {
509            self.wireframe = v;
510        }
511        if let Some(v) = value.get("showFaces").and_then(|v| v.as_bool()) {
512            self.show_faces = v;
513        }
514        if let Some(v) = value.get("showEdges").and_then(|v| v.as_bool()) {
515            self.show_edges = v;
516        }
517        if let Some(v) = value.get("showVertices").and_then(|v| v.as_bool()) {
518            self.show_vertices = v;
519        }
520        if let Some(v) = value.get("overrideModelColors").and_then(|v| v.as_bool()) {
521            self.override_model_colors = v;
522        }
523        if let Some(v) = value.get("toolbarStyle").and_then(|v| v.as_str()) {
524            self.toolbar_style = match v {
525                "Ribbon" => ToolbarStyle::Ribbon,
526                "Classic" => ToolbarStyle::Classic,
527                _ => return Err(format!("unknown toolbar style: {v}")),
528            };
529        }
530        if let Some(v) = value.get("showWorkbenchToolbar").and_then(|v| v.as_bool()) {
531            self.show_workbench_toolbar = v;
532        }
533        if let Some(v) = value.get("axisLengthPx").and_then(|v| v.as_f64()) {
534            self.axis_length_px = (v as f32).clamp(0.0, 512.0);
535        }
536        // ViewCube corner size — clamp to the SAME [40, 230] domain the settings
537        // slider offers, so a persisted value never silently re-clamps on reload.
538        if let Some(v) = value.get("viewcubeSizePx").and_then(|v| v.as_f64()) {
539            self.viewcube_size_px = (v as f32).clamp(40.0, 230.0);
540        }
541        if let Some(v) = value.get("pickDoubleSided").and_then(|v| v.as_bool()) {
542            self.pick_double_sided = v;
543        }
544        // The multi-select mode dropdown serializes its human label (the
545        // renderQuality pattern); match on the alphanumeric skeleton so
546        // "Ctrl+Click" / "ctrlClick" / "CTRL CLICK" all parse.
547        if let Some(v) = value.get("multiSelect").and_then(|v| v.as_str()) {
548            let skeleton: String = v
549                .chars()
550                .filter(|c| c.is_ascii_alphanumeric())
551                .collect::<String>()
552                .to_ascii_lowercase();
553            match skeleton.as_str() {
554                "ctrlclick" => self.multi_select = MultiSelectMode::CtrlClick,
555                "clicktoggles" => self.multi_select = MultiSelectMode::ClickToggles,
556                _ => {}
557            }
558        }
559        // The active UI workbench id (a plain string; the app validates it against
560        // its registry). Stored verbatim — an unknown id is tolerated here.
561        if let Some(v) = value.get("workbench").and_then(|v| v.as_str()) {
562            self.workbench = v.to_string();
563        }
564        if let Some(v) = value.get("assemblyAutoSolve").and_then(|v| v.as_bool()) {
565            self.assembly_auto_solve = v;
566        }
567        // The BOM column configuration, verbatim (see the field docs) — never
568        // normalized here, so a malformed line survives a save/reload and the
569        // panel can still point at the line the user has to fix.
570        if let Some(v) = value.get("bomColumns").and_then(|v| v.as_str()) {
571            self.bom_columns = v.to_string();
572        }
573        if let Some(v) = value.get("showConstraintGraphics").and_then(|v| v.as_bool()) {
574            self.show_constraint_graphics = v;
575        }
576        // "Render Quality" is a named dropdown (Draft…Ultra) mapping to the display
577        // LOD factor (higher quality = finer mesh = smaller factor). We store the
578        // resolved f64 so the tessellation path is unchanged.
579        if let Some(label) = value.get("renderQuality").and_then(|v| v.as_str()) {
580            if let Some(lod) = lod_from_quality(label) {
581                self.lod_factor = lod;
582            }
583        }
584        Ok(())
585    }
586
587    /// Serialize EVERY setting to the SAME camelCase / CSS-hex shape
588    /// [`apply_json`] reads, so `s.apply_json(&s.to_json())` is the identity.
589    /// This is the counterpart the settings schema serializes/persists through
590    /// (there was previously no serializer, only the partial-override reader).
591    pub fn to_json(&self) -> String {
592        serde_json::json!({
593            "theme": match self.theme {
594                ThemeMode::Auto => "auto",
595                ThemeMode::Light => "light",
596                ThemeMode::Dark => "dark",
597            },
598            "uiScale": self.ui_scale as f64,
599            "disableRecoveryPrompt": self.disable_recovery_prompt,
600            "labelScale": self.label_scale as f64,
601            "debugGrabHandles": self.debug_grab_handles,
602            "background": rgb_to_css_hex(self.background),
603            "faceColorMode": match self.face_color_mode {
604                FaceColorMode::Uniform => "uniform",
605                FaceColorMode::HashedBySolid => "hashedBySolid",
606            },
607            "faceColor": rgba_to_css_hex(self.face_color),
608            "faceSelectedColor": rgba_to_css_hex(self.face_selected_color),
609            "hoverColor": rgba_to_css_hex(self.hover_color),
610            "edgeColor": rgba_to_css_hex(self.edge_color),
611            "edgeSelectedColor": rgba_to_css_hex(self.edge_selected_color),
612            "edgeWidthPx": self.edge_width_px as f64,
613            "showOccludedEdges": self.show_occluded_edges,
614            "hiddenEdgeAlpha": self.hidden_edge_alpha as f64,
615            "vertexColor": rgba_to_css_hex(self.vertex_color),
616            "vertexSelectedColor": rgba_to_css_hex(self.vertex_selected_color),
617            "vertexSizePx": self.vertex_size_px as f64,
618            "flatShading": self.flat_shading,
619            "wireframe": self.wireframe,
620            "showFaces": self.show_faces,
621            "showEdges": self.show_edges,
622            "showVertices": self.show_vertices,
623            "overrideModelColors": self.override_model_colors,
624            "showWorkbenchToolbar": self.show_workbench_toolbar,
625            "toolbarStyle": self.toolbar_style.as_str(),
626            "axisLengthPx": self.axis_length_px as f64,
627            "viewcubeSizePx": self.viewcube_size_px as f64,
628            "pickDoubleSided": self.pick_double_sided,
629            "multiSelect": self.multi_select.label(),
630            "renderQuality": quality_from_lod(self.lod_factor),
631            "sketchMovableColor": rgba_to_css_hex(self.sketch_movable_color),
632            "sketchLockedColor": rgba_to_css_hex(self.sketch_locked_color),
633            "sketchGeometryColor": rgba_to_css_hex(self.sketch_geometry_color),
634            "sketchPointColor": rgba_to_css_hex(self.sketch_point_color),
635            "sketchConstructionPointColor": rgba_to_css_hex(self.sketch_construction_point_color),
636            "sketchUnderConstrainedPointColor": rgba_to_css_hex(self.sketch_under_constrained_point_color),
637            "sketchSelectedColor": rgba_to_css_hex(self.sketch_selected_color),
638            "sketchHoveredColor": rgba_to_css_hex(self.sketch_hovered_color),
639            "sketchPreviewColor": rgba_to_css_hex(self.sketch_preview_color),
640            "sketchConstraintColor": rgba_to_css_hex(self.sketch_constraint_color),
641            "sketchConflictColor": rgba_to_css_hex(self.sketch_conflict_color),
642            "workbench": self.workbench,
643            "assemblyAutoSolve": self.assembly_auto_solve,
644            "showConstraintGraphics": self.show_constraint_graphics,
645            "bomColumns": self.bom_columns,
646        })
647        .to_string()
648    }
649
650    /// The live [`SketchColors`] view of the sketcher palette — the tessellation /
651    /// overlay builders read their colors from THIS (via
652    /// [`crate::sketch::SketchSession::colors`]) so the display settings are the one
653    /// source of truth. Each `Rgba` is quantized back to `0xRRGGBB` the SAME way
654    /// [`rgb_to_css_hex`] serializes it, so a default settings value round-trips to
655    /// the default `SketchColors` byte-exact.
656    pub fn sketch_colors(&self) -> SketchColors {
657        SketchColors {
658            movable: rgba_to_u32(self.sketch_movable_color),
659            locked: rgba_to_u32(self.sketch_locked_color),
660            geometry: rgba_to_u32(self.sketch_geometry_color),
661            point: rgba_to_u32(self.sketch_point_color),
662            construction_point: rgba_to_u32(self.sketch_construction_point_color),
663            under_constrained_point: rgba_to_u32(self.sketch_under_constrained_point_color),
664            selected: rgba_to_u32(self.sketch_selected_color),
665            hovered: rgba_to_u32(self.sketch_hovered_color),
666            preview: rgba_to_u32(self.sketch_preview_color),
667            constraint: rgba_to_u32(self.sketch_constraint_color),
668            conflict: rgba_to_u32(self.sketch_conflict_color),
669        }
670    }
671
672    /// The settings schema WITH the current value baked into each field, as JSON
673    /// — mirrors the kernel's `feature_schemas_json` export so a UI shell (egui
674    /// here, a later `brep-ui` crate) can generate the whole form from data. The
675    /// `value` of each field is pulled live from [`to_json`], so the export
676    /// always reflects the current settings.
677    pub fn settings_schema_json(&self) -> String {
678        let current: serde_json::Value =
679            serde_json::from_str(&self.to_json()).unwrap_or(serde_json::Value::Null);
680        let fields: Vec<serde_json::Value> = settings_schema()
681            .iter()
682            .map(|field| {
683                let kind = match &field.kind {
684                    FieldKind::Color => serde_json::json!({ "type": "color" }),
685                    FieldKind::Bool => serde_json::json!({ "type": "bool" }),
686                    FieldKind::Enum { variants } => {
687                        serde_json::json!({ "type": "enum", "variants": variants })
688                    }
689                    FieldKind::Number { min, max, step } => serde_json::json!({
690                        "type": "number", "min": min, "max": max, "step": step
691                    }),
692                    FieldKind::Range { min, max, step } => serde_json::json!({
693                        "type": "range", "min": min, "max": max, "step": step
694                    }),
695                    // The feature-dialog kinds never appear in the settings
696                    // schema, but the match must stay exhaustive.
697                    FieldKind::Scalar { step } => {
698                        serde_json::json!({ "type": "scalar", "step": step })
699                    }
700                    FieldKind::BoundedScalar { min, max, step } => serde_json::json!({
701                        "type": "scalar", "min": min, "max": max, "step": step
702                    }),
703                    FieldKind::Text { read_only } => {
704                        serde_json::json!({ "type": "text", "readOnly": read_only })
705                    }
706                    FieldKind::Vec3 { step } => serde_json::json!({ "type": "vec3", "step": step }),
707                    FieldKind::Reference { filter, multiple } => serde_json::json!({
708                        "type": "reference", "filter": filter, "multiple": multiple
709                    }),
710                    FieldKind::Button { label } => {
711                        serde_json::json!({ "type": "button", "label": label })
712                    }
713                };
714                serde_json::json!({
715                    "key": field.key,
716                    "label": field.label,
717                    "group": field.group,
718                    "kind": kind,
719                    "value": current.get(field.key),
720                })
721            })
722            .collect();
723        serde_json::json!({ "fields": fields }).to_string()
724    }
725}
726
727/// Quantize an sRGB channel triple to a `#rrggbb` CSS hex string (the shape
728/// [`RenderSettings::apply_json`] parses back).
729fn rgb_to_css_hex(rgb: [f32; 3]) -> String {
730    format!("#{:06x}", rgba_to_u32([rgb[0], rgb[1], rgb[2], 1.0]))
731}
732
733/// Like [`rgb_to_css_hex`] but for an `Rgba` (the alpha is intentionally dropped
734/// — `apply_json` only overrides the rgb channels, preserving existing alpha).
735fn rgba_to_css_hex(rgba: Rgba) -> String {
736    rgb_to_css_hex([rgba[0], rgba[1], rgba[2]])
737}
738
739/// Clamp and round sRGB channels to packed `0xRRGGBB`, dropping alpha.
740/// Shared by CSS serialization and the sketch palette.
741fn rgba_to_u32(rgba: Rgba) -> u32 {
742    let q = |c: f32| (c.clamp(0.0, 1.0) * 255.0).round() as u32;
743    (q(rgba[0]) << 16) | (q(rgba[1]) << 8) | q(rgba[2])
744}
745
746/// The kind of one settings field — the closed set of widget shapes the generic
747/// form renderer knows how to emit. Plain data, NO egui dependency: the schema
748/// lives in the engine, the renderer (brep-app / a later brep-ui) walks it.
749#[derive(Debug, Clone, PartialEq)]
750pub enum FieldKind {
751    /// An sRGB color (`#rrggbb`) → a color picker button.
752    Color,
753    /// A boolean toggle → a checkbox.
754    Bool,
755    /// A closed choice → a combo box. `variants` are the JSON string values
756    /// (exactly what `apply_json` accepts / `to_json` emits).
757    Enum { variants: Vec<String> },
758    /// A bounded number → a slider / drag-value honoring `min`/`max`/`step`.
759    Number { min: f64, max: f64, step: f64 },
760    /// A 0..1 (or otherwise fractional) number → a slider honoring the bounds.
761    Range { min: f64, max: f64, step: f64 },
762    // --- extra kinds the FEATURE dialogs need (settings never use these) -------
763    /// An UNBOUNDED number (feature params carry no min/max) → a drag value.
764    Scalar { step: f64 },
765    /// A scalar text field whose numeric edits are bounded on commit. Drawing
766    /// the field never clamps or quantizes its existing value.
767    BoundedScalar { min: f64, max: f64, step: f64 },
768    /// A single-line text edit. `read_only` protects identity fields whose
769    /// renaming must also update references.
770    Text { read_only: bool },
771    /// A 3-vector (position / rotationEuler / scale) → three drag values.
772    Vec3 { step: f64 },
773    /// A reference-selection field for viewport picking. `filter` limits entity
774    /// kinds (e.g. `["SOLID"]`); `multiple` allows a list of selections.
775    Reference { filter: Vec<String>, multiple: bool },
776    /// An ACTION button (schema `"type":"button"`) → a clickable button. It binds
777    /// to no value; a click is surfaced to the caller by the field `key` (e.g.
778    /// `editSketch`), which the host acts on. `label` is the button caption.
779    Button { label: String },
780}
781
782/// One field of the settings form: the camelCase `apply_json`/`to_json` key, a
783/// human label, a UI group, and the widget `kind`. The ordered list of these
784/// (see [`settings_schema`]) fully describes the form — a UI shell generates a
785/// widget per field with no per-field code.
786#[derive(Debug, Clone)]
787pub struct SettingsField {
788    /// The camelCase key — the SAME one `apply_json`/`to_json` use.
789    pub key: &'static str,
790    pub label: &'static str,
791    pub group: &'static str,
792    pub kind: FieldKind,
793}
794
795/// The GENERAL form field — the schema element ONE form engine renders for BOTH
796/// the display-settings dialog AND the schema-driven feature dialogs. Unlike
797/// [`SettingsField`] (which uses `&'static str` because the settings schema is
798/// compile-time), this owns its strings so it can carry a per-feature schema
799/// pulled from the kernel catalogue at run time, and it carries a `path` (a
800/// chain of JSON object keys) so a field can bind to a NESTED value —
801/// `["transform","position"]`, `["boolean","operation"]` — not just a top-level
802/// key. The settings form is `path == [key]`.
803#[derive(Debug, Clone)]
804pub struct FormField {
805    /// JSON object-key chain into the document the form edits (≥ 1 segment).
806    pub path: Vec<String>,
807    pub label: String,
808    pub group: String,
809    pub kind: FieldKind,
810}
811
812impl FormField {
813    /// The last path segment — a stable per-field id for egui salting / probing.
814    pub fn key(&self) -> &str {
815        self.path.last().map(String::as_str).unwrap_or("")
816    }
817}
818
819/// The "Render Quality" dropdown levels shown in Settings, each mapped to a
820/// display-tessellation LOD factor. Higher quality = finer mesh = SMALLER factor
821/// (chord tolerance = extent · 1.5e-3 · factor). Order is coarse→fine, the order
822/// the ComboBox lists them. `lod_factor` stays the internal representation the
823/// tessellation path reads; only the SETTINGS UI/serialization speaks in levels.
824pub const RENDER_QUALITY: &[(&str, f64)] = &[
825    ("Draft", 4.0),
826    ("Low", 2.0),
827    ("Medium", 1.0),
828    ("High", 0.5),
829    ("Ultra", 0.25),
830];
831
832/// The LOD factor for a quality label (`None` if not a known level).
833fn lod_from_quality(label: &str) -> Option<f64> {
834    RENDER_QUALITY
835        .iter()
836        .find(|(name, _)| *name == label)
837        .map(|(_, factor)| *factor)
838}
839
840/// The quality label NEAREST a LOD factor — the serialization inverse of
841/// [`lod_from_quality`]. A stored factor is always one of the level values in
842/// normal use; nearest-match keeps a hand-set/legacy value mapping to a sane label.
843fn quality_from_lod(lod: f64) -> &'static str {
844    RENDER_QUALITY
845        .iter()
846        .min_by(|(_, a), (_, b)| {
847            (a - lod).abs().total_cmp(&(b - lod).abs())
848        })
849        .map(|(name, _)| *name)
850        .unwrap_or("Medium")
851}
852
853/// Lift the compile-time display-settings schema into general [`FormField`]s so
854/// the ONE `field_input` engine (which the feature dialogs also use) renders the
855/// settings panel too — a single schema-driven dialog engine, not two.
856pub fn settings_form_fields() -> Vec<FormField> {
857    settings_schema()
858        .into_iter()
859        .map(|field| FormField {
860            path: vec![field.key.to_string()],
861            label: field.label.to_string(),
862            group: field.group.to_string(),
863            kind: field.kind,
864        })
865        .collect()
866}
867
868/// The Rust-owned settings schema: the ordered list of display-settings fields,
869/// grouped, analogous to the kernel feature schemas. Adding a field here (plus
870/// its `apply_json`/`to_json` handling) makes the whole UI grow a widget for it
871/// with ZERO renderer changes.
872pub fn settings_schema() -> Vec<SettingsField> {
873    let f = |key, label, group, kind| SettingsField { key, label, group, kind };
874    vec![
875        // --- Appearance ----------------------------------------------------
876        // FIRST so the "Appearance" group renders at the TOP of the settings tree
877        // (groups are ordered by first field appearance). The GUI-chrome theme —
878        // NOT the 3D viewport background (that lives under Scene).
879        f(
880            "theme",
881            "Theme",
882            "Appearance",
883            FieldKind::Enum { variants: ["auto", "light", "dark"].iter().map(|s| s.to_string()).collect() },
884        ),
885        // A SLIDER (both `Range` and `Number` render an `egui::Slider` over the
886        // given domain) scaling the whole egui UI via `Context::set_zoom_factor`.
887        f(
888            "uiScale",
889            "UI scale",
890            "Appearance",
891            FieldKind::Range { min: 0.5, max: 3.0, step: 0.05 },
892        ),
893        // The size of the floating text labels overlaid on the MODEL (dimension
894        // value chips, constraint chips, gizmo axis letters) — a multiplier over
895        // their base monospace size, NOT a point size. Bounds MATCH the
896        // `apply_json` clamp so the slider can't set a value that re-clamps on
897        // reload. The 0.25 floor (a quarter of the base, on the 0.05 step) is the
898        // smallest chip whose click/drag target a pointer can still land on — see
899        // `RenderSettings::label_scale`. Separate from `uiScale`, which sizes the
900        // egui chrome.
901        f(
902            "labelScale",
903            "Label scale",
904            "Appearance",
905            FieldKind::Range { min: 0.25, max: 3.0, step: 0.05 },
906        ),
907        // The workbench actions toolbar (the feature-button strip under the
908        // primary toolbar). Chrome, so it sits with the other chrome settings.
909        f(
910            "showWorkbenchToolbar",
911            "Show workbench actions toolbar",
912            "Appearance",
913            FieldKind::Bool,
914        ),
915        f("toolbarStyle", "Toolbar style", "Appearance",
916          FieldKind::Enum { variants: ["Ribbon", "Classic"].iter().map(|s| s.to_string()).collect() }),
917        // --- Startup -------------------------------------------------------
918        f(
919            "disableRecoveryPrompt",
920            "Disable recovery dialog on startup",
921            "Startup",
922            FieldKind::Bool,
923        ),
924        // --- Scene ---------------------------------------------------------
925        f("background", "Background", "Scene", FieldKind::Color),
926        f(
927            "axisLengthPx",
928            "Axis length (px)",
929            "Scene",
930            FieldKind::Number { min: 0.0, max: 512.0, step: 1.0 },
931        ),
932        // The corner ViewCube's on-screen size. Bounds MATCH the `apply_json` clamp
933        // ([40, 230], centered on the 135px default) so the slider can't set a value
934        // that re-clamps on reload. Renders as an `egui::Slider`.
935        f(
936            "viewcubeSizePx",
937            "ViewCube size (px)",
938            "Scene",
939            FieldKind::Number { min: 40.0, max: 230.0, step: 1.0 },
940        ),
941        f(
942            "renderQuality",
943            "Render Quality",
944            "Scene",
945            FieldKind::Enum { variants: RENDER_QUALITY.iter().map(|(label, _)| label.to_string()).collect() },
946        ),
947        // --- Faces ---------------------------------------------------------
948        f(
949            "faceColorMode",
950            "Face color mode",
951            "Faces",
952            FieldKind::Enum { variants: ["uniform", "hashedBySolid"].iter().map(|s| s.to_string()).collect() },
953        ),
954        f("faceColor", "Face color", "Faces", FieldKind::Color),
955        f("faceSelectedColor", "Selected face", "Faces", FieldKind::Color),
956        f("hoverColor", "Hover", "Faces", FieldKind::Color),
957        f("flatShading", "Flat shading", "Faces", FieldKind::Bool),
958        f("wireframe", "Wireframe", "Faces", FieldKind::Bool),
959        f("showFaces", "Show faces", "Faces", FieldKind::Bool),
960        f(
961            "overrideModelColors",
962            "Override model colors",
963            "Faces",
964            FieldKind::Bool,
965        ),
966        // --- Edges ---------------------------------------------------------
967        f("showEdges", "Show edges", "Edges", FieldKind::Bool),
968        f("edgeColor", "Edge color", "Edges", FieldKind::Color),
969        f("edgeSelectedColor", "Selected edge", "Edges", FieldKind::Color),
970        f(
971            "edgeWidthPx",
972            "Edge width (px)",
973            "Edges",
974            FieldKind::Number { min: 0.0, max: 32.0, step: 0.1 },
975        ),
976        f("showOccludedEdges", "Show occluded edges", "Edges", FieldKind::Bool),
977        f(
978            "hiddenEdgeAlpha",
979            "Hidden-edge alpha",
980            "Edges",
981            FieldKind::Range { min: 0.0, max: 1.0, step: 0.01 },
982        ),
983        // --- Vertices ------------------------------------------------------
984        f("showVertices", "Show vertices", "Vertices", FieldKind::Bool),
985        f("vertexColor", "Vertex color", "Vertices", FieldKind::Color),
986        f("vertexSelectedColor", "Selected vertex", "Vertices", FieldKind::Color),
987        f(
988            "vertexSizePx",
989            "Vertex size (px)",
990            "Vertices",
991            FieldKind::Number { min: 0.0, max: 64.0, step: 0.5 },
992        ),
993        // --- Picking -------------------------------------------------------
994        f("pickDoubleSided", "Pick double-sided", "Picking", FieldKind::Bool),
995        // How a plain viewport click builds a multi-selection: the classic
996        // Ctrl+Click add, or modifier-free click-toggles (click an item to add
997        // it, click it again to remove it).
998        f(
999            "multiSelect",
1000            "Multi-select",
1001            "Picking",
1002            FieldKind::Enum {
1003                variants: MultiSelectMode::ALL.iter().map(|m| m.label().to_string()).collect(),
1004            },
1005        ),
1006        // --- Sketch --------------------------------------------------------
1007        // The sketcher overlay palette, editable live like every other display
1008        // color. `sketch_colors()` feeds these to the tessellation/overlay builders.
1009        f("sketchMovableColor", "Movable geometry", "Sketch", FieldKind::Color),
1010        f("sketchLockedColor", "Locked geometry", "Sketch", FieldKind::Color),
1011        f("sketchGeometryColor", "Geometry (no mobility)", "Sketch", FieldKind::Color),
1012        f("sketchPointColor", "Point", "Sketch", FieldKind::Color),
1013        f("sketchConstructionPointColor", "Construction point", "Sketch", FieldKind::Color),
1014        f("sketchUnderConstrainedPointColor", "Under-constrained point", "Sketch", FieldKind::Color),
1015        f("sketchSelectedColor", "Selected", "Sketch", FieldKind::Color),
1016        f("sketchHoveredColor", "Hovered", "Sketch", FieldKind::Color),
1017        f("sketchPreviewColor", "Draw preview", "Sketch", FieldKind::Color),
1018        f("sketchConstraintColor", "Constraint / dimension", "Sketch", FieldKind::Color),
1019        f("sketchConflictColor", "Conflicting constraint", "Sketch", FieldKind::Color),
1020        // --- Debug ---------------------------------------------------------
1021        // LAST so the "Debug" group renders at the BOTTOM of the settings tree.
1022        f("debugGrabHandles", "Debug grab handles", "Debug", FieldKind::Bool),
1023    ]
1024}
1025
1026/// A selected/hovered vertex reference: vertices have no kernel names, so they
1027/// resolve by owning solid + position.
1028#[derive(Debug, Clone)]
1029pub struct VertexRef {
1030    pub solid: String,
1031    pub position: [f64; 3],
1032}
1033
1034/// A set of entity NAMES that remembers the order they were ADDED in — the
1035/// selection's pick order.
1036///
1037/// The selection used to be a plain `HashSet`, so which of two picked faces
1038/// came out first was the hash seed's choice and differed between processes.
1039/// That is not cosmetic: an assembly Distance takes element 0 as its BASE face,
1040/// whose outward normal gives the value its sign and the arrow its direction,
1041/// so the same two picks could seed opposite constraints in two runs. Every
1042/// reader of the selection — [`EngineState::selection_json`], the context bar's
1043/// feature offers, the constraint seeder — now sees the picks in the order they
1044/// were made.
1045///
1046/// [`insert`](Self::insert) appends, and a name already in the set keeps its
1047/// place; [`remove`](Self::remove) keeps the rest in order. Toggling a name off
1048/// and on therefore moves it to the END, which is where a re-pick belongs.
1049/// Membership rides in a `HashSet` beside the order, because `contains` is
1050/// called for every face and every edge of every solid, every frame, by the
1051/// emphasis colour feed.
1052#[derive(Debug, Clone, Default, PartialEq, Eq)]
1053pub struct OrderedNames {
1054    order: Vec<String>,
1055    index: HashSet<String>,
1056}
1057
1058impl OrderedNames {
1059    /// Add `name` at the END. Returns whether it was not already there (the
1060    /// `HashSet::insert` contract), and an already-present name does NOT move.
1061    pub fn insert(&mut self, name: String) -> bool {
1062        if !self.index.insert(name.clone()) {
1063            return false;
1064        }
1065        self.order.push(name);
1066        true
1067    }
1068
1069    /// Drop `name`, keeping the order of everything else. Returns whether it
1070    /// was there (the `HashSet::remove` contract).
1071    pub fn remove(&mut self, name: &str) -> bool {
1072        if !self.index.remove(name) {
1073            return false;
1074        }
1075        self.order.retain(|n| n != name);
1076        true
1077    }
1078
1079    pub fn contains(&self, name: &str) -> bool {
1080        self.index.contains(name)
1081    }
1082
1083    pub fn clear(&mut self) {
1084        self.order.clear();
1085        self.index.clear();
1086    }
1087
1088    pub fn len(&self) -> usize {
1089        self.order.len()
1090    }
1091
1092    pub fn is_empty(&self) -> bool {
1093        self.order.is_empty()
1094    }
1095
1096    /// The names in PICK ORDER, oldest first.
1097    pub fn iter(&self) -> std::slice::Iter<'_, String> {
1098        self.order.iter()
1099    }
1100}
1101
1102impl FromIterator<String> for OrderedNames {
1103    fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> Self {
1104        let mut out = Self::default();
1105        for name in iter {
1106            out.insert(name);
1107        }
1108        out
1109    }
1110}
1111
1112impl Extend<String> for OrderedNames {
1113    fn extend<I: IntoIterator<Item = String>>(&mut self, iter: I) {
1114        for name in iter {
1115            self.insert(name);
1116        }
1117    }
1118}
1119
1120impl<'a> IntoIterator for &'a OrderedNames {
1121    type Item = &'a String;
1122    type IntoIter = std::slice::Iter<'a, String>;
1123    fn into_iter(self) -> Self::IntoIter {
1124        self.order.iter()
1125    }
1126}
1127
1128/// The emphasis state (selection + hover), name-keyed like `SelectionFilter`.
1129/// Solid-level emphasis cascades to that solid's faces/edges (the
1130/// `SelectionState._applyToSolid` behavior).
1131#[derive(Debug, Default, Clone)]
1132pub struct Emphasis {
1133    pub selected_solids: OrderedNames,
1134    pub selected_faces: OrderedNames,
1135    pub selected_edges: OrderedNames,
1136    pub selected_vertices: Vec<VertexRef>,
1137    /// Selected construction datum/plane FRAMES, keyed by frame NAME (`{id}:XY`
1138    /// for a DATUM base plane, `{id}` for a PLANE feature). Datums carry no
1139    /// resident geometry, so — like the render-color feed — they emphasize purely
1140    /// by name; a selected datum is re-colored with the selection accent when the
1141    /// engine re-feeds the datum planes.
1142    pub selected_datums: OrderedNames,
1143    pub hovered_solids: HashSet<String>,
1144    pub hovered_faces: HashSet<String>,
1145    pub hovered_edges: HashSet<String>,
1146    pub hovered_vertices: Vec<VertexRef>,
1147    /// HOVERED construction datum/plane FRAMES — the hover twin of
1148    /// [`selected_datums`](Self::selected_datums), keyed the same way. Construction
1149    /// planes are ordinary pick candidates, so the pointer (and a pick-list row)
1150    /// pre-highlights one exactly like a face; the accent is applied when the engine
1151    /// re-feeds the datum planes.
1152    pub hovered_datums: HashSet<String>,
1153    /// Bumped on every change — cache key for derived GPU state.
1154    pub generation: u64,
1155}
1156
1157impl Emphasis {
1158    pub fn is_empty(&self) -> bool {
1159        self.selected_solids.is_empty()
1160            && self.selected_faces.is_empty()
1161            && self.selected_edges.is_empty()
1162            && self.selected_vertices.is_empty()
1163            && self.selected_datums.is_empty()
1164            && self.hovered_solids.is_empty()
1165            && self.hovered_faces.is_empty()
1166            && self.hovered_edges.is_empty()
1167            && self.hovered_vertices.is_empty()
1168            && self.hovered_datums.is_empty()
1169    }
1170
1171    /// Replace the whole emphasis state from the R3 JSON shape:
1172    /// `{selected: {solids, faces, edges, vertices:[{solid,position}]}, hovered: {...}}`.
1173    pub fn apply_json(&mut self, json: &str) -> Result<(), String> {
1174        let value: serde_json::Value =
1175            serde_json::from_str(json).map_err(|error| format!("emphasis parse: {error}"))?;
1176        let names = |group: &serde_json::Value, key: &str| -> HashSet<String> {
1177            crate::json_support::string_values(group.get(key))
1178                .map(str::to_string)
1179                .collect()
1180        };
1181        // The SELECTED buckets keep the order they are given: a saved selection
1182        // comes back in the order it was picked in.
1183        let ordered = |group: &serde_json::Value, key: &str| -> OrderedNames {
1184            crate::json_support::string_values(group.get(key))
1185                .map(str::to_string)
1186                .collect()
1187        };
1188        let vertices = |group: &serde_json::Value| -> Vec<VertexRef> {
1189            group
1190                .get("vertices")
1191                .and_then(|v| v.as_array())
1192                .map(|list| {
1193                    list.iter()
1194                        .filter_map(|v| {
1195                            let solid = v.get("solid")?.as_str()?.to_string();
1196                            let p = v.get("position")?.as_array()?;
1197                            Some(VertexRef {
1198                                solid,
1199                                position: [
1200                                    p.first()?.as_f64()?,
1201                                    p.get(1)?.as_f64()?,
1202                                    p.get(2)?.as_f64()?,
1203                                ],
1204                            })
1205                        })
1206                        .collect()
1207                })
1208                .unwrap_or_default()
1209        };
1210        let empty = serde_json::json!({});
1211        let selected = value.get("selected").unwrap_or(&empty);
1212        let hovered = value.get("hovered").unwrap_or(&empty);
1213        self.selected_solids = ordered(selected, "solids");
1214        self.selected_faces = ordered(selected, "faces");
1215        self.selected_edges = ordered(selected, "edges");
1216        self.selected_datums = ordered(selected, "datums");
1217        self.selected_vertices = vertices(selected);
1218        self.hovered_solids = names(hovered, "solids");
1219        self.hovered_faces = names(hovered, "faces");
1220        self.hovered_edges = names(hovered, "edges");
1221        self.hovered_datums = names(hovered, "datums");
1222        self.hovered_vertices = vertices(hovered);
1223        self.generation = self.generation.wrapping_add(1);
1224        Ok(())
1225    }
1226}
1227
1228/// The visual state of one displayed face/edge (hover wins over selected, the
1229/// `SelectionState` order).
1230#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1231pub enum EmphasisState {
1232    Base,
1233    Selected,
1234    Hovered,
1235}
1236
1237impl Emphasis {
1238    pub fn face_state(&self, solid: &str, face: &str) -> EmphasisState {
1239        if self.hovered_solids.contains(solid) || (!face.is_empty() && self.hovered_faces.contains(face)) {
1240            EmphasisState::Hovered
1241        } else if self.selected_solids.contains(solid)
1242            || (!face.is_empty() && self.selected_faces.contains(face))
1243        {
1244            EmphasisState::Selected
1245        } else {
1246            EmphasisState::Base
1247        }
1248    }
1249
1250    pub fn edge_state(&self, solid: &str, edge: &str) -> EmphasisState {
1251        if self.hovered_solids.contains(solid) || (!edge.is_empty() && self.hovered_edges.contains(edge)) {
1252            EmphasisState::Hovered
1253        } else if self.selected_solids.contains(solid)
1254            || (!edge.is_empty() && self.selected_edges.contains(edge))
1255        {
1256            EmphasisState::Selected
1257        } else {
1258            EmphasisState::Base
1259        }
1260    }
1261
1262    pub fn vertex_state(&self, solid: &str, position: [f64; 3], tol: f64) -> EmphasisState {
1263        let matches = |refs: &[VertexRef]| {
1264            refs.iter().any(|r| {
1265                r.solid == solid
1266                    && (r.position[0] - position[0]).abs() <= tol
1267                    && (r.position[1] - position[1]).abs() <= tol
1268                    && (r.position[2] - position[2]).abs() <= tol
1269            })
1270        };
1271        if matches(&self.hovered_vertices) {
1272            EmphasisState::Hovered
1273        } else if matches(&self.selected_vertices) {
1274            EmphasisState::Selected
1275        } else {
1276            EmphasisState::Base
1277        }
1278    }
1279}
1280
1281