rsplot 0.5.0

silx-style scientific plotting for egui, rendered with wgpu
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
//! [`SceneWidget`] — an interactive 3D scene inside an egui `Ui`.
//!
//! The plot3d analogue of [`crate::widget::plot_widget::PlotView`]: it owns a
//! [`Camera`], the scene bounds, and the scene geometry; on each frame it
//! handles orbit/pan/zoom pointer interaction (driven by the pure helpers in
//! [`crate::core::scene3d::interaction`]) and registers the wgpu paint callback
//! ([`paint_scene3d`]) that renders the scene offscreen and blits it in.
//!
//! Port of silx `Plot3DWidget` + `SceneWidget`'s default `RotateCameraControl`
//! (`orbitAroundCenter=False`, wheel mode `"position"`): left-drag orbits around
//! the picked point under the press (scene centre on a miss), Ctrl+left-drag pans
//! on the picked depth plane, and the wheel zooms keeping the picked pixel
//! invariant — each gesture anchors on [`SceneWidget::pick`], the CPU stand-in
//! for silx's depth-buffer read. [`SceneWidget::set_interactive_mode`] selects the
//! mode (silx `setInteractiveMode`): [`SceneInteractiveMode::Rotate`] (default),
//! [`Pan`](SceneInteractiveMode::Pan) which swaps the orbit/pan bindings, or
//! [`Disabled`](SceneInteractiveMode::Disabled) which takes no pointer
//! interaction. The right button is unbound, as in silx's string modes.
//! The scene chrome (bounding box + RGB axes) is generated from the bounds via
//! [`Scene3dGeometry::add_bounding_box_with_axes`]; data-item geometry set with
//! [`SceneWidget::set_geometry`] is merged in beneath the chrome (every channel,
//! via [`Scene3dGeometry::extend_from`]).

use egui::{Align2, Color32, FontId, PointerButton, Pos2, Response, Sense, Ui};
use egui_wgpu::RenderState;

use crate::core::scene3d::axes::{dash_segments, labelled_axes_chrome};
use crate::core::scene3d::camera::{Camera, CameraDirection, CameraFace};
use crate::core::scene3d::interaction::{OrbitDrag, PanDrag, window_to_ndc};
use crate::core::scene3d::mat4::Vec3;
use crate::core::scene3d::pick::{picking_segment, segment_triangles_intersection};
use crate::core::scene3d::plane::segment_plane_intersect;
use crate::render::gpu_scene3d::{
    OVERVIEW_SIZE_PX, PointMarker, Scene3dFog, Scene3dGeometry, Scene3dId, Scene3dShading,
    install_scene3d, paint_scene3d_with, set_scene3d, snapshot_scene3d_with,
};

/// Default scene background: silx `Plot3DWidget` clears to `(0.2, 0.2, 0.2, 1.0)`
/// (`Plot3DWidget.py:161`), i.e. grey 51.
const DEFAULT_BACKGROUND: Color32 = Color32::from_gray(51);
/// Default foreground (bounding-box / wireframe) colour: white, as silx
/// `SceneWidget` (`SceneWidget.py:374` `_foregroundColor = 1., 1., 1., 1.`,
/// matching `primitives.py` `BoxWithAxes(color=(1., 1., 1., 1.))`).
const DEFAULT_FOREGROUND: Color32 = Color32::WHITE;
/// Default text colour (axis/tick labels): white, as silx `SceneWidget`
/// (`SceneWidget.py:373` `_textColor = 1., 1., 1., 1.`).
const DEFAULT_TEXT_COLOR: Color32 = Color32::WHITE;
/// Font size of the axes labels: silx `LabelledAxes` uses `Font(size=10)`
/// (`scene/axes.py:48`).
const AXES_FONT_SIZE: f32 = 10.0;
/// XOR salt deriving the orientation indicator's companion [`Scene3dId`] from
/// the widget's id (per-scene uniform buffers force the overview's slaved
/// camera into a scene of its own). Collides with a user scene only if two
/// widget ids differ by exactly this value.
const OVERVIEW_ID_SALT: Scene3dId = 0x4F56_5256_4945_5750; // "OVRVIEWP"

/// Fog mode of the scene — port of silx `Plot3DWidget.FogMode`
/// (`Plot3DWidget.py:119-124`): either no fog or a linear fog fading the scene
/// content toward the background colour over its depth extent.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FogMode {
    /// No fog (the silx default).
    #[default]
    None,
    /// Linear fog over the scene's camera-space depth extent.
    Linear,
}

/// The camera interaction mode, silx `Plot3DWidget.setInteractiveMode`
/// (`Plot3DWidget.py:177-219`).
///
/// silx wires two-string modes plus `None`. [`Rotate`](Self::Rotate) (the
/// default, silx `RotateCameraControl`, `interaction.py:448-469`) orbits on
/// left-drag and pans on **Ctrl**+left-drag; [`Pan`](Self::Pan) (silx
/// `PanCameraControl`, `interaction.py:472-491`) swaps those two;
/// [`Disabled`](Self::Disabled) (silx `None`, `Plot3DWidget.py:186-187`) takes no
/// pointer interaction at all. The wheel zooms in `Rotate`/`Pan` and is inert in
/// `Disabled` — silx puts `CameraWheel` in *both* the default and the Ctrl
/// handler set, so the modifier never gates it.
///
/// The right mouse button is unbound in every string mode: silx binds it only in
/// the separate two-button `CameraControl` (`interaction.py:494-511`), which is
/// passed as a `StateMachine` instance rather than a string mode and is not
/// exposed here.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SceneInteractiveMode {
    /// Left-drag orbits, Ctrl+left-drag pans (silx `RotateCameraControl`).
    #[default]
    Rotate,
    /// Left-drag pans, Ctrl+left-drag orbits (silx `PanCameraControl`).
    Pan,
    /// No pointer interaction (silx `setInteractiveMode(None)`).
    Disabled,
}

