siplot 0.3.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
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
//! The 3D scene renderer — wgpu line/triangle pipelines that draw depth-tested
//! geometry into an offscreen color+depth target, then blit that color into
//! egui's (depth-less) paint pass.
//!
//! This is the plot3d analogue of [`crate::render::backend_wgpu`]: persistent
//! GPU state ([`Scene3dResources`]) lives in `egui_wgpu`'s `callback_resources`
//! type map, installed once via [`install_scene3d`]; the egui side re-registers
//! a lightweight `Scene3dCallback` each frame via [`paint_scene3d`].
//!
//! Why offscreen-then-blit: egui's render pass has **no depth attachment**
//! (`doc/plot3d-parity-roadmap.md` Architecture), so depth-tested 3D cannot
//! draw straight into it. Each frame:
//!
//! - `prepare()` sizes an offscreen color+depth texture pair to the widget's
//!   pixel rect, writes the camera MVP uniform, and encodes one depth-tested
//!   pass (clear → triangles → lines) into the offscreen color target.
//! - `paint()` blits that color texture into egui's pass as a viewport-clipped
//!   full-screen triangle.
//!
//! Geometry is uploaded once via [`set_scene3d`] (mirroring `set_curves`); the
//! per-frame camera transform is applied in the shader from the MVP uniform.

use std::collections::HashMap;
use std::num::NonZeroU64;

use egui::Color32;
use egui_wgpu::{RenderState, wgpu};

use crate::core::scene3d::camera::Camera;
use crate::core::scene3d::mat4::Vec3;

/// Scene identity key (mirrors [`crate::core::plot::PlotId`]); lets several
/// independent 3D scenes coexist in one egui app without sharing GPU state.
pub type Scene3dId = u64;

/// Offscreen depth-buffer format. 32-bit float — ample range for the camera's
/// near/far span, and universally supported as a render attachment.
const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;

/// One scene vertex: world-space position + linear-premultiplied RGBA. Used by
/// both the line and triangle pipelines (shared vertex layout). `repr(C)` so the
/// 28-byte stride matches the WGSL vertex attributes exactly.
#[repr(C)]
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct Scene3dVertex {
    /// World-space position (the model transform, if any, is folded into the MVP).
    pub pos: [f32; 3],
    /// Linear color space, premultiplied alpha — same convention as the 2D path.
    pub color: [f32; 4],
}

/// Vertex attributes for [`Scene3dVertex`]: position at location 0 (offset 0),
/// color at location 1 (offset 12). Kept as a `'static` const so the
/// [`wgpu::VertexBufferLayout`] can borrow it for pipeline creation.
const SCENE3D_VERTEX_ATTRS: [wgpu::VertexAttribute; 2] = [
    wgpu::VertexAttribute {
        format: wgpu::VertexFormat::Float32x3,
        offset: 0,
        shader_location: 0,
    },
    wgpu::VertexAttribute {
        format: wgpu::VertexFormat::Float32x4,
        offset: 12,
        shader_location: 1,
    },
];

/// Point-sprite marker shape — the silx `_Points` markers (`SUPPORTED_MARKERS`).
/// The discriminant order matches the `marker` id read by the `alpha_symbol`
/// switch in `scene3d_points.wgsl`; keep the two in lock-step.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum PointMarker {
    /// `'o'` — filled circle (silx default).
    #[default]
    Circle,
    /// `'d'` — diamond.
    Diamond,
    /// `'s'` — square (the full sprite).
    Square,
    /// `'+'` — plus.
    Plus,
    /// `'x'` — diagonal cross.
    Cross,
    /// `'*'` — asterisk (plus + cross + soft circle edge).
    Asterisk,
    /// `'_'` — horizontal line.
    HLine,
    /// `'|'` — vertical line.
    VLine,
}

impl PointMarker {
    /// The `marker` id handed to the GPU; must match `scene3d_points.wgsl`.
    pub fn id(self) -> u32 {
        match self {
            PointMarker::Circle => 0,
            PointMarker::Diamond => 1,
            PointMarker::Square => 2,
            PointMarker::Plus => 3,
            PointMarker::Cross => 4,
            PointMarker::Asterisk => 5,
            PointMarker::HLine => 6,
            PointMarker::VLine => 7,
        }
    }
}

/// One scatter point (one instance): world-space centre, linear-premultiplied
/// RGBA, pixel diameter, and marker id. `repr(C)` so the 36-byte stride matches
/// `SCENE3D_POINT_ATTRS` and `scene3d_points.wgsl`.
#[repr(C)]
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct Scene3dPoint {
    /// World-space centre (the model transform, if any, folds into the MVP).
    pub pos: [f32; 3],
    /// Linear color space, premultiplied alpha — same convention as the 2D path.
    pub color: [f32; 4],
    /// Sprite diameter in physical pixels (silx `gl_PointSize`).
    pub size: f32,
    /// Marker shape id (see [`PointMarker::id`]).
    pub marker: u32,
}

/// Per-instance attributes for [`Scene3dPoint`]: pos at location 0 (offset 0),
/// color at 1 (offset 12), size at 2 (offset 28), marker at 3 (offset 32).
const SCENE3D_POINT_ATTRS: [wgpu::VertexAttribute; 4] = [
    wgpu::VertexAttribute {
        format: wgpu::VertexFormat::Float32x3,
        offset: 0,
        shader_location: 0,
    },
    wgpu::VertexAttribute {
        format: wgpu::VertexFormat::Float32x4,
        offset: 12,
        shader_location: 1,
    },
    wgpu::VertexAttribute {
        format: wgpu::VertexFormat::Float32,
        offset: 28,
        shader_location: 2,
    },
    wgpu::VertexAttribute {
        format: wgpu::VertexFormat::Uint32,
        offset: 32,
        shader_location: 3,
    },
];

/// One shaded-mesh vertex: world-space position, linear-premultiplied RGBA, and
/// a world-space normal for lighting. `repr(C)` so the 40-byte stride matches
/// `SCENE3D_MESH_ATTRS` and `scene3d_mesh.wgsl`.
#[repr(C)]
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct Scene3dMeshVertex {
    /// World-space position (model is identity; items bake world coordinates).
    pub pos: [f32; 3],
    /// Linear color space, premultiplied alpha — same convention as the 2D path.
    pub color: [f32; 4],
    /// World-space surface normal (need not be unit; the shader normalizes).
    pub normal: [f32; 3],
}

/// Per-vertex attributes for [`Scene3dMeshVertex`]: pos at location 0 (offset 0),
/// color at 1 (offset 12), normal at 2 (offset 28).
const SCENE3D_MESH_ATTRS: [wgpu::VertexAttribute; 3] = [
    wgpu::VertexAttribute {
        format: wgpu::VertexFormat::Float32x3,
        offset: 0,
        shader_location: 0,
    },
    wgpu::VertexAttribute {
        format: wgpu::VertexFormat::Float32x4,
        offset: 12,
        shader_location: 1,
    },
    wgpu::VertexAttribute {
        format: wgpu::VertexFormat::Float32x3,
        offset: 28,
        shader_location: 2,
    },
];

/// One textured-primitive vertex: world-space position + texture UV. Shared by
/// the image quad and the arbitrary-triangle textured mesh (the cut plane).
/// `repr(C)` so the 20-byte stride matches [`SCENE3D_IMAGE_ATTRS`] and
/// `scene3d_image.wgsl`.
#[repr(C)]
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct Scene3dImageVertex {
    pos: [f32; 3],
    uv: [f32; 2],
}

/// Per-vertex attributes for [`Scene3dImageVertex`]: pos at location 0 (offset 0),
/// uv at 1 (offset 12).
const SCENE3D_IMAGE_ATTRS: [wgpu::VertexAttribute; 2] = [
    wgpu::VertexAttribute {
        format: wgpu::VertexFormat::Float32x3,
        offset: 0,
        shader_location: 0,
    },
    wgpu::VertexAttribute {
        format: wgpu::VertexFormat::Float32x2,
        offset: 12,
        shader_location: 1,
    },
];

/// Texture sampling for an image layer (silx `InterpolationMixIn`: 'nearest' vs
/// 'linear').
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum ImageInterpolation {
    /// Nearest-neighbour — crisp pixels (silx default for `ImageData`/`ImageRgba`).
    #[default]
    Nearest,
    /// Bilinear — smooth.
    Linear,
}

