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