/// Which camera gesture the left button drives for a given mode + modifier.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum LeftGesture {
    Orbit,
    Pan,
}

impl SceneInteractiveMode {
    /// The gesture the left button performs given whether **Ctrl** is held.
    ///
    /// silx's `FocusManager` swaps its default handler set for the Ctrl set on
    /// key-press and back on key-release (`interaction.py:435-441`); the drag that
    /// begins under the active set keeps that handler for its whole life. So the
    /// choice is made once, at press: `Rotate` orbits (pans under Ctrl), `Pan`
    /// pans (orbits under Ctrl), `Disabled` does nothing.
    fn left_gesture(self, ctrl: bool) -> Option<LeftGesture> {
        match (self, ctrl) {
            (SceneInteractiveMode::Rotate, false) | (SceneInteractiveMode::Pan, true) => {
                Some(LeftGesture::Orbit)
            }
            (SceneInteractiveMode::Pan, false) | (SceneInteractiveMode::Rotate, true) => {
                Some(LeftGesture::Pan)
            }
            (SceneInteractiveMode::Disabled, _) => None,
        }
    }

    /// Whether the wheel zooms in this mode (every mode but `Disabled`).
    fn wheel_zooms(self) -> bool {
        !matches!(self, SceneInteractiveMode::Disabled)
    }
}

/// An interactive 3D scene widget. Construct with [`SceneWidget::new`], optionally
/// set the data bounds and content geometry, then call [`SceneWidget::show`] each
/// frame.
pub struct SceneWidget {
    id: Scene3dId,
    camera: Camera,
    /// Axis-aligned scene bounds `(min, max)`; the chrome and camera framing
    /// derive from these.
    bounds: (Vec3, Vec3),
    box_color: Color32,
    text_color: Color32,
    /// Axis name labels `(x, y, z)` of the LabelledAxes chrome; empty (the
    /// silx `Text2D` default) draws no name.
    axes_labels: [String; 3],
    background: Color32,
    /// Fog mode (silx `Plot3DWidget.setFogMode`); default off.
    fog_mode: FogMode,
    /// Phong shininess of the viewport light (silx `viewport.light.shininess`);
    /// 0 (no specular) for plain scenes, 32 in [`crate::ScalarFieldView`].
    light_shininess: f32,
    /// Whether the corner orientation indicator (disc + RGB axes) is drawn;
    /// on by default, as silx (`Plot3DWidget.py:165`).
    orientation_indicator: bool,
    /// Data-item geometry (excludes the box/axes chrome, which is regenerated
    /// from `bounds` on every upload). Empty until [`SceneWidget::set_geometry`].
    content: Scene3dGeometry,
    /// Current camera interaction mode (silx `Plot3DWidget.setInteractiveMode`);
    /// `Rotate` by default, matching silx's default `RotateCameraControl`.
    interaction_mode: SceneInteractiveMode,
    /// In-progress orbit drag, if any. Driven by the left button whenever the
    /// active [`SceneInteractiveMode`] + Ctrl resolves to [`LeftGesture::Orbit`].
    orbit: Option<OrbitDrag>,
    /// In-progress pan drag, if any. Driven by the left button whenever the active
    /// [`SceneInteractiveMode`] + Ctrl resolves to [`LeftGesture::Pan`].
    pan: Option<PanDrag>,
}

impl SceneWidget {
    /// Create a scene widget bound to `id`, installing the 3D GPU resources into
    /// `render_state` if needed. Starts with a unit-box scene framed from the
    /// silx front viewpoint (down the -Z axis).
    pub fn new(render_state: &RenderState, id: Scene3dId) -> Self {
        install_scene3d(render_state);

        let bounds = (Vec3::ZERO, Vec3::new(1.0, 1.0, 1.0));
        let mut camera = Camera::new(
            30.0,
            0.1,
            100.0,
            (1.0, 1.0),
            Vec3::new(0.0, 0.0, 1.0),
            Vec3::new(0.0, 0.0, -1.0),
            Vec3::new(0.0, 1.0, 0.0),
        );
        // silx's viewport camera opens face-on down -Z: `direction=(0, 0, -1)`,
        // `position=(0, 0, 12)` (viewport.py:221-223, camera.py:50); the only
        // startup adjustment is `centerScene()`. 'side' is a viewpoint-action
        // preset, not the default. Frame the front view.
        camera.extrinsic.reset(CameraFace::Front);
        camera.reset_camera(bounds);
        camera.adjust_depth_extent(bounds);

        let widget = SceneWidget {
            id,
            camera,
            bounds,
            box_color: DEFAULT_FOREGROUND,
            text_color: DEFAULT_TEXT_COLOR,
            axes_labels: [String::new(), String::new(), String::new()],
            background: DEFAULT_BACKGROUND,
            fog_mode: FogMode::None,
            light_shininess: 0.0,
            orientation_indicator: true,
            content: Scene3dGeometry::new(),
            interaction_mode: SceneInteractiveMode::default(),
            orbit: None,
            pan: None,
        };
        widget.upload(render_state);
        // Upload the orientation indicator's companion scene once: its
        // geometry is static, only its per-frame camera follows the widget's.
        set_scene3d(render_state, widget.overview_id(), &overview_geometry());
        widget
    }

    /// Set the scene background colour (used to clear the offscreen target).
    /// Port of silx `Plot3DWidget.setBackgroundColor`.
    pub fn set_background(&mut self, color: Color32) {
        self.background = color;
    }

    /// The scene background colour (silx `Plot3DWidget.getBackgroundColor`).
    pub fn background(&self) -> Color32 {
        self.background
    }

    /// Set the foreground colour — the bounding-box wireframe stroke. Port of
    /// silx `SceneWidget.setForegroundColor` (`SceneWidget.py:648`, applied to
    /// the root `BoxWithAxes`). Re-uploads the chrome geometry.
    pub fn set_foreground_color(&mut self, render_state: &RenderState, color: Color32) {
        if self.box_color != color {
            self.box_color = color;
            self.upload(render_state);
        }
    }

