BREP_render 0.2.0

BREP Rust rendering engine: kernel-fed scene store + wgpu renderer (headless artifact, desktop window, and wasm canvas shells).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
//! Render settings (R14 — the `CADmaterials` semantics: per-kind material
//! variants, hover color, flat-shading toggle, user-persisted overrides) and
//! the selection/hover emphasis state (R17/R24 — name-keyed, fed by the host's
//! `SelectionFilter`). Plain data, shared by the engine core and the wgpu
//! renderer; JSON in/out at the R3 boundary.

use std::collections::HashSet;

/// sRGB color in 0..1 + alpha.
pub type Rgba = [f32; 4];

fn hex(hex: u32, alpha: f32) -> Rgba {
    [
        ((hex >> 16) & 0xff) as f32 / 255.0,
        ((hex >> 8) & 0xff) as f32 / 255.0,
        (hex & 0xff) as f32 / 255.0,
        alpha,
    ]
}

/// Parse `#rrggbb` / `#rgb` / `0xrrggbb` (returns None on anything else).
pub fn parse_css_hex(value: &str) -> Option<[f32; 3]> {
    let v = value.trim();
    let digits = v
        .strip_prefix('#')
        .or_else(|| v.strip_prefix("0x"))
        .or_else(|| v.strip_prefix("0X"))?;
    let expand = |c: char| c.to_digit(16).map(|d| (d * 17) as f32 / 255.0);
    match digits.len() {
        3 => {
            let mut chars = digits.chars();
            Some([
                expand(chars.next()?)?,
                expand(chars.next()?)?,
                expand(chars.next()?)?,
            ])
        }
        6 => {
            let n = u32::from_str_radix(digits, 16).ok()?;
            Some([
                ((n >> 16) & 0xff) as f32 / 255.0,
                ((n >> 8) & 0xff) as f32 / 255.0,
                (n & 0xff) as f32 / 255.0,
            ])
        }
        _ => None,
    }
}

/// The sketcher's overlay palette as plain `0xRRGGBB` hex — the ONE place the
/// default color literals live. [`RenderSettings`] stores each of these as an
/// editable [`Rgba`] field (defaults derived from here via [`hex`]) and hands the
/// sketch tessellation/overlay builders a live `SketchColors` view via
/// [`RenderSettings::sketch_colors`], so the sketch renderer reads its colors from
/// the display settings just like faces/edges/vertices do — no scattered constants.
///
/// The `constraint` green is a deliberate user directive (2026-08-22): CONSTRAINT
/// annotations (geometric-constraint glyphs + dimension leaders/labels) read in
/// green so they stand apart from the blue/white sketch GEOMETRY.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SketchColors {
    /// Movable geometry / point (blue).
    pub movable: u32,
    /// Locked geometry / point (near-white).
    pub locked: u32,
    /// No-mobility geometry fallback (yellow).
    pub geometry: u32,
    /// No-mobility point fallback.
    pub point: u32,
    /// Construction point (orange).
    pub construction_point: u32,
    /// Heuristic under-constrained point.
    pub under_constrained_point: u32,
    /// Selected entity — amber (the transform-gizmo accent); beats hover.
    pub selected: u32,
    /// Hovered entity — light blue (brighter than movable).
    pub hovered: u32,
    /// Draw-tool rubber-band preview (dim, so it reads as tentative).
    pub preview: u32,
    /// Constraint annotations — glyphs + dimension leaders/labels (green).
    pub constraint: u32,
}

impl Default for SketchColors {
    fn default() -> Self {
        // The previous sketcher's theme defaults — the single source of these literals.
        Self {
            movable: 0x4aa3ff,
            locked: 0xe6ebf2,
            geometry: 0xffff88,
            point: 0x9ec9ff,
            construction_point: 0xffa86a,
            under_constrained_point: 0xffb347,
            selected: 0xffa500,
            hovered: 0x7fd0ff,
            preview: 0x8fa0b8,
            constraint: 0x4ade80,
        }
    }
}

/// The GUI chrome theme (panels, windows, toolbar, text) — controls the egui
/// look, NOT the 3D viewport background (that is the separate `background`
/// setting). `Auto` follows the OS/system theme (`prefers-color-scheme` on web).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ThemeMode {
    /// Follow the system's theme preference (falls back to dark when no OS signal).
    Auto,
    Light,
    Dark,
}

/// How a plain viewport click builds a MULTI-selection (the Settings "Multi-select"
/// dropdown). Read by the app's viewport click routing — the engine's selection
/// primitives (`select_candidate` replace / `toggle_candidate` toggle) are
/// mode-agnostic; this only chooses which one a plain click drives.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MultiSelectMode {
    /// A plain click REPLACES the selection; Ctrl/Cmd+click adds/toggles (the
    /// classic CAD behavior).
    CtrlClick,
    /// A plain click TOGGLES the item in the selection (click again to unselect)
    /// so a multi-selection needs no modifier key; a click on empty space clears.
    ClickToggles,
}

impl MultiSelectMode {
    /// Every mode, in the order the Settings dropdown lists them.
    pub const ALL: [MultiSelectMode; 2] = [MultiSelectMode::CtrlClick, MultiSelectMode::ClickToggles];

    /// The human label — ALSO the serialized `multiSelect` value (the
    /// renderQuality pattern: the dropdown and the stored JSON speak the label;
    /// `apply_json` parses it back tolerantly).
    pub fn label(&self) -> &'static str {
        match self {
            MultiSelectMode::CtrlClick => "Ctrl+Click",
            MultiSelectMode::ClickToggles => "Click toggles",
        }
    }
}

/// How base face color is chosen per solid.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FaceColorMode {
    /// The app look: every face gets `face_color` (unless the solid carries a
    /// metadata override).
    Uniform,
    /// The artifact look: stable name-hashed color per solid.
    HashedBySolid,
}

