viewport-lib-types 0.3.0

Pure-data types for viewport-lib: submission payloads, handles, and frame config, free of any GPU dependency.
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
//! Per-item material and rendering settings.

use crate::colour::ColourSpace;
use crate::data::texture::{TextureRequirement, TextureRole};
use crate::plugin::material::{
    MATERIAL_PLUGIN_MAX_PARAMS, MATERIAL_PLUGIN_MAX_TEXTURES, ParamValue,
};

/// Per-item render settings: visibility, appearance overrides, pick identity, and selection state.
///
/// Always use `Default::default()` as the base, then set individual fields:
///
/// ```rust
/// # use viewport_lib_types::material::ItemSettings;
/// let mut s = ItemSettings::default();
/// s.hidden = true;
/// ```
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ItemSettings {
    /// Hide the object entirely. Default `false`.
    pub hidden: bool,
    /// Skip all lighting calculations and output raw colour. Default `false`.
    pub unlit: bool,
    /// Global opacity multiplier. 1.0 = fully opaque, 0.0 = fully transparent. Default 1.0.
    pub opacity: f32,
    /// Replaces the material's base colour for this item. Default `None`.
    ///
    /// Items that differ only in colour can share one material, and so one
    /// batch, with a colour each; recolouring one item needs no new material.
    pub colour: Option<crate::colour::Colour>,
    /// Render as wireframe regardless of the global wireframe flag. Default `false`. Extended conceptually to non-mesh
    /// objects to render their sub-objects as meshes, e.g., a VolumeItem has its voxels as wireframe boxes.
    pub wireframe: bool,
    /// GPU pick identifier. `PickId::NONE` = not pickable. Default `PickId::NONE`.
    pub pick_id: crate::ids::PickId,
    /// Whether the item is currently selected. Default `false`.
    pub selected: bool,
    /// Whether this item casts shadows in the shadow map pass. Default `true`.
    ///
    /// Set to `false` for items that should be visible but should not contribute
    /// to the shadow map (HUD-style overlays, debug helpers, light source
    /// indicators). Honoured by mesh-family items; non-mesh items currently do
    /// not participate in the shadow pass and treat this flag as a no-op.
    pub cast_shadows: bool,
    /// Whether this item samples the shadow map when shaded. Default `true`.
    ///
    /// Set to `false` to render the item as if no shadow caster occludes it.
    /// Useful for items that should remain fully lit regardless of the scene's
    /// shadow casters (debug visualisations, glowing markers). Honoured by
    /// mesh-family items; non-mesh items currently do not sample shadow maps and
    /// treat this flag as a no-op.
    pub receive_shadows: bool,
    /// Whether this item is exempt from the global clip objects. Default `false`
    /// (the item is clipped like the rest of the scene).
    ///
    /// Set to `true` for annotations and manipulator visuals that must stay fully
    /// visible even where clip planes / box / sphere / cylinder volumes cut the
    /// scene (clip-object outlines, section-plane indicators, debug guides).
    /// Honoured by item types whose shader samples the clip uniform; types that
    /// do not sample it treat this flag as a no-op.
    pub ignore_clip: bool,
    /// Raw per-instance material inputs, read by the shading path and (through a
    /// material plugin) by custom material graphs. Default `[0.0; 8]`.
    ///
    /// This is the per-instance channel that lets instances sharing a material
    /// vary their appearance without breaking batching, matching Unity's
    /// `MaterialPropertyBlock` GPU-instanced properties and Unreal's ISM / HISM
    /// per-instance custom float data. It is independent of `Material` (which is
    /// shared across a batch) and of the per-instance `colour` tint.
    ///
    /// Built-in mesh shading reads slots `0..3` as an emissive addition in nits
    /// (zero is a no-op, so unset custom data changes nothing). Slot `3` is
    /// padding and is not read. Slots `4..8` are a raw channel for material
    /// plugins to interpret, handed to the plugin hook as `surf.attr`. Honoured
    /// on the scene-graph instanced mesh path; item types that do not sample it
    /// treat it as a no-op.
    pub custom_data: [f32; 8],
    /// Layer membership for this item, as a 32-bit mask. Default `!0` (member
    /// of every layer). Two things read it, both AND-tests against another
    /// mask, so the default is inert:
    ///
    /// - Per-camera cull: an item is skipped on a camera whose
    ///   `CameraFrame::cull_mask` shares no bit with this mask
    ///   (`visibility_mask & cull_mask == 0`). This is the quad-view /
    ///   editor-layer filter: give each camera the layers it should draw.
    /// - Light channels: a light only lights an item when the light's
    ///   `LightSource::channel_mask` shares a bit with this mask. Lets a light
    ///   affect a chosen subset of the scene.
    ///
    /// Honoured by mesh-family items (the scene-graph per-object and instanced
    /// paths); item types that do not carry the mask treat it as `!0`.
    ///
    /// Decals read it too, through the surface mask: a decal lands on an item
    /// when the decal's `channel_mask` shares a layer with this mask. The
    /// surface mask holds layers 0 to 7 only, so that test sees the low eight
    /// bits of both masks. Clearing all eight (`visibility_mask &= !0xFF`)
    /// keeps every decal off the item while leaving it on layers 8 and up for
    /// cameras and lights.
    ///
    /// For decals this is honoured by mesh surfaces and by the item types
    /// that stamp the surface mask: every depth-writing type in
    /// `viewport-lib-plugins` does. A type that writes depth and does not
    /// stamp it takes every decal whatever its mask; one that writes no depth
    /// takes none.
    pub visibility_mask: u32,
    /// Draw order of the item within its pass. Default `0`; lower draws first.
    ///
    /// Opaque mesh draws are ordered by priority before anything else in their
    /// pass, so a later priority draws over an earlier one where depth testing
    /// lets it (equal depth, or depth writes off). Blended mesh draws on the
    /// LDR path and in the foreground layer sort by priority first and view
    /// depth second. On the HDR path the scene's blended draws resolve through
    /// order-independent transparency, which ignores priority. Shadow passes
    /// ignore it, and so do non-mesh item types.
    #[cfg_attr(feature = "serde", serde(default))]
    pub draw_priority: i8,
    /// Fixed blend order for a blended mesh item. Default `None`.
    ///
    /// `None` sorts the item back to front by view depth. `Some(n)` replaces
    /// the depth with `n`: within one `draw_priority`, items with a blend order
    /// draw before every depth-sorted item, lowest `n` first, so a higher `n`
    /// draws on top whatever the distance. Honoured where blended draws are
    /// sorted (the LDR path and the foreground layer); the HDR path's
    /// order-independent transparency ignores it. Opaque draws ignore it.
    #[cfg_attr(feature = "serde", serde(default))]
    pub blend_order: Option<u16>,
}

impl Default for ItemSettings {
    fn default() -> Self {
        Self {
            hidden: false,
            unlit: false,
            opacity: 1.0,
            colour: None,
            wireframe: false,
            pick_id: crate::ids::PickId::NONE,
            selected: false,
            cast_shadows: true,
            receive_shadows: true,
            ignore_clip: false,
            custom_data: [0.0; 8],
            visibility_mask: !0,
            draw_priority: 0,
            blend_order: None,
        }
    }
}

/// Lit shading model selected by a [`Material`].
///
/// The variants are mutually exclusive: a material picks one path. The `unlit`
/// per-item bypass on [`ItemSettings`] is checked independently and takes
/// precedence over the shading model.
///
/// New shading models (Toon, SSS, Gooch, ...) are added here as new variants.
/// The glTF PBR extensions (clearcoat, sheen, anisotropy, iridescence) layer on
/// top of `Pbr` as separate fields on `Material` rather than as variants here.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum ShadingModel {
    /// Blinn-Phong lit shading using `ambient` / `diffuse` / `specular` / `shininess`.
    Phong,
    /// Cook-Torrance GGX physically based shading driven by `metallic` and `roughness`.
    Pbr,
    /// Matcap lookup. Replaces the lit path with a captured-lighting texture.
    /// Blendable matcaps tint with `base_colour`; static matcaps override colour entirely.
    Matcap(crate::ids::MatcapId),
    /// Flat (faceted) shading: the per-vertex normal is discarded and a
    /// geometric normal is recomputed per-fragment from screen-space
    /// derivatives of world position. Produces visible polygon edges on
    /// triangulated meshes without changing the lighting block; everything
    /// else (hemisphere ambient, scene lights, shadows, AO, alpha mode)
    /// runs as it does for [`Phong`](Self::Phong).
    ///
    /// Edges appear at the triangulation level, not at logical-face
    /// boundaries. A quad authored as two triangles shows both; a CAD
    /// surface tessellated finely shows the tessellation.
    Flat,
}

impl Default for ShadingModel {
    fn default() -> Self {
        Self::Phong
    }
}

/// Procedural UV visualisation mode for parameterisation inspection.
///
/// When set on a [`Material`], the mesh fragment shader ignores the albedo texture and
/// renders a procedural pattern driven by the mesh UV coordinates instead. Useful for
/// inspecting UV distortion, seams, and parameterisation quality without needing a texture.
///
/// Requires the mesh to have UV coordinates. Has no effect if the mesh lacks UVs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ParamVisMode {
    /// Alternating black/white squares tiled in UV space.
    Checker = 1,
    /// Thin grid lines at UV integer boundaries.
    Grid = 2,
    /// Polar checkerboard centred at UV (0.5, 0.5) : reveals rotational consistency.
    LocalChecker = 3,
    /// Concentric rings centred at UV (0.5, 0.5) : reveals radial distortion.
    LocalRadial = 4,
}

