BREP_render 0.2.1

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
use super::transform_gizmo::{
    euler_xyz_deg_from_quat, normalize3, quat_from_axis_angle, quat_from_euler_xyz_deg, quat_mul,
    Quat,
};
use super::*;

// ============================================================================
// The COMPONENT Move gizmo (build-spec §8.5, lane H) — free move + re-solve on
// commit. Reuses the SAME widget transform gizmo (brep-gizmos) as the feature
// transform controller, but with component semantics:
//
//   * ATTACHES at the component's member-bbox CENTER (not the pose origin).
//   * The Move toggle ARMS/DISARMS (`component_move_toggle`); the armed gizmo
//     shows EVERY handle set at once — axis arrows + the center free-move ball
//     + the rotation arcs — so moving and rotating never needs a mode switch.
//   * FIXED components refuse with a toast and never arm.
//   * A drag moves ONLY the gizmo (free move) — the pose param is written ONCE
//     on release (`component_release`), composing the drag delta onto the
//     ACOMP's `inputParams.transform` `{translate, rotateEulerDeg}` (intrinsic-
//     XYZ degrees, the kernel `compose_trs_matrix` convention) and re-running.
//     The constraint tail re-solves on that run and may snap the component back
//     into compliance — BY DESIGN (free move + re-solve on commit; live
//     drag-solve is the named follow-up).
//
// EXCLUSIVE with the feature transform/dimension gizmos: arming any one of the
// three resets the others (they share the one widget slot).
// ============================================================================

/// The component-Move controller state (one per engine, like [`TransformArm`]).
#[derive(Default)]
pub struct ComponentMoveArm {
    /// The ACOMP feature id the gizmo is armed for (`None` = disarmed).
    pub(super) feature_id: Option<String>,
    /// The gizmo pivot — the component's member-bbox center, re-synced after
    /// every applied run so the gizmo follows a re-solved (snapped) component.
    pub(super) anchor: [f64; 3],
    /// The in-flight handle drag (grab snapshot + the pending composed pose).
    pub(super) drag: Option<ComponentMoveDrag>,
}

/// A grab snapshot: the handle, the grab screen point, the pose AT GRAB (the
/// frozen frame every drag move resolves against — no error accumulation), and
/// the PENDING composed pose the release commits.
#[derive(Clone)]
pub(super) struct ComponentMoveDrag {
    handle: u32,
    sx: f32,
    sy: f32,
    start: ComponentPose,
    pending: Option<ComponentPose>,
}

/// A component pose as the gizmo tracks it: the ACOMP `transform` pair plus the
/// gizmo anchor (bbox center) it pivots about.
#[derive(Clone, Copy, PartialEq, Debug)]
pub(super) struct ComponentPose {
    pub translate: [f64; 3],
    pub rotate_deg: [f64; 3],
    pub anchor: [f64; 3],
}

/// A resolved world-space gizmo delta (parsed off the widget drag JSON).
#[derive(Clone, Copy, PartialEq, Debug)]
pub(super) enum ComponentDelta {
    Translate([f64; 3]),
    Rotate { axis: [f64; 3], radians: f64 },
}

impl EngineState {
    /// Whether the component Move gizmo is armed (for any component).
    pub fn component_move_armed(&self) -> bool {
        self.component_move.feature_id.is_some()
    }

    /// The armed component feature id (empty when disarmed).
    pub fn component_move_armed_feature(&self) -> String {
        self.component_move.feature_id.clone().unwrap_or_default()
    }

    /// The Move toggle (context bar / tree action): ARMS the full gizmo (all
    /// handle sets) for `feature_id`, or DISARMS when it is already armed
    /// (arming fresh replaces any other armed component). A FIXED component
    /// refuses with a toast and never arms (spec §8.5).
    pub fn component_move_toggle(&mut self, feature_id: &str) {
        let Some(info) = self.component_info(feature_id) else {
            self.push_notice(format!("'{feature_id}' is not an assembly component"));
            return;
        };
        if info.fixed {
            self.push_notice(format!(
                "{} ({feature_id}) is fixed — unfix it to move",
                info.part_name
            ));
            return;
        }
        if self.component_move.feature_id.as_deref() == Some(feature_id) {
            self.disarm_transform();
        } else {
            self.component_move_arm_widget(feature_id);
        }
    }

