BREP_render 0.1.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
use super::*;
use super::sketch_edit_ops::is_plain_number_literal;

/// The world-space overlay group carrying the FD leaders + arrowheads.
const FEATURE_DIM_OVERLAY: &str = "feature-dim-leaders";

impl EngineState {
    /// The armed ◎ gizmo mode: `"none"`, `"transform"`, or `"dimension"`. Drives
    /// the ◎ highlight + the app's dimension-overlay draw / input routing.
    pub fn gizmo_mode(&self) -> &'static str {
        match self.transform_gizmo.mode {
            GizmoMode::None => "none",
            GizmoMode::Transform => "transform",
            GizmoMode::Dimension => "dimension",
        }
    }

    /// Whether the DIMENSION gizmo is armed for THIS feature (drives the ◎
    /// dimension-mode highlight).
    pub fn dimension_armed_for(&self, feature_id: &str) -> bool {
        matches!(self.transform_gizmo.mode, GizmoMode::Dimension)
            && self.transform_gizmo.feature_id.as_deref() == Some(feature_id)
    }

    /// The dimension-armed feature id (empty unless in dimension mode).
    pub fn dimension_armed_feature(&self) -> String {
        if matches!(self.transform_gizmo.mode, GizmoMode::Dimension) {
            self.transform_gizmo.feature_id.clone().unwrap_or_default()
        } else {
            String::new()
        }
    }

    /// Arm the DIMENSION gizmo for `feature_id`: hide the transform widget, show
    /// the annotation overlay. Re-arming a different feature moves it.
    pub fn arm_dimension(&mut self, feature_id: &str) {
        self.transform_gizmo.feature_id = Some(feature_id.to_string());
        self.transform_gizmo.mode = GizmoMode::Dimension;
        self.transform_gizmo.drag = None;
        // The transform widget and the dimension overlay are mutually exclusive.
        let _ = self.widgets.set_transform_json("null");
        self.refresh_feature_dimension_overlay();
        self.dirty = true;
    }

    // --- The orange center-sphere ◎ TOGGLE (dimension ↔ transform) ---------
    //
    // A single orange sphere sits at the gizmo center in BOTH modes: the
    // transform gizmo's `HANDLE_CENTER` sphere and the dimension arrows' shared
    // origin sphere project to the same point. Clicking it flips the two modes,
    // mirroring the old app's `CombinedTransformControls` center-handle toggle
    // (pointer-down on `HANDLE_CENTER` calls
    // `toggleDisplayMode`). The viewport routes a bare CLICK here; a DRAG on the
    // center still free-moves via `transform_press` (unchanged).

    /// Whether a screen-px pick in TRANSFORM mode lands on the orange CENTER
    /// free-move sphere (`HANDLE_CENTER`). The viewport uses this to make a bare
    /// click on the center TOGGLE to the dimension arrows (via
    /// [`toggle_to_dimension`](Self::toggle_to_dimension)) instead of swallowing
    /// it as a generic handle click. False in any other gizmo mode.
    pub fn transform_center_pick(&self, x: f64, y: f64) -> bool {
        matches!(self.transform_gizmo.mode, GizmoMode::Transform)
            && self.transform_pick(x, y) == brep_gizmos::transform::HANDLE_CENTER
    }

    /// Whether a screen-px pick in DIMENSION mode lands on an orange ORIGIN
    /// sphere of the armed feature's dimension arrows. Each distinct annotation
    /// draws such a sphere — a LINEAR dim at its `point_a` (a cube's three axis
    /// dims share one, a cone/pyramid draw two), an ANGULAR dim at its arc
    /// `center` (the vertex; its sweep-END sphere is the angle DRAG handle, not a
    /// toggle) — so every one is projected via the camera and hit-tested against
    /// the screen-constant sphere radius. The viewport uses this to TOGGLE back to
    /// the transform gizmo (via [`toggle_to_transform`](Self::toggle_to_transform)),
    /// which is the ONLY way an angular-only feature (a revolve) reaches transform.
    /// False in any other gizmo mode. The hit radius mirrors the gizmo center's own
    /// tolerance (`PX_CENTER_RAD + 2.0`, transform.rs) so the two toggle targets match.
    pub fn dimension_origin_pick(&self, x: f64, y: f64) -> bool {
        if !matches!(self.transform_gizmo.mode, GizmoMode::Dimension) {
            return false;
        }
        let feature = self.dimension_armed_feature();
        if feature.is_empty() {
            return false;
        }
        let hit_r = crate::feature_dimensions::ORIGIN_SPHERE_RAD_PX + 2.0;
        let hit_r2 = hit_r * hit_r;
        for ann in self.feature_dimension_annotations(&feature) {
            // A LINEAR dim's orange origin sphere sits at `point_a`; an ANGULAR
            // dim's sits at `center` (the arc vertex). Project whichever this
            // annotation uses as its mode-toggle target.
            let target = match ann.kind {
                crate::feature_dimensions::FeatureDimKind::Linear => ann.point_a,
                crate::feature_dimensions::FeatureDimKind::Angular => ann.center,
            };
            let (sx, sy, depth) = self.camera.project(target);
            if depth <= 0.0 {
                continue; // origin behind the camera → no sphere on screen
            }
            let (dx, dy) = (sx - x, sy - y);
            if dx * dx + dy * dy <= hit_r2 {
                return true;
            }
        }
        false
    }

    /// Whether a screen-px pick in DIMENSION mode lands on a dimension ARROWHEAD
    /// (a linear leader's orange cone TIP at `point_b`, or an angular arc's orange
    /// sweep-END handle sphere). Returns the grabbed annotation's `field_key` — the
    /// viewport routes a DRAG that starts here to [`feature_dimension_drag`](Self::
    /// feature_dimension_drag), editing that param live (Fix 4). `None` in any other
    /// gizmo mode / when no arrowhead is under the pointer. Distinct from
    /// [`dimension_origin_pick`](Self::dimension_origin_pick): that grabs the SHARED
    /// origin sphere (a mode toggle), this grabs an arrowHEAD (a value edit). The
    /// nearest arrowhead within the screen-constant hit radius wins.
    pub fn dimension_arrow_pick(&self, x: f64, y: f64) -> Option<String> {
        if !matches!(self.transform_gizmo.mode, GizmoMode::Dimension) {
            return None;
        }
        let feature = self.dimension_armed_feature();
        if feature.is_empty() {
            return None;
        }
        let wpp = self.camera.world_per_pixel();
        let hit_r = crate::feature_dimensions::ARROW_HANDLE_HIT_RAD_PX;
        let hit_r2 = hit_r * hit_r;
        let mut best: Option<(f64, String)> = None;
        for ann in self.feature_dimension_annotations(&feature) {
            let tip = crate::feature_dimensions::arrow_handle_point(&ann, wpp);
            let (sx, sy, depth) = self.camera.project(tip);
            if depth <= 0.0 {
                continue; // arrowhead behind the camera
            }
            let (dx, dy) = (sx - x, sy - y);
            let d2 = dx * dx + dy * dy;
            if d2 <= hit_r2 && best.as_ref().map(|(bd, _)| d2 < *bd).unwrap_or(true) {
                best = Some((d2, ann.field_key.clone()));
            }
        }
        best.map(|(_, key)| key)
    }

    /// Toggle the armed ◎ gizmo from TRANSFORM to DIMENSION for the currently
    /// transform-armed feature (the orange center-sphere click). No-op unless a
    /// feature is transform-armed.
    pub fn toggle_to_dimension(&mut self) {
        let feature = self.transform_armed_feature();
        if !feature.is_empty() {
            self.arm_dimension(&feature);
        }
    }

    /// Toggle the armed ◎ gizmo from DIMENSION to TRANSFORM for the currently
    /// dimension-armed feature (the orange origin-sphere click). No-op unless a
    /// feature is dimension-armed.
    pub fn toggle_to_transform(&mut self) {
        let feature = self.dimension_armed_feature();
        if !feature.is_empty() {
            self.arm_transform(&feature);
        }
    }

    /// The linear dimension annotations for `feature_id` (resolving expression
    /// params against the live history env first). `[]` for a feature type with
    /// no FD-1 builder / a missing feature.
    fn feature_dimension_annotations(
        &self,
        feature_id: &str,
    ) -> Vec<crate::feature_dimensions::FeatureDimAnnotation> {
        let Some(index) = self.history.index_of(feature_id) else {
            return Vec::new();
        };
        let Some(feature_type) = self.history.feature_type(index) else {
            return Vec::new();
        };
        let Some(params) = self.history.feature_params(index) else {
            return Vec::new();
        };
        let resolved = self.resolve_param_expressions(&params);
        // Resolve any scene references the builder needs (extrude profile plane,
        // revolve axis line) from the run report's profiles/axes — keyed off the
        // ORIGINAL params so reference-name strings are read verbatim.
        let refs = self.feature_dimension_refs(&feature_type, &params);
        crate::feature_dimensions::build_annotations_with_refs(&feature_type, &resolved, &refs)
    }

    /// Resolve the scene references a feature-dimension builder needs beyond its
    /// pure params: the extrude/revolve profile PLANE (center + normal) and the
    /// revolve AXIS line. Sourced from the run report the engine already holds —
    /// `sketch_profiles` (the sketch's world profile, which survives being
    /// consumed by the extrude/revolve since only solids honor `removed`) and
    /// `sketch_axes` (a sketch's published axis lines), with a resident-edge
    /// polyline fallback for the axis. Empty for any other feature type; missing
    /// pieces stay `None` so the builder degrades to `[]` gracefully.
    fn feature_dimension_refs(
        &self,
        feature_type: &str,
        params: &serde_json::Value,
    ) -> crate::feature_dimensions::ResolvedRefs {
        let mut refs = crate::feature_dimensions::ResolvedRefs::default();
        match feature_type {
            "E" => {
                if let Some(profile) = self.lookup_sketch_profile(params.get("profile")) {
                    refs.profile_center = Some(sketch_profile_centroid(profile));
                    refs.profile_normal = Some(vec3_to_arr(profile.z_axis));
                }
            }
            "R" => {
                if let Some(profile) = self.lookup_sketch_profile(params.get("profile")) {
                    refs.profile_center = Some(sketch_profile_centroid(profile));
                    refs.profile_normal = Some(vec3_to_arr(profile.z_axis));
                }
                if let Some((point, dir)) = self.lookup_axis_line(params.get("axis")) {
                    refs.axis_point = Some(point);
                    refs.axis_dir = Some(dir);
                }
            }
            _ => {}
        }
        refs
    }

    /// Resolve a `profile` reference param to the sketch profile the engine holds
    /// (exact name, or the `:PROFILE`-suffixed form — mirrors `SceneMap::resolve_profile`).
    fn lookup_sketch_profile(
        &self,
        profile_param: Option<&serde_json::Value>,
    ) -> Option<&brep_kernel::SketchProfile> {
        let name = first_reference_name(profile_param?)?;
        // A committed sketch is surfaced as a render display sheet aliased
        // `{sketch}:FACE`, and profile consumers may reference the `{sketch}:PROFILE`
        // form; both alias the base sketch id the run report keys `sketch_profiles`
        // by. Strip either so the extrude/revolve gizmo resolves the same profile the
        // kernel does (mirrors `common::normalize_profile_alias` / `resolve_profile`).
        let base = name
            .strip_suffix(":FACE")
            .or_else(|| name.strip_suffix(":PROFILE"))
            .unwrap_or(&name);
        self.sketch_profiles
            .iter()
            .find(|(id, _)| id == &name || id == base)
            .map(|(_, profile)| profile)
    }

    /// Resolve an `axis` reference param to a world line `(point, unit direction)`:
    /// a published sketch axis first (`sketch_axes`), else a resident solid EDGE's
    /// polyline endpoints (`scene.edge_polyline_world`). `None` if neither resolves.
    fn lookup_axis_line(
        &self,
        axis_param: Option<&serde_json::Value>,
    ) -> Option<([f64; 3], [f64; 3])> {
        let name = first_reference_name(axis_param?)?;
        if let Some((_, axis)) = self.sketch_axes.iter().find(|(id, _)| id == &name) {
            let dir = fd_normalize3(vec3_to_arr(axis.direction));
            return Some((vec3_to_arr(axis.point), dir));
        }
        // Fallback: a resident edge used as an axis — take its polyline endpoints.
        let poly = self.scene.edge_polyline_world(&name)?;
        let first = *poly.first()?;
        let last = *poly.last()?;
        let dir = fd_sub3(last, first);
        if fd_norm3(dir) < 1e-9 {
            return None;
        }
        Some((first, fd_normalize3(dir)))
    }

    /// A copy of `params` with each top-level STRING field evaluated against the
    /// history's `expressions` + `configurator` (the kernel `eval_expression`) and
    /// replaced by its finite numeric result — so an expression-valued param
    /// (e.g. `sizeX: "a + b"`) places its dimension at the resolved length.
    /// Non-numeric strings (ids, enum options) fail to eval and stay verbatim.
    fn resolve_param_expressions(&self, params: &serde_json::Value) -> serde_json::Value {
        let expressions = self.history.expressions();
        let configurator = self.history.configurator();
        let mut out = params.clone();
        if let Some(object) = out.as_object_mut() {
            for value in object.values_mut() {
                if let Some(source) = value.as_str() {
                    if let Ok(number) =
                        brep_kernel::eval_expression(&expressions, &configurator, source)
                    {
                        if number.is_finite() {
                            *value = serde_json::json!(number);
                        }
                    }
                }
            }
        }
        out
    }

    /// The dimension annotations for `feature_id` as JSON:
    /// `[{ fieldKey, pointA, pointB, value, label, mid }]` (world-space points;
    /// `mid` is the leader midpoint the app anchors the label at). `[]` when the
    /// feature type has no FD-1 builder.
    pub fn feature_dimension_annotations_json(&self, feature_id: &str) -> String {
        use crate::feature_dimensions::FeatureDimKind;
        let annotations = self.feature_dimension_annotations(feature_id);
        let wpp = self.camera.world_per_pixel();
        let out: Vec<serde_json::Value> = annotations
            .iter()
            .map(|a| {
                // The chip anchor: a linear leader's midpoint, or an angular arc's
                // mid-sweep point at the screen-constant radius (camera-dependent,
                // so computed here with the live `world_per_pixel`). `kind` lets the
                // app format the chip (`A 234°` for an angular value in DEGREES).
                let (kind, mid) = match a.kind {
                    FeatureDimKind::Linear => ("linear", a.midpoint()),
                    FeatureDimKind::Angular => {
                        ("angular", crate::feature_dimensions::angular_chip_anchor(a, wpp))
                    }
                };
                serde_json::json!({
                    "fieldKey": a.field_key,
                    "pointA": a.point_a,
                    "pointB": a.point_b,
                    "value": a.value,
                    "label": a.label,
                    "mid": mid,
                    "kind": kind,
                })
            })
            .collect();
        serde_json::to_string(&out).unwrap_or_else(|_| "[]".to_string())
    }

    /// The `{ mode, feature, annotations }` snapshot the headless verifier reads
    /// (published as `__brepFeatureDim`).
    pub fn feature_dimension_state_json(&self) -> String {
        let feature = self.dimension_armed_feature();
        let annotations: serde_json::Value = if feature.is_empty() {
            serde_json::json!([])
        } else {
            serde_json::from_str(&self.feature_dimension_annotations_json(&feature))
                .unwrap_or_else(|_| serde_json::json!([]))
        };
        serde_json::json!({
            "mode": self.gizmo_mode(),
            "feature": feature,
            "annotations": annotations,
        })
        .to_string()
    }

    /// The `set_overlay` JSON for the `feature-dim-leaders` group — the annotation
    /// leaders + arrowheads for the dimension-armed feature (empty when not in
    /// dimension mode, so a stale group is cleared).
    fn feature_dimension_overlay_json(&self) -> String {
        let feature = self.dimension_armed_feature();
        let annotations = if feature.is_empty() {
            Vec::new()
        } else {
            self.feature_dimension_annotations(&feature)
        };
        let (positions, colors) = crate::feature_dimensions::leaders_buffers(
            &annotations,
            self.camera.world_per_pixel(),
        );
        serde_json::json!({
            "groups": [
                {
                    "name": FEATURE_DIM_OVERLAY,
                    "renderOrder": 10003,
                    "tris": { "positions": positions, "colors": colors },
                }
            ]
        })
        .to_string()
    }

    /// (Re)project the dimension leaders onto the current geometry. Called on arm
    /// + after every param change (drag / value edit / rerun in dimension mode).
    pub fn refresh_feature_dimension_overlay(&mut self) {
        let json = self.feature_dimension_overlay_json();
        let _ = self.set_overlay_json(&json);
    }

    /// Clear the dimension overlay (an empty group), e.g. when disarming or
    /// switching to transform mode.
    pub(super) fn clear_feature_dimension_overlay(&mut self) {
        let _ = self.set_overlay_json(&serde_json::json!({
            "groups": [ { "name": FEATURE_DIM_OVERLAY } ]
        }).to_string());
    }

    /// Drag a dimension handle: project the pointer pixel `(x, y)` onto the
    /// annotation's world axis (`pointA → pointB`), take the distance along the
    /// axis from `pointA` as the new value (correcting for any transform scale so
    /// the PARAM — not the scaled world length — is what changes), set the param,
    /// and re-run the history live. Degenerate projections (parallel ray / zero
    /// axis) no-op.
    pub fn feature_dimension_drag(&mut self, feature_id: &str, field_key: &str, x: f64, y: f64) {
        let annotations = self.feature_dimension_annotations(feature_id);
        let Some(annotation) = annotations.iter().find(|a| a.field_key == field_key) else {
            return;
        };
        if annotation.kind == crate::feature_dimensions::FeatureDimKind::Angular {
            if let Some(degrees) = self.angular_drag_degrees(annotation, x, y) {
                self.write_feature_dimension_param(feature_id, field_key, serde_json::json!(degrees));
                // Live-follow: re-bake the world-space leaders onto the rebuilt
                // geometry so the arc tracks the pointer this frame (Fix 3).
                self.refresh_feature_dimension_overlay();
            }
            return;
        }
        let a = annotation.point_a;
        let b = annotation.point_b;
        let axis = fd_sub3(b, a);
        let len = fd_norm3(axis);
        if len < 1e-9 {
            return;
        }
        let dir = [axis[0] / len, axis[1] / len, axis[2] / len];
        let ray = self.camera.pick_ray(x, y);
        let ray_dir = fd_normalize3(ray.dir);
        let Some(t_world) = closest_t_on_axis(a, dir, ray.origin, ray_dir) else {
            return;
        };
        // World distance → param value: correct for the local axis scale via the
        // CURRENT ratio (world length / current param). Under unit scale this is
        // the identity; when the param is ~0 there is no ratio, so use the world
        // distance directly (unit-scale assumption).
        let scale_recip = if annotation.value.abs() > 1e-9 && len > 1e-9 {
            annotation.value / len
        } else {
            1.0
        };
        // Preserve SIGN so a linear dim can be dragged through the origin to the
        // negative side (a directional dim — cube size, height — then extends the
        // other way; the kernel takes |value| for magnitude dims). A small dead-zone
        // keeps it off an exact 0 (a degenerate extent the builders reject).
        let raw = t_world * scale_recip;
        let new_value = if raw >= 0.0 { raw.max(1e-4) } else { raw.min(-1e-4) };
        self.write_feature_dimension_param(feature_id, field_key, serde_json::json!(new_value));
        // Live-follow: re-bake the world-space leaders onto the rebuilt geometry so
        // the arrow tracks the pointer this frame (Fix 3).
        self.refresh_feature_dimension_overlay();
    }

    /// Map a pointer pixel to a swept angle (DEGREES) for an ANGULAR annotation:
    /// search the sweep for the degree whose arc-end projects nearest the pointer
    /// (a coarse 2° pass, then a ±2° refine at 0.25°), snap to 1°, clamp to
    /// `[-360, 360]`. Ported from the overlay `angle` drag. The magnitude is
    /// floored off exactly 0 so a torus `arc` drag never lands on 0 — which the
    /// kernel's `|| 360` falsy fallback would flip to a FULL torus mid-drag.
    /// `None` if the arc never projects in front of the camera.
    fn angular_drag_degrees(
        &self,
        ann: &crate::feature_dimensions::FeatureDimAnnotation,
        x: f64,
        y: f64,
    ) -> Option<f64> {
        let radius = crate::feature_dimensions::ANGLE_ARC_RAD_PX * self.camera.world_per_pixel();
        if radius <= 1e-9 {
            return None;
        }
        // A sweep of `deg` and `deg - 360` share the SAME arc-end world point, so
        // the screen-nearest search alone can't tell them apart at the wrap. Break
        // the tie toward the CURRENT value (angle-unwrap
        // continuity) with a tiny bias `~1e-6·Δ°²` — decisive only when screen
        // errors are essentially equal, negligible against any real pointer move.
        let current = ann.value;
        let combined = |screen_err: f64, deg: f64| -> f64 {
            let d = deg - current;
            screen_err + 1e-6 * d * d
        };
        let mut best_deg = current;
        let mut best_err = f64::INFINITY;
        // Coarse sweep over the full range.
        let mut deg = -360.0;
        while deg <= 360.0 {
            if let Some(err) = self.angle_arc_end_err(ann, radius, deg, x, y) {
                let err = combined(err, deg);
                if err < best_err {
                    best_err = err;
                    best_deg = deg;
                }
            }
            deg += 2.0;
        }
        if !best_err.is_finite() {
            return None;
        }
        // Refine around the coarse best.
        let center = best_deg;
        let mut deg = center - 2.0;
        while deg <= center + 2.0 {
            if (-360.0..=360.0).contains(&deg) {
                if let Some(err) = self.angle_arc_end_err(ann, radius, deg, x, y) {
                    let err = combined(err, deg);
                    if err < best_err {
                        best_err = err;
                        best_deg = deg;
                    }
                }
            }
            deg += 0.25;
        }
        let clamped = best_deg.round().clamp(-360.0, 360.0);
        let floored = if clamped.abs() < 0.1 {
            if clamped < 0.0 { -0.1 } else { 0.1 }
        } else {
            clamped
        };
        Some(floored)
    }

    /// Squared screen-pixel distance from `(x, y)` to the arc-end at `deg` for an
    /// angular annotation (`center + rotate(ref_dir, axis, deg) * radius`), or
    /// `None` when that point is behind the camera.
    fn angle_arc_end_err(
        &self,
        ann: &crate::feature_dimensions::FeatureDimAnnotation,
        radius: f64,
        deg: f64,
        x: f64,
        y: f64,
    ) -> Option<f64> {
        let dir = fd_normalize3(crate::feature_dimensions::rotate_about_axis(
            ann.ref_dir,
            ann.axis,
            deg.to_radians(),
        ));
        let p = [
            ann.center[0] + dir[0] * radius,
            ann.center[1] + dir[1] * radius,
            ann.center[2] + dir[2] * radius,
        ];
        let (sx, sy, depth) = self.camera.project(p);
        if depth <= 0.0 {
            return None;
        }
        Some((sx - x) * (sx - x) + (sy - y) * (sy - y))
    }

    /// Edit a dimension value from a label field: a plain numeric literal sets the
    /// param to that number; otherwise the input is treated as an EXPRESSION —
    /// evaluated LIVE against the history's `expressions` + `configurator` (the
    /// kernel `eval_expression`) and, on success, STORED as the expression string
    /// (the kernel re-evaluates it via `ctx.number`, so it stays live). A blank /
    /// bad-expression input no-ops (never corrupts the feature). Re-runs live.
    pub fn feature_dimension_set_value(&mut self, feature_id: &str, field_key: &str, input: &str) {
        let trimmed = input.trim();
        if trimmed.is_empty() {
            return;
        }
        if is_plain_number_literal(trimmed) {
            let Ok(number) = trimmed.parse::<f64>() else {
                return;
            };
            if !number.is_finite() {
                return;
            }
            self.write_feature_dimension_param(feature_id, field_key, serde_json::json!(number));
        } else {
            // Validate the expression before storing it (a bad expression no-ops).
            let expressions = self.history.expressions();
            let configurator = self.history.configurator();
            match brep_kernel::eval_expression(&expressions, &configurator, trimmed) {
                Ok(number) if number.is_finite() => {
                    self.write_feature_dimension_param(
                        feature_id,
                        field_key,
                        serde_json::Value::String(trimmed.to_string()),
                    );
                }
                _ => {}
            }
        }
    }

    /// Set one `inputParams` field of `feature_id` (a number or an expression
    /// string) and re-run the history (which re-projects the leaders in dimension
    /// mode). No-op when the feature is absent.
    fn write_feature_dimension_param(
        &mut self,
        feature_id: &str,
        field_key: &str,
        value: serde_json::Value,
    ) {
        let Some(index) = self.history.index_of(feature_id) else {
            return;
        };
        let mut params = self
            .history
            .feature_params(index)
            .unwrap_or_else(|| serde_json::json!({}));
        let Some(object) = params.as_object_mut() else {
            return;
        };
        object.insert(field_key.to_string(), value);
        let _ = self.update_feature_params(feature_id, &params.to_string());
    }
}