    /// The foreground (bounding-box) colour (silx `SceneWidget.getForegroundColor`).
    pub fn foreground_color(&self) -> Color32 {
        self.box_color
    }

    /// Set the text colour used for the scene's axis and tick labels. Port of
    /// silx `SceneWidget.setTextColor` (`SceneWidget.py:623`, forwarded to the
    /// root `LabelledAxes.tickColor` — which also tints the dashed tick lines
    /// at 60 % alpha, `scene/axes.py:110-118`). Re-uploads the chrome.
    pub fn set_text_color(&mut self, render_state: &RenderState, color: Color32) {
        if self.text_color != color {
            self.text_color = color;
            self.upload(render_state);
        }
    }

    /// The text colour (silx `SceneWidget.getTextColor`).
    pub fn text_color(&self) -> Color32 {
        self.text_color
    }

    /// Set the text labels of the three axes (silx `setAxesLabels`,
    /// `items/core.py:702-717`; `None` leaves an axis unchanged). Names draw
    /// at the box edge midpoints (`scene/axes.py:57-67`); the default empty
    /// string draws nothing.
    pub fn set_axes_labels(
        &mut self,
        xlabel: Option<&str>,
        ylabel: Option<&str>,
        zlabel: Option<&str>,
    ) {
        for (slot, label) in self.axes_labels.iter_mut().zip([xlabel, ylabel, zlabel]) {
            if let Some(label) = label {
                *slot = label.to_string();
            }
        }
    }

    /// The current axis labels `(x, y, z)` (silx `getAxesLabels`).
    pub fn axes_labels(&self) -> (&str, &str, &str) {
        (
            &self.axes_labels[0],
            &self.axes_labels[1],
            &self.axes_labels[2],
        )
    }

    /// Set the fog mode. Port of silx `Plot3DWidget.setFogMode`
    /// (`Plot3DWidget.py:279-288`: `viewport.fog.isOn = mode is FogMode.LINEAR`).
    pub fn set_fog_mode(&mut self, mode: FogMode) {
        self.fog_mode = mode;
    }

    /// The fog mode (silx `Plot3DWidget.getFogMode`).
    pub fn fog_mode(&self) -> FogMode {
        self.fog_mode
    }

    /// Set the Phong shininess of the viewport's directional light; `0`
    /// disables the specular term (the silx `DirectionalLight` default,
    /// `function.py:296-300`). `ScalarFieldView` sets 32
    /// (`ScalarFieldView.py:928`).
    pub fn set_light_shininess(&mut self, shininess: f32) {
        self.light_shininess = shininess;
    }

    /// The viewport light's Phong shininess (`0` = no specular).
    pub fn light_shininess(&self) -> f32 {
        self.light_shininess
    }

    /// The per-frame shading options (fog + shininess) matching this widget's
    /// current state — the one owner used by both [`SceneWidget::show`] and
    /// [`SceneWidget::snapshot`], so the snapshot matches the screen.
    fn shading(&self) -> Scene3dShading {
        Scene3dShading {
            fog: (self.fog_mode == FogMode::Linear)
                .then(|| Scene3dFog::linear(&self.camera, self.bounds, self.background)),
            shininess: self.light_shininess,
        }
    }

    /// Set whether to display the orientation indicator — the half-transparent
    /// disc with the RGB axes in the top-right corner, its camera slaved to the
    /// scene's. Port of silx `Plot3DWidget.setOrientationIndicatorVisible`
    /// (`Plot3DWidget.py:325-336`); on by default (`:165`).
    pub fn set_orientation_indicator_visible(&mut self, visible: bool) {
        self.orientation_indicator = visible;
    }

    /// Whether the orientation indicator is displayed (silx
    /// `Plot3DWidget.isOrientationIndicatorVisible`, `Plot3DWidget.py:320-323`).
    pub fn is_orientation_indicator_visible(&self) -> bool {
        self.orientation_indicator
    }

    /// The companion scene id holding the orientation indicator's geometry.
    fn overview_id(&self) -> Scene3dId {
        self.id ^ OVERVIEW_ID_SALT
    }

    /// The scene's centre of bounds (centre of rotation for orbit/pan).
    pub fn center(&self) -> Vec3 {
        (self.bounds.0 + self.bounds.1) * 0.5
    }

    /// Read-only access to the camera.
    pub fn camera(&self) -> &Camera {
        &self.camera
    }

    /// Mutable access to the camera (e.g. to apply a viewpoint preset).
    pub fn camera_mut(&mut self) -> &mut Camera {
        &mut self.camera
    }

    /// Set the axis-aligned scene bounds, re-frame the camera, and re-upload the
    /// chrome geometry.
    pub fn set_bounds(&mut self, render_state: &RenderState, bounds: (Vec3, Vec3)) {
        self.bounds = bounds;
        self.camera.reset_camera(bounds);
        self.camera.adjust_depth_extent(bounds);
        self.upload(render_state);
    }

    /// Set the scene bounds and re-upload the chrome **without** re-framing the
    /// camera, so the user's current orbit/zoom is preserved. Used when the data
    /// changes but the viewpoint should stay put — silx re-frames (`centerScene`)
    /// only on the first `setData`, not on subsequent updates. The depth frustum
    /// is still adjusted so the new bounds stay clipped correctly.
    pub fn set_bounds_keep_view(&mut self, render_state: &RenderState, bounds: (Vec3, Vec3)) {
        self.bounds = bounds;
        self.camera.adjust_depth_extent(bounds);
        self.upload(render_state);
    }

    /// Replace the data-item geometry (the box/axes chrome is kept) and re-upload.
    pub fn set_geometry(&mut self, render_state: &RenderState, geometry: Scene3dGeometry) {
        self.content = geometry;
        self.upload(render_state);
    }