    /// The `arm_transform` ROUTE for ACOMP features (history-panel expand):
    /// a FIXED component silently stays armless (the explicit Move action is
    /// the one that toasts).
    pub(super) fn component_move_arm(&mut self, feature_id: &str) {
        match self.component_info(feature_id) {
            Some(info) if !info.fixed => self.component_move_arm_widget(feature_id),
            _ => {}
        }
    }

    /// Drop the component arm STATE only (the caller owns the widget slot) —
    /// the exclusivity hook `arm_transform` / `arm_dimension` / `disarm_transform`
    /// call before taking the slot for themselves.
    pub(super) fn component_move_reset(&mut self) {
        self.component_move = ComponentMoveArm::default();
    }

    /// Arm for `feature_id`: claim the shared widget slot (clearing the
    /// feature gizmo + dimension overlay), pin the anchor at the member-bbox
    /// center, and feed the full handle set.
    fn component_move_arm_widget(&mut self, feature_id: &str) {
        // Claim the shared slot WITHOUT disarm_transform (which would also reset
        // the component state we are about to set).
        self.transform_gizmo.feature_id = None;
        self.transform_gizmo.mode = GizmoMode::None;
        self.transform_gizmo.drag = None;
        self.clear_feature_dimension_overlay();

        let anchor = self
            .component_bbox_center(feature_id)
            .or_else(|| self.component_info(feature_id).map(|info| info.translate))
            .unwrap_or([0.0; 3]);
        self.component_move.feature_id = Some(feature_id.to_string());
        self.component_move.anchor = anchor;
        self.component_move.drag = None;
        self.feed_component_widget();
        self.dirty = true;
    }

    /// (Re)feed the widget gizmo at the armed component's current pose+anchor.
    fn feed_component_widget(&mut self) {
        let Some(id) = self.component_move.feature_id.clone() else {
            return;
        };
        let Some(info) = self.component_info(&id) else {
            return;
        };
        let pose = ComponentPose {
            translate: info.translate,
            rotate_deg: info.rotate_deg,
            anchor: self.component_move.anchor,
        };
        let json = component_frame_json(&pose);
        let _ = self.widgets.set_transform_json(&json);
    }

    /// Post-run re-sync (the [`finish_apply`] hook, mirroring
    /// `sync_transform_gizmo`): re-anchor at the possibly re-solved member bbox
    /// and re-feed; auto-disarm when the component vanished or became fixed.
    pub(super) fn component_move_sync(&mut self) {
        let Some(id) = self.component_move.feature_id.clone() else {
            return;
        };
        match self.component_info(&id) {
            Some(info) if !info.fixed => {
                self.component_move.anchor =
                    self.component_bbox_center(&id).unwrap_or(info.translate);
                self.feed_component_widget();
                self.dirty = true;
            }
            _ => self.disarm_transform(),
        }
    }

    /// Begin a component-gizmo drag at viewport px `(x, y)`; `true` when a
    /// handle was grabbed (the viewport routes the drag here, not the camera).
    pub fn component_press(&mut self, x: f64, y: f64) -> bool {
        let Some(id) = self.component_move.feature_id.clone() else {
            return false;
        };
        let handle = self.transform_pick(x, y);
        if handle == 0 {
            return false;
        }
        let Some(info) = self.component_info(&id) else {
            return false;
        };
        self.widgets.set_transform_active(handle);
        self.component_move.drag = Some(ComponentMoveDrag {
            handle,
            sx: x as f32,
            sy: y as f32,
            start: ComponentPose {
                translate: info.translate,
                rotate_deg: info.rotate_deg,
                anchor: self.component_move.anchor,
            },
            pending: None,
        });
        self.dirty = true;
        true
    }