// --- FD-1 geometry helpers (self-contained, `fd_` prefixed to avoid clashes) ---

fn fd_sub3(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
    [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
}

fn fd_dot3(a: [f64; 3], b: [f64; 3]) -> f64 {
    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}

fn fd_norm3(v: [f64; 3]) -> f64 {
    fd_dot3(v, v).sqrt()
}

fn fd_normalize3(v: [f64; 3]) -> [f64; 3] {
    let n = fd_norm3(v);
    if n < 1e-12 {
        [0.0, 0.0, 1.0]
    } else {
        [v[0] / n, v[1] / n, v[2] / n]
    }
}

/// The parameter `t` of the point on the axis line `a + t*dir` (dir UNIT) closest
/// to the ray `ray_o + s*ray_d` (ray_d UNIT). `None` when the two are parallel
/// (no well-defined projection). `t` is the signed world distance along `dir`
/// from `a`.
fn closest_t_on_axis(
    a: [f64; 3],
    dir: [f64; 3],
    ray_o: [f64; 3],
    ray_d: [f64; 3],
) -> Option<f64> {
    let w0 = fd_sub3(a, ray_o);
    let b = fd_dot3(dir, ray_d);
    let d = fd_dot3(dir, w0);
    let e = fd_dot3(ray_d, w0);
    let denom = 1.0 - b * b;
    if denom.abs() < 1e-9 {
        return None;
    }
    Some((b * e - d) / denom)
}

fn vec3_to_arr(v: brep_kernel::Vec3) -> [f64; 3] {
    [v.x, v.y, v.z]
}

/// The FIRST reference NAME in a `reference_selection` param: a bare string, an
/// object's `name`, or the first name in an array (port of the kernel
/// `first_reference_name`). Trims + drops empties.
fn first_reference_name(value: &serde_json::Value) -> Option<String> {
    match value {
        serde_json::Value::String(text) => {
            let trimmed = text.trim();
            (!trimmed.is_empty()).then(|| trimmed.to_string())
        }
        serde_json::Value::Object(map) => map
            .get("name")
            .and_then(|v| v.as_str())
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty()),
        serde_json::Value::Array(items) => items.iter().find_map(first_reference_name),
        _ => None,
    }
}