/// UV parameterisation visualisation settings.
///
/// Attach to [`Material::param_vis`] to enable procedural UV pattern rendering.
/// The `scale` controls tile frequency : higher values produce more, smaller tiles.
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ParamVis {
    /// Which procedural pattern to render.
    pub mode: ParamVisMode,
    /// Tile frequency multiplier. Default 8.0 : produces 8 checker squares per UV unit.
    pub scale: f32,
}

impl Default for ParamVis {
    fn default() -> Self {
        Self {
            mode: ParamVisMode::Checker,
            scale: 8.0,
        }
    }
}

/// Procedural pattern for back-face rendering.
///
/// Used with [`PatternConfig`] to select which procedural pattern is drawn on back faces.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum BackfacePattern {
    /// Alternating squares in world XY.
    Checker = 0,
    /// Diagonal lines (45 degrees).
    Hatching = 1,
    /// Two sets of diagonal lines (45 and 135 degrees).
    Crosshatch = 2,
    /// Horizontal stripes.
    Stripes = 3,
}

/// Configuration for procedural back-face patterns.
///
/// Used with [`BackfacePolicy::Pattern`]. The `scale` controls how many pattern cells
/// fit across the object's longest bounding-box dimension, so the pattern always looks
/// proportional regardless of the mesh's physical size.
///
/// Prefer using `..Default::default()` when constructing so that future fields
/// added to this struct do not require changes at every call site:
///
/// ```rust
/// # use viewport_lib_types::material::{PatternConfig, BackfacePattern};
/// # use viewport_lib_types::colour::Colour;
/// let cfg = PatternConfig {
///     pattern: BackfacePattern::Hatching,
///     colour: Colour::rgb(255, 128, 0),
///     ..Default::default()
/// };
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PatternConfig {
    /// Which procedural pattern to draw on back faces.
    pub pattern: BackfacePattern,
    /// Foreground colour for the pattern.
    pub colour: crate::colour::Colour,
    /// Number of pattern cells across the object's longest bounding-box dimension.
    ///
    /// Default 20.0. Increase for finer detail, decrease for coarser.
    pub scale: f32,
}

impl Default for PatternConfig {
    fn default() -> Self {
        Self {
            pattern: BackfacePattern::Checker,
            colour: crate::colour::Colour::linear_rgb(1.0, 0.5, 0.0),
            scale: 20.0,
        }
    }
}

/// Controls how back faces of a mesh are rendered.
///
/// Use [`BackfacePolicy::Cull`] (the default) to hide back faces, [`BackfacePolicy::Identical`]
/// to shade them as front faces lit from the viewer's side, or [`BackfacePolicy::DifferentColour`]
/// to shade back faces in a distinct colour : useful for spotting mesh orientation errors or
/// highlighting the interior of open surfaces.
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum BackfacePolicy {
    /// Back faces are culled (invisible). Default.
    Cull,
    /// Back faces are visible and shaded as front faces, with the normal
    /// flipped toward the viewer, so an open sheet seen from behind is lit from
    /// the side the camera is on.
    Identical,
    /// Back faces are visible and shaded in the given colour.
    ///
    /// Front faces receive normal shading; back faces receive Blinn-Phong shading
    /// with the supplied colour and the same ambient/diffuse/specular coefficients.
    /// The normal is flipped so lighting is computed from the back-face perspective.
    DifferentColour(crate::colour::Colour),
    /// Back faces are visible and tinted darker by the given factor (0.0..1.0).
    ///
    /// The base colour is multiplied by `(1.0 - factor)`, so `Tint(0.3)` means
    /// back faces are 30% darker. The normal is flipped for correct lighting.
    Tint(f32),
    /// Back faces are rendered with a procedural pattern scaled to the object's size.
    ///
    /// The pattern density is relative to the object's world-space bounding box, so
    /// the appearance stays consistent across meshes of different physical sizes.
    /// The normal is flipped for correct lighting.
    Pattern(PatternConfig),
}

impl Default for BackfacePolicy {
    fn default() -> Self {
        BackfacePolicy::Cull
    }
}

/// Alpha blending mode for a material, matching the glTF `alphaMode` field.
///
/// Controls how the fragment alpha value is interpreted by the renderer.
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum AlphaMode {
    /// Alpha is ignored; the surface is always fully opaque. Default.
    Opaque,
    /// Fragments with alpha below the cutoff are discarded; others are fully opaque.
    /// The f32 value is the cutoff threshold in [0, 1].
    Mask(f32),
    /// Standard (straight, non-premultiplied) alpha blending through the OIT pass.
    /// The fragment colour is treated as un-premultiplied: the pass multiplies it
    /// by alpha before compositing.
    Blend,
    /// Alpha blending for content whose RGB is already premultiplied by alpha.
    ///
    /// Like [`Blend`](AlphaMode::Blend) it routes through the OIT pass, but the
    /// pass does not multiply RGB by alpha a second time. Use it for sources that
    /// deliver premultiplied colour: authored images stored premultiplied, hardware
    /// video-decode surfaces, and external GPU textures brought in through
    /// `register_texture_view` (a Wayland client buffer, for instance, is
    /// premultiplied by convention). Blending premultiplied content with the
    /// straight `Blend` equation double-applies alpha at antialiased edges and
    /// leaves a dark halo; this mode composites it correctly.
    BlendPremultiplied,
}

impl Default for AlphaMode {
    fn default() -> Self {
        AlphaMode::Opaque
    }
}

/// Number of texture slots a material can transform independently, in the order
/// [`TextureSlot`] lists: albedo, normal, AO, metallic-roughness, emissive.
pub const MATERIAL_TEXTURE_SLOTS: usize = 5;

/// The texture maps a [`Material`] can carry, used to index the per-slot
/// arrays on it, and saying what each map needs from its texture.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum TextureSlot {
    /// Base colour map.
    Albedo = 0,
    /// Tangent-space normal map.
    Normal = 1,
    /// Ambient occlusion map.
    Ao = 2,
    /// Packed metallic-roughness map.
    MetallicRoughness = 3,
    /// Emissive map.
    Emissive = 4,
}

impl TextureSlot {
    /// Every slot, in discriminant order.
    pub const ALL: [TextureSlot; MATERIAL_TEXTURE_SLOTS] = [
        TextureSlot::Albedo,
        TextureSlot::Normal,
        TextureSlot::Ao,
        TextureSlot::MetallicRoughness,
        TextureSlot::Emissive,
    ];

    /// The slot's position in the per-slot arrays on [`Material`], such as
    /// [`Material::texture_transforms`].
    pub const fn index(self) -> usize {
        self as usize
    }

    /// What the slot needs from its texture, with the [`Material`] field it is
    /// set through. The renderer checks bound textures against this.
    pub const fn requirement(self) -> TextureRequirement {
        match self {
            TextureSlot::Albedo => TextureRequirement::colour("Material::texture_id"),
            TextureSlot::Normal => TextureRequirement::normal_map("Material::normal_map_id"),
            TextureSlot::Ao => TextureRequirement::linear("Material::ao_map_id"),
            TextureSlot::MetallicRoughness => {
                TextureRequirement::linear("Material::metallic_roughness_texture_id")
            }
            TextureSlot::Emissive => TextureRequirement::colour("Material::emissive_texture_id"),
        }
    }

    /// The colour space the slot samples in: sRGB for [`Albedo`](Self::Albedo)
    /// and [`Emissive`](Self::Emissive), linear for the rest.
    pub const fn colour_space(self) -> ColourSpace {
        self.requirement().colour_space()
    }

    /// The role the slot binds its texture as: a normal map for
    /// [`Normal`](Self::Normal), an image for the rest.
    pub const fn role(self) -> TextureRole {
        self.requirement().role()
    }
}

/// A per-texture UV transform: offset, scale, rotation, and UV-set selection.
///
/// This matches the glTF `KHR_texture_transform` extension (and Unity per-map
/// `_ST`). The UV is transformed as
/// `uv' = rotate((mesh_uv * scale + offset) - 0.5, rotation) + 0.5`, i.e. scale
/// and offset apply first (as before rotation existed), then the result rotates
/// about the texture centre `(0.5, 0.5)`. With `rotation = 0` this is exactly the
/// prior `mesh_uv * scale + offset`, so adding rotation does not disturb existing
/// scale/offset materials.
///
/// Set one on a material with [`Material::with_texture_transform`] to make a
/// single map tile or orient differently from the material's shared
/// [`uv_offset`](Material::uv_offset) / [`uv_scale`](Material::uv_scale) /
/// [`uv_rotation`](Material::uv_rotation). A slot left unset uses the shared
/// transform.
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct UvTransform {
    /// UV offset added after scale. Default `[0.0, 0.0]`.
    pub offset: [f32; 2],
    /// UV scale (tiling). Default `[1.0, 1.0]`.
    pub scale: [f32; 2],
    /// Rotation about the texture centre, in radians. Default `0.0`.
    pub rotation: f32,
    /// UV-set index (glTF `texCoord`). `0` samples the mesh's primary UVs, `1`
    /// samples [`MeshData::uvs1`](crate::data::mesh::MeshData::uvs1). A mesh
    /// carrying no second set binds a zero fallback, so a slot selecting `1`
    /// there samples `vec2(0.0)` rather than falling back to UV0. Values above
    /// `1` are not carried: the renderer has two streams.
    pub uv_set: u32,
}