    /// Whether a component-gizmo drag is in flight.
    pub fn component_move_dragging(&self) -> bool {
        self.component_move.drag.is_some()
    }

    /// Continue the drag: resolve the world delta against the FROZEN grab frame,
    /// compose the pending pose, and move ONLY the visible gizmo (free move —
    /// the mesh follows on release, when the commit re-runs + re-solves).
    pub fn component_drag_to(&mut self, cx: f64, cy: f64) {
        let Some(drag) = self.component_move.drag.clone() else {
            return;
        };
        let cam = gizmo_camera(&self.camera);
        let frame = component_frame_json(&drag.start);
        let json = self.widgets.transform_drag_json_with_frame(
            &cam,
            &frame,
            drag.handle,
            drag.sx,
            drag.sy,
            cx as f32,
            cy as f32,
        );
        let Some(delta) = parse_drag_delta(&json) else {
            return;
        };
        let pending = compose_component_delta(&drag.start, &delta);
        // Live-follow the WIDGET at the pending pose; the gold active-handle
        // highlight survives (only a null feed clears it).
        let json = component_frame_json(&pending);
        let _ = self.widgets.set_transform_json(&json);
        if let Some(live) = self.component_move.drag.as_mut() {
            live.pending = Some(pending);
        }
        self.dirty = true;
    }

    /// End the drag: COMMIT the pending pose into the ACOMP's
    /// `inputParams.transform` (one param write → one undo entry → one rerun
    /// whose constraint tail re-solves; the post-run sync then re-glues the
    /// gizmo to wherever the solve left the component). A grab that never moved
    /// commits nothing.
    pub fn component_release(&mut self) {
        let Some(drag) = self.component_move.drag.take() else {
            return;
        };
        self.widgets.set_transform_active(0);
        self.dirty = true;
        let Some(pending) = drag.pending else {
            return;
        };
        let Some(id) = self.component_move.feature_id.clone() else {
            return;
        };
        self.component_move.anchor = pending.anchor;
        let Some(index) = self.history.index_of(&id) else {
            return;
        };
        let mut params = self
            .history
            .feature_params(index)
            .unwrap_or_else(|| serde_json::json!({}));
        if !params.get("transform").map(|t| t.is_object()).unwrap_or(false) {
            if let Some(object) = params.as_object_mut() {
                object.insert("transform".into(), serde_json::json!({}));
            }
        }
        if let Some(transform) = params.get_mut("transform").and_then(|t| t.as_object_mut()) {
            transform.insert("translate".into(), serde_json::json!(pending.translate));
            transform.insert("rotateEulerDeg".into(), serde_json::json!(pending.rotate_deg));
        }
        let _ = self.update_feature_params(&id, &params.to_string());
    }

    /// The armed component gizmo's logical state for the verifier:
    /// `{armed, feature, anchor}`.
    pub fn component_move_json(&self) -> String {
        serde_json::json!({
            "armed": self.component_move_armed(),
            "feature": self.component_move_armed_feature(),
            "anchor": self.component_move.anchor,
        })
        .to_string()
    }
}

/// The widget frame feed for a component pose: origin = the ANCHOR (bbox
/// center), axes = the pose's rotated basis (intrinsic XYZ, the kernel bake).
/// EVERY handle set is shown (center free-move ball + axis arrows + rotation
/// arcs) — move and rotate coexist, no mode switch.
fn component_frame_json(pose: &ComponentPose) -> String {
    let euler = [
        pose.rotate_deg[0].to_radians(),
        pose.rotate_deg[1].to_radians(),
        pose.rotate_deg[2].to_radians(),
    ];
    let x = normalize3(rotate_euler_xyz_f64([1.0, 0.0, 0.0], euler));
    let y = normalize3(rotate_euler_xyz_f64([0.0, 1.0, 0.0], euler));
    let z = normalize3(rotate_euler_xyz_f64([0.0, 0.0, 1.0], euler));
    serde_json::json!({
        "origin": pose.anchor,
        "x": x,
        "y": y,
        "z": z,
        "showCenter": true,
        "showAxes": true,
        "showRings": true,
    })
    .to_string()
}