/// The viewer's material palette + display toggles. Defaults are the
/// `CADmaterials` values.
#[derive(Debug, Clone, PartialEq)]
pub struct RenderSettings {
    /// GUI chrome theme (egui panels/windows/toolbar/text). Defaults to `Auto`,
    /// following the OS light/dark preference.
    pub theme: ThemeMode,
    /// Global UI size scale applied to the whole egui chrome via
    /// [`egui::Context::set_zoom_factor`]. 1.0 = native size; composes with the
    /// device pixel ratio. Clamped to `[0.5, 3.0]`.
    pub ui_scale: f32,
    /// Size multiplier for the floating TEXT LABELS the app overlays on the 3D
    /// model — the dimension-gizmo value chips (sketch + feature dimensions), the
    /// assembly-constraint chips, and the transform gizmo's axis letters. 1.0 = the
    /// base monospace size; the label's glyphs, its measured edit-box width, and its
    /// chip padding all scale together (see `brep-app`'s `viewport::labels`). A
    /// MULTIPLIER, not a point size, so labels stay consistent with each other and
    /// the setting survives a restyle. Clamped to `[0.25, 3.0]`: 0.25 is the
    /// smallest label that is still a LABEL rather than a smudge — a quarter of the
    /// 12pt base monospace is a ~3.8pt glyph row inside a ~4.5pt-tall chip, which is
    /// the point at which the double-click/drag target stops being something a
    /// pointer can reliably land on (and it composes with `uiScale` + the device
    /// pixel ratio, so it is not an absolute 3pt on screen). The 3.0 ceiling keeps a
    /// user from filling the viewport with one label. Independent of
    /// [`RenderSettings::ui_scale`], which sizes the egui CHROME (panels/toolbar)
    /// and not the model overlay.
    pub label_scale: f32,
    /// Debug overlay: draw the 1px red outline of each gizmo grab handle's hit
    /// region (arrows/leaders as capsules, balls as circles). Off by default;
    /// toggled from Settings to inspect exactly where a drag will grab.
    pub debug_grab_handles: bool,
    pub background: [f32; 3],
    pub face_color_mode: FaceColorMode,
    pub face_color: Rgba,
    pub face_selected_color: Rgba,
    pub hover_color: Rgba,
    pub edge_color: Rgba,
    pub edge_selected_color: Rgba,
    pub edge_width_px: f32,
    /// Occluded edges render dimmed, not dropped (R17): alpha of the
    /// depth-failing edge pass. 0 disables the pass.
    pub hidden_edge_alpha: f32,
    pub vertex_color: Rgba,
    pub vertex_selected_color: Rgba,
    pub vertex_size_px: f32,
    pub flat_shading: bool,
    /// Wireframe display (R14): when true the shaded face-fill pass is skipped so
    /// only edges draw (the CAD wireframe look; back edges show through). Does
    /// NOT affect picking (CPU ray-based) or the overlay pass.
    pub wireframe: bool,
    /// World-axis helper (R20): screen length in CSS px; 0 disables.
    pub axis_length_px: f32,
    /// On-screen edge length of the always-on corner ViewCube, in CSS px. Drives
    /// BOTH the rendered mini-camera viewport AND the hit-test corner rect (they
    /// read the same value), so the cube and its clickable region scale together.
    /// Defaults to [`ViewCube::DEFAULT_SIZE_PX`], so the cube is unchanged until edited.
    pub viewcube_size_px: f32,
    pub pick_double_sided: bool,
    /// How a plain viewport click builds a multi-selection (see [`MultiSelectMode`]).
    pub multi_select: MultiSelectMode,
    /// Tessellation LOD factor (1.0 = the app's "Normal" preset).
    pub lod_factor: f64,
    // --- Sketcher overlay palette (managed here like every other display color) ---
    // Defaults come from `SketchColors::default()` (the single source of the
    // literals); `sketch_colors()` re-derives a `SketchColors` view for the
    // tessellation/overlay builders.
    pub sketch_movable_color: Rgba,
    pub sketch_locked_color: Rgba,
    pub sketch_geometry_color: Rgba,
    pub sketch_point_color: Rgba,
    pub sketch_construction_point_color: Rgba,
    pub sketch_under_constrained_point_color: Rgba,
    pub sketch_selected_color: Rgba,
    pub sketch_hovered_color: Rgba,
    pub sketch_preview_color: Rgba,
    pub sketch_constraint_color: Rgba,
    /// The active UI WORKBENCH id (`"all"` / `"modeling"` / `"sheetMetal"`), a
    /// plain string (NOT an enum) so the app-side per-file workbench registry
    /// stays the sole owner of the valid-id set — adding a workbench never touches
    /// this crate. This is purely a UI FILTER over feature-CREATION: it does not
    /// affect what the history executes or renders. Default `"modeling"`. An
    /// unknown stored id is tolerated here and validated app-side (the registry's
    /// resolver falls back to the default).
    pub workbench: String,
    /// Assembly AUTO-SOLVE (build-spec §6 scheduling): when true (the default)
    /// every constraint mutation re-solves + re-runs immediately; when false the
    /// mutation paths only update state and the user drives the manual Solve
    /// button. Consulted by the app's constraint-mutation path.
    pub assembly_auto_solve: bool,
    /// Show Constraint Graphics (build-spec §8.3/§8.4): the render toggle the
    /// viewport overlay lane consumes — per-constraint leader/label graphics
    /// draw only while this is on. Owned here so the panel toggle, persistence,
    /// and the overlay renderer all read ONE flag.
    pub show_constraint_graphics: bool,
    /// The BOM's COLUMN CONFIGURATION — the raw text of the Settings panel's
    /// Assemblies textarea (one `[*]prefix.Field` per line). Stored VERBATIM,
    /// exactly as the user typed it: parsing, the known-field catalogue and the
    /// `part.` / `occurrence.` vocabulary all live app-side
    /// (`panels::bom_columns`), so adding a BOM field never touches this crate
    /// — the same division of labour that keeps `workbench` a plain string here.
    ///
    /// Default EMPTY, which means "the app's shipped default configuration".
    /// A document that was never configured therefore persists byte-for-byte as
    /// before, and a later change to the shipped default still reaches every
    /// user who never overrode it.
    pub bom_columns: String,
}

impl Default for RenderSettings {
    fn default() -> Self {
        let sk = SketchColors::default();
        Self {
            // Default to Auto so the chrome follows the OS light/dark preference
            // (egui's `ThemePreference::System`; falls back to dark when there is
            // no OS signal).
            theme: ThemeMode::Auto,
            // 1.0 = native UI size (no zoom); scales the whole egui chrome.
            ui_scale: 1.0,
            // 1.0 = the labels' native monospace size (no scaling).
            label_scale: 1.0,
            // Debug grab-handle outlines are off by default (a diagnostic aid).
            debug_grab_handles: false,
            background: [
                ((0x0b) as f32) / 255.0,
                ((0x0d) as f32) / 255.0,
                ((0x10) as f32) / 255.0,
            ],
            face_color_mode: FaceColorMode::Uniform,
            face_color: hex(0x00009e, 1.0),
            face_selected_color: hex(0xffc400, 1.0),
            hover_color: hex(0xfbff00, 1.0),
            edge_color: hex(0x009dff, 1.0),
            edge_selected_color: hex(0xff00ff, 1.0),
            edge_width_px: 2.0,
            hidden_edge_alpha: 0.22,
            vertex_color: hex(0x4aff03, 1.0),
            vertex_selected_color: hex(0x00ffff, 1.0),
            vertex_size_px: 6.0,
            flat_shading: false,
            wireframe: false,
            axis_length_px: 46.0,
            // The corner ViewCube's current on-screen size — the single source of
            // the literal is `ViewCube::DEFAULT_SIZE_PX`, so the settings default and
            // the widget default can never drift.
            viewcube_size_px: brep_gizmos::view_cube::ViewCube::DEFAULT_SIZE_PX,
            pick_double_sided: true,
            multi_select: MultiSelectMode::ClickToggles,
            lod_factor: 1.0,
            // Sketch palette: derive each Rgba from the ONE source of the literals
            // (`SketchColors::default`) so nothing changes visually until edited.
            sketch_movable_color: hex(sk.movable, 1.0),
            sketch_locked_color: hex(sk.locked, 1.0),
            sketch_geometry_color: hex(sk.geometry, 1.0),
            sketch_point_color: hex(sk.point, 1.0),
            sketch_construction_point_color: hex(sk.construction_point, 1.0),
            sketch_under_constrained_point_color: hex(sk.under_constrained_point, 1.0),
            sketch_selected_color: hex(sk.selected, 1.0),
            sketch_hovered_color: hex(sk.hovered, 1.0),
            sketch_preview_color: hex(sk.preview, 1.0),
            sketch_constraint_color: hex(sk.constraint, 1.0),
            // Default workbench: general Modeling.
            workbench: "modeling".to_string(),
            // Assembly: auto-solve every constraint mutation (spec §6 default);
            // constraint graphics shown while a document has constraints.
            assembly_auto_solve: true,
            show_constraint_graphics: true,
            // Empty = the app's shipped BOM column configuration.
            bom_columns: String::new(),
        }
    }
}

impl RenderSettings {
    /// The artifact-corpus preset: byte-faithful to the slice-1 artifact look
    /// (per-solid hashed colors, 0x101418 background, 1.6px edges in
    /// 0x0d1030, no hidden-edge pass, no vertices, no axes).
    pub fn artifact() -> Self {
        Self {
            background: [
                ((0x10) as f32) / 255.0,
                ((0x14) as f32) / 255.0,
                ((0x18) as f32) / 255.0,
            ],
            face_color_mode: FaceColorMode::HashedBySolid,
            edge_color: hex(0x0d1030, 1.0),
            edge_width_px: 1.6,
            hidden_edge_alpha: 0.0,
            vertex_size_px: 0.0,
            axis_length_px: 0.0,
            ..Self::default()
        }
    }