impl Default for UvTransform {
    fn default() -> Self {
        UvTransform {
            offset: [0.0, 0.0],
            scale: [1.0, 1.0],
            rotation: 0.0,
            uv_set: 0,
        }
    }
}

impl UvTransform {
    /// Identity: passes UVs through unchanged.
    pub const IDENTITY: UvTransform = UvTransform {
        offset: [0.0, 0.0],
        scale: [1.0, 1.0],
        rotation: 0.0,
        uv_set: 0,
    };

    /// A pure rotation (radians) about the texture centre.
    pub fn from_rotation(radians: f32) -> Self {
        UvTransform {
            rotation: radians,
            ..UvTransform::IDENTITY
        }
    }
}

/// Texture address (wrap) mode: how a sampler treats UVs outside `[0, 1]`.
/// Matches the glTF sampler wrap modes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum WrapMode {
    /// Tile the texture: the fractional part of the UV is used (glTF `REPEAT`).
    /// This is the default and what makes [`UvTransform`] tiling work.
    #[default]
    Repeat,
    /// Clamp to the nearest edge texel (glTF `CLAMP_TO_EDGE`).
    ClampToEdge,
    /// Mirror on each repeat (glTF `MIRRORED_REPEAT`).
    MirrorRepeat,
}

/// Texture filtering: how a sampler blends texels for minification,
/// magnification, and between mip levels.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum TextureFilter {
    /// Nearest-neighbour: crisp, blocky under magnification (pixel-art, data
    /// textures that must not blend).
    Nearest,
    /// Linear (bi/trilinear): smooth. The default.
    #[default]
    Linear,
}

/// Per-texture sampler state: wrap mode, filtering, anisotropy, and LOD bias.
///
/// Set one per texture slot on a [`Material`] with [`Material::with_sampler`],
/// paralleling [`Material::texture_transforms`]. A slot left `None` uses the
/// renderer's default sampler (repeat + linear, anisotropy 1). This carries the
/// glTF sampler state (wrap S/T, min/mag filter) so an importer can honour it.
///
/// Note the current renderer binds one sampler per lit draw, so it uses the
/// first slot that sets a key (see [`Material::selected_sampler`]); distinct
/// per-slot samplers land with the bindless sampler heap. The field is per-slot
/// now so that later change is not breaking.
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SamplerKey {
    /// Wrap mode for the U (S) axis. Default [`WrapMode::Repeat`].
    pub wrap_u: WrapMode,
    /// Wrap mode for the V (T) axis. Default [`WrapMode::Repeat`].
    pub wrap_v: WrapMode,
    /// Min/mag/mip filtering. Default [`TextureFilter::Linear`].
    pub filter: TextureFilter,
    /// Max anisotropy, clamped to `1..=16` by the renderer. `1` disables
    /// anisotropic filtering. Values above `1` force linear filtering.
    pub anisotropy: u16,
    /// LOD bias added when selecting the mip level. `0.0` is neutral; negative
    /// sharpens, positive blurs. Reserved: the renderer does not apply it yet
    /// (a sampler carries no LOD bias; it needs a shader-side bias), so today
    /// only `wrap_u`/`wrap_v`/`filter`/`anisotropy` take effect.
    pub lod_bias: f32,
}

impl Default for SamplerKey {
    fn default() -> Self {
        SamplerKey {
            wrap_u: WrapMode::Repeat,
            wrap_v: WrapMode::Repeat,
            filter: TextureFilter::Linear,
            anisotropy: 1,
            lod_bias: 0.0,
        }
    }
}

impl SamplerKey {
    /// Clamp-to-edge on both axes, linear filtering. For textures that must not
    /// tile (a decal, a gradient ramp, a UI atlas cell).
    pub fn clamp() -> Self {
        SamplerKey {
            wrap_u: WrapMode::ClampToEdge,
            wrap_v: WrapMode::ClampToEdge,
            ..SamplerKey::default()
        }
    }

    /// Nearest filtering, repeat wrap. For crisp pixel-art or data textures that
    /// must sample a single texel without blending.
    pub fn nearest() -> Self {
        SamplerKey {
            filter: TextureFilter::Nearest,
            ..SamplerKey::default()
        }
    }
}