    /// Re-frame the camera to the current bounds without changing orientation.
    pub fn reset_camera(&mut self) {
        self.camera.reset_camera(self.bounds);
        self.camera.adjust_depth_extent(self.bounds);
    }

    /// Set the camera to one of the predefined viewpoints (front/back/left/
    /// right/top/bottom/side) and re-frame the scene. Port of silx
    /// `_SetViewpointAction`: `camera.extrinsic.reset(face)` followed by
    /// `centerScene()`.
    pub fn set_viewpoint(&mut self, face: CameraFace) {
        self.camera.extrinsic.reset(face);
        self.camera.reset_camera(self.bounds);
        self.camera.adjust_depth_extent(self.bounds);
    }

    /// Set the camera interaction mode (silx `Plot3DWidget.setInteractiveMode`,
    /// `Plot3DWidget.py:177-219`): `Rotate` (default) orbits on left-drag and pans
    /// on Ctrl+left-drag, `Pan` swaps those, `Disabled` takes no pointer
    /// interaction. Any drag in progress is cancelled so the new binding takes
    /// effect on the next press rather than mid-gesture.
    pub fn set_interactive_mode(&mut self, mode: SceneInteractiveMode) {
        self.interaction_mode = mode;
        self.orbit = None;
        self.pan = None;
    }

    /// The current camera interaction mode.
    pub fn interactive_mode(&self) -> SceneInteractiveMode {
        self.interaction_mode
    }

    /// Orbit the scene about its centre around the vertical axis by
    /// `angle_degrees` (positive = the silx "left" orbit direction). Port of
    /// silx `RotateViewpoint`'s per-frame `viewport.orbitCamera("left", angle)`;
    /// the caller drives the animation (e.g. `angle = deg_per_sec * dt` each
    /// frame, requesting a repaint). The depth frustum is re-adjusted so the
    /// scene stays clipped correctly.
    pub fn rotate_scene(&mut self, angle_degrees: f32) {
        let center = self.center();
        self.camera
            .extrinsic
            .orbit(CameraDirection::Left, center, angle_degrees);
        self.camera.adjust_depth_extent(self.bounds);
    }

    /// Build the combined geometry (chrome + content) and upload it for this
    /// scene id.
    fn upload(&self, render_state: &RenderState) {
        let mut geometry = Scene3dGeometry::new();
        geometry.add_bounding_box_with_axes(self.bounds, self.box_color);
        self.add_tick_lines(&mut geometry);
        // Append every data-item channel beneath the chrome (points, meshes,
        // images, and textured meshes too — not only lines/triangles), so the
        // P1.x/P2.x items render through the widget.
        geometry.extend_from(&self.content);
        set_scene3d(render_state, self.id, &geometry);
    }

    /// Dashed tick lines of the LabelledAxes chrome (silx
    /// `LabelledAxes._updateTicks`, `scene/axes.py:172-213`): per tick one
    /// segment across each of the two box planes containing its axis, drawn
    /// in the text colour at 60 % alpha (`axes.py:110-118`). silx dashes
    /// 5 px on / 10 px off in *screen* space via a fragment shader
    /// (`axes.py:71-73`, `primitives.py:589-593`); here the dashes are
    /// generated CPU-side in world units scaled to the bounds diagonal
    /// (5/500 · diagonal on, 10/500 off — a ~500 px viewport shows roughly
    /// the silx period), so the on-screen dash length varies with zoom
    /// (documented deviation).
    fn add_tick_lines(&self, geometry: &mut Scene3dGeometry) {
        let chrome = labelled_axes_chrome(self.bounds, ["", "", ""]);
        let unit = (self.bounds.1 - self.bounds.0).length() / 500.0;
        let color = Color32::from_rgba_unmultiplied(
            self.text_color.r(),
            self.text_color.g(),
            self.text_color.b(),
            (self.text_color.a() as f32 * 0.6).round() as u8,
        );
        for &(a, b) in &chrome.tick_segments {
            for (s, e) in dash_segments(a, b, 5.0 * unit, 10.0 * unit) {
                geometry.add_line(s.to_array(), e.to_array(), color);
            }
        }
    }

    /// Draw the LabelledAxes text — axis names and tick values — as egui
    /// overlay text at the projected anchors: the port of silx's GL-rendered
    /// `Text2D` billboards (`scene/axes.py:57-67` names, `:216-245` tick
    /// values; align/valign center, `Font(size=10)`, foreground = tickColor).
    /// Because the labels are egui text rather than scene geometry, they
    /// appear in [`SceneWidget::show`] but not in [`SceneWidget::snapshot`]
    /// (documented deviation).
    fn draw_axes_labels(&self, ui: &Ui, rect: egui::Rect) {
        let chrome = labelled_axes_chrome(
            self.bounds,
            [
                self.axes_labels[0].as_str(),
                self.axes_labels[1].as_str(),
                self.axes_labels[2].as_str(),
            ],
        );
        let mvp = self.camera.matrix();
        let painter = ui.painter_at(rect);
        let font = FontId::proportional(AXES_FONT_SIZE);
        for label in chrome.axis_labels.iter().chain(&chrome.tick_labels) {
            let ndc = mvp.transform_point(label.position, true);
            // Skip labels outside the frustum (clipped or behind the camera).
            if !(ndc.x.is_finite()
                && ndc.y.is_finite()
                && ndc.x.abs() <= 1.2
                && ndc.y.abs() <= 1.2
                && (-1.0..=1.0).contains(&ndc.z))
            {
                continue;
            }
            let pos = Pos2::new(
                rect.min.x + (ndc.x + 1.0) * 0.5 * rect.width(),
                rect.min.y + (1.0 - ndc.y) * 0.5 * rect.height(),
            );
            painter.text(
                pos,
                Align2::CENTER_CENTER,
                &label.text,
                font.clone(),
                self.text_color,
            );
        }
    }