    /// Apply a partial JSON override (R3 settings entrypoint). Unknown keys
    /// are ignored; colors are CSS hex strings.
    pub fn apply_json(&mut self, json: &str) -> Result<(), String> {
        let value: serde_json::Value =
            serde_json::from_str(json).map_err(|error| format!("settings parse: {error}"))?;
        let color = |key: &str, target: &mut Rgba| {
            if let Some(v) = value.get(key).and_then(|v| v.as_str()) {
                if let Some(rgb) = parse_css_hex(v) {
                    target[0] = rgb[0];
                    target[1] = rgb[1];
                    target[2] = rgb[2];
                }
            }
        };
        color("faceColor", &mut self.face_color);
        color("faceSelectedColor", &mut self.face_selected_color);
        color("hoverColor", &mut self.hover_color);
        color("edgeColor", &mut self.edge_color);
        color("edgeSelectedColor", &mut self.edge_selected_color);
        color("vertexColor", &mut self.vertex_color);
        color("vertexSelectedColor", &mut self.vertex_selected_color);
        // Sketcher overlay palette (same CSS-hex shape as the face/edge/vertex colors).
        color("sketchMovableColor", &mut self.sketch_movable_color);
        color("sketchLockedColor", &mut self.sketch_locked_color);
        color("sketchGeometryColor", &mut self.sketch_geometry_color);
        color("sketchPointColor", &mut self.sketch_point_color);
        color("sketchConstructionPointColor", &mut self.sketch_construction_point_color);
        color("sketchUnderConstrainedPointColor", &mut self.sketch_under_constrained_point_color);
        color("sketchSelectedColor", &mut self.sketch_selected_color);
        color("sketchHoveredColor", &mut self.sketch_hovered_color);
        color("sketchPreviewColor", &mut self.sketch_preview_color);
        color("sketchConstraintColor", &mut self.sketch_constraint_color);
        if let Some(v) = value.get("background").and_then(|v| v.as_str()) {
            if let Some(rgb) = parse_css_hex(v) {
                self.background = rgb;
            }
        }
        if let Some(v) = value.get("edgeWidthPx").and_then(|v| v.as_f64()) {
            self.edge_width_px = (v as f32).clamp(0.0, 32.0);
        }
        if let Some(v) = value.get("vertexSizePx").and_then(|v| v.as_f64()) {
            self.vertex_size_px = (v as f32).clamp(0.0, 64.0);
        }
        if let Some(v) = value.get("hiddenEdgeAlpha").and_then(|v| v.as_f64()) {
            self.hidden_edge_alpha = (v as f32).clamp(0.0, 1.0);
        }
        if let Some(v) = value.get("faceColorMode").and_then(|v| v.as_str()) {
            match v.trim().to_ascii_lowercase().as_str() {
                "hashedbysolid" | "hashed" => self.face_color_mode = FaceColorMode::HashedBySolid,
                "uniform" => self.face_color_mode = FaceColorMode::Uniform,
                _ => {}
            }
        }
        if let Some(v) = value.get("theme").and_then(|v| v.as_str()) {
            match v.trim().to_ascii_lowercase().as_str() {
                "auto" => self.theme = ThemeMode::Auto,
                "light" => self.theme = ThemeMode::Light,
                "dark" => self.theme = ThemeMode::Dark,
                _ => {}
            }
        }
        if let Some(v) = value.get("uiScale").and_then(|v| v.as_f64()) {
            self.ui_scale = (v as f32).clamp(0.5, 3.0);
        }
        // Model-overlay label size. Clamped to the SAME [0.25, 3.0] domain the
        // settings slider offers, so a persisted value never silently re-clamps on
        // reload (the `viewcubeSizePx` rule).
        if let Some(v) = value.get("labelScale").and_then(|v| v.as_f64()) {
            self.label_scale = (v as f32).clamp(0.25, 3.0);
        }
        if let Some(v) = value.get("debugGrabHandles").and_then(|v| v.as_bool()) {
            self.debug_grab_handles = v;
        }
        if let Some(v) = value.get("flatShading").and_then(|v| v.as_bool()) {
            self.flat_shading = v;
        }
        if let Some(v) = value.get("wireframe").and_then(|v| v.as_bool()) {
            self.wireframe = v;
        }
        if let Some(v) = value.get("axisLengthPx").and_then(|v| v.as_f64()) {
            self.axis_length_px = (v as f32).clamp(0.0, 512.0);
        }
        // ViewCube corner size — clamp to the SAME [40, 230] domain the settings
        // slider offers, so a persisted value never silently re-clamps on reload.
        if let Some(v) = value.get("viewcubeSizePx").and_then(|v| v.as_f64()) {
            self.viewcube_size_px = (v as f32).clamp(40.0, 230.0);
        }
        if let Some(v) = value.get("pickDoubleSided").and_then(|v| v.as_bool()) {
            self.pick_double_sided = v;
        }
        // The multi-select mode dropdown serializes its human label (the
        // renderQuality pattern); match on the alphanumeric skeleton so
        // "Ctrl+Click" / "ctrlClick" / "CTRL CLICK" all parse.
        if let Some(v) = value.get("multiSelect").and_then(|v| v.as_str()) {
            let skeleton: String = v
                .chars()
                .filter(|c| c.is_ascii_alphanumeric())
                .collect::<String>()
                .to_ascii_lowercase();
            match skeleton.as_str() {
                "ctrlclick" => self.multi_select = MultiSelectMode::CtrlClick,
                "clicktoggles" => self.multi_select = MultiSelectMode::ClickToggles,
                _ => {}
            }
        }
        // The active UI workbench id (a plain string; the app validates it against
        // its registry). Stored verbatim — an unknown id is tolerated here.
        if let Some(v) = value.get("workbench").and_then(|v| v.as_str()) {
            self.workbench = v.to_string();
        }
        if let Some(v) = value.get("assemblyAutoSolve").and_then(|v| v.as_bool()) {
            self.assembly_auto_solve = v;
        }
        // The BOM column configuration, verbatim (see the field docs) — never
        // normalized here, so a malformed line survives a save/reload and the
        // panel can still point at the line the user has to fix.
        if let Some(v) = value.get("bomColumns").and_then(|v| v.as_str()) {
            self.bom_columns = v.to_string();
        }
        if let Some(v) = value.get("showConstraintGraphics").and_then(|v| v.as_bool()) {
            self.show_constraint_graphics = v;
        }
        // "Render Quality" is a named dropdown (Draft…Ultra) mapping to the display
        // LOD factor (higher quality = finer mesh = smaller factor). We store the
        // resolved f64 so the tessellation path is unchanged.
        if let Some(label) = value.get("renderQuality").and_then(|v| v.as_str()) {
            if let Some(lod) = lod_from_quality(label) {
                self.lod_factor = lod;
            }
        }
        Ok(())
    }

    /// Serialize EVERY setting to the SAME camelCase / CSS-hex shape
    /// [`apply_json`] reads, so `s.apply_json(&s.to_json())` is the identity.
    /// This is the counterpart the settings schema serializes/persists through
    /// (there was previously no serializer, only the partial-override reader).
    pub fn to_json(&self) -> String {
        serde_json::json!({
            "theme": match self.theme {
                ThemeMode::Auto => "auto",
                ThemeMode::Light => "light",
                ThemeMode::Dark => "dark",
            },
            "uiScale": self.ui_scale as f64,
            "labelScale": self.label_scale as f64,
            "debugGrabHandles": self.debug_grab_handles,
            "background": rgb_to_css_hex(self.background),
            "faceColorMode": match self.face_color_mode {
                FaceColorMode::Uniform => "uniform",
                FaceColorMode::HashedBySolid => "hashedBySolid",
            },
            "faceColor": rgba_to_css_hex(self.face_color),
            "faceSelectedColor": rgba_to_css_hex(self.face_selected_color),
            "hoverColor": rgba_to_css_hex(self.hover_color),
            "edgeColor": rgba_to_css_hex(self.edge_color),
            "edgeSelectedColor": rgba_to_css_hex(self.edge_selected_color),
            "edgeWidthPx": self.edge_width_px as f64,
            "hiddenEdgeAlpha": self.hidden_edge_alpha as f64,
            "vertexColor": rgba_to_css_hex(self.vertex_color),
            "vertexSelectedColor": rgba_to_css_hex(self.vertex_selected_color),
            "vertexSizePx": self.vertex_size_px as f64,
            "flatShading": self.flat_shading,
            "wireframe": self.wireframe,
            "axisLengthPx": self.axis_length_px as f64,
            "viewcubeSizePx": self.viewcube_size_px as f64,
            "pickDoubleSided": self.pick_double_sided,
            "multiSelect": self.multi_select.label(),
            "renderQuality": quality_from_lod(self.lod_factor),
            "sketchMovableColor": rgba_to_css_hex(self.sketch_movable_color),
            "sketchLockedColor": rgba_to_css_hex(self.sketch_locked_color),
            "sketchGeometryColor": rgba_to_css_hex(self.sketch_geometry_color),
            "sketchPointColor": rgba_to_css_hex(self.sketch_point_color),
            "sketchConstructionPointColor": rgba_to_css_hex(self.sketch_construction_point_color),
            "sketchUnderConstrainedPointColor": rgba_to_css_hex(self.sketch_under_constrained_point_color),
            "sketchSelectedColor": rgba_to_css_hex(self.sketch_selected_color),
            "sketchHoveredColor": rgba_to_css_hex(self.sketch_hovered_color),
            "sketchPreviewColor": rgba_to_css_hex(self.sketch_preview_color),
            "sketchConstraintColor": rgba_to_css_hex(self.sketch_constraint_color),
            "workbench": self.workbench,
            "assemblyAutoSolve": self.assembly_auto_solve,
            "showConstraintGraphics": self.show_constraint_graphics,
            "bomColumns": self.bom_columns,
        })
        .to_string()
    }

