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