/// One image layer: a `width × height` premultiplied-linear RGBA8 raster placed
/// as a quad in the scene. The quad spans pixel-corner `origin` to
/// `origin + (width·scale.x, height·scale.y)` in the `z = origin.z` plane (silx
/// `ImageData`/`ImageRgba`: pixel `(col, row)` → world `(x, y)`). `pixels` is
/// row-major (row 0 first), length `width · height · 4`.
#[derive(Clone, Debug)]
pub struct Scene3dImageLayer {
    /// Premultiplied-linear RGBA8, row-major, length `width · height · 4`.
    pub pixels: Vec<u8>,
    /// Image width in pixels.
    pub width: u32,
    /// Image height in pixels.
    pub height: u32,
    /// World position of pixel-corner `(0, 0)`.
    pub origin: [f32; 3],
    /// World size of one pixel along x and y.
    pub scale: [f32; 2],
    /// Nearest vs linear sampling.
    pub interpolation: ImageInterpolation,
}

/// One textured arbitrary-triangle mesh: a `width × height` premultiplied-linear
/// RGBA8 raster sampled across a triangle list at explicit world positions. This
/// is the general case of [`Scene3dImageLayer`] (whose geometry is fixed to an
/// axis-aligned quad) — used by the cut plane, which maps a colormapped slice of
/// the volume onto the (arbitrary) plane∩box contour polygon.
///
/// `vertices` is a flat triangle list (every three a triangle, `TriangleList`
/// topology); `uvs` carries the matching per-vertex texture coordinate into
/// `pixels` (same length as `vertices`). `pixels` is row-major (row 0 first),
/// length `width · height · 4`.
#[derive(Clone, Debug)]
pub struct Scene3dTexturedMesh {
    /// Premultiplied-linear RGBA8, row-major, length `width · height · 4`.
    pub pixels: Vec<u8>,
    /// Texture width in pixels.
    pub width: u32,
    /// Texture height in pixels.
    pub height: u32,
    /// World-space triangle-list vertices (length a multiple of 3).
    pub vertices: Vec<[f32; 3]>,
    /// Per-vertex texture UV (same length as `vertices`).
    pub uvs: Vec<[f32; 2]>,
    /// Nearest vs linear sampling.
    pub interpolation: ImageInterpolation,
}

/// Uniform block for `scene3d.wgsl`: the column-major, clip-corrected MVP.
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct Scene3dParams {
    /// `camera.matrix() × model`, transposed to column-major and depth-corrected
    /// for wgpu z∈[0,1] (see [`crate::core::scene3d::mat4::Mat4::to_gpu_clip_cols`]).
    mvp: [[f32; 4]; 4],
}

/// Uniform block for `scene3d_mesh.wgsl`: the clip MVP plus the camera-space
/// normal transform (the view matrix, column-major, no depth correction).
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct Scene3dMeshParams {
    mvp: [[f32; 4]; 4],
    normal_mat: [[f32; 4]; 4],
}

/// Uniform block for `scene3d_points.wgsl`: the MVP plus the offscreen viewport
/// pixel size (the sprite-corner offset is computed in pixels then converted to
/// NDC, so the shader needs the viewport extent).
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct Scene3dPointParams {
    mvp: [[f32; 4]; 4],
    viewport: [f32; 2],
    _pad: [f32; 2],
}

/// CPU-side geometry for one scene: a flat line-list and a flat triangle-list,
/// each vertex carrying its own color. Build with [`Scene3dGeometry::add_line`]
/// / [`Scene3dGeometry::add_triangle`], then upload via [`set_scene3d`].
#[derive(Clone, Debug, Default)]
pub struct Scene3dGeometry {
    /// Pairs of vertices, each pair one line segment (`LineList` topology).
    pub(crate) lines: Vec<Scene3dVertex>,
    /// Triples of vertices, each triple one triangle (`TriangleList` topology),
    /// flat-shaded (no lighting) — chrome and simple fills.
    pub(crate) triangles: Vec<Scene3dVertex>,
    /// Scatter points, each drawn as a billboarded marker sprite.
    pub(crate) points: Vec<Scene3dPoint>,
    /// Triples of vertices, each triple one triangle of a **lit** mesh (carries
    /// per-vertex normals; `TriangleList` topology).
    pub(crate) meshes: Vec<Scene3dMeshVertex>,
    /// Textured image quads (one texture each), drawn after the opaque geometry.
    pub(crate) images: Vec<Scene3dImageLayer>,
    /// Textured arbitrary-triangle meshes (one texture each), drawn in the same
    /// alpha-blended textured pass as the image quads. Used by the cut plane.
    pub(crate) textured_meshes: Vec<Scene3dTexturedMesh>,
}

impl Scene3dGeometry {
    /// An empty geometry.
    pub fn new() -> Self {
        Self::default()
    }

    /// True when there is nothing to draw.
    pub fn is_empty(&self) -> bool {
        self.lines.is_empty()
            && self.triangles.is_empty()
            && self.points.is_empty()
            && self.meshes.is_empty()
            && self.images.is_empty()
            && self.textured_meshes.is_empty()
    }

    /// Drop all geometry, keeping allocated capacity for reuse.
    pub fn clear(&mut self) {
        self.lines.clear();
        self.triangles.clear();
        self.points.clear();
        self.meshes.clear();
        self.images.clear();
        self.textured_meshes.clear();
    }

    /// Append a textured image layer (see [`Scene3dImageLayer`]).
    pub fn add_image_layer(&mut self, layer: Scene3dImageLayer) {
        self.images.push(layer);
    }

    /// Append a textured arbitrary-triangle mesh (see [`Scene3dTexturedMesh`]).
    pub fn add_textured_mesh(&mut self, mesh: Scene3dTexturedMesh) {
        self.textured_meshes.push(mesh);
    }

    /// Append all of `other`'s primitives onto this geometry, every channel
    /// (lines, triangles, points, meshes, images, textured meshes). The single
    /// owner of the geometry-merge rule, so a composite (e.g. chrome + data
    /// items) forwards every primitive kind, not a hand-picked subset.
    pub fn extend_from(&mut self, other: &Scene3dGeometry) {
        self.lines.extend_from_slice(&other.lines);
        self.triangles.extend_from_slice(&other.triangles);
        self.points.extend_from_slice(&other.points);
        self.meshes.extend_from_slice(&other.meshes);
        self.images.extend_from_slice(&other.images);
        self.textured_meshes
            .extend_from_slice(&other.textured_meshes);
    }

    /// World-space triangles for CPU picking, as `[v0, v1, v2]` triples: the
    /// flat-shaded `triangles` channel followed by the lit `meshes` channel
    /// (iso-surfaces, colormapped meshes, the cylindrical-volume primitives).
    /// Image quads and textured meshes (the cut plane) are excluded — those are
    /// picked as planes/volumes by the field-aware pickers, not as raw triangles.
    /// Used by [`crate::SceneWidget::pick`].
    pub fn pick_triangles(&self) -> Vec<[Vec3; 3]> {
        let mut out = Vec::with_capacity(self.triangles.len() / 3 + self.meshes.len() / 3);
        for tri in self.triangles.chunks_exact(3) {
            out.push([
                Vec3::from_array(tri[0].pos),
                Vec3::from_array(tri[1].pos),
                Vec3::from_array(tri[2].pos),
            ]);
        }
        for tri in self.meshes.chunks_exact(3) {
            out.push([
                Vec3::from_array(tri[0].pos),
                Vec3::from_array(tri[1].pos),
                Vec3::from_array(tri[2].pos),
            ]);
        }
        out
    }

    /// World-space scatter-point positions (the `points` channel), for
    /// threshold picking. Used by [`crate::SceneWidget::pick`].
    pub fn pick_points(&self) -> Vec<Vec3> {
        self.points
            .iter()
            .map(|p| Vec3::from_array(p.pos))
            .collect()
    }

    /// Append a line segment `a→b` in one solid [`Color32`].
    pub fn add_line(&mut self, a: [f32; 3], b: [f32; 3], color: Color32) {
        let rgba = egui::Rgba::from(color).to_array();
        self.add_line_rgba(a, b, rgba);
    }

    /// Append a line segment `a→b` with explicit linear-premultiplied RGBA.
    pub fn add_line_rgba(&mut self, a: [f32; 3], b: [f32; 3], rgba: [f32; 4]) {
        self.lines.push(Scene3dVertex {
            pos: a,
            color: rgba,
        });
        self.lines.push(Scene3dVertex {
            pos: b,
            color: rgba,
        });
    }

    /// Append a triangle `a, b, c` in one solid [`Color32`].
    pub fn add_triangle(&mut self, a: [f32; 3], b: [f32; 3], c: [f32; 3], color: Color32) {
        let rgba = egui::Rgba::from(color).to_array();
        self.add_triangle_rgba(a, b, c, rgba);
    }