    /// The live [`SketchColors`] view of the sketcher palette — the tessellation /
    /// overlay builders read their colors from THIS (via
    /// [`crate::sketch::SketchSession::colors`]) so the display settings are the one
    /// source of truth. Each `Rgba` is quantized back to `0xRRGGBB` the SAME way
    /// [`rgb_to_css_hex`] serializes it, so a default settings value round-trips to
    /// the default `SketchColors` byte-exact.
    pub fn sketch_colors(&self) -> SketchColors {
        SketchColors {
            movable: rgba_to_u32(self.sketch_movable_color),
            locked: rgba_to_u32(self.sketch_locked_color),
            geometry: rgba_to_u32(self.sketch_geometry_color),
            point: rgba_to_u32(self.sketch_point_color),
            construction_point: rgba_to_u32(self.sketch_construction_point_color),
            under_constrained_point: rgba_to_u32(self.sketch_under_constrained_point_color),
            selected: rgba_to_u32(self.sketch_selected_color),
            hovered: rgba_to_u32(self.sketch_hovered_color),
            preview: rgba_to_u32(self.sketch_preview_color),
            constraint: rgba_to_u32(self.sketch_constraint_color),
        }
    }

    /// The settings schema WITH the current value baked into each field, as JSON
    /// — mirrors the kernel's `feature_schemas_json` export so a UI shell (egui
    /// here, a later `brep-ui` crate) can generate the whole form from data. The
    /// `value` of each field is pulled live from [`to_json`], so the export
    /// always reflects the current settings.
    pub fn settings_schema_json(&self) -> String {
        let current: serde_json::Value =
            serde_json::from_str(&self.to_json()).unwrap_or(serde_json::Value::Null);
        let fields: Vec<serde_json::Value> = settings_schema()
            .iter()
            .map(|field| {
                let kind = match &field.kind {
                    FieldKind::Color => serde_json::json!({ "type": "color" }),
                    FieldKind::Bool => serde_json::json!({ "type": "bool" }),
                    FieldKind::Enum { variants } => {
                        serde_json::json!({ "type": "enum", "variants": variants })
                    }
                    FieldKind::Number { min, max, step } => serde_json::json!({
                        "type": "number", "min": min, "max": max, "step": step
                    }),
                    FieldKind::Range { min, max, step } => serde_json::json!({
                        "type": "range", "min": min, "max": max, "step": step
                    }),
                    // The feature-dialog kinds never appear in the settings
                    // schema, but the match must stay exhaustive.
                    FieldKind::Scalar { step } => {
                        serde_json::json!({ "type": "scalar", "step": step })
                    }
                    FieldKind::Text { read_only } => {
                        serde_json::json!({ "type": "text", "readOnly": read_only })
                    }
                    FieldKind::Vec3 { step } => serde_json::json!({ "type": "vec3", "step": step }),
                    FieldKind::Reference { filter, multiple } => serde_json::json!({
                        "type": "reference", "filter": filter, "multiple": multiple
                    }),
                    FieldKind::Button { label } => {
                        serde_json::json!({ "type": "button", "label": label })
                    }
                };
                serde_json::json!({
                    "key": field.key,
                    "label": field.label,
                    "group": field.group,
                    "kind": kind,
                    "value": current.get(field.key),
                })
            })
            .collect();
        serde_json::json!({ "fields": fields }).to_string()
    }
}

/// Quantize an sRGB channel triple to a `#rrggbb` CSS hex string (the shape
/// [`RenderSettings::apply_json`] parses back).
fn rgb_to_css_hex(rgb: [f32; 3]) -> String {
    let q = |c: f32| (c.clamp(0.0, 1.0) * 255.0).round() as u32;
    format!("#{:02x}{:02x}{:02x}", q(rgb[0]), q(rgb[1]), q(rgb[2]))
}

/// Like [`rgb_to_css_hex`] but for an `Rgba` (the alpha is intentionally dropped
/// — `apply_json` only overrides the rgb channels, preserving existing alpha).
fn rgba_to_css_hex(rgba: Rgba) -> String {
    rgb_to_css_hex([rgba[0], rgba[1], rgba[2]])
}

/// Quantize an `Rgba` to a packed `0xRRGGBB` (alpha dropped), using the SAME
/// per-channel rounding as [`rgb_to_css_hex`] so the sketcher's `u32` palette
/// (`SketchColors`) is byte-identical to what the CSS-hex serialization would
/// produce — a default settings value maps back to the default `SketchColors`.
fn rgba_to_u32(rgba: Rgba) -> u32 {
    let q = |c: f32| (c.clamp(0.0, 1.0) * 255.0).round() as u32;
    (q(rgba[0]) << 16) | (q(rgba[1]) << 8) | q(rgba[2])
}

/// The kind of one settings field — the closed set of widget shapes the generic
/// form renderer knows how to emit. Plain data, NO egui dependency: the schema
/// lives in the engine, the renderer (brep-app / a later brep-ui) walks it.
#[derive(Debug, Clone, PartialEq)]
pub enum FieldKind {
    /// An sRGB color (`#rrggbb`) → a color picker button.
    Color,
    /// A boolean toggle → a checkbox.
    Bool,
    /// A closed choice → a combo box. `variants` are the JSON string values
    /// (exactly what `apply_json` accepts / `to_json` emits).
    Enum { variants: Vec<String> },
    /// A bounded number → a slider / drag-value honoring `min`/`max`/`step`.
    Number { min: f64, max: f64, step: f64 },
    /// A 0..1 (or otherwise fractional) number → a slider honoring the bounds.
    Range { min: f64, max: f64, step: f64 },
    // --- extra kinds the FEATURE dialogs need (settings never use these) -------
    /// An UNBOUNDED number (feature params carry no min/max) → a drag value.
    Scalar { step: f64 },
    /// A free-text string → a single-line text edit. `read_only` marks an
    /// identity field (a feature `id`) that is shown but not editable here (a
    /// rename must cascade to references — a later slice).
    Text { read_only: bool },
    /// A 3-vector (position / rotationEuler / scale) → three drag values.
    Vec3 { step: f64 },
    /// A reference-selection field (solid / face / edge / … picked in the 3D
    /// view). The schema-driven form renders a DISABLED placeholder here — the
    /// real engine-native picker is the NEXT slice (#42). `filter` is the
    /// selection filter (e.g. `["SOLID"]`), `multiple` whether it takes a list.
    Reference { filter: Vec<String>, multiple: bool },
    /// An ACTION button (schema `"type":"button"`) → a clickable button. It binds
    /// to no value; a click is surfaced to the caller by the field `key` (e.g.
    /// `editSketch`), which the host acts on. `label` is the button caption.
    Button { label: String },
}