/// Per-object material properties for Blinn-Phong and PBR shading.
///
/// Uploaded once with `upload_material`; items name it by the returned
/// `MaterialId`, and every item holding the id draws with it.
///
/// This struct is `#[non_exhaustive]`: construct via [`Material::default`],
/// [`Material::from_colour`], or spread syntax (`..Default::default()`). This allows new
/// fields to be added later without breaking downstream code.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Material {
    /// Base diffuse colour. Build it with [`Colour::rgb`](crate::colour::Colour::rgb)
    /// / [`hex`](crate::colour::Colour::hex) for an sRGB value, or
    /// [`Colour::linear_rgb`](crate::colour::Colour::linear_rgb) for one already in
    /// linear space. Default is linear `[0.7, 0.7, 0.7]`.
    pub base_colour: crate::colour::Colour,
    /// Ambient light coefficient of [`ShadingModel::Phong`] and
    /// [`ShadingModel::Flat`], added to the hemisphere fill. PBR shading does
    /// not read it: with image-based lighting off its ambient is the hemisphere
    /// fill alone. Default 0.15.
    pub ambient: f32,
    /// Diffuse light coefficient. Default 0.75.
    pub diffuse: f32,
    /// Blinn-Phong specular highlight coefficient. Default 0.4. Only the Phong
    /// shading model reads it; PBR takes its dielectric reflectance from
    /// [`reflectance`](Self::reflectance).
    pub specular: f32,
    /// Specular shininess exponent. Default 32.0.
    pub shininess: f32,
    /// Metallic factor for PBR Cook-Torrance shading. 0=dielectric, 1=metal. Default 0.0.
    pub metallic: f32,
    /// Roughness factor for PBR microfacet distribution. 0=mirror, 1=fully rough. Default 0.5.
    pub roughness: f32,
    /// Optional albedo texture identifier. None = no texture applied. Default None.
    ///
    /// Colour, so the texture must be uploaded sRGB
    /// ([`TextureData::srgb`](crate::data::texture::TextureData::srgb)).
    pub texture_id: Option<crate::ids::TextureId>,
    /// Optional normal map texture identifier. None = no normal mapping. Default None.
    ///
    /// The normal map must be in tangent-space with XY encoded as RG (0..1 -> -1..+1).
    /// Requires UVs and tangents on the mesh for correct TBN construction.
    ///
    /// Directions, not colour, so the texture must be uploaded linear
    /// ([`TextureData::normal_map`](crate::data::texture::TextureData::normal_map)).
    /// Uploading it sRGB decodes a neutral 128 to 0.216 instead of 0 and biases
    /// every normal the same way.
    pub normal_map_id: Option<crate::ids::TextureId>,
    /// Scales the tangent-space normal's XY before the TBN transform, so a normal
    /// map can be dialled up or down without re-authoring the texture. Default 1.0
    /// (the map is used at authored strength). `0.0` flattens to the geometric
    /// normal; values above 1.0 exaggerate the relief. Matches glTF `normalScale`
    /// and Unity `_BumpScale`. No effect when `normal_map_id` is None.
    #[cfg_attr(feature = "serde", serde(default = "default_normal_strength"))]
    pub normal_strength: f32,
    /// Optional ambient occlusion map texture identifier. None = no AO map. Default None.
    ///
    /// The AO map R channel encodes cavity factor (0=fully occluded, 1=fully lit).
    /// Applied multiplicatively to ambient and diffuse terms.
    ///
    /// A factor, not colour, so the texture must be uploaded linear
    /// ([`TextureData::linear`](crate::data::texture::TextureData::linear)).
    pub ao_map_id: Option<crate::ids::TextureId>,
    /// Optional combined metallic-roughness texture (ORM layout). Default None.
    ///
    /// Matches the glTF `metallicRoughnessTexture`: G channel encodes roughness,
    /// B channel encodes metallic. Each channel is multiplied by the corresponding
    /// scalar factor (`roughness`, `metallic`). Only sampled when the material's
    /// `shading_model` is `ShadingModel::Pbr`.
    ///
    /// Factors, not colour, so the texture must be uploaded linear
    /// ([`TextureData::linear`](crate::data::texture::TextureData::linear)).
    pub metallic_roughness_texture_id: Option<crate::ids::TextureId>,
    /// Self-illumination colour, added to outgoing radiance after lighting.
    /// Default [0.0, 0.0, 0.0].
    ///
    /// Matches glTF `emissiveFactor` (a 0..1 colour). The emitted luminance in
    /// **nits** is `emissive * emissive_strength`, so this sets the hue and
    /// `emissive_strength` sets the brightness. Applied to both the Blinn-Phong
    /// and PBR paths. When `emissive_texture_id` is set, it is multiplied by the
    /// texture sample. The camera's exposure scales it as set by
    /// [`emissive_exposure_weight`](Self::emissive_exposure_weight).
    pub emissive: crate::colour::Colour,
    /// Emissive luminance in **nits**, multiplying [`Self::emissive`]. Default
    /// `1.0`.
    ///
    /// Matches glTF `KHR_materials_emissive_strength`. Under photometric exposure
    /// an emitter must reach a luminance comparable to the lit scene to read as
    /// glowing: a few hundred nits for a soft indoor glow, thousands to stay
    /// bright against daylight. `emissive = [0, 0, 0]` emits nothing regardless.
    /// [`emissive_exposure_weight`](Self::emissive_exposure_weight) sets how
    /// far the camera's exposure scales it.
    pub emissive_strength: f32,
    /// How far the camera's exposure scales this material's emissive, 0..1.
    /// Default `1.0`.
    ///
    /// At 1 the emissive is radiance in nits, exposed with the rest of the
    /// scene. At 0 it is display-relative: added after exposure, so an
    /// emitter of 1 nit adds 1 to the exposed colour whatever the exposure,
    /// for annotation and UI-like surfaces that should read the same in
    /// daylight and indoors. Values between blend the scale linearly,
    /// `mix(1, exposure, weight)`. Applies to the emissive factor and map, the
    /// item's custom-data emissive and a material plugin's emissive.
    #[cfg_attr(feature = "serde", serde(default = "default_emissive_exposure_weight"))]
    pub emissive_exposure_weight: f32,
    /// Optional emissive texture identifier. Default None.
    ///
    /// Matches glTF `emissiveTexture`. Sampled and multiplied by `emissive`
    /// (and hence by `emissive_strength`).
    ///
    /// Colour, so the texture must be uploaded sRGB
    /// ([`TextureData::srgb`](crate::data::texture::TextureData::srgb)).
    pub emissive_texture_id: Option<crate::ids::TextureId>,
    /// Alpha handling mode. Default [`AlphaMode::Opaque`].
    ///
    /// `Mask(cutoff)` discards fragments below the cutoff using the alpha channel.
    /// `Blend` routes the mesh through the OIT transparent pass.
    pub alpha_mode: AlphaMode,
    /// Which lit shading model evaluates this surface. Default [`ShadingModel::Phong`].
    ///
    /// `Phong` uses Blinn-Phong (the faithful default: a cheaper model with a
    /// distinct highlight, energy-matched to PBR's diffuse so the two read at the
    /// same brightness under a given light); `Pbr` uses Cook-Torrance GGX driven
    /// by `metallic` and `roughness`; `Matcap(id)` replaces the lit path with a
    /// matcap texture lookup.
    /// The `unlit` per-item bypass on [`ItemSettings`] is checked independently
    /// and takes precedence over any value here.
    pub shading_model: ShadingModel,
    /// UV parameterisation visualisation. When set, replaces albedo/lighting with a
    /// procedural pattern in UV space : useful for inspecting parameterisation quality.
    ///
    /// Requires UV coordinates on the mesh. Default None (standard shading).
    pub param_vis: Option<ParamVis>,
    /// Back-face rendering policy. Default [`BackfacePolicy::Cull`] (back faces hidden).
    ///
    /// Use [`BackfacePolicy::Identical`] for single-sided geometry like planes and open
    /// surfaces. Use [`BackfacePolicy::DifferentColour`] to highlight back faces in a
    /// distinct colour : helpful for diagnosing mesh orientation errors.
    pub backface_policy: BackfacePolicy,
    /// Per-material UV offset applied to all texture samples (albedo, normal,
    /// AO, metallic-roughness, emissive). Default `[0.0, 0.0]`.
    ///
    /// Sampled as `uv = mesh_uv * uv_scale + uv_offset` in the fragment shader.
    /// Lets one mesh be shared between multiple atlas-region materials without
    /// duplicating vertex buffers : an asset pack with a single tree atlas can
    /// pick the trunk or leaves region per material instance.
    pub uv_offset: [f32; 2],
    /// Per-material UV scale. Default `[1.0, 1.0]`.
    ///
    /// See [`uv_offset`](Self::uv_offset) for the full sampling formula.
    pub uv_scale: [f32; 2],
    /// Shared UV rotation for every texture slot, in radians about the texture
    /// centre `(0.5, 0.5)`. Default `0.0`. Applied after scale and offset:
    /// `uv' = rotate((mesh_uv * uv_scale + uv_offset) - 0.5, uv_rotation) + 0.5`,
    /// so `0.0` leaves the prior `mesh_uv * uv_scale + uv_offset` unchanged.
    ///
    /// This is the common case for orienting a directional texture (a road,
    /// brick coursing, wood grain). For a single map to rotate or tile
    /// differently from the rest, set a [`UvTransform`] on its slot via
    /// [`with_texture_transform`](Self::with_texture_transform).
    pub uv_rotation: f32,
    /// Optional per-texture UV transform override, indexed by [`TextureSlot`]
    /// (`0` albedo .. `4` emissive). A slot left `None` uses the shared
    /// [`uv_offset`](Self::uv_offset) / [`uv_scale`](Self::uv_scale) /
    /// [`uv_rotation`](Self::uv_rotation). Default all `None`.
    ///
    /// This carries glTF `KHR_texture_transform` per texture (offset, scale,
    /// rotation, and `texCoord`) so an importer can honour it faithfully.
    pub texture_transforms: [Option<UvTransform>; MATERIAL_TEXTURE_SLOTS],
    /// Optional per-texture sampler state (wrap/filter/aniso/LOD bias), indexed
    /// by [`TextureSlot`]. A slot left `None` uses the renderer's default
    /// sampler (repeat + linear, anisotropy 1). Default all `None`.
    ///
    /// Carries the glTF sampler wrap/filter so an importer can honour it, and
    /// lets a clamp-wrapped map (a decal, a gradient ramp) coexist with the
    /// repeat-wrapped default. The current renderer binds one sampler per lit
    /// draw, so it uses [`selected_sampler`](Self::selected_sampler) (the first
    /// slot that sets a key); the per-slot form is kept for the bindless sampler
    /// heap.
    pub sampler: [Option<SamplerKey>; MATERIAL_TEXTURE_SLOTS],
    /// Min/max range applied to the AO map's R sample. Identity `[0.0, 1.0]`
    /// passes the sample through unchanged. Skipped when `ao_map_id` is None.
    ///
    /// The remap is `mix(min, max, raw_sample)`. Useful when a packed mask
    /// map authors AO in a reduced range (e.g. `[0.4, 1.0]`) and the renderer
    /// needs to normalise the sample before it drives lighting.
    ///
    /// This field also expresses glTF `occlusionStrength`: since strength is
    /// `mix(1.0, sample, strength)`, set `ao_range = [1.0 - strength, 1.0]`.
    /// There is deliberately no separate `occlusion_strength` field; an importer
    /// maps the glTF value onto this range. (grep: occlusionStrength, occlusion_strength)
    pub ao_range: [f32; 2],
    /// Min/max range applied to the metallic sample (B channel of the
    /// metallic-roughness texture in the glTF/ORM convention). Identity
    /// `[0.0, 1.0]`. Skipped when `metallic_roughness_texture_id` is None.
    ///
    /// Applied to the texture sample before the scalar `metallic` factor:
    /// `final = clamp(mix(min, max, raw.b) * metallic, 0.0, 1.0)`.
    pub metallic_range: [f32; 2],
    /// Min/max range applied to the roughness sample (G channel of the
    /// metallic-roughness texture). Identity `[0.0, 1.0]`. Skipped when
    /// `metallic_roughness_texture_id` is None.
    ///
    /// Applied to the texture sample before the scalar `roughness` factor:
    /// `final = max(mix(min, max, raw.g) * roughness, 0.04)`.
    pub roughness_range: [f32; 2],
    /// Custom shading through a registered material plugin. Default None (the
    /// built-in shading models above).
    ///
    /// `Some(id)` routes this material through the plugin registered with
    /// `register_material_plugin` under that id: the plugin's hooks replace the
    /// built-in lighting terms, always on the PBR loop structure
    /// (`shading_model` is ignored for the lit path). Set it with
    /// [`with_plugin`](Self::with_plugin).
    #[cfg_attr(feature = "serde", serde(default))]
    pub shading_plugin: Option<MaterialPluginId>,
    /// Values for the parameters the plugin declares, by name. A parameter left
    /// unset draws with the plugin's declared default. Ignored without a
    /// plugin. Set them with [`with_param`](Self::with_param).
    #[cfg_attr(feature = "serde", serde(default))]
    pub plugin_params: PluginParams,
    /// The plugin's texture slots (`material_texture_0..N`). A slot left `None`,
    /// or naming a freed texture, samples a 1x1 white texture. Ignored without
    /// a plugin, and past the plugin's `texture_count`.
    #[cfg_attr(feature = "serde", serde(default))]
    pub plugin_textures: [Option<crate::ids::TextureId>; MATERIAL_PLUGIN_MAX_TEXTURES],
    /// Dielectric reflectance at normal incidence, as a perceptual 0..1 value:
    /// PBR shading takes F0 = `0.16 * reflectance^2`. Default 0.5 (F0 = 0.04,
    /// the reflectance of most plastics and glass). 0 removes the dielectric
    /// specular; 1 gives F0 = 0.16, about a gemstone. Metals ignore it: their
    /// F0 is the base colour. Set it from an index of refraction with
    /// [`with_ior`](Self::with_ior).
    #[cfg_attr(feature = "serde", serde(default = "default_reflectance"))]
    pub reflectance: f32,
    /// Scales the dielectric specular at normal and grazing incidence, as glTF
    /// `KHR_materials_specular`'s `specularFactor`. Default 1.0. 0 removes the
    /// dielectric specular lobe entirely, grazing Fresnel included.
    #[cfg_attr(feature = "serde", serde(default = "default_specular_factor"))]
    pub specular_factor: f32,
    /// Tints the dielectric F0, as glTF `KHR_materials_specular`'s
    /// `specularColorFactor`. Default linear white. The tinted F0 is clamped
    /// to 1 before [`specular_factor`](Self::specular_factor) scales it.
    #[cfg_attr(feature = "serde", serde(default = "default_specular_colour"))]
    pub specular_colour: crate::colour::Colour,
    /// Index of refraction, for refraction and transmission only. Default 1.5.
    /// It bends the light [`transmission`](Self::transmission) lets through;
    /// F0 comes from [`reflectance`](Self::reflectance), which
    /// [`with_ior`](Self::with_ior) sets together with this field.
    #[cfg_attr(feature = "serde", serde(default = "default_ior"))]
    pub ior: f32,
    /// Strength of a clear coat layered over the base, 0..1, as glTF
    /// `KHR_materials_clearcoat`'s `clearcoatFactor`. Default 0 (no coat). The
    /// coat is a dielectric (F0 0.04) GGX lobe on the shading normal; the
    /// light it reflects is taken from the base beneath it. PBR shading only.
    #[cfg_attr(feature = "serde", serde(default))]
    pub clearcoat: f32,
    /// Perceptual roughness of the clear coat, 0..1. Default 0. The base's
    /// roughness is raised toward it by [`clearcoat`](Self::clearcoat).
    #[cfg_attr(feature = "serde", serde(default))]
    pub clearcoat_roughness: f32,
    /// Colour of a sheen layer (a Charlie microfibre lobe, for cloth and
    /// velvet), as glTF `KHR_materials_sheen`'s `sheenColorFactor`. Default
    /// black (no sheen). The base is dimmed by the light the sheen reflects.
    #[cfg_attr(feature = "serde", serde(default = "default_sheen_colour"))]
    pub sheen_colour: crate::colour::Colour,
    /// Perceptual roughness of the sheen, 0..1. Default 0.
    #[cfg_attr(feature = "serde", serde(default))]
    pub sheen_roughness: f32,
    /// Anisotropy of the base specular lobe, -1..1. Default 0 (isotropic).
    /// Positive values stretch the highlight along the tangent, negative along
    /// the bitangent. Reads the mesh's tangents, or a frame built from the
    /// normal when the mesh has none.
    #[cfg_attr(feature = "serde", serde(default))]
    pub anisotropy: f32,
    /// Rotation of the anisotropy direction from the tangent toward the
    /// bitangent, in radians. Default 0.
    #[cfg_attr(feature = "serde", serde(default))]
    pub anisotropy_rotation: f32,
    /// Fraction of light that passes through the surface rather than being
    /// diffusely reflected, 0..1, as glTF `KHR_materials_transmission`'s
    /// `transmissionFactor`. Default 0 (opaque). The transmitted light is
    /// tinted by the base colour and refracted by [`ior`](Self::ior). PBR
    /// shading in the opaque or mask alpha mode only; metals do not transmit.
    ///
    /// An opaque-mode transmissive mesh draws after the opaque scene and reads
    /// a copy of it, blurred by roughness. It sees opaque geometry only: a
    /// transmissive surface behind another shows through as the environment.
    #[cfg_attr(feature = "serde", serde(default))]
    pub transmission: f32,
    /// Thickness of the volume under the surface, in world units, as glTF
    /// `KHR_materials_volume`'s `thicknessFactor`. Default 0 (a thin wall that
    /// does not bend what is behind it). Sets how far the refracted ray
    /// travels before it reads the scene behind, and the path length for
    /// [`attenuation_colour`](Self::attenuation_colour).
    #[cfg_attr(feature = "serde", serde(default))]
    pub thickness: f32,
    /// Colour white light becomes after travelling
    /// [`attenuation_distance`](Self::attenuation_distance) through the
    /// volume, as `KHR_materials_volume`'s `attenuationColor`. Default linear
    /// white (no absorption).
    #[cfg_attr(feature = "serde", serde(default = "default_attenuation_colour"))]
    pub attenuation_colour: crate::colour::Colour,
    /// Distance in world units over which light is absorbed to
    /// [`attenuation_colour`](Self::attenuation_colour), as
    /// `KHR_materials_volume`'s `attenuationDistance`. Default `f32::MAX`
    /// (no absorption); `f32::MAX` rather than infinity so the value survives
    /// formats without infinities.
    #[cfg_attr(feature = "serde", serde(default = "default_attenuation_distance"))]
    pub attenuation_distance: f32,
}