    /// Lay out the scene over the available space, handle interaction, and paint.
    /// Returns the egui [`Response`] for the scene rect.
    pub fn show(&mut self, ui: &mut Ui) -> Response {
        let (rect, response) = ui.allocate_exact_size(ui.available_size(), Sense::click_and_drag());
        let ppp = ui.ctx().pixels_per_point();
        let size_px = (
            (rect.width() * ppp).max(1.0),
            (rect.height() * ppp).max(1.0),
        );
        // Keep the camera aspect in sync so interaction un-projection matches the
        // rendered frame (paint_scene3d uses the same physical pixel size).
        self.camera.set_size(size_px);
        let center = self.center();

        // Pointer position in physical pixels relative to the scene rect's origin.
        let to_local = |p: Pos2| ((p.x - rect.min.x) * ppp, (p.y - rect.min.y) * ppp);
        // Where the button went down. A drag is only *recognised* after the pointer
        // clears egui's click-vs-drag threshold, by which point
        // `interact_pointer_pos` has already moved; anchoring the orbit/pan at the
        // press origin keeps that threshold travel from being silently dropped.
        let press_origin = ui.ctx().input(|i| i.pointer.press_origin());

        // Left drag — orbit or pan, chosen once at press from the interaction
        // mode and the Ctrl modifier. silx's FocusManager selects its default or
        // Ctrl handler set at press and keeps that handler for the whole drag
        // (interaction.py:435-441), so the gesture never switches mid-drag even if
        // Ctrl is toggled. `Rotate` orbits (pans under Ctrl), `Pan` pans (orbits
        // under Ctrl), `Disabled` binds nothing. The modifier is read as egui's
        // `command` (Ctrl on Windows/Linux, ⌘ on macOS) to mirror Qt's default
        // Ctrl↔Meta swap that makes silx's "Ctrl" the ⌘ key on macOS.
        //
        // Orbit pivots on the picked object point under the press (silx
        // CameraSelectRotate.beginDrag, orbitAroundCenter=False,
        // interaction.py:150-161), a miss falling back to the scene centre; the
        // pan plane sits at the picked depth (silx CameraSelectPan.beginDrag:
        // `ndcZ = _pickNdcZGL(x, y)`, interaction.py:226-235), a miss reading the
        // cleared depth buffer — the far plane (NDC z = 1). The right button is
        // unbound in every string mode, as silx (it binds RIGHT only in the
        // separate two-button CameraControl, interaction.py:494-511).
        if response.drag_started_by(PointerButton::Primary)
            && let Some(p) = press_origin
        {
            let ctrl = ui.ctx().input(|i| i.modifiers.command);
            let win = to_local(p);
            match self.interaction_mode.left_gesture(ctrl) {
                Some(LeftGesture::Orbit) => {
                    let pivot = self
                        .pick(window_to_ndc(win, size_px))
                        .map_or(center, |hit| hit.position);
                    self.orbit = Some(OrbitDrag::begin(&self.camera, win, pivot));
                }
                Some(LeftGesture::Pan) => {
                    let plane_z = self
                        .pick(window_to_ndc(win, size_px))
                        .map_or(1.0, |hit| hit.ndc_depth);
                    self.pan = Some(PanDrag::begin(win, size_px, plane_z));
                }
                None => {}
            }
        }
        if response.dragged_by(PointerButton::Primary)
            && let Some(p) = response.interact_pointer_pos()
        {
            let local = to_local(p);
            if let Some(orbit) = self.orbit {
                orbit.update(&mut self.camera, local, size_px);
            }
            if let Some(mut pan) = self.pan {
                pan.update(&mut self.camera, local, size_px);
                self.pan = Some(pan);
            }
        }
        if response.drag_stopped_by(PointerButton::Primary) {
            self.orbit = None;
            self.pan = None;
        }

        // Zoom — wheel while hovering. Un-project the cursor at its own picked
        // depth so the pixel under the mouse stays invariant (silx CameraWheel
        // mode "position", interaction.py:329-341); a miss anchors at the far
        // plane, as silx's depth-buffer read does.
        //
        // silx applies a FIXED ±0.2 step once per wheel EVENT, magnitude-
        // independent (one Qt `wheelEvent` → one `handleEvent("wheel", …)`,
        // Plot3DWidget.py:407-416 → interaction.py:340-341), so this reads the
        // raw `MouseWheel` events, not the frame's `smooth_scroll_delta` —
        // egui's sum-conserving smoothing dribbles one notch over N frames,
        // and a per-frame trigger would fire the full step N times (0.8^N per
        // notch, frame-rate-dependent). Same per-notch family as the 2D
        // calibration (R1-8), but the exponential composition trick does not
        // apply here because silx's 3D step does not scale with the angle.
        // silx keeps `CameraWheel` in both the default and the Ctrl handler set
        // for `Rotate`/`Pan` but has no handler at all for `None`, so the wheel
        // zooms in every mode except `Disabled`.
        if self.interaction_mode.wheel_zooms()
            && let Some(p) = response.hover_pos()
        {
            let steps = ui.input(|i| wheel_zoom_steps(&i.events));
            let ndc = window_to_ndc(to_local(p), size_px);
            for zoom_in in steps {
                // Re-pick per step: each zoom moves the camera, and silx
                // re-reads the depth buffer on every event.
                let ndc_z = self.pick(ndc).map_or(1.0, |hit| hit.ndc_depth);
                self.camera.zoom_at(ndc, ndc_z, zoom_in);
            }
        }

        // Keep the scene within the depth frustum after any interaction.
        self.camera.adjust_depth_extent(self.bounds);

        paint_scene3d_with(
            ui,
            rect,
            self.id,
            &self.camera,
            self.background,
            self.shading(),
            self.orientation_indicator.then(|| self.overview_id()),
        );
        self.draw_axes_labels(ui, rect);
        response
    }