/// One field of the settings form: the camelCase `apply_json`/`to_json` key, a
/// human label, a UI group, and the widget `kind`. The ordered list of these
/// (see [`settings_schema`]) fully describes the form — a UI shell generates a
/// widget per field with no per-field code.
#[derive(Debug, Clone)]
pub struct SettingsField {
    /// The camelCase key — the SAME one `apply_json`/`to_json` use.
    pub key: &'static str,
    pub label: &'static str,
    pub group: &'static str,
    pub kind: FieldKind,
}

/// The GENERAL form field — the schema element ONE form engine renders for BOTH
/// the display-settings dialog AND the schema-driven feature dialogs. Unlike
/// [`SettingsField`] (which uses `&'static str` because the settings schema is
/// compile-time), this owns its strings so it can carry a per-feature schema
/// pulled from the kernel catalogue at run time, and it carries a `path` (a
/// chain of JSON object keys) so a field can bind to a NESTED value —
/// `["transform","position"]`, `["boolean","operation"]` — not just a top-level
/// key. The settings form is `path == [key]`.
#[derive(Debug, Clone)]
pub struct FormField {
    /// JSON object-key chain into the document the form edits (≥ 1 segment).
    pub path: Vec<String>,
    pub label: String,
    pub group: String,
    pub kind: FieldKind,
}

impl FormField {
    /// The last path segment — a stable per-field id for egui salting / probing.
    pub fn key(&self) -> &str {
        self.path.last().map(String::as_str).unwrap_or("")
    }
}

/// The "Render Quality" dropdown levels shown in Settings, each mapped to a
/// display-tessellation LOD factor. Higher quality = finer mesh = SMALLER factor
/// (chord tolerance = extent · 1.5e-3 · factor). Order is coarse→fine, the order
/// the ComboBox lists them. `lod_factor` stays the internal representation the
/// tessellation path reads; only the SETTINGS UI/serialization speaks in levels.
pub const RENDER_QUALITY: &[(&str, f64)] = &[
    ("Draft", 4.0),
    ("Low", 2.0),
    ("Medium", 1.0),
    ("High", 0.5),
    ("Ultra", 0.25),
];

/// The LOD factor for a quality label (`None` if not a known level).
fn lod_from_quality(label: &str) -> Option<f64> {
    RENDER_QUALITY
        .iter()
        .find(|(name, _)| *name == label)
        .map(|(_, factor)| *factor)
}

/// The quality label NEAREST a LOD factor — the serialization inverse of
/// [`lod_from_quality`]. A stored factor is always one of the level values in
/// normal use; nearest-match keeps a hand-set/legacy value mapping to a sane label.
fn quality_from_lod(lod: f64) -> &'static str {
    RENDER_QUALITY
        .iter()
        .min_by(|(_, a), (_, b)| {
            (a - lod).abs().total_cmp(&(b - lod).abs())
        })
        .map(|(name, _)| *name)
        .unwrap_or("Medium")
}

/// Lift the compile-time display-settings schema into general [`FormField`]s so
/// the ONE `field_input` engine (which the feature dialogs also use) renders the
/// settings panel too — a single schema-driven dialog engine, not two.
pub fn settings_form_fields() -> Vec<FormField> {
    settings_schema()
        .into_iter()
        .map(|field| FormField {
            path: vec![field.key.to_string()],
            label: field.label.to_string(),
            group: field.group.to_string(),
            kind: field.kind,
        })
        .collect()
}

/// The Rust-owned settings schema: the ordered list of display-settings fields,
/// grouped, analogous to the kernel feature schemas. Adding a field here (plus
/// its `apply_json`/`to_json` handling) makes the whole UI grow a widget for it
/// with ZERO renderer changes.
pub fn settings_schema() -> Vec<SettingsField> {
    let f = |key, label, group, kind| SettingsField { key, label, group, kind };
    vec![
        // --- Appearance ----------------------------------------------------
        // FIRST so the "Appearance" group renders at the TOP of the settings tree
        // (groups are ordered by first field appearance). The GUI-chrome theme —
        // NOT the 3D viewport background (that lives under Scene).
        f(
            "theme",
            "Theme",
            "Appearance",
            FieldKind::Enum { variants: ["auto", "light", "dark"].iter().map(|s| s.to_string()).collect() },
        ),
        // A SLIDER (both `Range` and `Number` render an `egui::Slider` over the
        // given domain) scaling the whole egui UI via `Context::set_zoom_factor`.
        f(
            "uiScale",
            "UI scale",
            "Appearance",
            FieldKind::Range { min: 0.5, max: 3.0, step: 0.05 },
        ),
        // The size of the floating text labels overlaid on the MODEL (dimension
        // value chips, constraint chips, gizmo axis letters) — a multiplier over
        // their base monospace size, NOT a point size. Bounds MATCH the
        // `apply_json` clamp so the slider can't set a value that re-clamps on
        // reload. The 0.25 floor (a quarter of the base, on the 0.05 step) is the
        // smallest chip whose click/drag target a pointer can still land on — see
        // `RenderSettings::label_scale`. Separate from `uiScale`, which sizes the
        // egui chrome.
        f(
            "labelScale",
            "Label scale",
            "Appearance",
            FieldKind::Range { min: 0.25, max: 3.0, step: 0.05 },
        ),
        // --- Scene ---------------------------------------------------------
        f("background", "Background", "Scene", FieldKind::Color),
        f(
            "axisLengthPx",
            "Axis length (px)",
            "Scene",
            FieldKind::Number { min: 0.0, max: 512.0, step: 1.0 },
        ),
        // The corner ViewCube's on-screen size. Bounds MATCH the `apply_json` clamp
        // ([40, 230], centered on the 135px default) so the slider can't set a value
        // that re-clamps on reload. Renders as an `egui::Slider`.
        f(
            "viewcubeSizePx",
            "ViewCube size (px)",
            "Scene",
            FieldKind::Number { min: 40.0, max: 230.0, step: 1.0 },
        ),
        f(
            "renderQuality",
            "Render Quality",
            "Scene",
            FieldKind::Enum { variants: RENDER_QUALITY.iter().map(|(label, _)| label.to_string()).collect() },
        ),
        // --- Faces ---------------------------------------------------------
        f(
            "faceColorMode",
            "Face color mode",
            "Faces",
            FieldKind::Enum { variants: ["uniform", "hashedBySolid"].iter().map(|s| s.to_string()).collect() },
        ),
        f("faceColor", "Face color", "Faces", FieldKind::Color),
        f("faceSelectedColor", "Selected face", "Faces", FieldKind::Color),
        f("hoverColor", "Hover", "Faces", FieldKind::Color),
        f("flatShading", "Flat shading", "Faces", FieldKind::Bool),
        f("wireframe", "Wireframe", "Faces", FieldKind::Bool),
        // --- Edges ---------------------------------------------------------
        f("edgeColor", "Edge color", "Edges", FieldKind::Color),
        f("edgeSelectedColor", "Selected edge", "Edges", FieldKind::Color),
        f(
            "edgeWidthPx",
            "Edge width (px)",
            "Edges",
            FieldKind::Number { min: 0.0, max: 32.0, step: 0.1 },
        ),
        f(
            "hiddenEdgeAlpha",
            "Hidden-edge alpha",
            "Edges",
            FieldKind::Range { min: 0.0, max: 1.0, step: 0.01 },
        ),
        // --- Vertices ------------------------------------------------------
        f("vertexColor", "Vertex color", "Vertices", FieldKind::Color),
        f("vertexSelectedColor", "Selected vertex", "Vertices", FieldKind::Color),
        f(
            "vertexSizePx",
            "Vertex size (px)",
            "Vertices",
            FieldKind::Number { min: 0.0, max: 64.0, step: 0.5 },
        ),
        // --- Picking -------------------------------------------------------
        f("pickDoubleSided", "Pick double-sided", "Picking", FieldKind::Bool),
        // How a plain viewport click builds a multi-selection: the classic
        // Ctrl+Click add, or modifier-free click-toggles (click an item to add
        // it, click it again to remove it).
        f(
            "multiSelect",
            "Multi-select",
            "Picking",
            FieldKind::Enum {
                variants: MultiSelectMode::ALL.iter().map(|m| m.label().to_string()).collect(),
            },
        ),
        // --- Sketch --------------------------------------------------------
        // The sketcher overlay palette, editable live like every other display
        // color. `sketch_colors()` feeds these to the tessellation/overlay builders.
        f("sketchMovableColor", "Movable geometry", "Sketch", FieldKind::Color),
        f("sketchLockedColor", "Locked geometry", "Sketch", FieldKind::Color),
        f("sketchGeometryColor", "Geometry (no mobility)", "Sketch", FieldKind::Color),
        f("sketchPointColor", "Point", "Sketch", FieldKind::Color),
        f("sketchConstructionPointColor", "Construction point", "Sketch", FieldKind::Color),
        f("sketchUnderConstrainedPointColor", "Under-constrained point", "Sketch", FieldKind::Color),
        f("sketchSelectedColor", "Selected", "Sketch", FieldKind::Color),
        f("sketchHoveredColor", "Hovered", "Sketch", FieldKind::Color),
        f("sketchPreviewColor", "Draw preview", "Sketch", FieldKind::Color),
        f("sketchConstraintColor", "Constraint / dimension", "Sketch", FieldKind::Color),
        // --- Debug ---------------------------------------------------------
        // LAST so the "Debug" group renders at the BOTTOM of the settings tree.
        f("debugGrabHandles", "Debug grab handles", "Debug", FieldKind::Bool),
    ]
}