/// A material's values for its plugin's declared parameters, keyed by name.
///
/// Holds up to [`MATERIAL_PLUGIN_MAX_PARAMS`] values. Names are matched
/// against the plugin's [`param_layout`](crate::plugin::material::MaterialPlugin::param_layout)
/// when the material is uploaded; an unknown name, a value of the wrong kind,
/// or more values than fit is refused there.
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PluginParams {
    names: [u64; MATERIAL_PLUGIN_MAX_PARAMS],
    values: [ParamValue; MATERIAL_PLUGIN_MAX_PARAMS],
    len: u8,
    overflowed: bool,
}

impl Default for PluginParams {
    fn default() -> Self {
        Self {
            names: [0; MATERIAL_PLUGIN_MAX_PARAMS],
            values: [ParamValue::F32(0.0); MATERIAL_PLUGIN_MAX_PARAMS],
            len: 0,
            overflowed: false,
        }
    }
}

impl PluginParams {
    /// Set `name` to `value`, replacing an earlier value for the same name.
    pub fn set(&mut self, name: &str, value: impl Into<ParamValue>) {
        let key = param_name_hash(name);
        let value = value.into();
        let n = self.len as usize;
        if let Some(i) = self.names[..n].iter().position(|&k| k == key) {
            self.values[i] = value;
        } else if n < MATERIAL_PLUGIN_MAX_PARAMS {
            self.names[n] = key;
            self.values[n] = value;
            self.len += 1;
        } else {
            self.overflowed = true;
        }
    }

    /// The value set for `name`, if any. Unset parameters draw with the
    /// plugin's default, which this does not report.
    pub fn get(&self, name: &str) -> Option<ParamValue> {
        let key = param_name_hash(name);
        self.iter().find(|(k, _)| *k == key).map(|(_, v)| v)
    }

    /// Remove the value for `name`, so it draws with the plugin's default.
    pub fn unset(&mut self, name: &str) {
        let key = param_name_hash(name);
        let n = self.len as usize;
        if let Some(i) = self.names[..n].iter().position(|&k| k == key) {
            self.names.copy_within(i + 1..n, i);
            self.values.copy_within(i + 1..n, i);
            self.len -= 1;
        }
    }

    /// Number of values set.
    pub fn len(&self) -> usize {
        self.len as usize
    }

    /// Whether no value is set.
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// The values set, by name hash ([`param_name_hash`]).
    #[doc(hidden)]
    pub fn iter(&self) -> impl Iterator<Item = (u64, ParamValue)> + '_ {
        let n = self.len as usize;
        self.names[..n]
            .iter()
            .copied()
            .zip(self.values[..n].iter().copied())
    }

    /// Whether a `set` was dropped because every slot was taken.
    #[doc(hidden)]
    pub fn overflowed(&self) -> bool {
        self.overflowed
    }
}

/// The key [`PluginParams`] stores a parameter name under (64-bit FNV-1a).
#[doc(hidden)]
pub fn param_name_hash(name: &str) -> u64 {
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    for b in name.bytes() {
        h ^= b as u64;
        h = h.wrapping_mul(0x0000_0100_0000_01b3);
    }
    h
}

/// Handle to a material plugin registered with `register_material_plugin`.
///
/// A small `Copy` id carried on [`Material::shading_plugin`]. Every material on
/// a plugin shares its WGSL and pipelines; each carries its own
/// [`plugin_params`](Material::plugin_params) and
/// [`plugin_textures`](Material::plugin_textures). The renderer resolves the id
/// against its registry at draw time. An id that does not resolve falls back
/// to built-in shading: one from a different session (e.g. a deserialized
/// scene rendered before the plugin is re-registered), or one whose plugin
/// was unregistered. Unregistering moves the slot's generation on, so the id
/// does not resolve to a plugin registered into the same slot later.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MaterialPluginId {
    pub(crate) plugin: u32,
    #[cfg_attr(feature = "serde", serde(default))]
    pub(crate) generation: u32,
}

impl MaterialPluginId {
    /// Index of the underlying shading-hook registration.
    pub fn plugin_index(&self) -> u32 {
        self.plugin
    }

    /// Generation of the registration slot when this id was issued.
    pub fn generation(&self) -> u32 {
        self.generation
    }

    /// Build a handle from a plugin registration index, at the slot's first
    /// generation. Crate-internal: the shading-hook registry mints these;
    /// outside code obtains them from registration calls and treats them as
    /// opaque.
    #[doc(hidden)]
    pub fn from_index(plugin: u32) -> Self {
        Self::from_parts(plugin, 0)
    }

    /// Build a handle from a registration index and slot generation.
    /// Crate-internal, like [`from_index`](Self::from_index).
    #[doc(hidden)]
    pub fn from_parts(plugin: u32, generation: u32) -> Self {
        Self { plugin, generation }
    }
}

/// serde default for [`Material::normal_strength`]: the neutral 1.0, so a material
/// deserialized from data saved before this field existed reads as full strength
/// rather than the type default of 0.0 (which would flatten normals).
#[cfg(feature = "serde")]
fn default_normal_strength() -> f32 {
    1.0
}

#[cfg(feature = "serde")]
fn default_reflectance() -> f32 {
    0.5
}