    /// Append a triangle `a, b, c` with explicit linear-premultiplied RGBA.
    pub fn add_triangle_rgba(&mut self, a: [f32; 3], b: [f32; 3], c: [f32; 3], rgba: [f32; 4]) {
        for pos in [a, b, c] {
            self.triangles.push(Scene3dVertex { pos, color: rgba });
        }
    }

    /// Append one scatter point at `pos`, drawn as a `marker` sprite `size`
    /// physical pixels across in solid [`Color32`].
    pub fn add_point(&mut self, pos: [f32; 3], color: Color32, size: f32, marker: PointMarker) {
        let rgba = egui::Rgba::from(color).to_array();
        self.add_point_rgba(pos, rgba, size, marker);
    }

    /// Append one scatter point with explicit linear-premultiplied RGBA.
    pub fn add_point_rgba(
        &mut self,
        pos: [f32; 3],
        rgba: [f32; 4],
        size: f32,
        marker: PointMarker,
    ) {
        self.points.push(Scene3dPoint {
            pos,
            color: rgba,
            size,
            marker: marker.id(),
        });
    }

    /// Append one lit-mesh triangle with explicit per-vertex positions, linear-
    /// premultiplied RGBA colors, and world-space normals.
    pub fn add_mesh_triangle_rgba(
        &mut self,
        positions: [[f32; 3]; 3],
        rgba: [[f32; 4]; 3],
        normals: [[f32; 3]; 3],
    ) {
        for i in 0..3 {
            self.meshes.push(Scene3dMeshVertex {
                pos: positions[i],
                color: rgba[i],
                normal: normals[i],
            });
        }
    }

    /// Append one lit-mesh triangle in a single solid [`Color32`] with explicit
    /// per-vertex normals.
    pub fn add_mesh_triangle(
        &mut self,
        positions: [[f32; 3]; 3],
        color: Color32,
        normals: [[f32; 3]; 3],
    ) {
        let rgba = egui::Rgba::from(color).to_array();
        self.add_mesh_triangle_rgba(positions, [rgba; 3], normals);
    }

    /// Append one lit-mesh triangle `a, b, c` in a solid [`Color32`], using the
    /// geometric (flat) face normal `(b−a)×(c−a)` for all three vertices — the
    /// fallback when a mesh provides no per-vertex normals.
    pub fn add_mesh_triangle_flat(
        &mut self,
        a: [f32; 3],
        b: [f32; 3],
        c: [f32; 3],
        color: Color32,
    ) {
        let n = flat_normal(a, b, c);
        self.add_mesh_triangle([a, b, c], color, [n; 3]);
    }

    /// Append the bounding-box wireframe + RGB axes for `bounds`, the scene's
    /// spatial chrome. Port of silx `primitives.BoxWithAxes`: three coloured axis
    /// lines from the min corner (X red, Y green, Z blue, each spanning the box
    /// extent) plus the nine remaining box edges in `box_color` (the three edges
    /// that coincide with the axes are drawn as the axes, not repeated).
    pub fn add_bounding_box_with_axes(&mut self, bounds: (Vec3, Vec3), box_color: Color32) {
        let (min, max) = bounds;
        let size = max - min;
        // Unit-cube coordinate → world (silx scales the unit `_vertices` by size
        // and the GroupBBox transform translates them to the min corner).
        let v = |ux: f32, uy: f32, uz: f32| {
            [
                min.x + size.x * ux,
                min.y + size.y * uy,
                min.z + size.z * uz,
            ]
        };
        // The 13 vertices of silx `BoxWithAxes._vertices` (axes origin+tips, then
        // the box corners not already covered by an axis tip).
        let verts = [
            v(0.0, 0.0, 0.0), // 0 axes origin
            v(1.0, 0.0, 0.0), // 1 X tip
            v(0.0, 0.0, 0.0), // 2 axes origin
            v(0.0, 1.0, 0.0), // 3 Y tip
            v(0.0, 0.0, 0.0), // 4 axes origin
            v(0.0, 0.0, 1.0), // 5 Z tip
            v(1.0, 0.0, 0.0), // 6 box corners, z=0
            v(1.0, 1.0, 0.0), // 7
            v(0.0, 1.0, 0.0), // 8
            v(0.0, 0.0, 1.0), // 9 box corners, z=1
            v(1.0, 0.0, 1.0), // 10
            v(1.0, 1.0, 1.0), // 11
            v(0.0, 1.0, 1.0), // 12
        ];

        // RGB axes (X red, Y green, Z blue).
        self.add_line(verts[0], verts[1], Color32::from_rgb(255, 0, 0));
        self.add_line(verts[2], verts[3], Color32::from_rgb(0, 255, 0));
        self.add_line(verts[4], verts[5], Color32::from_rgb(0, 0, 255));

        // The remaining nine box edges (silx `_lineIndices` minus the three axes).
        const BOX_EDGES: [(usize, usize); 9] = [
            (6, 7),
            (7, 8),
            (6, 10),
            (7, 11),
            (8, 12),
            (9, 10),
            (10, 11),
            (11, 12),
            (12, 9),
        ];
        for &(a, b) in &BOX_EDGES {
            self.add_line(verts[a], verts[b], box_color);
        }
    }
}

/// The shared pipelines + layouts for 3D rendering. Built once in
/// [`Scene3dResources::new`].
struct Scene3dPipeline {
    /// egui's surface format; the offscreen color target uses it too so colors
    /// round-trip through the blit without an extra color-space conversion.
    target_format: wgpu::TextureFormat,
    /// `group(0)` layout for the MVP uniform (vertex stage).
    scene_bgl: wgpu::BindGroupLayout,
    /// Depth-tested `LineList` pipeline.
    line_pipeline: wgpu::RenderPipeline,
    /// Depth-tested `TriangleList` pipeline (no face culling).
    tri_pipeline: wgpu::RenderPipeline,
    /// `group(0)` layout for the point-sprite uniform (MVP + viewport, vertex stage).
    point_bgl: wgpu::BindGroupLayout,
    /// Depth-tested, alpha-blended billboarded point-sprite pipeline.
    point_pipeline: wgpu::RenderPipeline,
    /// `group(0)` layout for the mesh uniform (MVP + normal matrix, vertex stage).
    mesh_bgl: wgpu::BindGroupLayout,
    /// Depth-tested, headlight-shaded `TriangleList` mesh pipeline (no culling).
    mesh_pipeline: wgpu::RenderPipeline,
    /// `group(1)` layout for an image layer (sampled texture + sampler, fragment).
    image_tex_bgl: wgpu::BindGroupLayout,
    /// Depth-tested, alpha-blended textured-quad pipeline (group 0 = scene MVP).
    image_pipeline: wgpu::RenderPipeline,
    /// Nearest-filtering, clamp-to-edge sampler for crisp image pixels.
    image_sampler_nearest: wgpu::Sampler,
    /// Linear-filtering, clamp-to-edge sampler for smooth images.
    image_sampler_linear: wgpu::Sampler,
    /// `group(0)` layout for the blit (sampled texture + sampler, fragment stage).
    blit_bgl: wgpu::BindGroupLayout,
    /// Depth-less full-screen blit pipeline (offscreen color → egui pass).
    blit_pipeline: wgpu::RenderPipeline,
    /// Linear-filtering, clamp-to-edge sampler for the blit.
    sampler: wgpu::Sampler,
}