/// A selected/hovered vertex reference: vertices have no kernel names, so they
/// resolve by owning solid + position.
#[derive(Debug, Clone)]
pub struct VertexRef {
    pub solid: String,
    pub position: [f64; 3],
}

/// The emphasis state (selection + hover), name-keyed like `SelectionFilter`.
/// Solid-level emphasis cascades to that solid's faces/edges (the
/// `SelectionState._applyToSolid` behavior).
#[derive(Debug, Default)]
pub struct Emphasis {
    pub selected_solids: HashSet<String>,
    pub selected_faces: HashSet<String>,
    pub selected_edges: HashSet<String>,
    pub selected_vertices: Vec<VertexRef>,
    /// Selected construction datum/plane FRAMES, keyed by frame NAME (`{id}:XY`
    /// for a DATUM base plane, `{id}` for a PLANE feature). Datums carry no
    /// resident geometry, so — like the render-color feed — they emphasize purely
    /// by name; a selected datum is re-colored with the selection accent when the
    /// engine re-feeds the datum planes.
    pub selected_datums: HashSet<String>,
    pub hovered_solids: HashSet<String>,
    pub hovered_faces: HashSet<String>,
    pub hovered_edges: HashSet<String>,
    pub hovered_vertices: Vec<VertexRef>,
    /// HOVERED construction datum/plane FRAMES — the hover twin of
    /// [`selected_datums`](Self::selected_datums), keyed the same way. Construction
    /// planes are ordinary pick candidates, so the pointer (and a pick-list row)
    /// pre-highlights one exactly like a face; the accent is applied when the engine
    /// re-feeds the datum planes.
    pub hovered_datums: HashSet<String>,
    /// Bumped on every change — cache key for derived GPU state.
    pub generation: u64,
}

impl Emphasis {
    pub fn is_empty(&self) -> bool {
        self.selected_solids.is_empty()
            && self.selected_faces.is_empty()
            && self.selected_edges.is_empty()
            && self.selected_vertices.is_empty()
            && self.selected_datums.is_empty()
            && self.hovered_solids.is_empty()
            && self.hovered_faces.is_empty()
            && self.hovered_edges.is_empty()
            && self.hovered_vertices.is_empty()
            && self.hovered_datums.is_empty()
    }

    /// Replace the whole emphasis state from the R3 JSON shape:
    /// `{selected: {solids, faces, edges, vertices:[{solid,position}]}, hovered: {...}}`.
    pub fn apply_json(&mut self, json: &str) -> Result<(), String> {
        let value: serde_json::Value =
            serde_json::from_str(json).map_err(|error| format!("emphasis parse: {error}"))?;
        let names = |group: &serde_json::Value, key: &str| -> HashSet<String> {
            group
                .get(key)
                .and_then(|v| v.as_array())
                .map(|list| {
                    list.iter()
                        .filter_map(|v| v.as_str().map(str::to_string))
                        .collect()
                })
                .unwrap_or_default()
        };
        let vertices = |group: &serde_json::Value| -> Vec<VertexRef> {
            group
                .get("vertices")
                .and_then(|v| v.as_array())
                .map(|list| {
                    list.iter()
                        .filter_map(|v| {
                            let solid = v.get("solid")?.as_str()?.to_string();
                            let p = v.get("position")?.as_array()?;
                            Some(VertexRef {
                                solid,
                                position: [
                                    p.first()?.as_f64()?,
                                    p.get(1)?.as_f64()?,
                                    p.get(2)?.as_f64()?,
                                ],
                            })
                        })
                        .collect()
                })
                .unwrap_or_default()
        };
        let empty = serde_json::json!({});
        let selected = value.get("selected").unwrap_or(&empty);
        let hovered = value.get("hovered").unwrap_or(&empty);
        self.selected_solids = names(selected, "solids");
        self.selected_faces = names(selected, "faces");
        self.selected_edges = names(selected, "edges");
        self.selected_datums = names(selected, "datums");
        self.selected_vertices = vertices(selected);
        self.hovered_solids = names(hovered, "solids");
        self.hovered_faces = names(hovered, "faces");
        self.hovered_edges = names(hovered, "edges");
        self.hovered_datums = names(hovered, "datums");
        self.hovered_vertices = vertices(hovered);
        self.generation = self.generation.wrapping_add(1);
        Ok(())
    }
}

/// The visual state of one displayed face/edge (hover wins over selected, the
/// `SelectionState` order).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EmphasisState {
    Base,
    Selected,
    Hovered,
}

impl Emphasis {
    pub fn face_state(&self, solid: &str, face: &str) -> EmphasisState {
        if self.hovered_solids.contains(solid) || (!face.is_empty() && self.hovered_faces.contains(face)) {
            EmphasisState::Hovered
        } else if self.selected_solids.contains(solid)
            || (!face.is_empty() && self.selected_faces.contains(face))
        {
            EmphasisState::Selected
        } else {
            EmphasisState::Base
        }
    }

    pub fn edge_state(&self, solid: &str, edge: &str) -> EmphasisState {
        if self.hovered_solids.contains(solid) || (!edge.is_empty() && self.hovered_edges.contains(edge)) {
            EmphasisState::Hovered
        } else if self.selected_solids.contains(solid)
            || (!edge.is_empty() && self.selected_edges.contains(edge))
        {
            EmphasisState::Selected
        } else {
            EmphasisState::Base
        }
    }

