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