impl Scene3dPipeline {
    fn new(device: &wgpu::Device, target_format: wgpu::TextureFormat) -> Self {
        let scene_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("siplot scene3d"),
            source: wgpu::ShaderSource::Wgsl(include_str!("shaders/scene3d.wgsl").into()),
        });
        let blit_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("siplot scene3d blit"),
            source: wgpu::ShaderSource::Wgsl(include_str!("shaders/scene3d_blit.wgsl").into()),
        });
        let point_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("siplot scene3d points"),
            source: wgpu::ShaderSource::Wgsl(include_str!("shaders/scene3d_points.wgsl").into()),
        });
        let mesh_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("siplot scene3d mesh"),
            source: wgpu::ShaderSource::Wgsl(include_str!("shaders/scene3d_mesh.wgsl").into()),
        });
        let image_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("siplot scene3d image"),
            source: wgpu::ShaderSource::Wgsl(include_str!("shaders/scene3d_image.wgsl").into()),
        });

        let scene_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("siplot scene3d scene bgl"),
            entries: &[wgpu::BindGroupLayoutEntry {
                binding: 0,
                visibility: wgpu::ShaderStages::VERTEX,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Uniform,
                    has_dynamic_offset: false,
                    min_binding_size: NonZeroU64::new(64),
                },
                count: None,
            }],
        });

        let scene_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("siplot scene3d scene layout"),
            bind_group_layouts: &[Some(&scene_bgl)],
            immediate_size: 0,
        });

        let vertex_buffers = [wgpu::VertexBufferLayout {
            array_stride: std::mem::size_of::<Scene3dVertex>() as u64,
            step_mode: wgpu::VertexStepMode::Vertex,
            attributes: &SCENE3D_VERTEX_ATTRS,
        }];

        // Lines and triangles differ only in primitive topology; everything else
        // (shader, vertex layout, depth state, target) is shared.
        let make_scene_pipeline = |topology: wgpu::PrimitiveTopology, label: &str| {
            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                label: Some(label),
                layout: Some(&scene_layout),
                vertex: wgpu::VertexState {
                    module: &scene_shader,
                    entry_point: Some("vs_main"),
                    buffers: &vertex_buffers,
                    compilation_options: wgpu::PipelineCompilationOptions::default(),
                },
                fragment: Some(wgpu::FragmentState {
                    module: &scene_shader,
                    entry_point: Some("fs_main"),
                    // blend: None (from target_format.into()) → opaque write;
                    // depth testing resolves occlusion.
                    targets: &[Some(target_format.into())],
                    compilation_options: wgpu::PipelineCompilationOptions::default(),
                }),
                primitive: wgpu::PrimitiveState {
                    topology,
                    // No culling: wireframes/axes and double-sided meshes must
                    // show both faces (silx does not cull these).
                    cull_mode: None,
                    ..Default::default()
                },
                depth_stencil: Some(wgpu::DepthStencilState {
                    format: DEPTH_FORMAT,
                    depth_write_enabled: Some(true),
                    depth_compare: Some(wgpu::CompareFunction::Less),
                    stencil: wgpu::StencilState::default(),
                    bias: wgpu::DepthBiasState::default(),
                }),
                multisample: wgpu::MultisampleState::default(),
                multiview_mask: None,
                cache: None,
            })
        };

        let line_pipeline =
            make_scene_pipeline(wgpu::PrimitiveTopology::LineList, "siplot scene3d lines");
        let tri_pipeline = make_scene_pipeline(
            wgpu::PrimitiveTopology::TriangleList,
            "siplot scene3d triangles",
        );

        // Point sprites: their own uniform (MVP + viewport, 80 bytes) and an
        // instanced billboard pipeline with premultiplied-alpha blending so the
        // antialiased marker edges composite over the opaque scene behind them.
        let point_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("siplot scene3d point bgl"),
            entries: &[wgpu::BindGroupLayoutEntry {
                binding: 0,
                visibility: wgpu::ShaderStages::VERTEX,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Uniform,
                    has_dynamic_offset: false,
                    min_binding_size: NonZeroU64::new(
                        std::mem::size_of::<Scene3dPointParams>() as u64
                    ),
                },
                count: None,
            }],
        });
        let point_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("siplot scene3d point layout"),
            bind_group_layouts: &[Some(&point_bgl)],
            immediate_size: 0,
        });
        let point_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("siplot scene3d points"),
            layout: Some(&point_layout),
            vertex: wgpu::VertexState {
                module: &point_shader,
                entry_point: Some("vs_main"),
                // No vertex buffer: corners come from vertex_index. One instance
                // per point carries pos/color/size/marker.
                buffers: &[wgpu::VertexBufferLayout {
                    array_stride: std::mem::size_of::<Scene3dPoint>() as u64,
                    step_mode: wgpu::VertexStepMode::Instance,
                    attributes: &SCENE3D_POINT_ATTRS,
                }],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: &point_shader,
                entry_point: Some("fs_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: target_format,
                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                cull_mode: None,
                ..Default::default()
            },
            depth_stencil: Some(wgpu::DepthStencilState {
                format: DEPTH_FORMAT,
                depth_write_enabled: Some(true),
                depth_compare: Some(wgpu::CompareFunction::Less),
                stencil: wgpu::StencilState::default(),
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: wgpu::MultisampleState::default(),
            multiview_mask: None,
            cache: None,
        });

        // Shaded meshes: their own uniform (MVP + normal matrix, 128 bytes) and a
        // depth-tested, opaque, double-sided triangle pipeline with headlight
        // lighting in the fragment shader.
        let mesh_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("siplot scene3d mesh bgl"),
            entries: &[wgpu::BindGroupLayoutEntry {
                binding: 0,
                visibility: wgpu::ShaderStages::VERTEX,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Uniform,
                    has_dynamic_offset: false,
                    min_binding_size: NonZeroU64::new(
                        std::mem::size_of::<Scene3dMeshParams>() as u64
                    ),
                },
                count: None,
            }],
        });
        let mesh_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("siplot scene3d mesh layout"),
            bind_group_layouts: &[Some(&mesh_bgl)],
            immediate_size: 0,
        });
        let mesh_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("siplot scene3d mesh"),
            layout: Some(&mesh_layout),
            vertex: wgpu::VertexState {
                module: &mesh_shader,
                entry_point: Some("vs_main"),
                buffers: &[wgpu::VertexBufferLayout {
                    array_stride: std::mem::size_of::<Scene3dMeshVertex>() as u64,
                    step_mode: wgpu::VertexStepMode::Vertex,
                    attributes: &SCENE3D_MESH_ATTRS,
                }],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: &mesh_shader,
                entry_point: Some("fs_main"),
                // Opaque (blend None): depth testing resolves occlusion.
                targets: &[Some(target_format.into())],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                // No culling: silx lights one-sided but does not cull, so a face
                // seen from behind shows at ambient (its normal faces away).
                cull_mode: None,
                ..Default::default()
            },
            depth_stencil: Some(wgpu::DepthStencilState {
                format: DEPTH_FORMAT,
                depth_write_enabled: Some(true),
                depth_compare: Some(wgpu::CompareFunction::Less),
                stencil: wgpu::StencilState::default(),
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: wgpu::MultisampleState::default(),
            multiview_mask: None,
            cache: None,
        });

        // Textured image quads: group 0 reuses the scene MVP uniform; group 1 is
        // the per-image texture + sampler. Depth-tested, premultiplied-alpha
        // blended (opaque images write fully; RGBA images composite).
        let image_tex_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("siplot scene3d image tex bgl"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
            ],
        });
        let image_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("siplot scene3d image layout"),
            bind_group_layouts: &[Some(&scene_bgl), Some(&image_tex_bgl)],
            immediate_size: 0,
        });
        let image_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("siplot scene3d image"),
            layout: Some(&image_layout),
            vertex: wgpu::VertexState {
                module: &image_shader,
                entry_point: Some("vs_main"),
                buffers: &[wgpu::VertexBufferLayout {
                    array_stride: std::mem::size_of::<Scene3dImageVertex>() as u64,
                    step_mode: wgpu::VertexStepMode::Vertex,
                    attributes: &SCENE3D_IMAGE_ATTRS,
                }],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: &image_shader,
                entry_point: Some("fs_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: target_format,
                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                cull_mode: None,
                ..Default::default()
            },
            depth_stencil: Some(wgpu::DepthStencilState {
                format: DEPTH_FORMAT,
                depth_write_enabled: Some(true),
                depth_compare: Some(wgpu::CompareFunction::Less),
                stencil: wgpu::StencilState::default(),
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: wgpu::MultisampleState::default(),
            multiview_mask: None,
            cache: None,
        });
        let image_sampler_nearest = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("siplot scene3d image sampler (nearest)"),
            address_mode_u: wgpu::AddressMode::ClampToEdge,
            address_mode_v: wgpu::AddressMode::ClampToEdge,
            address_mode_w: wgpu::AddressMode::ClampToEdge,
            mag_filter: wgpu::FilterMode::Nearest,
            min_filter: wgpu::FilterMode::Nearest,
            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
            ..Default::default()
        });
        let image_sampler_linear = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("siplot scene3d image sampler (linear)"),
            address_mode_u: wgpu::AddressMode::ClampToEdge,
            address_mode_v: wgpu::AddressMode::ClampToEdge,
            address_mode_w: wgpu::AddressMode::ClampToEdge,
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
            ..Default::default()
        });

        let blit_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("siplot scene3d blit bgl"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
            ],
        });

        let blit_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("siplot scene3d blit layout"),
            bind_group_layouts: &[Some(&blit_bgl)],
            immediate_size: 0,
        });

        let blit_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("siplot scene3d blit pipeline"),
            layout: Some(&blit_layout),
            vertex: wgpu::VertexState {
                module: &blit_shader,
                entry_point: Some("vs_main"),
                buffers: &[],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: &blit_shader,
                entry_point: Some("fs_main"),
                // blend: None → replace; the scene (opaque background) occludes
                // whatever egui drew behind the widget rect.
                targets: &[Some(target_format.into())],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            }),
            primitive: wgpu::PrimitiveState::default(),
            // egui's pass has no depth attachment, so the blit must not test depth.
            depth_stencil: None,
            multisample: wgpu::MultisampleState::default(),
            multiview_mask: None,
            cache: None,
        });

        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("siplot scene3d blit sampler"),
            address_mode_u: wgpu::AddressMode::ClampToEdge,
            address_mode_v: wgpu::AddressMode::ClampToEdge,
            address_mode_w: wgpu::AddressMode::ClampToEdge,
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
            ..Default::default()
        });

        Self {
            target_format,
            scene_bgl,
            line_pipeline,
            tri_pipeline,
            point_bgl,
            point_pipeline,
            mesh_bgl,
            mesh_pipeline,
            image_tex_bgl,
            image_pipeline,
            image_sampler_nearest,
            image_sampler_linear,
            blit_bgl,
            blit_pipeline,
            sampler,
        }
    }
}