#[cfg(feature = "serde")]
fn default_specular_factor() -> f32 {
    1.0
}

#[cfg(feature = "serde")]
fn default_specular_colour() -> crate::colour::Colour {
    crate::colour::Colour::linear_rgb(1.0, 1.0, 1.0)
}

#[cfg(feature = "serde")]
fn default_emissive_exposure_weight() -> f32 {
    1.0
}

#[cfg(feature = "serde")]
fn default_ior() -> f32 {
    1.5
}

#[cfg(feature = "serde")]
fn default_attenuation_colour() -> crate::colour::Colour {
    crate::colour::Colour::linear_rgb(1.0, 1.0, 1.0)
}

#[cfg(feature = "serde")]
fn default_attenuation_distance() -> f32 {
    f32::MAX
}

#[cfg(feature = "serde")]
fn default_sheen_colour() -> crate::colour::Colour {
    crate::colour::Colour::linear_rgb(0.0, 0.0, 0.0)
}

impl Default for Material {
    fn default() -> Self {
        Self {
            base_colour: crate::colour::Colour::linear_rgb(0.7, 0.7, 0.7),
            ambient: 0.15,
            diffuse: 0.75,
            specular: 0.4,
            shininess: 32.0,
            metallic: 0.0,
            roughness: 0.5,
            texture_id: None,
            normal_map_id: None,
            normal_strength: 1.0,
            ao_map_id: None,
            metallic_roughness_texture_id: None,
            emissive: crate::colour::Colour::BLACK,
            emissive_strength: 1.0,
            emissive_exposure_weight: 1.0,
            emissive_texture_id: None,
            alpha_mode: AlphaMode::Opaque,
            shading_model: ShadingModel::Phong,
            param_vis: None,
            backface_policy: BackfacePolicy::Cull,
            uv_offset: [0.0, 0.0],
            uv_scale: [1.0, 1.0],
            uv_rotation: 0.0,
            texture_transforms: [None; MATERIAL_TEXTURE_SLOTS],
            sampler: [None; MATERIAL_TEXTURE_SLOTS],
            ao_range: [0.0, 1.0],
            metallic_range: [0.0, 1.0],
            roughness_range: [0.0, 1.0],
            shading_plugin: None,
            plugin_params: PluginParams::default(),
            plugin_textures: [None; MATERIAL_PLUGIN_MAX_TEXTURES],
            reflectance: 0.5,
            specular_factor: 1.0,
            specular_colour: crate::colour::Colour::linear_rgb(1.0, 1.0, 1.0),
            ior: 1.5,
            clearcoat: 0.0,
            clearcoat_roughness: 0.0,
            sheen_colour: crate::colour::Colour::linear_rgb(0.0, 0.0, 0.0),
            sheen_roughness: 0.0,
            anisotropy: 0.0,
            anisotropy_rotation: 0.0,
            transmission: 0.0,
            thickness: 0.0,
            attenuation_colour: crate::colour::Colour::linear_rgb(1.0, 1.0, 1.0),
            attenuation_distance: f32::MAX,
        }
    }
}

impl Material {
    /// Returns `true` if the backface policy makes back faces visible.
    pub fn is_two_sided(&self) -> bool {
        !matches!(self.backface_policy, BackfacePolicy::Cull)
    }

    /// Set the shared UV rotation (radians about the texture centre) for every
    /// texture slot. See [`uv_rotation`](Self::uv_rotation).
    pub fn with_uv_rotation(mut self, radians: f32) -> Self {
        self.uv_rotation = radians;
        self
    }

    /// Override one texture slot's UV transform, leaving the others on the shared
    /// transform. See [`texture_transforms`](Self::texture_transforms).
    pub fn with_texture_transform(mut self, slot: TextureSlot, transform: UvTransform) -> Self {
        self.texture_transforms[slot as usize] = Some(transform);
        self
    }

    /// Override one texture slot's sampler state, leaving the others on the
    /// renderer default. See [`sampler`](Self::sampler).
    pub fn with_sampler(mut self, slot: TextureSlot, sampler: SamplerKey) -> Self {
        self.sampler[slot as usize] = Some(sampler);
        self
    }

    /// The texture bound to `slot`: [`texture_id`](Self::texture_id) for
    /// albedo, [`normal_map_id`](Self::normal_map_id) for normal, and so on.
    pub fn texture(&self, slot: TextureSlot) -> Option<crate::ids::TextureId> {
        match slot {
            TextureSlot::Albedo => self.texture_id,
            TextureSlot::Normal => self.normal_map_id,
            TextureSlot::Ao => self.ao_map_id,
            TextureSlot::MetallicRoughness => self.metallic_roughness_texture_id,
            TextureSlot::Emissive => self.emissive_texture_id,
        }
    }

    /// Bind `id` to `slot`, or clear the slot with `None`. Sets the same field
    /// [`texture`](Self::texture) reads.
    pub fn set_texture(&mut self, slot: TextureSlot, id: Option<crate::ids::TextureId>) {
        let field = match slot {
            TextureSlot::Albedo => &mut self.texture_id,
            TextureSlot::Normal => &mut self.normal_map_id,
            TextureSlot::Ao => &mut self.ao_map_id,
            TextureSlot::MetallicRoughness => &mut self.metallic_roughness_texture_id,
            TextureSlot::Emissive => &mut self.emissive_texture_id,
        };
        *field = id;
    }

    /// Bind `id` to `slot`. See [`set_texture`](Self::set_texture).
    pub fn with_texture(mut self, slot: TextureSlot, id: crate::ids::TextureId) -> Self {
        self.set_texture(slot, Some(id));
        self
    }

    /// Set how far the camera's exposure scales the emissive: 1 exposes it with
    /// the scene, 0 keeps it display-relative. See
    /// [`emissive_exposure_weight`](Self::emissive_exposure_weight).
    pub fn with_emissive_exposure_weight(mut self, weight: f32) -> Self {
        self.emissive_exposure_weight = weight;
        self
    }

    /// Set the index of refraction and derive [`reflectance`](Self::reflectance)
    /// from it, so F0 = `((ior - 1) / (ior + 1))^2`. An IOR of 1.5 gives the
    /// default reflectance of 0.5.
    pub fn with_ior(mut self, ior: f32) -> Self {
        self.ior = ior;
        self.reflectance = ((ior - 1.0) / (ior + 1.0)).abs() / 0.4;
        self
    }

    /// Layer a clear coat of `amount` (0..1) and perceptual `roughness` over
    /// the base. See [`clearcoat`](Self::clearcoat).
    pub fn with_clearcoat(mut self, amount: f32, roughness: f32) -> Self {
        self.clearcoat = amount;
        self.clearcoat_roughness = roughness;
        self
    }

    /// Layer a sheen of `colour` and perceptual `roughness` over the base. See
    /// [`sheen_colour`](Self::sheen_colour).
    pub fn with_sheen(mut self, colour: crate::colour::Colour, roughness: f32) -> Self {
        self.sheen_colour = colour;
        self.sheen_roughness = roughness;
        self
    }

    /// Stretch the base specular lobe by `strength` (-1..1), turned by
    /// `rotation` radians from the tangent. See [`anisotropy`](Self::anisotropy).
    pub fn with_anisotropy(mut self, strength: f32, rotation: f32) -> Self {
        self.anisotropy = strength;
        self.anisotropy_rotation = rotation;
        self
    }

    /// Let `transmission` (0..1) of the light through a volume `thickness`
    /// world units deep. See [`transmission`](Self::transmission).
    pub fn with_transmission(mut self, transmission: f32, thickness: f32) -> Self {
        self.transmission = transmission;
        self.thickness = thickness;
        self
    }

    /// Absorb light inside the volume so white becomes `colour` after
    /// `distance` world units. See
    /// [`attenuation_colour`](Self::attenuation_colour).
    pub fn with_attenuation(mut self, colour: crate::colour::Colour, distance: f32) -> Self {
        self.attenuation_colour = colour;
        self.attenuation_distance = distance;
        self
    }

    /// Shade through a registered material plugin. See
    /// [`shading_plugin`](Self::shading_plugin).
    pub fn with_plugin(mut self, plugin: MaterialPluginId) -> Self {
        self.shading_plugin = Some(plugin);
        self
    }

    /// Set one of the plugin's declared parameters. See
    /// [`plugin_params`](Self::plugin_params).
    pub fn with_param(mut self, name: &str, value: impl Into<ParamValue>) -> Self {
        self.plugin_params.set(name, value);
        self
    }

    /// Set one of the plugin's declared parameters in place.
    pub fn set_param(&mut self, name: &str, value: impl Into<ParamValue>) {
        self.plugin_params.set(name, value);
    }

    /// The value set for one of the plugin's parameters, if any.
    pub fn param(&self, name: &str) -> Option<ParamValue> {
        self.plugin_params.get(name)
    }

    /// Bind `id` to the plugin's texture slot `slot` (`material_texture_<slot>`).
    ///
    /// # Panics
    ///
    /// When `slot` is [`MATERIAL_PLUGIN_MAX_TEXTURES`] or more.
    pub fn with_plugin_texture(mut self, slot: usize, id: crate::ids::TextureId) -> Self {
        self.plugin_textures[slot] = Some(id);
        self
    }

    /// The sampler this material binds for its textures, or `None` for the
    /// renderer default (repeat + linear). The current renderer binds a single
    /// sampler per lit draw at group-1 binding 2, so this returns the first slot
    /// that sets a [`SamplerKey`] (usually albedo). Per-slot samplers land with
    /// the bindless sampler heap; until then every slot on a material shares this
    /// one sampler.
    pub fn selected_sampler(&self) -> Option<SamplerKey> {
        self.sampler.iter().flatten().next().copied()
    }