/// Parse the widget drag JSON (`transform_drag_json_with_frame`) into a world
/// delta; `None` for `{"kind":"none"}` / degenerate drags.
fn parse_drag_delta(json: &str) -> Option<ComponentDelta> {
    let value: serde_json::Value = serde_json::from_str(json).ok()?;
    let vec3 = |key: &str| -> [f64; 3] {
        let mut out = [0.0; 3];
        if let Some(array) = value.get(key).and_then(|v| v.as_array()) {
            for (index, slot) in out.iter_mut().enumerate() {
                if let Some(number) = array.get(index).and_then(|v| v.as_f64()) {
                    *slot = number;
                }
            }
        }
        out
    };
    match value.get("kind").and_then(|k| k.as_str()) {
        Some("translate") => Some(ComponentDelta::Translate(vec3("world"))),
        Some("rotate") => Some(ComponentDelta::Rotate {
            axis: vec3("axisWorld"),
            radians: value.get("radians").and_then(|n| n.as_f64()).unwrap_or(0.0),
        }),
        _ => None,
    }
}

/// Compose a world-space gizmo delta onto a component pose. PURE (unit-tested
/// directly). Translation shifts pose + anchor together; rotation pivots about
/// the ANCHOR `C` (the gizmo sits at the bbox center, so the component spins in
/// place about it): `R' = dR·R` and `translate' = C + dR·(translate − C)` —
/// decomposed back to intrinsic-XYZ degrees exactly like the kernel's
/// `compose_trs_matrix` convention (shared quaternion helpers with the feature
/// transform gizmo).
pub(super) fn compose_component_delta(
    start: &ComponentPose,
    delta: &ComponentDelta,
) -> ComponentPose {
    match delta {
        ComponentDelta::Translate(d) => ComponentPose {
            translate: add3(start.translate, *d),
            rotate_deg: start.rotate_deg,
            anchor: add3(start.anchor, *d),
        },
        ComponentDelta::Rotate { axis, radians } => {
            let dq = quat_from_axis_angle(*axis, *radians);
            let q0 = quat_from_euler_xyz_deg(start.rotate_deg);
            let rotate_deg = euler_xyz_deg_from_quat(quat_mul(dq, q0));
            let offset = sub3(start.translate, start.anchor);
            ComponentPose {
                translate: add3(start.anchor, quat_rotate(dq, offset)),
                rotate_deg,
                anchor: start.anchor,
            }
        }
    }
}

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

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

/// Rotate `v` by quaternion `q`: `v + 2·(q.xyz × (q.xyz × v + w·v))`.
fn quat_rotate(q: Quat, v: [f64; 3]) -> [f64; 3] {
    let u = [q[0], q[1], q[2]];
    let w = q[3];
    let cross = |a: [f64; 3], b: [f64; 3]| -> [f64; 3] {
        [
            a[1] * b[2] - a[2] * b[1],
            a[2] * b[0] - a[0] * b[2],
            a[0] * b[1] - a[1] * b[0],
        ]
    };
    let t = cross(u, add3(cross(u, v), [w * v[0], w * v[1], w * v[2]]));
    [v[0] + 2.0 * t[0], v[1] + 2.0 * t[1], v[2] + 2.0 * t[2]]
}

#[cfg(test)]
mod component_move_tests {
    use super::super::component_fixtures::two_instance_assembly_json;
    use super::*;

    fn pose(translate: [f64; 3], rotate_deg: [f64; 3], anchor: [f64; 3]) -> ComponentPose {
        ComponentPose { translate, rotate_deg, anchor }
    }

    #[test]
    fn compose_translate_shifts_pose_and_anchor_together() {
        let out = compose_component_delta(
            &pose([20.0, 0.0, 0.0], [0.0, 0.0, 0.0], [25.0, 5.0, 5.0]),
            &ComponentDelta::Translate([4.0, -1.0, 0.5]),
        );
        assert_eq!(out.translate, [24.0, -1.0, 0.5]);
        assert_eq!(out.anchor, [29.0, 4.0, 5.5]);
        assert_eq!(out.rotate_deg, [0.0, 0.0, 0.0]);
    }