    /// Render the current scene at `size_px` physical pixels from the widget's
    /// camera, returning it as tightly packed RGBA8 (`width * height * 4`, top
    /// row first), or `None` if the GPU readback fails. Off-screen and
    /// synchronous — independent of the egui frame loop — so it suits saving a
    /// scene to an image file (pair with [`crate::encode_png`]).
    pub fn snapshot(&self, render_state: &RenderState, size_px: (u32, u32)) -> Option<Vec<u8>> {
        snapshot_scene3d_with(
            render_state,
            self.id,
            &self.camera,
            self.background,
            size_px,
            self.shading(),
            self.orientation_indicator.then(|| self.overview_id()),
        )
    }

    /// Pick the scene geometry under a click at normalized device coordinates
    /// `ndc` (`x, y ∈ [-1, 1]`; convert a widget-local pixel with
    /// [`window_to_ndc`]). Returns the nearest hit (smallest NDC depth) among the
    /// data surfaces and scatter points, or `None` if the ray misses everything
    /// or the camera is singular.
    ///
    /// Port of silx `SceneWidget.pickItems`: it builds the picking segment
    /// ([`picking_segment`]) and intersects it with the data triangles
    /// ([`segment_triangles_intersection`] over
    /// `Scene3dGeometry::pick_triangles` — flat fills, lit meshes,
    /// iso-surfaces); scatter points are hit-tested by projecting each to NDC
    /// and keeping those within [`PICK_POINT_TOLERANCE_PX`] of the click;
    /// Scatter2D-LINES data points via the [`PICK_LINE_TOLERANCE_PX`] square
    /// test (silx `_pickPoints`); image quads by plane intersection with a
    /// pixel row/column payload (silx `_Image._pickFull`). The bounding-box /
    /// axes chrome is excluded (it is not part of the data content), matching
    /// silx picking scene items rather than the frame.
    ///
    /// Uses the camera's current viewport size, so call after [`SceneWidget::show`]
    /// has run this frame (it syncs the camera aspect to the rendered rect).
    pub fn pick(&self, ndc: (f32, f32)) -> Option<ScenePick> {
        let segment = picking_segment(&self.camera, ndc)?;
        let mvp = self.camera.matrix();

        let mut best: Option<ScenePick> = None;
        let mut consider = |cand: ScenePick| {
            if best.is_none_or(|b| cand.ndc_depth < b.ndc_depth) {
                best = Some(cand);
            }
        };

        // Surfaces: the nearest triangle hit (the list is depth-sorted).
        let triangles = self.content.pick_triangles();
        if let Some(hit) = segment_triangles_intersection(segment, &triangles).first() {
            let position = hit.position(segment.0, segment.1);
            let ndc_depth = mvp.transform_point(position, true).z;
            consider(ScenePick {
                position,
                ndc_depth,
                kind: ScenePickKind::Surface,
            });
        }

        // Scatter points: nearest within the click tolerance, in front of the camera.
        let (vw, vh) = self.camera.size();
        let radius_ndc_x = 2.0 * PICK_POINT_TOLERANCE_PX / vw.max(1.0);
        let radius_ndc_y = 2.0 * PICK_POINT_TOLERANCE_PX / vh.max(1.0);
        for (index, world) in self.content.pick_points().into_iter().enumerate() {
            let p = mvp.transform_point(world, true);
            if !(-1.0..=1.0).contains(&p.z) {
                continue; // outside the depth frustum (behind camera / clipped)
            }
            let dx = (p.x - ndc.0) / radius_ndc_x;
            let dy = (p.y - ndc.1) / radius_ndc_y;
            if dx * dx + dy * dy <= 1.0 {
                consider(ScenePick {
                    position: world,
                    ndc_depth: p.z,
                    kind: ScenePickKind::Point { index },
                });
            }
        }

        // Pick-only anchors (Scatter2D LINES mode): silx `_pickPoints` with a
        // 5 px threshold (items/scatter.py:424-434, called with threshold=5.0
        // from :511) — a per-axis square test `|Δndc| < threshold/viewport`
        // plus the segment depth range `z ∈ [-1, 1]`, nearest by depth.
        let square_ndc_x = PICK_LINE_TOLERANCE_PX / vw.max(1.0);
        let square_ndc_y = PICK_LINE_TOLERANCE_PX / vh.max(1.0);
        for (index, &pos) in self.content.line_pick_anchors().iter().enumerate() {
            let world = Vec3::new(pos[0], pos[1], pos[2]);
            let p = mvp.transform_point(world, true);
            if !(-1.0..=1.0).contains(&p.z) {
                continue;
            }
            if (p.x - ndc.0).abs() < square_ndc_x && (p.y - ndc.1).abs() < square_ndc_y {
                consider(ScenePick {
                    position: world,
                    ndc_depth: p.z,
                    kind: ScenePickKind::LinePoint { index },
                });
            }
        }

        // Image quads: silx `_Image._pickFull` (items/image.py:55-84) —
        // intersect the picking segment with the image plane; exactly one
        // crossing (a coplanar segment picks nothing), reject in front of the
        // origin edge, then floor to the pixel row/column and bounds-check.
        // The layer is axis-aligned in its z = origin.z plane, pixel (col,row)
        // spanning origin + (col..col+1, row..row+1)·scale.
        for (image, layer) in self.content.images.iter().enumerate() {
            let hits = segment_plane_intersect(
                segment.0,
                segment.1,
                Vec3::new(0.0, 0.0, 1.0),
                Vec3::new(0.0, 0.0, layer.origin[2]),
            );
            let [hit] = hits.as_slice() else {
                continue; // no crossing, or segment coplanar with the image
            };
            // World → image-frame (column, row) continuous coordinates.
            let col_f = (hit.x - layer.origin[0]) / layer.scale[0];
            let row_f = (hit.y - layer.origin[1]) / layer.scale[1];
            if col_f < 0.0 || row_f < 0.0 {
                continue; // outside image (silx rejects negatives)
            }
            let (col, row) = (col_f as usize, row_f as usize);
            if row >= layer.height as usize || col >= layer.width as usize {
                continue; // outside image
            }
            consider(ScenePick {
                position: *hit,
                ndc_depth: mvp.transform_point(*hit, true).z,
                kind: ScenePickKind::Image { image, row, col },
            });
        }

        // Textured meshes (the cut plane): silx's gesture anchors read the depth
        // buffer, which contains every rendered fragment — the cut plane included
        // (`interaction.py:153-156, 228-229, 331` via `viewport._pickNdcZGL`), so
        // orbit/pan/zoom anchor on the slice, not the far plane. The
        // `pick_triangles` channel deliberately excludes these (they are not raw
        // data triangles); intersect them here as their own channel so the
        // gesture depth read is geometry-complete like silx's buffer read.
        for (mesh, tm) in self.content.textured_meshes.iter().enumerate() {
            let tris: Vec<[Vec3; 3]> = tm
                .vertices
                .chunks_exact(3)
                .map(|t| {
                    [
                        Vec3::from_array(t[0]),
                        Vec3::from_array(t[1]),
                        Vec3::from_array(t[2]),
                    ]
                })
                .collect();
            if let Some(hit) = segment_triangles_intersection(segment, &tris).first() {
                let position = hit.position(segment.0, segment.1);
                consider(ScenePick {
                    position,
                    ndc_depth: mvp.transform_point(position, true).z,
                    kind: ScenePickKind::TexturedSurface { mesh },
                });
            }
        }

        best
    }
}