    /// The effective transform for a texture slot: its override if set, otherwise
    /// the material's shared `uv_offset` / `uv_scale` / `uv_rotation`.
    pub fn effective_texture_transform(&self, slot: TextureSlot) -> UvTransform {
        self.texture_transforms[slot as usize].unwrap_or(UvTransform {
            offset: self.uv_offset,
            scale: self.uv_scale,
            rotation: self.uv_rotation,
            uv_set: 0,
        })
    }

    /// Returns `true` if back faces need the per-object draw path.
    ///
    /// `Cull` and `Identical` render correctly through the instanced path: `Cull`
    /// uses back-face culling and `Identical` disables culling and flips the
    /// normal on back faces, neither of which needs per-item state the instanced
    /// shader does not carry. The styled policies (`DifferentColour`, `Tint`,
    /// `Pattern`) also read a per-item back-face colour, so they stay on the
    /// per-object path.
    pub fn backface_needs_per_object(&self) -> bool {
        matches!(
            self.backface_policy,
            BackfacePolicy::DifferentColour(_)
                | BackfacePolicy::Tint(_)
                | BackfacePolicy::Pattern(_)
        )
    }

    /// Returns `true` if this material uses alpha blending and should go through
    /// the OIT pass. True for both straight [`AlphaMode::Blend`] and
    /// [`AlphaMode::BlendPremultiplied`]; the two differ only in whether the pass
    /// premultiplies RGB, not in which pass they route to.
    pub fn is_blend(&self) -> bool {
        matches!(
            self.alpha_mode,
            AlphaMode::Blend | AlphaMode::BlendPremultiplied
        )
    }

    /// Returns `true` if this material's colour is already premultiplied by alpha
    /// ([`AlphaMode::BlendPremultiplied`]), so the OIT pass must skip its own
    /// premultiply step.
    pub fn is_premultiplied(&self) -> bool {
        matches!(self.alpha_mode, AlphaMode::BlendPremultiplied)
    }

    /// The emitted luminance in nits: `emissive` scaled by `emissive_strength`.
    /// This is the value the renderer packs into the GPU material and adds to
    /// outgoing radiance (an emissive texture, when present, multiplies it too).
    #[doc(hidden)]
    pub fn emissive_nits(&self) -> [f32; 3] {
        let e = self.emissive.to_linear_rgb();
        [
            e[0] * self.emissive_strength,
            e[1] * self.emissive_strength,
            e[2] * self.emissive_strength,
        ]
    }

    /// Construct from a base colour, all other parameters at their defaults.
    ///
    /// Pass a [`Colour`](crate::colour::Colour) (`Colour::rgb` / `hex` for sRGB,
    /// `Colour::linear_rgb` for linear); a bare `[f32; 3]` is taken as linear.
    pub fn from_colour(colour: impl Into<crate::colour::Colour>) -> Self {
        Self {
            base_colour: colour.into(),
            ..Default::default()
        }
    }

    /// A self-illuminated material glowing in the given `colour` at `nits`
    /// luminance. `base_colour` is set to the same colour so the surface reads
    /// consistently where the emission is dim. All other parameters take their
    /// defaults.
    pub fn emissive(colour: impl Into<crate::colour::Colour>, nits: f32) -> Self {
        let colour = colour.into();
        Self {
            base_colour: colour,
            emissive: colour,
            emissive_strength: nits,
            ..Default::default()
        }
    }

    /// Construct a Cook-Torrance PBR material.
    ///
    /// - `metallic`: 0.0 = dielectric, 1.0 = full metal
    /// - `roughness`: 0.0 = mirror, 1.0 = fully rough
    ///
    /// All other parameters take their defaults. Enable post-processing
    /// (`PostProcessSettings::enabled = true`) for correct HDR tone mapping.
    pub fn pbr(
        base_colour: impl Into<crate::colour::Colour>,
        metallic: f32,
        roughness: f32,
    ) -> Self {
        Self {
            base_colour: base_colour.into(),
            shading_model: ShadingModel::Pbr,
            metallic,
            roughness,
            ..Default::default()
        }
    }

    /// Returns `true` when the material's shading model is Cook-Torrance PBR.
    pub fn is_pbr(&self) -> bool {
        matches!(self.shading_model, ShadingModel::Pbr)
    }

    /// Returns `true` when the material's shading model is flat / faceted.
    pub fn is_flat(&self) -> bool {
        matches!(self.shading_model, ShadingModel::Flat)
    }

    /// Construct a flat (faceted) material with the given base colour. The
    /// per-vertex normal is replaced at the fragment stage by a geometric
    /// normal recovered from screen-space derivatives, so polygon edges
    /// remain visible on otherwise smooth meshes. Everything else takes
    /// material defaults.
    pub fn flat(base_colour: impl Into<crate::colour::Colour>) -> Self {
        Self {
            base_colour: base_colour.into(),
            shading_model: ShadingModel::Flat,
            ..Default::default()
        }
    }

    /// Returns the matcap id when the material uses a matcap shading model.
    pub fn matcap_id(&self) -> Option<crate::ids::MatcapId> {
        match self.shading_model {
            ShadingModel::Matcap(id) => Some(id),
            _ => None,
        }
    }

    /// Alias for [`Material::from_colour`].
    ///
    /// Returns a material with the given base colour and all other fields at defaults.
    /// "solid" is a more familiar name in some graphics contexts; both names are kept
    /// so existing `from_colour` call sites do not need updating.
    pub fn solid(colour: impl Into<crate::colour::Colour>) -> Self {
        Self::from_colour(colour)
    }

    /// Returns a material with only `texture_id` set; all other fields take defaults.
    ///
    /// Useful when the mesh already carries a UV layout and the only requirement is
    /// to apply a texture. Base colour, lighting model, and all other fields stay at
    /// their default values.
    pub fn textured(texture_id: crate::ids::TextureId) -> Self {
        Self {
            texture_id: Some(texture_id),
            ..Default::default()
        }
    }