    /// The pivot math pin: +90° about world Z through the anchor C=[25,5,5]
    /// maps the pose origin t=[20,0,0] to C + Rz90·(t−C) = [30,0,0] and the
    /// orientation to [0,0,90] — the exact intrinsic-XYZ compose the kernel's
    /// `compose_trs_matrix` bakes, so committing this pose re-poses the solid
    /// identically to spinning it in place about its bbox center.
    #[test]
    fn compose_rotate_pivots_about_the_anchor() {
        let out = compose_component_delta(
            &pose([20.0, 0.0, 0.0], [0.0, 0.0, 0.0], [25.0, 5.0, 5.0]),
            &ComponentDelta::Rotate {
                axis: [0.0, 0.0, 1.0],
                radians: std::f64::consts::FRAC_PI_2,
            },
        );
        for (got, want) in out.translate.iter().zip([30.0, 0.0, 0.0]) {
            assert!((got - want).abs() < 1e-9, "translate {:?}", out.translate);
        }
        assert!((out.rotate_deg[2] - 90.0).abs() < 1e-6, "{:?}", out.rotate_deg);
        assert!(out.rotate_deg[0].abs() < 1e-6 && out.rotate_deg[1].abs() < 1e-6);
        assert_eq!(out.anchor, [25.0, 5.0, 5.0], "rotation never moves the pivot");

        // Round-trip: −90° about the same pivot undoes it exactly.
        let back = compose_component_delta(
            &out,
            &ComponentDelta::Rotate {
                axis: [0.0, 0.0, 1.0],
                radians: -std::f64::consts::FRAC_PI_2,
            },
        );
        for (got, want) in back.translate.iter().zip([20.0, 0.0, 0.0]) {
            assert!((got - want).abs() < 1e-9, "round-trip {:?}", back.translate);
        }
        for angle in back.rotate_deg {
            assert!(angle.abs() < 1e-6, "round-trip {:?}", back.rotate_deg);
        }
    }

    fn assembly_engine_with_camera() -> EngineState {
        let mut engine = EngineState::new();
        engine
            .set_history_json(&two_instance_assembly_json())
            .unwrap();
        engine.resize(800.0, 600.0);
        // Look straight down −Z at ACOMP2's bbox center [25,5,5] so it projects
        // to the viewport center and screen-right is world +X.
        engine.camera.eye = [25.0, 5.0, 45.0];
        engine.camera.target = [25.0, 5.0, 5.0];
        engine.camera.up = [0.0, 1.0, 0.0];
        engine.camera.projection = crate::view::Projection::Orthographic { half_height: 20.0 };
        engine
    }

    #[test]
    fn toggle_arms_the_full_gizmo_then_disarms_and_fixed_refuses() {
        let mut engine = assembly_engine_with_camera();
        assert!(!engine.component_move_armed());

        // FIXED component: toast + never arms.
        engine.component_move_toggle("ACOMP1");
        assert!(!engine.component_move_armed());
        let notices = engine.take_notices();
        assert!(
            notices.iter().any(|n| n.contains("fixed")),
            "fixed refusal toast: {notices:?}"
        );

        // Free component: one toggle arms EVERY handle set at once (the ring
        // grabs prove the arcs are up alongside the arrows/center).
        engine.component_move_toggle("ACOMP2");
        assert!(engine.component_move_armed());
        assert!(engine.widgets.has_transform(), "arming feeds the widget");
        let cam = gizmo_camera(&engine.camera);
        assert!(
            engine.widgets.transform_ring_grabs(&cam).is_some(),
            "rotation arcs are shown together with the move handles"
        );
        assert!(!engine.transform_armed(), "the FEATURE gizmo stays disarmed");

        engine.component_move_toggle("ACOMP2");
        assert!(!engine.component_move_armed(), "second toggle disarms");
        assert!(!engine.widgets.has_transform(), "widget cleared");
        assert!(engine.take_notices().is_empty(), "no spurious toasts");
    }