/// One uploaded textured primitive: its vertex buffer (`vertex_count` verts —
/// 6 for an image quad, `3·triangles` for a textured mesh) and the group(1) bind
/// group over its texture + the chosen sampler. Rebuilt on each
/// [`Scene3dGpu::upload`].
struct Scene3dImageGpu {
    vbuf: wgpu::Buffer,
    bind_group: wgpu::BindGroup,
    vertex_count: u32,
}

/// Per-scene GPU data: vertex buffers, the MVP uniform, and the offscreen
/// color+depth render target (recreated on size change).
struct Scene3dGpu {
    /// MVP uniform, written each frame in [`Scene3dResources::prepare_scene`].
    params_buf: wgpu::Buffer,
    /// `group(0)` bind group over `params_buf` for the scene pipelines.
    scene_bind_group: wgpu::BindGroup,
    /// Line vertices; `None` while empty (skip the draw).
    line_vbuf: Option<wgpu::Buffer>,
    line_count: u32,
    /// Triangle vertices; `None` while empty (skip the draw).
    tri_vbuf: Option<wgpu::Buffer>,
    tri_count: u32,
    /// Point-sprite uniform (MVP + viewport), written each frame.
    point_params_buf: wgpu::Buffer,
    /// `group(0)` bind group over `point_params_buf` for the point pipeline.
    point_bind_group: wgpu::BindGroup,
    /// Per-instance scatter points; `None` while empty (skip the draw).
    point_vbuf: Option<wgpu::Buffer>,
    point_count: u32,
    /// Mesh uniform (MVP + normal matrix), written each frame.
    mesh_params_buf: wgpu::Buffer,
    /// `group(0)` bind group over `mesh_params_buf` for the mesh pipeline.
    mesh_bind_group: wgpu::BindGroup,
    /// Lit-mesh vertices; `None` while empty (skip the draw).
    mesh_vbuf: Option<wgpu::Buffer>,
    mesh_count: u32,
    /// Uploaded image layers (texture + quad), drawn in order after the meshes.
    images: Vec<Scene3dImageGpu>,
    /// Pixel size of the current offscreen target (`[0, 0]` until first sized).
    size: [u32; 2],
    /// Offscreen color view (target format); the blit samples this.
    color_view: Option<wgpu::TextureView>,
    /// Offscreen depth view (`Depth32Float`), for depth testing.
    depth_view: Option<wgpu::TextureView>,
    /// `group(0)` bind group over the color view + sampler for the blit pipeline.
    blit_bind_group: Option<wgpu::BindGroup>,
}

impl Scene3dGpu {
    fn new(device: &wgpu::Device, pipeline: &Scene3dPipeline) -> Self {
        let params_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("siplot scene3d params"),
            size: std::mem::size_of::<Scene3dParams>() as u64,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let scene_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("siplot scene3d scene bind group"),
            layout: &pipeline.scene_bgl,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: params_buf.as_entire_binding(),
            }],
        });
        let point_params_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("siplot scene3d point params"),
            size: std::mem::size_of::<Scene3dPointParams>() as u64,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let point_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("siplot scene3d point bind group"),
            layout: &pipeline.point_bgl,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: point_params_buf.as_entire_binding(),
            }],
        });
        let mesh_params_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("siplot scene3d mesh params"),
            size: std::mem::size_of::<Scene3dMeshParams>() as u64,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let mesh_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("siplot scene3d mesh bind group"),
            layout: &pipeline.mesh_bgl,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: mesh_params_buf.as_entire_binding(),
            }],
        });
        Self {
            params_buf,
            scene_bind_group,
            line_vbuf: None,
            line_count: 0,
            tri_vbuf: None,
            tri_count: 0,
            point_params_buf,
            point_bind_group,
            point_vbuf: None,
            point_count: 0,
            mesh_params_buf,
            mesh_bind_group,
            mesh_vbuf: None,
            mesh_count: 0,
            images: Vec::new(),
            size: [0, 0],
            color_view: None,
            depth_view: None,
            blit_bind_group: None,
        }
    }

    /// Replace the line + triangle + point + mesh buffers and the image layers
    /// from `geometry`.
    fn upload(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        pipeline: &Scene3dPipeline,
        geometry: &Scene3dGeometry,
    ) {
        self.line_vbuf = make_vertex_buffer(device, queue, &geometry.lines, "siplot scene3d lines");
        self.line_count = geometry.lines.len() as u32;
        self.tri_vbuf =
            make_vertex_buffer(device, queue, &geometry.triangles, "siplot scene3d tris");
        self.tri_count = geometry.triangles.len() as u32;
        self.point_vbuf =
            make_vertex_buffer(device, queue, &geometry.points, "siplot scene3d points");
        self.point_count = geometry.points.len() as u32;
        self.mesh_vbuf =
            make_vertex_buffer(device, queue, &geometry.meshes, "siplot scene3d meshes");
        self.mesh_count = geometry.meshes.len() as u32;
        // Image quads and textured meshes both upload to a `Scene3dImageGpu`
        // (texture + vertex buffer) and draw through the one textured pipeline;
        // collect them into a single list (quads first, then meshes).
        self.images = geometry
            .images
            .iter()
            .filter_map(|layer| build_image_gpu(device, queue, pipeline, layer))
            .chain(
                geometry
                    .textured_meshes
                    .iter()
                    .filter_map(|mesh| build_textured_mesh_gpu(device, queue, pipeline, mesh)),
            )
            .collect();
    }

    /// Ensure the offscreen color+depth target matches `size` (in physical
    /// pixels), recreating the textures and blit bind group on a size change.
    fn ensure_offscreen(
        &mut self,
        device: &wgpu::Device,
        pipeline: &Scene3dPipeline,
        size: [u32; 2],
    ) {
        let size = [size[0].max(1), size[1].max(1)];
        if self.size == size && self.color_view.is_some() {
            return;
        }
        let extent = wgpu::Extent3d {
            width: size[0],
            height: size[1],
            depth_or_array_layers: 1,
        };
        let color = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("siplot scene3d color"),
            size: extent,
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: pipeline.target_format,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
            view_formats: &[],
        });
        let depth = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("siplot scene3d depth"),
            size: extent,
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: DEPTH_FORMAT,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
            view_formats: &[],
        });
        let color_view = color.create_view(&wgpu::TextureViewDescriptor::default());
        let depth_view = depth.create_view(&wgpu::TextureViewDescriptor::default());
        let blit_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("siplot scene3d blit bind group"),
            layout: &pipeline.blit_bgl,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(&color_view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(&pipeline.sampler),
                },
            ],
        });
        self.size = size;
        self.color_view = Some(color_view);
        self.depth_view = Some(depth_view);
        self.blit_bind_group = Some(blit_bind_group);
    }

    /// Encode the offscreen depth-tested pass (clear → triangles → lines) into
    /// `encoder`, targeting `color_view` + `depth_view`. The on-screen path
    /// (`prepare`) passes the persistent blit target; [`Scene3dResources::snapshot_scene`]
    /// passes a transient copyable target — the draw sequence is identical, so
    /// the snapshot is pixel-for-pixel the rendered scene.
    fn encode_offscreen(
        &self,
        encoder: &mut wgpu::CommandEncoder,
        pipeline: &Scene3dPipeline,
        color_view: &wgpu::TextureView,
        depth_view: &wgpu::TextureView,
        background: [f32; 4],
    ) {
        let mut rp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("siplot scene3d offscreen pass"),
            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                view: color_view,
                depth_slice: None,
                resolve_target: None,
                ops: wgpu::Operations {
                    load: wgpu::LoadOp::Clear(wgpu::Color {
                        r: background[0] as f64,
                        g: background[1] as f64,
                        b: background[2] as f64,
                        a: background[3] as f64,
                    }),
                    store: wgpu::StoreOp::Store,
                },
            })],
            depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
                view: depth_view,
                depth_ops: Some(wgpu::Operations {
                    load: wgpu::LoadOp::Clear(1.0),
                    store: wgpu::StoreOp::Store,
                }),
                stencil_ops: None,
            }),
            timestamp_writes: None,
            occlusion_query_set: None,
            multiview_mask: None,
        });
        rp.set_bind_group(0, &self.scene_bind_group, &[]);
        if let (Some(buf), true) = (&self.tri_vbuf, self.tri_count > 0) {
            rp.set_pipeline(&pipeline.tri_pipeline);
            rp.set_vertex_buffer(0, buf.slice(..));
            rp.draw(0..self.tri_count, 0..1);
        }
        if let (Some(buf), true) = (&self.line_vbuf, self.line_count > 0) {
            rp.set_pipeline(&pipeline.line_pipeline);
            rp.set_vertex_buffer(0, buf.slice(..));
            rp.draw(0..self.line_count, 0..1);
        }
        // Shaded meshes (own bind group: MVP + normal matrix). Opaque; depth test
        // resolves occlusion against the flat triangles and lines above.
        if let (Some(buf), true) = (&self.mesh_vbuf, self.mesh_count > 0) {
            rp.set_pipeline(&pipeline.mesh_pipeline);
            rp.set_bind_group(0, &self.mesh_bind_group, &[]);
            rp.set_vertex_buffer(0, buf.slice(..));
            rp.draw(0..self.mesh_count, 0..1);
        }
        // Textured primitives — image quads and textured meshes (cut planes) —
        // share one pipeline (group 0 = scene MVP, group 1 = per-primitive
        // texture). Premultiplied-alpha blended and depth-tested; drawn after the
        // opaque geometry, before the point overlays.
        if !self.images.is_empty() {
            rp.set_pipeline(&pipeline.image_pipeline);
            rp.set_bind_group(0, &self.scene_bind_group, &[]);
            for image in &self.images {
                rp.set_bind_group(1, &image.bind_group, &[]);
                rp.set_vertex_buffer(0, image.vbuf.slice(..));
                rp.draw(0..image.vertex_count, 0..1);
            }
        }
        // Point sprites last: alpha-blended billboards over the opaque geometry.
        // Six vertices (two triangles) per instance, one instance per point.
        if let (Some(buf), true) = (&self.point_vbuf, self.point_count > 0) {
            rp.set_pipeline(&pipeline.point_pipeline);
            rp.set_bind_group(0, &self.point_bind_group, &[]);
            rp.set_vertex_buffer(0, buf.slice(..));
            rp.draw(0..6, 0..self.point_count);
        }
    }
}