    /// PBR constructor that also sets a baked ambient-occlusion texture.
    ///
    /// - `base_colour`: RGB albedo in linear 0..1
    /// - `metallic`: 0.0 = dielectric, 1.0 = full metal
    /// - `roughness`: 0.0 = mirror, 1.0 = fully rough
    /// - `ao_map`: baked AO texture id, or `None` to disable AO
    ///
    /// Sets `shading_model = ShadingModel::Pbr`. All other fields take defaults.
    /// Use [`Material::pbr`] when no AO map is needed.
    pub fn pbr_with_ao(
        base_colour: impl Into<crate::colour::Colour>,
        metallic: f32,
        roughness: f32,
        ao_map: Option<crate::ids::TextureId>,
    ) -> Self {
        Self {
            base_colour: base_colour.into(),
            shading_model: ShadingModel::Pbr,
            metallic,
            roughness,
            ao_map_id: ao_map,
            ..Default::default()
        }
    }
}

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

    #[test]
    fn with_ior_derives_reflectance() {
        let m = Material::default().with_ior(1.5);
        assert_eq!(m.ior, 1.5);
        assert!((m.reflectance - Material::default().reflectance).abs() < 1e-6);
        // F0 = 0.16 r^2 reproduces ((ior - 1) / (ior + 1))^2.
        let m = Material::default().with_ior(2.4);
        let f0 = 0.16 * m.reflectance * m.reflectance;
        let expected = ((2.4f32 - 1.0) / (2.4 + 1.0)).powi(2);
        assert!((f0 - expected).abs() < 1e-6, "{f0} vs {expected}");
    }

    #[cfg(feature = "serde")]
    #[test]
    fn emissive_exposure_weight_defaults_to_one_when_absent() {
        let mut json =
            serde_json::to_value(Material::default().with_emissive_exposure_weight(0.25)).unwrap();
        assert_eq!(json["emissive_exposure_weight"], 0.25);
        json.as_object_mut()
            .unwrap()
            .remove("emissive_exposure_weight");
        let m: Material = serde_json::from_value(json).unwrap();
        assert_eq!(m.emissive_exposure_weight, 1.0);
    }

    #[test]
    fn texture_slots_list_in_index_order() {
        for (i, slot) in TextureSlot::ALL.into_iter().enumerate() {
            assert_eq!(slot.index(), i);
        }
    }

    #[test]
    fn texture_slots_build_what_they_require() {
        use crate::data::texture::TextureData;
        for slot in TextureSlot::ALL {
            let req = slot.requirement();
            let built = TextureData::for_slot(1, 1, vec![0u8; 4], slot);
            assert_eq!(built.colour_space(), slot.colour_space(), "{slot:?}");
            assert_eq!(built.role(), slot.role(), "{slot:?}");
            let named = match req.constructor() {
                "TextureData::srgb" => TextureData::srgb(1, 1, vec![0u8; 4]),
                "TextureData::linear" => TextureData::linear(1, 1, vec![0u8; 4]),
                "TextureData::normal_map" => TextureData::normal_map(1, 1, vec![0u8; 4]),
                other => panic!("{slot:?} names an unknown constructor {other}"),
            };
            assert_eq!(named, built, "{slot:?}");
        }
        assert_eq!(TextureSlot::Albedo.colour_space(), ColourSpace::Srgb);
        assert_eq!(TextureSlot::Normal.role(), TextureRole::NormalMap);
        assert_eq!(TextureSlot::Ao.colour_space(), ColourSpace::Linear);
    }

    #[test]
    fn texture_by_slot_sets_and_reads_one_field() {
        use crate::ids::TextureId;
        for (i, slot) in TextureSlot::ALL.into_iter().enumerate() {
            let id = TextureId::from_raw(i as u64 + 1);
            let m = Material::default().with_texture(slot, id);
            for other in TextureSlot::ALL {
                let expected = (other == slot).then_some(id);
                assert_eq!(m.texture(other), expected, "{slot:?} set, {other:?} read");
            }
            // The slot's field is the one its requirement names.
            let field = slot.requirement().field_name();
            let direct = match field {
                "Material::texture_id" => m.texture_id,
                "Material::normal_map_id" => m.normal_map_id,
                "Material::ao_map_id" => m.ao_map_id,
                "Material::metallic_roughness_texture_id" => m.metallic_roughness_texture_id,
                "Material::emissive_texture_id" => m.emissive_texture_id,
                other => panic!("{slot:?} names an unknown field {other}"),
            };
            assert_eq!(direct, Some(id), "{slot:?}");
            let mut cleared = m;
            cleared.set_texture(slot, None);
            assert_eq!(cleared.texture(slot), None);
        }
    }

    #[test]
    fn item_settings_defaults() {
        let a = ItemSettings::default();
        assert!(!a.hidden);
        assert!(!a.unlit);
        assert!((a.opacity - 1.0).abs() < 1e-6);
        assert!(!a.wireframe);
        assert!(!a.selected);
    }

    #[test]
    fn item_settings_spread_syntax() {
        let a = ItemSettings {
            unlit: true,
            ..Default::default()
        };
        assert!(a.unlit);
        assert!(!a.hidden);
        assert!((a.opacity - 1.0).abs() < 1e-6);
    }

    #[test]
    fn flat_constructor_and_helpers() {
        let m = Material::flat(Colour::linear_rgb(0.4, 0.5, 0.6));
        assert!(m.is_flat());
        assert!(!m.is_pbr());
        assert!(m.matcap_id().is_none());
        assert!(matches!(m.shading_model, ShadingModel::Flat));
        assert_eq!(
            m.base_colour,
            crate::colour::Colour::linear_rgb(0.4, 0.5, 0.6)
        );

        let p = Material::default();
        assert!(!p.is_flat());
    }

    #[test]
    fn default_values() {
        let m = Material::default();
        assert!((m.base_colour.to_linear_rgb()[0] - 0.7).abs() < 1e-6);
        assert!((m.ambient - 0.15).abs() < 1e-6);
        assert!((m.diffuse - 0.75).abs() < 1e-6);
        assert!(!m.is_pbr());
        assert!(m.texture_id.is_none());
        assert!(m.normal_map_id.is_none());
        assert!(m.ao_map_id.is_none());
        assert!(m.matcap_id().is_none());
        assert!(m.param_vis.is_none());
    }

    #[test]
    fn from_colour_sets_base_colour() {
        let m = Material::from_colour(Colour::linear_rgb(1.0, 0.0, 0.5));
        assert!((m.base_colour.to_linear_rgb()[0] - 1.0).abs() < 1e-6);
        assert!((m.base_colour.to_linear_rgb()[1]).abs() < 1e-6);
        assert!((m.base_colour.to_linear_rgb()[2] - 0.5).abs() < 1e-6);
        // Other fields should be defaults
        assert!((m.ambient - 0.15).abs() < 1e-6);
    }

    #[test]
    fn pbr_constructor() {
        let m = Material::pbr(Colour::linear_rgb(0.8, 0.2, 0.1), 0.9, 0.3);
        assert!(m.is_pbr());
        assert!((m.metallic - 0.9).abs() < 1e-6);
        assert!((m.roughness - 0.3).abs() < 1e-6);
        assert!((m.base_colour.to_linear_rgb()[0] - 0.8).abs() < 1e-6);
    }

    #[test]
    fn is_two_sided_cull() {
        let m = Material::default();
        assert!(!m.is_two_sided());
    }

    #[test]
    fn is_two_sided_identical() {
        let m = Material {
            backface_policy: BackfacePolicy::Identical,
            ..Default::default()
        };
        assert!(m.is_two_sided());
    }

    #[test]
    fn is_two_sided_different_colour() {
        let m = Material {
            backface_policy: BackfacePolicy::DifferentColour(crate::colour::Colour::linear_rgb(
                1.0, 0.0, 0.0,
            )),
            ..Default::default()
        };
        assert!(m.is_two_sided());
    }

    #[test]
    fn is_two_sided_tint() {
        let m = Material {
            backface_policy: BackfacePolicy::Tint(0.3),
            ..Default::default()
        };
        assert!(m.is_two_sided());
    }

    #[test]
    fn is_two_sided_pattern() {
        let m = Material {
            backface_policy: BackfacePolicy::Pattern(PatternConfig {
                pattern: BackfacePattern::Hatching,
                colour: crate::colour::Colour::linear_rgb(0.5, 0.5, 0.5),
                ..Default::default()
            }),
            ..Default::default()
        };
        assert!(m.is_two_sided());
    }

    #[test]
    fn blend_modes_route_through_oit() {
        let straight = Material {
            alpha_mode: AlphaMode::Blend,
            ..Default::default()
        };
        assert!(straight.is_blend());
        assert!(!straight.is_premultiplied());

        let premult = Material {
            alpha_mode: AlphaMode::BlendPremultiplied,
            ..Default::default()
        };
        // Premultiplied routes through the same OIT pass as straight blend...
        assert!(premult.is_blend());
        // ...but flags itself so the pass skips its premultiply step.
        assert!(premult.is_premultiplied());

        let opaque = Material::default();
        assert!(!opaque.is_blend());
        assert!(!opaque.is_premultiplied());

        let mask = Material {
            alpha_mode: AlphaMode::Mask(0.5),
            ..Default::default()
        };
        assert!(!mask.is_blend());
        assert!(!mask.is_premultiplied());
    }

    #[test]
    fn param_vis_default() {
        let pv = ParamVis::default();
        assert_eq!(pv.mode, ParamVisMode::Checker);
        assert!((pv.scale - 8.0).abs() < 1e-6);
    }

    #[test]
    fn solid_delegates_to_from_colour() {
        let colour = [1.0_f32, 0.0, 0.5];
        let a = Material::solid(Colour::from_linear_rgb_array(colour));
        let b = Material::from_colour(Colour::from_linear_rgb_array(colour));
        assert!((a.base_colour.to_linear_rgb()[0] - b.base_colour.to_linear_rgb()[0]).abs() < 1e-6);
        assert!((a.base_colour.to_linear_rgb()[1] - b.base_colour.to_linear_rgb()[1]).abs() < 1e-6);
        assert!((a.base_colour.to_linear_rgb()[2] - b.base_colour.to_linear_rgb()[2]).abs() < 1e-6);
        assert_eq!(a.is_pbr(), b.is_pbr());
        assert_eq!(a.texture_id, b.texture_id);
        assert_eq!(a.ao_map_id, b.ao_map_id);
        assert!((a.ambient - b.ambient).abs() < 1e-6);
    }

    #[test]
    fn textured_sets_texture_id() {
        let m = Material::textured(crate::ids::TextureId::from_raw(42));
        assert_eq!(m.texture_id, Some(crate::ids::TextureId::from_raw(42)));
        let def = Material::default();
        assert!(
            (m.base_colour.to_linear_rgb()[0] - def.base_colour.to_linear_rgb()[0]).abs() < 1e-6
        );
        assert!(!m.is_pbr());
    }

    #[test]
    fn pbr_with_ao_sets_fields() {
        let m = Material::pbr_with_ao(
            Colour::linear_rgb(0.8, 0.2, 0.1),
            0.9,
            0.3,
            Some(crate::ids::TextureId::from_raw(7)),
        );
        assert!(m.is_pbr());
        assert!((m.metallic - 0.9).abs() < 1e-6);
        assert!((m.roughness - 0.3).abs() < 1e-6);
        assert_eq!(m.ao_map_id, Some(crate::ids::TextureId::from_raw(7)));
        assert!((m.base_colour.to_linear_rgb()[0] - 0.8).abs() < 1e-6);
    }

    #[test]
    fn pbr_with_ao_accepts_none() {
        let m = Material::pbr_with_ao(Colour::linear_rgb(0.5, 0.5, 0.5), 0.0, 1.0, None);
        assert_eq!(m.ao_map_id, None);
    }

    #[test]
    fn channel_ranges_default_to_identity() {
        let m = Material::default();
        assert_eq!(m.ao_range, [0.0, 1.0]);
        assert_eq!(m.metallic_range, [0.0, 1.0]);
        assert_eq!(m.roughness_range, [0.0, 1.0]);
    }

    #[test]
    fn channel_ranges_round_trip_with_spread() {
        let m = Material {
            ao_range: [0.4, 1.0],
            metallic_range: [0.1, 0.9],
            roughness_range: [0.2, 0.8],
            ..Default::default()
        };
        assert_eq!(m.ao_range, [0.4, 1.0]);
        assert_eq!(m.metallic_range, [0.1, 0.9]);
        assert_eq!(m.roughness_range, [0.2, 0.8]);
        // Other defaults unaffected.
        assert_eq!(m.uv_offset, [0.0, 0.0]);
        assert_eq!(m.uv_scale, [1.0, 1.0]);
    }
}