/// Pixel tolerance for scatter-point picking: a point is pickable when it
/// projects within this many pixels of the click. silx tests against the
/// marker footprint; a fixed tolerance is a documented simplification (the
/// per-point marker size is not threaded into the pick path).
pub const PICK_POINT_TOLERANCE_PX: f32 = 7.0;

/// Pixel threshold of the pick-anchor square test — silx picks `Scatter2D`
/// LINES mode at its data points with `threshold=5.0`
/// (`items/scatter.py:511`), tested as `|Δndc| < threshold/viewport` per axis
/// (`items/scatter.py:424-428`).
pub const PICK_LINE_TOLERANCE_PX: f32 = 5.0;

/// What [`SceneWidget::pick`] hit.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ScenePickKind {
    /// A data surface (a triangle of a fill, lit mesh, or iso-surface).
    Surface,
    /// A scatter point, with its index in the points channel.
    Point { index: usize },
    /// A pick-only data-point anchor (Scatter2D LINES mode — silx picks the
    /// data points, not the segments; `items/scatter.py:509-511`), with its
    /// index in the anchors channel.
    LinePoint { index: usize },
    /// An image-quad pixel (silx `_Image._pickFull`, `items/image.py:55-84`),
    /// with the layer's index in the images channel and the picked pixel's
    /// row/column in the image data.
    Image {
        image: usize,
        row: usize,
        col: usize,
    },
    /// A textured arbitrary-triangle mesh — the cut plane's colormapped slice
    /// (or a transformed image quad) — with its index in the textured-meshes
    /// channel. silx's gesture anchors read the depth buffer, which contains
    /// every rendered fragment including the cut plane
    /// (`interaction.py:153-156, 228-229, 331` via `viewport._pickNdcZGL`), so
    /// this channel keeps orbit/pan/zoom anchored on the slice.
    TexturedSurface { mesh: usize },
}

/// The nearest scene hit from [`SceneWidget::pick`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ScenePick {
    /// World-space position of the hit.
    pub position: Vec3,
    /// NDC depth `z ∈ [-1, 1]` of the hit (smaller is nearer the camera); the
    /// key used to choose the nearest across surfaces and points.
    pub ndc_depth: f32,
    /// Which channel was hit.
    pub kind: ScenePickKind,
}

/// The orientation indicator's scene — port of silx `_OverviewViewport.__init__`
/// (`Plot3DWidget.py:59-77`): a half-transparent white disc backdrop
/// (`ColorPoints(0, 0, 0, color=(1., 1., 1., 0.5), size=100)` with the `'o'`
/// marker, added first inside a depth-disabled group) and the RGB unit axes
/// (`primitives.Axes()`, `primitives.py:842-870`: unit lines from the origin
/// along +x red, +y green, +z blue). silx scales the whole scene by
/// `transforms.Scale(2.5)` (`Plot3DWidget.py:64`); the scale is baked into the
/// axis endpoints here (the screen-sized disc sprite is unaffected by it).
fn overview_geometry() -> Scene3dGeometry {
    let mut g = Scene3dGeometry::new();
    g.add_point(
        [0.0; 3],
        Color32::from_rgba_unmultiplied(255, 255, 255, 128),
        OVERVIEW_SIZE_PX as f32,
        PointMarker::Circle,
    );
    g.add_line([0.0; 3], [2.5, 0.0, 0.0], Color32::from_rgb(255, 0, 0));
    g.add_line([0.0; 3], [0.0, 2.5, 0.0], Color32::from_rgb(0, 255, 0));
    g.add_line([0.0; 3], [0.0, 0.0, 2.5], Color32::from_rgb(0, 0, 255));
    g
}

/// One 3D zoom trigger per raw `MouseWheel` event this frame, in delivery
/// order: `true` = zoom in (scroll up). silx's `_zoomToPosition` applies its
/// fixed 0.2 step exactly once per wheel event regardless of the wheel angle
/// (interaction.py:340-341), so the trigger count must equal the EVENT count —
/// never the number of frames egui's scroll smoothing spreads a notch over.
/// Horizontal-only wheel events (`delta.y == 0`) produce no trigger.
fn wheel_zoom_steps(events: &[egui::Event]) -> Vec<bool> {
    events
        .iter()
        .filter_map(|e| match e {
            egui::Event::MouseWheel { delta, .. } if delta.y != 0.0 => Some(delta.y > 0.0),
            _ => None,
        })
        .collect()
}