    pub fn vertex_state(&self, solid: &str, position: [f64; 3], tol: f64) -> EmphasisState {
        let matches = |refs: &[VertexRef]| {
            refs.iter().any(|r| {
                r.solid == solid
                    && (r.position[0] - position[0]).abs() <= tol
                    && (r.position[1] - position[1]).abs() <= tol
                    && (r.position[2] - position[2]).abs() <= tol
            })
        };
        if matches(&self.hovered_vertices) {
            EmphasisState::Hovered
        } else if matches(&self.selected_vertices) {
            EmphasisState::Selected
        } else {
            EmphasisState::Base
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn settings_json_overrides() {
        let mut settings = RenderSettings::default();
        settings
            .apply_json(
                r##"{"faceColor": "#ff0000", "edgeWidthPx": 4.5, "flatShading": true,
                     "hoverColor": "#0f0", "unknownKey": 1}"##,
            )
            .unwrap();
        assert_eq!(settings.face_color[0], 1.0);
        assert_eq!(settings.face_color[1], 0.0);
        assert_eq!(settings.edge_width_px, 4.5);
        assert!(settings.flat_shading);
        assert_eq!(settings.hover_color[1], 1.0);
    }

    #[test]
    fn settings_json_face_color_mode_and_wireframe() {
        let mut settings = RenderSettings::default();
        // Defaults: uniform faces, shaded (not wireframe).
        assert_eq!(settings.face_color_mode, FaceColorMode::Uniform);
        assert!(!settings.wireframe);
        settings
            .apply_json(r##"{"faceColorMode": "hashedBySolid", "wireframe": true}"##)
            .unwrap();
        assert_eq!(settings.face_color_mode, FaceColorMode::HashedBySolid);
        assert!(settings.wireframe);
        // Round-trip back to uniform + shaded.
        settings
            .apply_json(r##"{"faceColorMode": "uniform", "wireframe": false}"##)
            .unwrap();
        assert_eq!(settings.face_color_mode, FaceColorMode::Uniform);
        assert!(!settings.wireframe);
        // An unknown mode string is ignored (stays uniform).
        settings.apply_json(r##"{"faceColorMode": "bogus"}"##).unwrap();
        assert_eq!(settings.face_color_mode, FaceColorMode::Uniform);
    }

    #[test]
    fn settings_json_theme_mode() {
        let mut settings = RenderSettings::default();
        // Default follows the OS theme: Auto.
        assert_eq!(settings.theme, ThemeMode::Auto);
        // `apply_json` parses the lowercase string (case-insensitively).
        settings.apply_json(r##"{"theme": "light"}"##).unwrap();
        assert_eq!(settings.theme, ThemeMode::Light);
        // `to_json` emits the lowercase string form.
        assert!(
            settings.to_json().contains(r#""theme":"light""#),
            "to_json must emit the theme as a lowercase string: {}",
            settings.to_json()
        );
        settings.apply_json(r##"{"theme": "AUTO"}"##).unwrap();
        assert_eq!(settings.theme, ThemeMode::Auto);
        settings.apply_json(r##"{"theme": "Dark"}"##).unwrap();
        assert_eq!(settings.theme, ThemeMode::Dark);
        // An unknown value is ignored (leaves the current mode unchanged).
        settings.apply_json(r##"{"theme": "bogus"}"##).unwrap();
        assert_eq!(settings.theme, ThemeMode::Dark);
    }

    #[test]
    fn settings_json_multi_select_mode() {
        let mut settings = RenderSettings::default();
        // Default allows multi-selection without a modifier key.
        assert_eq!(settings.multi_select, MultiSelectMode::ClickToggles);
        // `apply_json` parses the human label (the serialized form)…
        settings.apply_json(r##"{"multiSelect": "Click toggles"}"##).unwrap();
        assert_eq!(settings.multi_select, MultiSelectMode::ClickToggles);
        // …and tolerant spellings (case / separators ignored).
        settings.apply_json(r##"{"multiSelect": "ctrlClick"}"##).unwrap();
        assert_eq!(settings.multi_select, MultiSelectMode::CtrlClick);
        settings.apply_json(r##"{"multiSelect": "CLICK-TOGGLES"}"##).unwrap();
        assert_eq!(settings.multi_select, MultiSelectMode::ClickToggles);
        // `to_json` emits the label and round-trips through `apply_json`.
        assert!(
            settings.to_json().contains(r#""multiSelect":"Click toggles""#),
            "to_json must emit the multi-select label: {}",
            settings.to_json()
        );
        let mut round = RenderSettings::default();
        round.apply_json(&settings.to_json()).unwrap();
        assert_eq!(round.multi_select, MultiSelectMode::ClickToggles);
        // An unknown value is ignored (leaves the current mode unchanged).
        round.apply_json(r##"{"multiSelect": "bogus"}"##).unwrap();
        assert_eq!(round.multi_select, MultiSelectMode::ClickToggles);
    }

    #[test]
    fn settings_json_ui_scale() {
        let mut settings = RenderSettings::default();
        // Default is native size (no zoom).
        assert_eq!(settings.ui_scale, 1.0);
        // `apply_json` parses the number.
        settings.apply_json(r##"{"uiScale": 1.5}"##).unwrap();
        assert_eq!(settings.ui_scale, 1.5);
        // Out-of-range values clamp to [0.5, 3.0].
        settings.apply_json(r##"{"uiScale": 10.0}"##).unwrap();
        assert_eq!(settings.ui_scale, 3.0);
        settings.apply_json(r##"{"uiScale": 0.1}"##).unwrap();
        assert_eq!(settings.ui_scale, 0.5);
        // `to_json` emits it (and round-trips through `apply_json`).
        settings.ui_scale = 1.25;
        assert!(
            settings.to_json().contains(r#""uiScale":1.25"#),
            "to_json must emit uiScale: {}",
            settings.to_json()
        );
        let mut round = RenderSettings::default();
        round.apply_json(&settings.to_json()).unwrap();
        assert_eq!(round.ui_scale, 1.25);
    }

    /// The model-overlay LABEL SCALE round-trips like every other numeric setting:
    /// it defaults to 1.0 (labels unchanged until edited), `apply_json` parses and
    /// CLAMPS it to the same [0.25, 3.0] domain the settings slider offers (so a
    /// persisted value never silently re-clamps on reload), and `to_json` emits it
    /// — which is what carries the setting through the `@settings` store across a
    /// document load and an app restart.
    #[test]
    fn settings_json_label_scale() {
        let mut settings = RenderSettings::default();
        // Default is the labels' native size — nothing changes until edited.
        assert_eq!(settings.label_scale, 1.0);
        // `apply_json` parses the number.
        settings.apply_json(r##"{"labelScale": 1.5}"##).unwrap();
        assert_eq!(settings.label_scale, 1.5);
        // Out-of-range values clamp to [0.25, 3.0] — a label can be neither
        // unclickable nor viewport-filling.
        settings.apply_json(r##"{"labelScale": 10.0}"##).unwrap();
        assert_eq!(settings.label_scale, 3.0);
        settings.apply_json(r##"{"labelScale": 0.1}"##).unwrap();
        assert_eq!(settings.label_scale, 0.25);
        // The FLOOR itself passes through untouched — the slider's own minimum must
        // never re-clamp on reload (the `viewcubeSizePx` rule), and 0.5 (the old
        // floor) is now an ordinary interior value.
        settings.apply_json(r##"{"labelScale": 0.25}"##).unwrap();
        assert_eq!(settings.label_scale, 0.25);
        settings.apply_json(r##"{"labelScale": 0.35}"##).unwrap();
        assert_eq!(settings.label_scale, 0.35);
        // ...and just under it still clamps.
        settings.apply_json(r##"{"labelScale": 0.24}"##).unwrap();
        assert_eq!(settings.label_scale, 0.25);
        // `to_json` emits it (and round-trips through `apply_json`).
        settings.label_scale = 1.25;
        assert!(
            settings.to_json().contains(r#""labelScale":1.25"#),
            "to_json must emit labelScale: {}",
            settings.to_json()
        );
        let mut round = RenderSettings::default();
        round.apply_json(&settings.to_json()).unwrap();
        assert_eq!(round.label_scale, 1.25);
        // It is INDEPENDENT of the chrome `uiScale` — editing one never moves the
        // other (the model overlay and the egui panels scale separately).
        assert_eq!(round.ui_scale, 1.0);
    }

    /// The setting is reachable from the SETTINGS PANEL: `labelScale` is a schema
    /// field, so the schema-driven panel grows a slider for it with no panel change.
    /// Its slider domain must MATCH the `apply_json` clamp, or a dragged-to-max
    /// value would re-clamp on reload.
    #[test]
    fn settings_schema_exposes_label_scale_over_the_clamped_domain() {
        let field = settings_form_fields()
            .into_iter()
            .find(|f| f.key() == "labelScale")
            .expect("the settings schema must expose labelScale");
        assert_eq!(field.group, "Appearance");
        match field.kind {
            FieldKind::Range { min, max, .. } => {
                assert_eq!(
                    (min, max),
                    (0.25, 3.0),
                    "the slider domain must match the apply_json clamp"
                );
                // The invariant, stated as the code does it: the slider's own
                // endpoints must survive `apply_json` unchanged.
                let mut probe = RenderSettings::default();
                probe
                    .apply_json(&format!(r##"{{"labelScale": {min}}}"##))
                    .unwrap();
                assert_eq!(probe.label_scale, min as f32, "the slider MIN re-clamped");
                probe
                    .apply_json(&format!(r##"{{"labelScale": {max}}}"##))
                    .unwrap();
                assert_eq!(probe.label_scale, max as f32, "the slider MAX re-clamped");
            }
            other => panic!("labelScale must be a bounded slider, got {other:?}"),
        }
    }

    #[test]
    fn settings_json_workbench_roundtrip() {
        let mut settings = RenderSettings::default();
        // Default is the general Modeling workbench.
        assert_eq!(settings.workbench, "modeling");
        // `apply_json` stores the id verbatim (validation is app-side).
        settings.apply_json(r##"{"workbench": "sheetMetal"}"##).unwrap();
        assert_eq!(settings.workbench, "sheetMetal");
        // `to_json` emits it and round-trips through `apply_json`.
        assert!(
            settings.to_json().contains(r#""workbench":"sheetMetal""#),
            "to_json must emit the workbench id: {}",
            settings.to_json()
        );
        let mut round = RenderSettings::default();
        round.apply_json(&settings.to_json()).unwrap();
        assert_eq!(round.workbench, "sheetMetal");
        // An apply that omits the key leaves the current id unchanged.
        round.apply_json(r##"{"wireframe": true}"##).unwrap();
        assert_eq!(round.workbench, "sheetMetal");
        // An unknown id is tolerated here (the app resolver falls back).
        round.apply_json(r##"{"workbench": "bogus"}"##).unwrap();
        assert_eq!(round.workbench, "bogus");
    }

    /// The BOM column configuration round-trips as VERBATIM text: it defaults
    /// empty (meaning "the app's shipped configuration"), stores multi-line
    /// text unchanged including a line this crate cannot parse, and an apply
    /// that omits the key leaves it alone.
    #[test]
    fn settings_json_bom_columns_roundtrip_verbatim() {
        let mut settings = RenderSettings::default();
        assert_eq!(
            settings.bom_columns, "",
            "empty by default = the app's shipped configuration"
        );
        // A malformed line is stored, not normalized: the panel needs to point
        // the user at the line they have to fix, which it cannot do if a
        // reload silently drops it.
        let text = "# mine\n*part.Part_Number\nnonsense\n*occurrence.Notes\n";
        settings
            .apply_json(&serde_json::json!({ "bomColumns": text }).to_string())
            .unwrap();
        assert_eq!(settings.bom_columns, text);
        let mut round = RenderSettings::default();
        round.apply_json(&settings.to_json()).unwrap();
        assert_eq!(round.bom_columns, text, "survives to_json → apply_json");
        round.apply_json(r##"{"wireframe": true}"##).unwrap();
        assert_eq!(round.bom_columns, text, "an unrelated apply leaves it alone");
    }

    #[test]
    fn emphasis_states_cascade_from_solid() {
        let mut emphasis = Emphasis::default();
        emphasis
            .apply_json(
                r#"{"selected": {"solids": ["A"], "faces": ["F1"]},
                    "hovered": {"edges": ["E1"], "vertices": [{"solid": "A", "position": [1, 2, 3]}]}}"#,
            )
            .unwrap();
        assert_eq!(emphasis.face_state("A", "anything"), EmphasisState::Selected);
        assert_eq!(emphasis.face_state("B", "F1"), EmphasisState::Selected);
        assert_eq!(emphasis.face_state("B", "F2"), EmphasisState::Base);
        assert_eq!(emphasis.edge_state("B", "E1"), EmphasisState::Hovered);
        assert_eq!(
            emphasis.vertex_state("A", [1.0, 2.0, 3.0], 1e-9),
            EmphasisState::Hovered
        );
        assert_eq!(
            emphasis.vertex_state("B", [1.0, 2.0, 3.0], 1e-9),
            EmphasisState::Base
        );
        let gen0 = emphasis.generation;
        emphasis.apply_json(r#"{}"#).unwrap();
        assert!(emphasis.is_empty());
        assert_ne!(emphasis.generation, gen0);
    }

    #[test]
    fn settings_to_json_roundtrip_is_identity() {
        // Start from defaults, then mutate a spread of fields with hex-exact
        // colors / representable numbers so the round-trip is exact.
        let mut s = RenderSettings::default();
        s.face_color = hex(0x123456, 1.0);
        s.edge_color = hex(0xabcdef, 1.0);
        s.background = [0.0, 0.0, 0.0];
        s.face_color_mode = FaceColorMode::HashedBySolid;
        s.edge_width_px = 3.5;
        s.hidden_edge_alpha = 0.5;
        s.vertex_size_px = 8.0;
        s.axis_length_px = 30.0;
        // Must be a "Render Quality" LEVEL value now (serialized as its label +
        // read back to the same factor) — Low = 2.0; a between-levels value would
        // snap to the nearest level and break the identity by design.
        s.lod_factor = 2.0;
        s.flat_shading = true;
        s.wireframe = true;
        s.pick_double_sided = false;
        // Sketch palette carried through the round-trip too (hex-exact values).
        s.sketch_movable_color = hex(0x112233, 1.0);
        s.sketch_constraint_color = hex(0x00ff00, 1.0);
        s.sketch_selected_color = hex(0xfedcba, 1.0);

        // The task's literal identity form: applying its own serialization is a
        // no-op.
        let mut identity = s.clone();
        identity.apply_json(&s.to_json()).unwrap();
        assert_eq!(identity, s);

        // And it reconstructs the same value from a fresh default (alphas match,
        // since apply_json preserves the target's existing alpha = 1.0).
        let mut rebuilt = RenderSettings::default();
        rebuilt.apply_json(&s.to_json()).unwrap();
        assert_eq!(rebuilt, s);
    }

    #[test]
    fn settings_schema_covers_every_json_key() {
        // Every schema key must be a key `to_json` emits (so the form can read a
        // live value for it) — the schema and the serializer stay in lockstep.
        let json: serde_json::Value =
            serde_json::from_str(&RenderSettings::default().to_json()).unwrap();
        for field in settings_schema() {
            assert!(
                json.get(field.key).is_some(),
                "schema field {} has no to_json value",
                field.key
            );
        }
        // The schema export reflects the current value (e.g. wireframe flips).
        let mut s = RenderSettings::default();
        s.wireframe = true;
        let export: serde_json::Value = serde_json::from_str(&s.settings_schema_json()).unwrap();
        let wf = export["fields"]
            .as_array()
            .unwrap()
            .iter()
            .find(|f| f["key"] == "wireframe")
            .unwrap();
        assert_eq!(wf["value"], serde_json::json!(true));
    }

    #[test]
    fn sketch_colors_default_matches_the_hex_constants() {
        // The default RenderSettings sketch palette round-trips BYTE-EXACT to the
        // single source of the literals (`SketchColors::default`), so nothing
        // changes visually until edited.
        assert_eq!(RenderSettings::default().sketch_colors(), SketchColors::default());
    }

    #[test]
    fn sketch_colors_follow_apply_json() {
        // Editing a sketch color in the settings (the dialog's apply path) reaches
        // the `SketchColors` view the tessellation reads.
        let mut s = RenderSettings::default();
        s.apply_json(r##"{"sketchConstraintColor": "#ff0000", "sketchMovableColor": "#00ff00"}"##)
            .unwrap();
        let c = s.sketch_colors();
        assert_eq!(c.constraint, 0xff0000);
        assert_eq!(c.movable, 0x00ff00);
        // Untouched entries keep their defaults.
        assert_eq!(c.locked, SketchColors::default().locked);
    }

    #[test]
    fn css_hex_parsing() {
        assert_eq!(parse_css_hex("#ffffff"), Some([1.0, 1.0, 1.0]));
        assert_eq!(parse_css_hex("#f00"), Some([1.0, 0.0, 0.0]));
        assert!(parse_css_hex("red").is_none());
        assert_eq!(parse_css_hex("0x00009e").map(|c| c[2]), Some(0x9e as f32 / 255.0));
    }
}