/// The geometric (flat) face normal of triangle `a, b, c`: the normalized cross
/// product `(b−a) × (c−a)`. A degenerate triangle yields a zero vector (the
/// mesh shader's `normalize` then leaves the face at ambient only).
///
/// `pub(crate)` so the item layer ([`crate::render::scene3d_items`]) can compute
/// the same fallback normal when a mesh provides none — one owner of the rule.
pub(crate) fn flat_normal(a: [f32; 3], b: [f32; 3], c: [f32; 3]) -> [f32; 3] {
    let va = Vec3::new(a[0], a[1], a[2]);
    let vb = Vec3::new(b[0], b[1], b[2]);
    let vc = Vec3::new(c[0], c[1], c[2]);
    (vb - va).cross(vc - va).normalized().to_array()
}

/// Create a `VERTEX | COPY_DST` buffer holding `verts`, or `None` when empty.
fn make_vertex_buffer<T: bytemuck::Pod>(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    verts: &[T],
    label: &str,
) -> Option<wgpu::Buffer> {
    if verts.is_empty() {
        return None;
    }
    let bytes = bytemuck::cast_slice(verts);
    let buffer = device.create_buffer(&wgpu::BufferDescriptor {
        label: Some(label),
        size: bytes.len() as u64,
        usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
        mapped_at_creation: false,
    });
    queue.write_buffer(&buffer, 0, bytes);
    Some(buffer)
}

/// Upload a `width × height` premultiplied-linear RGBA8 raster to an
/// `Rgba8Unorm` texture and build the group(1) bind group (texture + the
/// nearest/linear sampler). The single owner of the textured-primitive texture
/// path, shared by [`build_image_gpu`] and [`build_textured_mesh_gpu`]. Returns
/// `None` for zero dimensions or a pixel buffer of the wrong length.
fn build_image_texture_bind_group(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    pipeline: &Scene3dPipeline,
    pixels: &[u8],
    width: u32,
    height: u32,
    interpolation: ImageInterpolation,
) -> Option<wgpu::BindGroup> {
    if width == 0 || height == 0 || pixels.len() != (width as usize * height as usize * 4) {
        return None;
    }
    let extent = wgpu::Extent3d {
        width,
        height,
        depth_or_array_layers: 1,
    };
    let texture = device.create_texture(&wgpu::TextureDescriptor {
        label: Some("siplot scene3d image texture"),
        size: extent,
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        // Premultiplied-linear RGBA stored verbatim (no sRGB decode), so the
        // sampled colour matches the geometry path's linear convention.
        format: wgpu::TextureFormat::Rgba8Unorm,
        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
        view_formats: &[],
    });
    queue.write_texture(
        wgpu::TexelCopyTextureInfo {
            texture: &texture,
            mip_level: 0,
            origin: wgpu::Origin3d::ZERO,
            aspect: wgpu::TextureAspect::All,
        },
        pixels,
        wgpu::TexelCopyBufferLayout {
            offset: 0,
            bytes_per_row: Some(width * 4),
            rows_per_image: Some(height),
        },
        extent,
    );
    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
    let sampler = match interpolation {
        ImageInterpolation::Nearest => &pipeline.image_sampler_nearest,
        ImageInterpolation::Linear => &pipeline.image_sampler_linear,
    };
    Some(device.create_bind_group(&wgpu::BindGroupDescriptor {
        label: Some("siplot scene3d image bind group"),
        layout: &pipeline.image_tex_bgl,
        entries: &[
            wgpu::BindGroupEntry {
                binding: 0,
                resource: wgpu::BindingResource::TextureView(&view),
            },
            wgpu::BindGroupEntry {
                binding: 1,
                resource: wgpu::BindingResource::Sampler(sampler),
            },
        ],
    }))
}

/// Build the per-image GPU state for one [`Scene3dImageLayer`]: its texture bind
/// group plus the six-vertex quad (two triangles) at the layer's world rect with
/// corner UVs. Returns `None` for a degenerate layer (zero dimensions or a pixel
/// buffer of the wrong length).
fn build_image_gpu(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    pipeline: &Scene3dPipeline,
    layer: &Scene3dImageLayer,
) -> Option<Scene3dImageGpu> {
    let (w, h) = (layer.width, layer.height);
    let bind_group = build_image_texture_bind_group(
        device,
        queue,
        pipeline,
        &layer.pixels,
        w,
        h,
        layer.interpolation,
    )?;

    // Quad corners in the z = origin.z plane: (0,0) → (w·sx, h·sy). UV (0,0) at
    // the origin corner, (1,1) at the far corner (row 0 first → v increases with
    // y, no flip).
    let [ox, oy, oz] = layer.origin;
    let (sx, sy) = (layer.scale[0], layer.scale[1]);
    let (x1, y1) = (ox + w as f32 * sx, oy + h as f32 * sy);
    let v = |x: f32, y: f32, u: f32, vv: f32| Scene3dImageVertex {
        pos: [x, y, oz],
        uv: [u, vv],
    };
    let verts = [
        v(ox, oy, 0.0, 0.0),
        v(x1, oy, 1.0, 0.0),
        v(x1, y1, 1.0, 1.0),
        v(ox, oy, 0.0, 0.0),
        v(x1, y1, 1.0, 1.0),
        v(ox, y1, 0.0, 1.0),
    ];
    let vbuf = make_vertex_buffer(device, queue, &verts, "siplot scene3d image quad")?;
    Some(Scene3dImageGpu {
        vbuf,
        bind_group,
        vertex_count: 6,
    })
}