/// The seven predefined viewpoints in silx's menu order, each with its silx menu
/// label and tooltip (`actions/viewpoint.py`).
const VIEWPOINT_PRESETS: [(CameraFace, &str, &str); 7] = [
    (CameraFace::Front, "Front", "View along the -Z axis"),
    (CameraFace::Back, "Back", "View along the +Z axis"),
    (CameraFace::Top, "Top", "View along the -Y axis"),
    (CameraFace::Bottom, "Bottom", "View along the +Y axis"),
    (CameraFace::Right, "Right", "View along the -X axis"),
    (CameraFace::Left, "Left", "View along the +X axis"),
    (CameraFace::Side, "Side", "Side view"),
];

/// Draw a viewpoint drop-down menu button (port of silx
/// `tools.ViewpointTools.ViewpointToolButton`): a `View` button whose menu sets
/// one of the seven predefined viewpoints on `scene`. Returns the chosen
/// [`CameraFace`] when a preset is selected this frame, otherwise `None`.
pub fn viewpoint_menu(ui: &mut Ui, scene: &mut SceneWidget) -> Option<CameraFace> {
    let mut chosen = None;
    ui.menu_button("View", |ui| {
        for (face, label, tip) in VIEWPOINT_PRESETS {
            if ui.button(label).on_hover_text(tip).clicked() {
                scene.set_viewpoint(face);
                chosen = Some(face);
                ui.close();
            }
        }
    })
    .response
    .on_hover_text("Reset the viewpoint to a defined position");
    chosen
}

#[cfg(test)]
mod tests {
    use super::*;
    use egui::{Event, Modifiers, MouseWheelUnit, TouchPhase, Vec2};

    fn wheel(unit: MouseWheelUnit, x: f32, y: f32) -> Event {
        Event::MouseWheel {
            unit,
            delta: Vec2::new(x, y),
            // Momentum phases are deliberately NOT filtered: Qt delivers
            // momentum as more wheelEvents and silx steps on each.
            phase: TouchPhase::Move,
            modifiers: Modifiers::NONE,
        }
    }

    #[test]
    fn one_wheel_event_is_one_step_regardless_of_magnitude() {
        // R2-48: silx's step is fixed per EVENT (interaction.py:340-341) — a
        // one-line notch and a three-line notch are each ONE trigger.
        assert_eq!(
            wheel_zoom_steps(&[wheel(MouseWheelUnit::Line, 0.0, 1.0)]),
            vec![true]
        );
        assert_eq!(
            wheel_zoom_steps(&[wheel(MouseWheelUnit::Line, 0.0, -3.0)]),
            vec![false]
        );
        assert_eq!(
            wheel_zoom_steps(&[wheel(MouseWheelUnit::Point, 0.0, 2.5)]),
            vec![true]
        );
    }

    #[test]
    fn smoothing_frames_without_events_fire_nothing() {
        // egui dribbles smooth_scroll_delta over frames AFTER the event's
        // frame; those frames have no MouseWheel event and must not re-fire
        // the fixed step (the per-frame 0.8^N collapse this finding cites).
        assert_eq!(wheel_zoom_steps(&[]), Vec::<bool>::new());
        assert_eq!(wheel_zoom_steps(&[Event::PointerGone]), Vec::<bool>::new());
    }

    #[test]
    fn multiple_events_step_once_each_in_delivery_order() {
        let events = [
            wheel(MouseWheelUnit::Point, 0.0, 4.0),
            wheel(MouseWheelUnit::Point, 0.0, -2.0),
            wheel(MouseWheelUnit::Point, 0.0, 1.0),
        ];
        assert_eq!(wheel_zoom_steps(&events), vec![true, false, true]);
    }

    #[test]
    fn horizontal_only_wheel_events_do_not_zoom() {
        assert_eq!(
            wheel_zoom_steps(&[wheel(MouseWheelUnit::Line, 2.0, 0.0)]),
            Vec::<bool>::new()
        );
    }

    #[test]
    fn rotate_mode_left_gesture_orbits_and_ctrl_pans() {
        // R3-7: silx RotateCameraControl — default handler set orbits on the left
        // button, the Ctrl handler set pans (interaction.py:448-469).
        let m = SceneInteractiveMode::Rotate;
        assert_eq!(m.left_gesture(false), Some(LeftGesture::Orbit));
        assert_eq!(m.left_gesture(true), Some(LeftGesture::Pan));
    }

    #[test]
    fn pan_mode_left_gesture_pans_and_ctrl_orbits() {
        // R3-7: silx PanCameraControl is the mirror image — pan by default, orbit
        // under Ctrl (interaction.py:472-491).
        let m = SceneInteractiveMode::Pan;
        assert_eq!(m.left_gesture(false), Some(LeftGesture::Pan));
        assert_eq!(m.left_gesture(true), Some(LeftGesture::Orbit));
    }

    #[test]
    fn disabled_mode_binds_no_gesture_and_no_wheel() {
        // R3-7: silx setInteractiveMode(None) drops the event handler entirely
        // (Plot3DWidget.py:186-187), so neither the left button nor the wheel act.
        let m = SceneInteractiveMode::Disabled;
        assert_eq!(m.left_gesture(false), None);
        assert_eq!(m.left_gesture(true), None);
        assert!(!m.wheel_zooms());
    }

    #[test]
    fn rotate_and_pan_modes_zoom_on_wheel() {
        // silx keeps CameraWheel in both the default and the Ctrl handler set for
        // the two string modes, so the wheel zooms regardless of the modifier.
        assert!(SceneInteractiveMode::Rotate.wheel_zooms());
        assert!(SceneInteractiveMode::Pan.wheel_zooms());
    }

    #[test]
    fn rotate_is_the_default_mode() {
        // silx's default interactive mode is 'rotate' (RotateCameraControl).
        assert_eq!(
            SceneInteractiveMode::default(),
            SceneInteractiveMode::Rotate
        );
    }
}