    #[test]
    fn arm_transform_routes_acomp_to_the_component_gizmo() {
        let mut engine = assembly_engine_with_camera();
        // The history panel's expand path calls arm_transform for a dimension-
        // less transformable — an ACOMP must arm the COMPONENT gizmo instead.
        engine.arm_transform("ACOMP2");
        assert!(engine.component_move_armed());
        assert_eq!(engine.component_move_armed_feature(), "ACOMP2");
        assert!(!engine.transform_armed(), "generic gizmo must not arm for ACOMP");

        // A FIXED component silently stays armless on the routed path (only the
        // explicit Move action toasts).
        engine.disarm_transform();
        engine.arm_transform("ACOMP1");
        assert!(!engine.component_move_armed());
        assert!(!engine.transform_armed());
        assert!(engine.take_notices().is_empty(), "routed refusal is silent");
    }

    #[test]
    fn translate_drag_is_free_move_and_commits_on_release() {
        let mut engine = assembly_engine_with_camera();
        engine.component_move_toggle("ACOMP2");
        let anchor = engine.component_move.anchor;
        assert!((anchor[0] - 25.0).abs() < 1e-6, "bbox-center anchor: {anchor:?}");

        // The anchor projects to the viewport center; the center free-move
        // handle sits there (translate mode shows it).
        let (sx, sy, depth) = engine.camera.project(anchor);
        assert!(depth > 0.0);
        assert!(engine.component_press(sx, sy), "center handle grabbed");
        assert!(engine.component_move_dragging());

        // Drag 60 px screen-right (+X world). FREE MOVE: the widget follows,
        // the params + mesh do NOT (commit-on-release).
        engine.component_drag_to(sx + 60.0, sy);
        let info = engine.component_info("ACOMP2").unwrap();
        assert_eq!(info.translate, [20.0, 0.0, 0.0], "no param write mid-drag");
        let solid_x = engine
            .scene
            .solid("ACOMP2:Part")
            .expect("member solid")
            .bbox
            .min[0];
        assert!((solid_x - 20.0).abs() < 1e-6, "mesh stays put mid-drag");
        let widget_origin = engine.widgets.transform_origin().expect("widget shown");
        assert!(
            widget_origin[0] as f64 > anchor[0] + 2.0,
            "the gizmo follows the pointer: {widget_origin:?}"
        );

        // Release: ONE commit — 60 px at world_per_pixel (2·20/600) = 4 units.
        engine.component_release();
        assert!(!engine.component_move_dragging());
        let info = engine.component_info("ACOMP2").unwrap();
        assert!(
            (info.translate[0] - 24.0).abs() < 0.2,
            "committed translate: {:?}",
            info.translate
        );
        let solid_x = engine.scene.solid("ACOMP2:Part").unwrap().bbox.min[0];
        assert!(
            (solid_x - info.translate[0]).abs() < 1e-6,
            "the rerun re-posed the member to the committed pose"
        );
        // The commit is a real user edit → exactly one undo entry.
        assert!(engine.history.can_undo(), "commit minted an undo entry");
    }