/// Build the per-mesh GPU state for one [`Scene3dTexturedMesh`]: its texture bind
/// group plus the world-space triangle-list vertex buffer (UVs paired in).
/// Returns `None` for a degenerate mesh (empty, vertex/uv length mismatch, a
/// vertex count not a multiple of three, or a bad texture).
fn build_textured_mesh_gpu(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    pipeline: &Scene3dPipeline,
    mesh: &Scene3dTexturedMesh,
) -> Option<Scene3dImageGpu> {
    if mesh.vertices.is_empty()
        || mesh.vertices.len() != mesh.uvs.len()
        || !mesh.vertices.len().is_multiple_of(3)
    {
        return None;
    }
    let bind_group = build_image_texture_bind_group(
        device,
        queue,
        pipeline,
        &mesh.pixels,
        mesh.width,
        mesh.height,
        mesh.interpolation,
    )?;
    let verts: Vec<Scene3dImageVertex> = mesh
        .vertices
        .iter()
        .zip(&mesh.uvs)
        .map(|(&pos, &uv)| Scene3dImageVertex { pos, uv })
        .collect();
    let vbuf = make_vertex_buffer(device, queue, &verts, "siplot scene3d textured mesh")?;
    Some(Scene3dImageGpu {
        vbuf,
        bind_group,
        vertex_count: verts.len() as u32,
    })
}

/// Persistent 3D GPU resources, stored in `egui_wgpu`'s `callback_resources`.
/// Per-scene state is keyed by [`Scene3dId`].
pub struct Scene3dResources {
    pipeline: Scene3dPipeline,
    scenes: HashMap<Scene3dId, Scene3dGpu>,
}

impl Scene3dResources {
    fn new(device: &wgpu::Device, target_format: wgpu::TextureFormat) -> Self {
        Self {
            pipeline: Scene3dPipeline::new(device, target_format),
            scenes: HashMap::new(),
        }
    }

    /// Size the offscreen target, write the MVP uniform, and encode the
    /// depth-tested offscreen pass for `frame.id` (creating per-scene state if
    /// needed).
    fn prepare_scene(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        encoder: &mut wgpu::CommandEncoder,
        frame: &Scene3dFrame,
    ) {
        let Self { pipeline, scenes } = self;
        let scene = scenes
            .entry(frame.id)
            .or_insert_with(|| Scene3dGpu::new(device, pipeline));
        scene.ensure_offscreen(device, pipeline, frame.size_px);
        let params = Scene3dParams { mvp: frame.mvp };
        queue.write_buffer(&scene.params_buf, 0, bytemuck::bytes_of(&params));
        let point_params = Scene3dPointParams {
            mvp: frame.mvp,
            viewport: [frame.size_px[0] as f32, frame.size_px[1] as f32],
            _pad: [0.0, 0.0],
        };
        queue.write_buffer(
            &scene.point_params_buf,
            0,
            bytemuck::bytes_of(&point_params),
        );
        let mesh_params = Scene3dMeshParams {
            mvp: frame.mvp,
            normal_mat: frame.view,
        };
        queue.write_buffer(&scene.mesh_params_buf, 0, bytemuck::bytes_of(&mesh_params));
        if let (Some(color_view), Some(depth_view)) =
            (scene.color_view.as_ref(), scene.depth_view.as_ref())
        {
            scene.encode_offscreen(encoder, pipeline, color_view, depth_view, frame.background);
        }
    }

    /// Render scene `frame.id` into a transient copyable target at `frame.size_px`
    /// and read it back as tightly packed RGBA8 (`width * height * 4`). Returns
    /// `None` if the scene has no uploaded geometry yet or the GPU readback fails.
    ///
    /// The per-scene uniforms are (re)written for `frame`'s camera and size, then
    /// the same [`Scene3dGpu::encode_offscreen`] draw runs into a fresh
    /// `RENDER_ATTACHMENT | COPY_SRC` color target (the persistent blit target is
    /// `TEXTURE_BINDING`-only, so it cannot be copied). Synchronous: it submits and
    /// blocks on the readback, independent of the egui frame loop.
    fn snapshot_scene(
        &self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        frame: &Scene3dFrame,
    ) -> Option<Vec<u8>> {
        use crate::render::save::{padded_bytes_per_row, rows_to_rgba8};

        let Self { pipeline, scenes } = self;
        let scene = scenes.get(&frame.id)?;
        let (w, h) = (frame.size_px[0].max(1), frame.size_px[1].max(1));

        // Stamp this snapshot's uniforms (mirrors `prepare_scene`). The next
        // on-screen frame rewrites these, so clobbering them here is harmless.
        let params = Scene3dParams { mvp: frame.mvp };
        queue.write_buffer(&scene.params_buf, 0, bytemuck::bytes_of(&params));
        let point_params = Scene3dPointParams {
            mvp: frame.mvp,
            viewport: [w as f32, h as f32],
            _pad: [0.0, 0.0],
        };
        queue.write_buffer(
            &scene.point_params_buf,
            0,
            bytemuck::bytes_of(&point_params),
        );
        let mesh_params = Scene3dMeshParams {
            mvp: frame.mvp,
            normal_mat: frame.view,
        };
        queue.write_buffer(&scene.mesh_params_buf, 0, bytemuck::bytes_of(&mesh_params));

        let extent = wgpu::Extent3d {
            width: w,
            height: h,
            depth_or_array_layers: 1,
        };
        let color = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("siplot scene3d snapshot color"),
            size: extent,
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: pipeline.target_format,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
            view_formats: &[],
        });
        let depth = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("siplot scene3d snapshot depth"),
            size: extent,
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: DEPTH_FORMAT,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
            view_formats: &[],
        });
        let color_view = color.create_view(&wgpu::TextureViewDescriptor::default());
        let depth_view = depth.create_view(&wgpu::TextureViewDescriptor::default());

        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("siplot scene3d snapshot"),
        });
        scene.encode_offscreen(
            &mut encoder,
            pipeline,
            &color_view,
            &depth_view,
            frame.background,
        );

        // Copy the target into a readback buffer with a padded row stride.
        let bpr = padded_bytes_per_row(w);
        let buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("siplot scene3d snapshot readback"),
            size: (bpr as u64) * (h as u64),
            usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
            mapped_at_creation: false,
        });
        encoder.copy_texture_to_buffer(
            wgpu::TexelCopyTextureInfo {
                texture: &color,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::TexelCopyBufferInfo {
                buffer: &buffer,
                layout: wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(bpr),
                    rows_per_image: Some(h),
                },
            },
            extent,
        );
        queue.submit([encoder.finish()]);

        let (tx, rx) = std::sync::mpsc::channel();
        buffer.slice(..).map_async(wgpu::MapMode::Read, move |r| {
            let _ = tx.send(r);
        });
        device.poll(wgpu::PollType::wait_indefinitely()).ok()?;
        rx.recv().ok()?.ok()?;

        let rgba = {
            let mapped = buffer.slice(..).get_mapped_range();
            rows_to_rgba8(&mapped, w, h, bpr, pipeline.target_format)
        };
        buffer.unmap();
        Some(rgba)
    }
}

/// Install the 3D scene GPU resources into `render_state` if not already present.
/// Idempotent — safe to call once per app startup (independent of the 2D
/// [`crate::render::backend_wgpu::install`]).
pub fn install_scene3d(render_state: &RenderState) {
    let mut renderer = render_state.renderer.write();
    if renderer
        .callback_resources
        .get::<Scene3dResources>()
        .is_some()
    {
        return;
    }
    let resources = Scene3dResources::new(&render_state.device, render_state.target_format);
    renderer.callback_resources.insert(resources);
}

/// Upload `geometry` as scene `id`'s current geometry (replacing any existing).
/// Requires [`install_scene3d`] to have run first.
pub fn set_scene3d(render_state: &RenderState, id: Scene3dId, geometry: &Scene3dGeometry) {
    let mut renderer = render_state.renderer.write();
    let res: &mut Scene3dResources = renderer
        .callback_resources
        .get_mut()
        .expect("Scene3dResources not installed — call siplot::install_scene3d() first");
    let Scene3dResources { pipeline, scenes } = res;
    let scene = scenes
        .entry(id)
        .or_insert_with(|| Scene3dGpu::new(&render_state.device, pipeline));
    scene.upload(
        &render_state.device,
        &render_state.queue,
        pipeline,
        geometry,
    );
}