/// The world CENTROID of a sketch profile — the average of its outer-loop curve
/// start points (the profile-polygon vertices), approximating the previous
/// face-average-center computation. Falls back to the sketch plane origin when
/// no outer loop is available. Used to anchor the extrude/revolve gizmos on the
/// geometry rather than at a possibly-far sketch-plane origin.
fn sketch_profile_centroid(profile: &brep_kernel::SketchProfile) -> [f64; 3] {
    let mut sum = [0.0f64; 3];
    let mut count = 0usize;
    if let Some(outer) = profile.regions.first().and_then(|region| region.first()) {
        for curve in &outer.curves {
            if let Ok(domain) = curve.domain() {
                if let Ok(point) = curve.evaluate(domain[0]) {
                    sum[0] += point.x;
                    sum[1] += point.y;
                    sum[2] += point.z;
                    count += 1;
                }
            }
        }
    }
    if count > 0 {
        [sum[0] / count as f64, sum[1] / count as f64, sum[2] / count as f64]
    } else {
        vec3_to_arr(profile.origin)
    }
}

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

    /// A one-primitive history request (identity transform) for the given type +
    /// params, so the engine builds it and the dimension methods can read it.
    fn primitive_request(feature_type: &str, id: &str, params: serde_json::Value) -> String {
        let mut input = params.as_object().cloned().unwrap_or_default();
        input.insert("id".into(), serde_json::json!(id));
        input.insert(
            "transform".into(),
            serde_json::json!({
                "position": [0.0, 0.0, 0.0],
                "rotationEuler": [0.0, 0.0, 0.0],
                "scale": [1.0, 1.0, 1.0]
            }),
        );
        input.insert(
            "boolean".into(),
            serde_json::json!({ "targets": [], "operation": "NONE" }),
        );
        serde_json::json!({
            "expressions": "",
            "configurator": {},
            "features": [{
                "type": feature_type,
                "inputParams": input,
                "persistentData": {}
            }]
        })
        .to_string()
    }

    fn cube_engine() -> EngineState {
        let mut state = EngineState::new();
        state
            .set_history_json(&primitive_request(
                "P.CU",
                "Box",
                serde_json::json!({ "sizeX": 10.0, "sizeY": 20.0, "sizeZ": 30.0 }),
            ))
            .unwrap();
        state
    }

    #[test]
    fn annotations_json_for_a_cube_has_three_linear_dims() {
        let state = cube_engine();
        let json: serde_json::Value =
            serde_json::from_str(&state.feature_dimension_annotations_json("Box")).unwrap();
        let arr = json.as_array().unwrap();
        assert_eq!(arr.len(), 3);
        assert_eq!(arr[0]["fieldKey"], "sizeX");
        assert_eq!(arr[0]["value"].as_f64().unwrap(), 10.0);
        assert!(arr[0]["pointA"].is_array() && arr[0]["pointB"].is_array());
        assert!(arr[0]["mid"].is_array());
    }

    #[test]
    fn annotations_json_for_a_cylinder_has_radius_and_height() {
        let mut state = EngineState::new();
        state
            .set_history_json(&primitive_request(
                "P.CY",
                "Cyl",
                serde_json::json!({ "radius": 4.0, "height": 12.0 }),
            ))
            .unwrap();
        let json: serde_json::Value =
            serde_json::from_str(&state.feature_dimension_annotations_json("Cyl")).unwrap();
        let arr = json.as_array().unwrap();
        assert_eq!(arr.len(), 2);
        assert_eq!(arr[0]["fieldKey"], "radius");
        assert_eq!(arr[1]["fieldKey"], "height");
    }

    /// Task C audit — every PRIMITIVE that carries a Transform group also ships a
    /// dimension builder, so expanding it auto-arms a dimension gizmo (`HistoryPanel`
    /// guards on `feature_dimension_annotations_json != "[]"`). That gizmo's
    /// origin/center sphere is the ONLY route to the transform gizmo now that the ◎
    /// arm-button is gone, so a primitive with no dims would be stranded. Assert all
    /// six expose a non-empty dimension gizmo AND arm to dimension mode. (Datum /
    /// helix / pattern / port ALSO carry a Transform group but NO dim builder — they
    /// have no path to transform post-◎-removal; flagged in the handoff, not fixed.)
    #[test]
    fn every_transformable_primitive_auto_arms_a_dimension_gizmo() {
        let cases: [(&str, serde_json::Value); 6] = [
            ("P.CU", serde_json::json!({ "sizeX": 10.0, "sizeY": 20.0, "sizeZ": 30.0 })),
            ("P.CY", serde_json::json!({ "radius": 4.0, "height": 12.0 })),
            ("P.CO", serde_json::json!({ "radiusBottom": 4.0, "radiusTop": 2.0, "height": 10.0 })),
            ("P.S", serde_json::json!({ "radius": 5.0 })),
            ("P.PY", serde_json::json!({ "baseSideLength": 6.0, "height": 8.0 })),
            ("P.T", serde_json::json!({ "majorRadius": 6.0, "tubeRadius": 1.5, "arc": 120.0 })),
        ];
        for (ty, params) in cases {
            let mut state = EngineState::new();
            state
                .set_history_json(&primitive_request(ty, "Feat", params))
                .unwrap_or_else(|e| panic!("{ty} builds: {e}"));
            assert_ne!(
                state.feature_dimension_annotations_json("Feat"),
                "[]",
                "{ty} must expose a dimension gizmo so expanding it auto-arms one"
            );
            // Arming it (what expand does) lands in dimension mode.
            state.arm_dimension("Feat");
            assert_eq!(state.gizmo_mode(), "dimension", "{ty}");
        }
    }

    #[test]
    fn annotations_json_empty_for_unknown_feature() {
        let state = cube_engine();
        assert_eq!(state.feature_dimension_annotations_json("nope"), "[]");
    }

    #[test]
    fn set_value_updates_the_param_and_reruns() {
        let mut state = cube_engine();
        state.arm_dimension("Box");
        state.feature_dimension_set_value("Box", "sizeX", "25");
        let index = state.history.index_of("Box").unwrap();
        let params = state.history.feature_params(index).unwrap();
        assert_eq!(params["sizeX"].as_f64().unwrap(), 25.0);
        // The reported annotation picks up the new value.
        let json: serde_json::Value =
            serde_json::from_str(&state.feature_dimension_annotations_json("Box")).unwrap();
        assert_eq!(json[0]["value"].as_f64().unwrap(), 25.0);
    }

    #[test]
    fn set_value_stores_expression_string_when_not_a_literal() {
        let mut state = cube_engine();
        // Seed a variable in the history expressions.
        state.set_expressions("w = 7;");
        state.feature_dimension_set_value("Box", "sizeX", "w * 2");
        let index = state.history.index_of("Box").unwrap();
        let params = state.history.feature_params(index).unwrap();
        // The expression is stored verbatim (the kernel re-evaluates it live).
        assert_eq!(params["sizeX"].as_str().unwrap(), "w * 2");
        // …and resolves to 14 in the reported annotation.
        let json: serde_json::Value =
            serde_json::from_str(&state.feature_dimension_annotations_json("Box")).unwrap();
        assert_eq!(json[0]["value"].as_f64().unwrap(), 14.0);
    }

    #[test]
    fn set_value_rejects_a_bad_expression() {
        let mut state = cube_engine();
        state.feature_dimension_set_value("Box", "sizeX", "this is not valid");
        let index = state.history.index_of("Box").unwrap();
        let params = state.history.feature_params(index).unwrap();
        // Unchanged — the bad expression never landed.
        assert_eq!(params["sizeX"].as_f64().unwrap(), 10.0);
    }

    #[test]
    fn origin_sphere_and_center_sphere_toggle_the_two_modes() {
        // The single orange sphere at the gizmo center flips dimension ↔ transform:
        // clicking the dimension arrows' ORIGIN sphere arms the transform gizmo, and
        // clicking the transform gizmo's CENTER sphere arms the dimension arrows.
        let mut state = cube_engine();
        state.resize(800.0, 600.0);
        state.camera.eye = [0.0, 0.0, 40.0];
        state.camera.target = [0.0, 0.0, 0.0];
        state.camera.up = [0.0, 1.0, 0.0];
        state.camera.projection = crate::view::Projection::Orthographic { half_height: 20.0 };

        // Arm the DIMENSION arrows for the cube.
        state.arm_dimension("Box");
        assert_eq!(state.gizmo_mode(), "dimension");

        // The arrows share one ORIGIN sphere at the cube's min corner
        // (annotations[0].pointA). Project it the way `transform_gizmo_anchor` does.
        let anns: serde_json::Value =
            serde_json::from_str(&state.feature_dimension_annotations_json("Box")).unwrap();
        let pa = &anns[0]["pointA"];
        let origin = [
            pa[0].as_f64().unwrap(),
            pa[1].as_f64().unwrap(),
            pa[2].as_f64().unwrap(),
        ];
        let (ox, oy, depth) = state.camera.project(origin);
        assert!(depth > 0.0, "origin in front of camera");

        // A click on the origin sphere toggles DIMENSION → TRANSFORM (mirroring the
        // viewport click-chain). The cross-mode pick is inert here.
        assert!(state.dimension_origin_pick(ox, oy), "pick hits the origin sphere");
        assert!(
            !state.transform_center_pick(ox, oy),
            "no transform-center pick while in dimension mode"
        );
        state.toggle_to_transform();
        assert_eq!(state.gizmo_mode(), "transform");

        // The transform gizmo's orange CENTER sphere sits at the same anchor; a
        // click on it toggles TRANSFORM → DIMENSION.
        let (cx, cy) = state.transform_gizmo_anchor().expect("transform anchor");
        assert!(state.transform_center_pick(cx, cy), "pick hits the center handle");
        assert!(
            !state.dimension_origin_pick(cx, cy),
            "no dimension-origin pick while in transform mode"
        );
        state.toggle_to_dimension();
        assert_eq!(state.gizmo_mode(), "dimension");
    }

    /// A revolve is ANGULAR-ONLY: its single dimension is the sweep angle, whose
    /// mode-toggle target is the arc CENTER (there is no linear origin sphere). So
    /// the center-sphere pick is the ONLY way it reaches the transform gizmo. Assert
    /// the full round trip dimension → transform → dimension. (This guards the FD-2
    /// gap fix — restoring the old `kind != Linear { continue }` skip in
    /// `dimension_origin_pick` makes the first pick miss and fails this test.)
    #[test]
    fn angular_center_sphere_toggles_a_revolve_to_transform_and_back() {
        // Sketch "Sk": a radial rectangle (x∈[2,4], y∈[0,3]) profile + a +Y
        // construction line "Sk:G20" the revolve uses as its axis. The kernel
        // publishes both, and they survive the sketch being consumed by the revolve.
        let request = serde_json::json!({
            "expressions": "",
            "configurator": {},
            "features": [
                {
                    "type": "S",
                    "inputParams": { "id": "Sk" },
                    "persistentData": {
                        "basis": { "origin": [0,0,0], "x": [1,0,0], "y": [0,1,0], "z": [0,0,1] },
                        "sketch": {
                            "points": [
                                {"id":1,"x":2.0,"y":0.0}, {"id":2,"x":4.0,"y":0.0},
                                {"id":3,"x":4.0,"y":3.0}, {"id":4,"x":2.0,"y":3.0},
                                {"id":5,"x":0.0,"y":0.0}, {"id":6,"x":0.0,"y":1.0}
                            ],
                            "geometries": [
                                {"id":10,"type":"line","points":[1,2]},
                                {"id":11,"type":"line","points":[2,3]},
                                {"id":12,"type":"line","points":[3,4]},
                                {"id":13,"type":"line","points":[4,1]},
                                {"id":20,"type":"line","points":[5,6],"construction":true}
                            ],
                            "constraints": []
                        }
                    }
                },
                {
                    "type": "R",
                    "inputParams": { "id": "Rev", "profile": "Sk", "axis": "Sk:G20", "angle": 90.0 },
                    "persistentData": {}
                }
            ]
        })
        .to_string();

        let mut state = EngineState::new();
        state.set_history_json(&request).expect("revolve builds");
        state.resize(800.0, 600.0);
        state.camera.eye = [0.0, 0.0, 40.0];
        state.camera.target = [0.0, 0.0, 0.0];
        state.camera.up = [0.0, 1.0, 0.0];
        state.camera.projection = crate::view::Projection::Orthographic { half_height: 20.0 };

        // The revolve's ONLY dimension is angular — no linear origin sphere exists.
        let anns = state.feature_dimension_annotations("Rev");
        assert_eq!(anns.len(), 1, "revolve emits one (angular) dim: {anns:?}");
        assert_eq!(anns[0].kind, crate::feature_dimensions::FeatureDimKind::Angular);
        let center = anns[0].center;

        // Arm the dimension arrows (what expanding the feature does).
        state.arm_dimension("Rev");
        assert_eq!(state.gizmo_mode(), "dimension");

        // Clicking the arc-CENTER orange sphere toggles DIMENSION → TRANSFORM.
        let (cx, cy, depth) = state.camera.project(center);
        assert!(depth > 0.0, "arc center in front of the camera");
        assert!(
            state.dimension_origin_pick(cx, cy),
            "pick hits the angular center sphere"
        );
        state.toggle_to_transform();
        assert_eq!(state.gizmo_mode(), "transform");

        // And the transform gizmo's CENTER sphere toggles back to the arc.
        let (tx, ty) = state.transform_gizmo_anchor().expect("transform anchor");
        assert!(
            state.transform_center_pick(tx, ty),
            "pick hits the transform center handle"
        );
        state.toggle_to_dimension();
        assert_eq!(state.gizmo_mode(), "dimension");
        assert!(
            state.dimension_armed_for("Rev"),
            "round trip lands back on the revolve's dimension arrows"
        );
    }

    /// A revolve history: sketch "Sk" (radial rectangle profile x∈[2,4], y∈[0,3]
    /// plus a +Y construction line "Sk:G20" used as the axis) revolved `angle`°
    /// about that axis. Mirrors the fixture in
    /// `angular_center_sphere_toggles_a_revolve_to_transform_and_back` so the
    /// revolve's angular dim resolves against a real scene, parameterized by angle.
    fn revolve_engine(angle: f64) -> EngineState {
        revolve_engine_with_profile("Sk", angle)
    }

    /// As [`revolve_engine`] but with the revolve's `profile` reference spelled
    /// `profile` — so a test can drive the committed-sketch `{sketch}:FACE` display
    /// alias through the same live pipeline.
    fn revolve_engine_with_profile(profile: &str, angle: f64) -> EngineState {
        let request = serde_json::json!({
            "expressions": "",
            "configurator": {},
            "features": [
                {
                    "type": "S",
                    "inputParams": { "id": "Sk" },
                    "persistentData": {
                        "basis": { "origin": [0,0,0], "x": [1,0,0], "y": [0,1,0], "z": [0,0,1] },
                        "sketch": {
                            "points": [
                                {"id":1,"x":2.0,"y":0.0}, {"id":2,"x":4.0,"y":0.0},
                                {"id":3,"x":4.0,"y":3.0}, {"id":4,"x":2.0,"y":3.0},
                                {"id":5,"x":0.0,"y":0.0}, {"id":6,"x":0.0,"y":1.0}
                            ],
                            "geometries": [
                                {"id":10,"type":"line","points":[1,2]},
                                {"id":11,"type":"line","points":[2,3]},
                                {"id":12,"type":"line","points":[3,4]},
                                {"id":13,"type":"line","points":[4,1]},
                                {"id":20,"type":"line","points":[5,6],"construction":true}
                            ],
                            "constraints": []
                        }
                    }
                },
                {
                    "type": "R",
                    "inputParams": { "id": "Rev", "profile": profile, "axis": "Sk:G20", "angle": angle },
                    "persistentData": {}
                }
            ]
        })
        .to_string();

        let mut state = EngineState::new();
        state.set_history_json(&request).expect("revolve builds");
        state.resize(800.0, 600.0);
        // Look straight DOWN the revolve axis (the oriented axis is -Y for this
        // fixture; center is (0, 1.5, 0)) so the arc's (cosθ, sinθ) maps uniquely
        // to screen. An edge-on view would alias θ ↔ -θ and defeat the angular
        // drag's nearest-projection search.
        state.camera.eye = [0.0, 40.0, 0.0];
        state.camera.target = [0.0, 1.5, 0.0];
        state.camera.up = [0.0, 0.0, 1.0];
        state.camera.projection = crate::view::Projection::Orthographic { half_height: 20.0 };
        state
    }

    /// The revolve's `angle` surfaces as an ANGULAR annotation in the JSON the app
    /// reads (so the auto-arm lights it up), and its arc arrowhead is pickable +
    /// draggable, writing the swept degrees back to `angle`. Exercises the whole
    /// revolve angle-gizmo pipeline end-to-end against a live scene: `axis`
    /// reference → oriented arc (`orient_revolve_axis`, the kernel's rule) → pick →
    /// angular drag. (The struct-level annotation + center-sphere mode toggle are
    /// covered by `angular_center_sphere_toggles_a_revolve_to_transform_and_back`;
    /// this locks in the JSON surface + the live pick/drag for the revolve.)
    #[test]
    fn revolve_angle_json_is_angular_and_drag_writes_the_swept_degrees() {
        let mut state = revolve_engine(90.0);

        // JSON surface: exactly one angular `angle` entry (what the app + auto-arm
        // read — a non-`[]` result is what auto-arms the gizmo on expand).
        let json: serde_json::Value =
            serde_json::from_str(&state.feature_dimension_annotations_json("Rev")).unwrap();
        let arr = json.as_array().unwrap();
        assert_eq!(arr.len(), 1, "revolve emits one dim: {arr:?}");
        assert_eq!(arr[0]["fieldKey"], "angle");
        assert_eq!(arr[0]["kind"], "angular");
        assert!((arr[0]["value"].as_f64().unwrap() - 90.0).abs() < 1e-9);
        assert!(arr[0]["mid"].is_array(), "angular chip anchors on the arc");

        // Arm the dimension arrows (what expanding the feature does), then grab the
        // revolve's angular dim.
        state.arm_dimension("Rev");
        let ann = state
            .feature_dimension_annotations("Rev")
            .into_iter()
            .find(|a| a.field_key == "angle")
            .expect("angle dim");
        assert_eq!(ann.kind, crate::feature_dimensions::FeatureDimKind::Angular);

        // PRESS on the arc's CURRENT (90°) arrowhead handle → pick grabs `angle`.
        let handle =
            crate::feature_dimensions::arrow_handle_point(&ann, state.world_per_pixel());
        let (hx, hy, hdepth) = state.camera.project(handle);
        assert!(hdepth > 0.0, "handle in front of the camera");
        assert_eq!(
            state.dimension_arrow_pick(hx, hy).as_deref(),
            Some("angle"),
            "pick at the arc arrowhead grabs the angle handle"
        );

        // DRAG toward the arc-end for a larger sweep; the nearest-projection search
        // must recover that degree (within the 1° snap).
        let target = 200.0_f64;
        let radius = crate::feature_dimensions::ANGLE_ARC_RAD_PX * state.world_per_pixel();
        let dir = crate::feature_dimensions::rotate_about_axis(
            ann.ref_dir,
            ann.axis,
            target.to_radians(),
        );
        let world = [
            ann.center[0] + dir[0] * radius,
            ann.center[1] + dir[1] * radius,
            ann.center[2] + dir[2] * radius,
        ];
        let (tx, ty, tdepth) = state.camera.project(world);
        assert!(tdepth > 0.0, "drag target in front of the camera");
        state.feature_dimension_drag("Rev", "angle", tx, ty);

        let after = state.feature_dimension_annotations("Rev");
        let new_angle = after.iter().find(|a| a.field_key == "angle").expect("angle dim");
        assert!(
            (new_angle.value - target).abs() < 2.0,
            "drag should sweep the angle to ~{target}°, got {}",
            new_angle.value
        );
    }

    /// Regression: a revolve (or extrude) whose `profile` references the committed
    /// sketch by its render display alias `{sketch}:FACE` must still resolve the
    /// sketch profile and auto-arm its dimension gizmo. `sketch_profiles` is keyed by
    /// the base sketch id (`Sk`), so `lookup_sketch_profile` has to strip the `:FACE`
    /// alias — exactly as the kernel's profile consumers do. Before the strip this
    /// returned `[]` and the angle arc silently never appeared (the real-world
    /// `RevolveSketch.BREP.json` symptom: profile `S4:FACE`).
    #[test]
    fn revolve_face_alias_profile_still_arms_the_angle_gizmo() {
        let state = revolve_engine_with_profile("Sk:FACE", 90.0);
        let json: serde_json::Value =
            serde_json::from_str(&state.feature_dimension_annotations_json("Rev")).unwrap();
        let arr = json.as_array().unwrap();
        assert_eq!(
            arr.len(),
            1,
            "the `:FACE`-aliased revolve profile must still emit its angular dim: {arr:?}"
        );
        assert_eq!(arr[0]["fieldKey"], "angle");
        assert_eq!(arr[0]["kind"], "angular");
        assert_eq!(arr[0]["value"].as_f64().unwrap(), 90.0);
    }

    #[test]
    fn closest_t_on_axis_projects_a_perpendicular_ray() {
        // Axis along +X from origin; a ray straight down through (7, 5, 0) hits the
        // axis at t = 7.
        let t = closest_t_on_axis(
            [0.0, 0.0, 0.0],
            [1.0, 0.0, 0.0],
            [7.0, 5.0, 0.0],
            [0.0, -1.0, 0.0],
        )
        .unwrap();
        assert!((t - 7.0).abs() < 1e-9, "t = {t}");
    }

    #[test]
    fn closest_t_on_axis_none_when_parallel() {
        assert!(closest_t_on_axis(
            [0.0, 0.0, 0.0],
            [1.0, 0.0, 0.0],
            [0.0, 5.0, 0.0],
            [1.0, 0.0, 0.0],
        )
        .is_none());
    }

    // --- FD-2 angular: torus arc (a primitive with an angular dim) -------------

    fn torus_engine(arc: f64) -> EngineState {
        let mut state = EngineState::new();
        state
            .set_history_json(&primitive_request(
                "P.T",
                "Tor",
                serde_json::json!({ "majorRadius": 6.0, "tubeRadius": 1.5, "arc": arc }),
            ))
            .unwrap();
        state
    }

    #[test]
    fn annotations_json_for_a_torus_has_two_linear_and_one_angular() {
        let state = torus_engine(120.0);
        let json: serde_json::Value =
            serde_json::from_str(&state.feature_dimension_annotations_json("Tor")).unwrap();
        let arr = json.as_array().unwrap();
        assert_eq!(arr.len(), 3);
        assert_eq!(arr[0]["fieldKey"], "majorRadius");
        assert_eq!(arr[0]["kind"], "linear");
        assert_eq!(arr[1]["fieldKey"], "tubeRadius");
        assert_eq!(arr[1]["kind"], "linear");
        // The arc dim is ANGULAR, its value is DEGREES, and its chip anchors on
        // the arc (a world point the app projects).
        assert_eq!(arr[2]["fieldKey"], "arc");
        assert_eq!(arr[2]["kind"], "angular");
        assert_eq!(arr[2]["value"].as_f64().unwrap(), 120.0);
        assert!(arr[2]["mid"].is_array());
    }

    #[test]
    fn dragging_a_torus_arc_writes_the_swept_degrees() {
        let mut state = torus_engine(90.0);
        state.arm_dimension("Tor");
        let anns = state.feature_dimension_annotations("Tor");
        let arc = anns
            .iter()
            .find(|a| a.field_key == "arc")
            .expect("arc dim")
            .clone();
        assert_eq!(arc.kind, crate::feature_dimensions::FeatureDimKind::Angular);

        // Aim the pointer exactly at the arc-end for a target sweep; the drag's
        // nearest-projection search must recover that degree (within the 1° snap).
        let target = 210.0_f64;
        let radius = crate::feature_dimensions::ANGLE_ARC_RAD_PX * state.world_per_pixel();
        let dir = crate::feature_dimensions::rotate_about_axis(
            arc.ref_dir,
            arc.axis,
            target.to_radians(),
        );
        let world = [
            arc.center[0] + dir[0] * radius,
            arc.center[1] + dir[1] * radius,
            arc.center[2] + dir[2] * radius,
        ];
        let (sx, sy, depth) = state.camera.project(world);
        assert!(depth > 0.0, "arc-end must project in front of the camera");

        state.feature_dimension_drag("Tor", "arc", sx, sy);

        let after = state.feature_dimension_annotations("Tor");
        let new_arc = after.iter().find(|a| a.field_key == "arc").expect("arc dim");
        assert!(
            (new_arc.value - target).abs() < 2.0,
            "drag should sweep the arc to ~{target}°, got {}",
            new_arc.value
        );
    }

    // --- Fix 4: dimension-arrow pick + drag (a linear cube dim) ----------------

    #[test]
    fn dimension_arrow_pick_and_drag_edits_the_param_live() {
        let mut state = cube_engine();
        state.resize(800.0, 600.0);
        state.camera.eye = [0.0, 0.0, 40.0]; // look down -Z: +X screen-right, +Y up
        state.camera.target = [0.0, 0.0, 0.0];
        state.camera.up = [0.0, 1.0, 0.0];
        state.camera.projection = crate::view::Projection::Orthographic { half_height: 20.0 };

        // A pick is inert until the dimension arrows are armed.
        state.arm_transform("Box");
        assert!(
            state.dimension_arrow_pick(400.0, 300.0).is_none(),
            "no arrow pick in transform mode"
        );

        state.arm_dimension("Box");
        assert_eq!(state.gizmo_mode(), "dimension");

        // The sizeX dim runs origin → (sizeX,0,0); its orange arrowHEAD is at
        // `point_b`. A pick AT the projected arrowhead grabs the `sizeX` field.
        let ann = state
            .feature_dimension_annotations("Box")
            .into_iter()
            .find(|a| a.field_key == "sizeX")
            .expect("sizeX dim");
        let a = ann.point_a;
        let b = ann.point_b;
        let (bx, by, depth) = state.camera.project(b);
        assert!(depth > 0.0, "arrowhead in front of the camera");
        assert_eq!(
            state.dimension_arrow_pick(bx, by).as_deref(),
            Some("sizeX"),
            "pick at the arrowhead grabs sizeX"
        );
        // A far-off pixel grabs nothing.
        assert!(state.dimension_arrow_pick(10.0, 10.0).is_none(), "empty space → no arrow");

        // DRAG the arrow outward along +X to a target length; the value tracks the
        // pointer live (Fix 3 + Fix 4). Aim the pointer at a + dir*target_len.
        let len = {
            let d = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
            (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt()
        };
        let dir = [(b[0] - a[0]) / len, (b[1] - a[1]) / len, (b[2] - a[2]) / len];
        let target_len = 16.0_f64;
        let world = [
            a[0] + dir[0] * target_len,
            a[1] + dir[1] * target_len,
            a[2] + dir[2] * target_len,
        ];
        let (wx, wy, wdepth) = state.camera.project(world);
        assert!(wdepth > 0.0, "drag target in front of the camera");

        let before = state
            .history
            .feature_params(state.history.index_of("Box").unwrap())
            .unwrap()["sizeX"]
            .as_f64()
            .unwrap();
        state.feature_dimension_drag("Box", "sizeX", wx, wy);
        let after = state
            .history
            .feature_params(state.history.index_of("Box").unwrap())
            .unwrap()["sizeX"]
            .as_f64()
            .unwrap();

        // The param grew toward the drag target. The drag scales the world distance
        // by the current (value / world-length) ratio; under unit scale that is 1,
        // so the new value ≈ target_len.
        let expected = target_len * (ann.value / len);
        assert!(after > before, "sizeX grew: {before} → {after}");
        assert!(
            (after - expected).abs() < 0.5,
            "drag set sizeX to ~{expected}, got {after}"
        );
    }
}