    /// Draw==hit for the COMPONENT Move gizmo: `transform_hit_areas_json` emits
    /// the shared widget's screen regions while the component gizmo is armed —
    /// even though the ◎ mode stays `"none"` (the WIDGET FEED, not the mode, is
    /// authoritative, exactly like `transform_pick`) — with the full handle set
    /// (3 axis capsules + the center + 3 ring-grab circles), and a cursor at
    /// each region's own reference point picks a handle whose region contains
    /// it. Disarming retracts the outlines to `[]`.
    #[test]
    fn component_move_hit_areas_match_the_shared_hit_test() {
        let mut engine = assembly_engine_with_camera();
        // An oblique view so the three projected axis segments are distinct.
        engine.camera.eye = [55.0, 25.0, 45.0];
        assert_eq!(engine.transform_hit_areas_json(), "[]", "nothing armed → no outlines");

        engine.component_move_toggle("ACOMP2");
        assert_eq!(engine.gizmo_mode(), "none", "component arm keeps the ◎ mode none");
        let areas: Vec<serde_json::Value> =
            serde_json::from_str(&engine.transform_hit_areas_json()).unwrap();
        let capsules = areas.iter().filter(|a| a["kind"] == "capsule").count();
        let circles = areas.iter().filter(|a| a["kind"] == "circle").count();
        assert_eq!(capsules, 3, "one capsule per axis arrow");
        assert_eq!(circles, 4, "center + 3 ring grab circles");

        // Draw==hit invariant (the feature-gizmo test's probe): the picked
        // handle's region contains the cursor at each region's reference point
        // (regions overlap by design, so "same handle" isn't required).
        let cam = gizmo_camera(&engine.camera);
        let regions = engine.widgets.transform_hit_regions(&cam);
        assert_eq!(regions.len(), areas.len(), "outline set == hit-region set");
        for (_, shape) in &regions {
            let probe = match shape {
                brep_gizmos::hit_region::HitShape::Circle { c, .. } => *c,
                brep_gizmos::hit_region::HitShape::Capsule { a, b, .. } => {
                    [(a[0] + b[0]) * 0.5, (a[1] + b[1]) * 0.5]
                }
            };
            let picked = engine.transform_pick(probe[0] as f64, probe[1] as f64);
            assert_ne!(picked, 0, "a handle under its own region at {probe:?}");
            let picked_shape = regions.iter().find(|(id, _)| *id == picked).unwrap().1;
            assert!(
                picked_shape.contains(probe),
                "picked handle {picked}'s region must contain the cursor {probe:?}"
            );
        }

        engine.component_move_toggle("ACOMP2");
        assert_eq!(engine.transform_hit_areas_json(), "[]", "disarm retracts the outlines");
    }

    #[test]
    fn rotate_drag_commits_the_anchor_pivot_compose() {
        let mut engine = assembly_engine_with_camera();
        engine.component_move_toggle("ACOMP2"); // arcs are up alongside the arrows

        // Grab the Z-rotation ball (ARCS order puts Z first) and drag it +90°
        // about world Z through the anchor.
        let cam = gizmo_camera(&engine.camera);
        let grabs = engine.widgets.transform_ring_grabs(&cam).expect("gizmo shown");
        let grab = grabs[0];
        let anchor = engine.component_move.anchor;
        let start = cam
            .world_to_screen(grab)
            .expect("grab projects");
        assert!(engine.component_press(start[0] as f64, start[1] as f64), "ring grabbed");

        // Target = the grab point rotated +90° about Z through the anchor.
        let offset = [grab.x as f64 - anchor[0], grab.y as f64 - anchor[1]];
        let target_world = [
            anchor[0] - offset[1],
            anchor[1] + offset[0],
            grab.z as f64,
        ];
        let (tx, ty, _) = engine.camera.project(target_world);
        engine.component_drag_to(tx, ty);
        engine.component_release();

        let info = engine.component_info("ACOMP2").unwrap();
        assert!(
            (info.rotate_deg[2] - 90.0).abs() < 0.5,
            "committed +90° about Z: {:?}",
            info.rotate_deg
        );
        // translate' = C + Rz90·(t−C): [20,0,0] about [25,5,5] → [30,0,0].
        assert!(
            (info.translate[0] - 30.0).abs() < 0.1 && info.translate[1].abs() < 0.1,
            "pivot compose: {:?}",
            info.translate
        );
        // Spinning a cube about its own bbox center keeps the center in place.
        let center = engine.component_bbox_center("ACOMP2").unwrap();
        assert!(
            (center[0] - 25.0).abs() < 0.1 && (center[1] - 5.0).abs() < 0.1,
            "bbox center invariant under the pivot rotation: {center:?}"
        );
    }
}