/// Register the paint callback that renders scene `id` into `rect` from
/// `camera`'s viewpoint, on `background`. The camera's aspect is taken from
/// `rect`'s pixel size for this frame (the passed `camera` is not mutated).
/// Requires [`install_scene3d`] + [`set_scene3d`].
pub fn paint_scene3d(
    ui: &mut egui::Ui,
    rect: egui::Rect,
    id: Scene3dId,
    camera: &Camera,
    background: Color32,
) {
    let ppp = ui.ctx().pixels_per_point();
    let w = (rect.width() * ppp).round().max(1.0) as u32;
    let h = (rect.height() * ppp).round().max(1.0) as u32;
    let mut cam = *camera;
    cam.set_size((w as f32, h as f32));
    let mvp = cam.matrix().to_gpu_clip_cols();
    // The view matrix (camera-space transform) drives mesh-normal lighting; it
    // carries no projection, so plain column-major, no depth correction.
    let view = cam.extrinsic.matrix().to_gpu_cols();
    let background = egui::Rgba::from(background).to_array();
    ui.painter().add(egui_wgpu::Callback::new_paint_callback(
        rect,
        Scene3dCallback {
            frame: Scene3dFrame {
                id,
                mvp,
                view,
                size_px: [w, h],
                background,
            },
        },
    ));
}

/// Render scene `id` at `size_px` physical pixels from `camera`'s viewpoint on
/// `background`, reading the result back as tightly packed RGBA8
/// (`width * height * 4`, top row first). Returns `None` if the scene has no
/// uploaded geometry or the GPU readback fails.
///
/// The passed `camera` is not mutated; its aspect is taken from `size_px` for
/// this render, exactly as [`paint_scene3d`] does — so the snapshot matches the
/// on-screen scene at that size. Unlike [`paint_scene3d`], this renders
/// synchronously off the egui frame loop into its own copyable target, suiting a
/// "save scene to image" action (pair with [`crate::render::save::encode_png`]).
///
/// Requires [`install_scene3d`] + [`set_scene3d`].
pub fn snapshot_scene3d(
    render_state: &RenderState,
    id: Scene3dId,
    camera: &Camera,
    background: Color32,
    size_px: (u32, u32),
) -> Option<Vec<u8>> {
    let (w, h) = (size_px.0.max(1), size_px.1.max(1));
    let mut cam = *camera;
    cam.set_size((w as f32, h as f32));
    let mvp = cam.matrix().to_gpu_clip_cols();
    let view = cam.extrinsic.matrix().to_gpu_cols();
    let background = egui::Rgba::from(background).to_array();
    let frame = Scene3dFrame {
        id,
        mvp,
        view,
        size_px: [w, h],
        background,
    };
    let renderer = render_state.renderer.read();
    let res: &Scene3dResources = renderer.callback_resources.get()?;
    res.snapshot_scene(&render_state.device, &render_state.queue, &frame)
}

/// The per-frame render request for one scene: which scene, the camera MVP, the
/// target pixel size, and the clear color. Grouping these keeps the prepare API
/// to a single owner rather than a long positional argument list.
#[derive(Clone, Copy)]
struct Scene3dFrame {
    id: Scene3dId,
    /// Column-major, clip-corrected MVP for this frame.
    mvp: [[f32; 4]; 4],
    /// Column-major view matrix (no depth correction); the camera-space normal
    /// transform for mesh lighting.
    view: [[f32; 4]; 4],
    /// Offscreen target size in physical pixels.
    size_px: [u32; 2],
    /// Clear color, linear premultiplied.
    background: [f32; 4],
}

/// Lightweight per-frame paint callback (the heavy GPU state lives in
/// [`Scene3dResources`]). Renders offscreen in `prepare`, blits in `paint`.
struct Scene3dCallback {
    frame: Scene3dFrame,
}

impl egui_wgpu::CallbackTrait for Scene3dCallback {
    fn prepare(
        &self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        _screen_descriptor: &egui_wgpu::ScreenDescriptor,
        egui_encoder: &mut wgpu::CommandEncoder,
        resources: &mut egui_wgpu::CallbackResources,
    ) -> Vec<wgpu::CommandBuffer> {
        let res: &mut Scene3dResources = resources
            .get_mut()
            .expect("Scene3dResources not installed — call siplot::install_scene3d() at startup");
        res.prepare_scene(device, queue, egui_encoder, &self.frame);
        Vec::new()
    }

    fn paint(
        &self,
        _info: egui::PaintCallbackInfo,
        render_pass: &mut wgpu::RenderPass<'static>,
        resources: &egui_wgpu::CallbackResources,
    ) {
        let res: &Scene3dResources = resources
            .get()
            .expect("Scene3dResources not installed — call siplot::install_scene3d() at startup");
        if let Some(scene) = res.scenes.get(&self.frame.id)
            && let Some(blit_bind_group) = &scene.blit_bind_group
        {
            render_pass.set_pipeline(&res.pipeline.blit_pipeline);
            render_pass.set_bind_group(0, blit_bind_group, &[]);
            render_pass.draw(0..3, 0..1);
        }
    }
}

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

    #[test]
    fn bounding_box_with_axes_has_twelve_lines_and_rgb_axes() {
        let mut g = Scene3dGeometry::new();
        g.add_bounding_box_with_axes(
            (Vec3::ZERO, Vec3::new(2.0, 3.0, 4.0)),
            Color32::from_rgb(200, 200, 200),
        );

        // 3 axes + 9 box edges = 12 lines = 24 line vertices; no triangles.
        assert_eq!(g.lines.len(), 24);
        assert!(g.triangles.is_empty());

        // X axis: origin → (2,0,0), red.
        assert_eq!(g.lines[0].pos, [0.0, 0.0, 0.0]);
        assert_eq!(g.lines[1].pos, [2.0, 0.0, 0.0]);
        assert_eq!(g.lines[0].color, egui::Rgba::from(Color32::RED).to_array());
        // Y axis tip (0,3,0) green; Z axis tip (0,0,4) blue.
        assert_eq!(g.lines[3].pos, [0.0, 3.0, 0.0]);
        assert_eq!(
            g.lines[2].color,
            egui::Rgba::from(Color32::GREEN).to_array()
        );
        assert_eq!(g.lines[5].pos, [0.0, 0.0, 4.0]);
        assert_eq!(g.lines[4].color, egui::Rgba::from(Color32::BLUE).to_array());

        // Box edges carry the box color, and the far top corner (2,3,4) appears.
        let box_rgba = egui::Rgba::from(Color32::from_rgb(200, 200, 200)).to_array();
        assert_eq!(g.lines[6].color, box_rgba);
        assert!(
            g.lines.iter().any(|v| v.pos == [2.0, 3.0, 4.0]),
            "the far corner (max) should be a box-edge endpoint"
        );
    }

    #[test]
    fn extend_from_forwards_every_channel() {
        // A source geometry carrying one primitive in each of the six channels.
        let mut src = Scene3dGeometry::new();
        src.add_line([0.0; 3], [1.0; 3], Color32::WHITE); // 2 line verts
        src.add_triangle([0.0; 3], [1.0; 3], [2.0; 3], Color32::RED); // 3 tri verts
        src.add_point([0.0; 3], Color32::GREEN, 4.0, PointMarker::Square); // 1 point
        src.add_mesh_triangle_flat([0.0; 3], [1.0; 3], [2.0; 3], Color32::BLUE); // 3 mesh verts
        src.add_image_layer(Scene3dImageLayer {
            pixels: vec![0; 4],
            width: 1,
            height: 1,
            origin: [0.0; 3],
            scale: [1.0; 2],
            interpolation: ImageInterpolation::Nearest,
        });
        src.add_textured_mesh(Scene3dTexturedMesh {
            pixels: vec![0; 4],
            width: 1,
            height: 1,
            vertices: vec![[0.0; 3], [1.0; 3], [2.0; 3]],
            uvs: vec![[0.0; 2], [1.0, 0.0], [1.0; 2]],
            interpolation: ImageInterpolation::Nearest,
        });

        let mut dst = Scene3dGeometry::new();
        assert!(dst.is_empty());
        dst.extend_from(&src);

        // Every channel must be forwarded — not a hand-picked subset.
        assert_eq!(dst.lines.len(), 2);
        assert_eq!(dst.triangles.len(), 3);
        assert_eq!(dst.points.len(), 1);
        assert_eq!(dst.meshes.len(), 3);
        assert_eq!(dst.images.len(), 1);
        assert_eq!(dst.textured_meshes.len(), 1);

        // A second extend appends (does not replace).
        dst.extend_from(&src);
        assert_eq!(dst.lines.len(), 4);
        assert_eq!(dst.textured_meshes.len(), 2);
    }
}