wgpu-core 31.0.1

Core implementation logic of wgpu, the cross-platform, safe, pure-rust graphics API
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
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
use alloc::{
    borrow::{Cow, ToOwned},
    boxed::Box,
    string::String,
    sync::{Arc, Weak},
    vec::Vec,
};
use core::{
    fmt,
    mem::ManuallyDrop,
    num::{NonZeroU32, Saturating},
    ops::Range,
};

use arrayvec::ArrayVec;
use thiserror::Error;

#[cfg(feature = "serde")]
use serde::Deserialize;
#[cfg(feature = "serde")]
use serde::Serialize;

use wgpu_sync::OnceCell;
use wgt::error::{ErrorType, WebGpuError};

use crate::{
    api_log,
    device::{bgl, Device, DeviceError, MissingDownlevelFlags, MissingFeatures},
    init_tracker::{BufferInitTrackerAction, TextureInitTrackerAction},
    pipeline::{ComputePipeline, RenderPipeline},
    ray_tracing_pipeline::RayTracingPipeline,
    resource::{
        Buffer, DestroyedResourceError, ExternalTexture, InvalidOrDestroyedResourceError,
        InvalidResourceError, Labeled, MissingBufferUsageError, MissingTextureUsageError,
        RawResourceAccess, ResourceErrorIdent, ResourceState, Sampler, TextureView, Tlas,
        TrackingData,
    },
    resource_log,
    snatch::{SnatchGuard, Snatchable},
    track::{BindGroupStates, ResourceUsageCompatibilityError},
    Label,
};

#[derive(Clone, Debug, Error)]
#[non_exhaustive]
pub enum BindGroupLayoutEntryError {
    #[error("Multiple binding types provided, expected exactly one")]
    MultipleBindingTypesProvided,
    #[error("No binding types provided, expected exactly one")]
    NoBindingTypesProvided,
    #[error("Cube dimension is not expected for texture storage")]
    StorageTextureCube,
    #[error("Atomic storage textures are not allowed by baseline webgpu, they require the native only feature TEXTURE_ATOMIC")]
    StorageTextureAtomic,
    #[error("Arrays of bindings unsupported for this type of binding")]
    ArrayUnsupported,
    #[error("Multisampled binding with sample type `TextureSampleType::Float` must have filterable set to false.")]
    SampleTypeFloatFilterableBindingMultisampled,
    #[error("Multisampled texture binding view dimension must be 2d, got {0:?}")]
    Non2DMultisampled(wgt::TextureViewDimension),
    #[error(transparent)]
    MissingFeatures(#[from] MissingFeatures),
    #[error(transparent)]
    MissingDownlevelFlags(#[from] MissingDownlevelFlags),
}

#[derive(Clone, Debug, Error)]
#[non_exhaustive]
pub enum CreateBindGroupLayoutError {
    #[error(transparent)]
    Device(#[from] DeviceError),
    #[error("Conflicting binding at index {0}")]
    ConflictBinding(u32),
    #[error("Binding {binding} entry is invalid")]
    Entry {
        binding: u32,
        #[source]
        error: BindGroupLayoutEntryError,
    },
    #[error(transparent)]
    TooManyBindings(BindingTypeMaxCountError),
    #[error("Bind groups may not contain both a binding array and a dynamically offset buffer")]
    ContainsBothBindingArrayAndDynamicOffsetArray,
    #[error("Bind groups may not contain both a binding array and a uniform buffer")]
    ContainsBothBindingArrayAndUniformBuffer,
    #[error("Binding index {binding} is greater than the maximum number {maximum}")]
    InvalidBindingIndex { binding: u32, maximum: u32 },
    #[error("Invalid visibility {0:?}")]
    InvalidVisibility(wgt::ShaderStages),
    #[error("Binding index {binding}: {access:?} access to storage textures with format {format:?} is not supported")]
    UnsupportedStorageTextureAccess {
        binding: u32,
        access: wgt::StorageTextureAccess,
        format: wgt::TextureFormat,
    },
}

impl WebGpuError for CreateBindGroupLayoutError {
    fn webgpu_error_type(&self) -> ErrorType {
        match self {
            Self::Device(e) => e.webgpu_error_type(),

            Self::ConflictBinding(_)
            | Self::Entry { .. }
            | Self::TooManyBindings(_)
            | Self::InvalidBindingIndex { .. }
            | Self::InvalidVisibility(_)
            | Self::ContainsBothBindingArrayAndDynamicOffsetArray
            | Self::ContainsBothBindingArrayAndUniformBuffer
            | Self::UnsupportedStorageTextureAccess { .. } => ErrorType::Validation,
        }
    }
}

#[derive(Clone, Debug, Error)]
#[non_exhaustive]
pub enum BindingError {
    #[error(transparent)]
    DestroyedResource(#[from] DestroyedResourceError),
    #[error("Buffer {buffer}: Binding with size {binding_size} at offset {offset} would overflow buffer size of {buffer_size}")]
    BindingRangeTooLarge {
        buffer: ResourceErrorIdent,
        offset: wgt::BufferAddress,
        binding_size: u64,
        buffer_size: u64,
    },
    #[error("Buffer {buffer}: Binding offset {offset} is greater than buffer size {buffer_size}")]
    BindingOffsetTooLarge {
        buffer: ResourceErrorIdent,
        offset: wgt::BufferAddress,
        buffer_size: u64,
    },
    /// The supplied binding offset was equal to the buffer size.
    ///
    /// A binding offset equal to the buffer size is legal for vertex and index buffer
    /// bindings, but not for storage/uniform buffer bindings, thus this error should only
    /// be raised for the latter.
    #[error("Buffer {buffer}: Binding offset {offset} must be strictly less than buffer size {buffer_size}")]
    BindingOffsetEqualsSize {
        buffer: ResourceErrorIdent,
        offset: wgt::BufferAddress,
        buffer_size: u64,
    },
    #[error("Unbinding vertex buffer at slot {slot} expects offset to be 0. However an offset of {offset} was provided.")]
    UnbindingVertexBufferOffsetNotZero { slot: u32, offset: u64 },
    #[error("Unbinding vertex buffer at slot {slot} expects size to be 0. However a size of {size} was provided.")]
    UnbindingVertexBufferSizeNotZero { slot: u32, size: u64 },
}

impl WebGpuError for BindingError {
    fn webgpu_error_type(&self) -> ErrorType {
        match self {
            Self::DestroyedResource(e) => e.webgpu_error_type(),
            Self::BindingRangeTooLarge { .. }
            | Self::BindingOffsetTooLarge { .. }
            | Self::BindingOffsetEqualsSize { .. }
            | BindingError::UnbindingVertexBufferOffsetNotZero { .. }
            | BindingError::UnbindingVertexBufferSizeNotZero { .. } => ErrorType::Validation,
        }
    }
}

// TODO: there may be additional variants here that can be extracted into
// `BindingError`.
#[derive(Clone, Debug, Error)]
#[non_exhaustive]
pub enum CreateBindGroupError {
    #[error(transparent)]
    Device(#[from] DeviceError),
    #[error(transparent)]
    DestroyedResource(#[from] DestroyedResourceError),
    #[error(transparent)]
    BindingError(#[from] BindingError),
    #[error(
        "Binding count declared with at most {expected} items, but {actual} items were provided"
    )]
    BindingArrayPartialLengthMismatch { actual: usize, expected: usize },
    #[error(
        "Binding count declared with exactly {expected} items, but {actual} items were provided"
    )]
    BindingArrayLengthMismatch { actual: usize, expected: usize },
    #[error("Array binding provided zero elements")]
    BindingArrayZeroLength,
    #[error("Binding size {actual} of {buffer} is less than minimum {min}")]
    BindingSizeTooSmall {
        buffer: ResourceErrorIdent,
        actual: u64,
        min: u64,
    },
    #[error("{0} binding size is zero")]
    BindingZeroSize(ResourceErrorIdent),
    #[error("Number of bindings in bind group descriptor ({actual}) does not match the number of bindings defined in the bind group layout ({expected})")]
    BindingsNumMismatch { actual: usize, expected: usize },
    #[error("Binding {0} is used at least twice in the descriptor")]
    DuplicateBinding(u32),
    #[error("Unable to find a corresponding declaration for the given binding {0}")]
    MissingBindingDeclaration(u32),
    #[error(transparent)]
    MissingBufferUsage(#[from] MissingBufferUsageError),
    #[error(transparent)]
    MissingTextureUsage(#[from] MissingTextureUsageError),
    #[error("Binding declared as a single item, but bind group is using it as an array")]
    SingleBindingExpected,
    #[error("Effective buffer binding size {size} for storage buffers is expected to align to {alignment}, but size is {size}")]
    UnalignedEffectiveBufferBindingSizeForStorage { alignment: u32, size: u64 },
    #[error("Buffer offset {0} does not respect device's requested `{1}` limit {2}")]
    UnalignedBufferOffset(wgt::BufferAddress, &'static str, u32),
    #[error(
        "Buffer binding {binding} range {given} exceeds `max_*_buffer_binding_size` limit {limit}"
    )]
    BufferRangeTooLarge {
        binding: u32,
        given: u64,
        limit: u64,
    },
    #[error("Binding {binding} has a different type ({actual:?}) than the one in the layout ({expected:?})")]
    WrongBindingType {
        // Index of the binding
        binding: u32,
        // The type given to the function
        actual: wgt::BindingType,
        // Human-readable description of expected types
        expected: &'static str,
    },
    #[error("Texture binding {binding} expects multisampled = {layout_multisampled}, but given a view with samples = {view_samples}")]
    InvalidTextureMultisample {
        binding: u32,
        layout_multisampled: bool,
        view_samples: u32,
    },
    #[error(
        "Texture binding {} expects sample type {:?}, but was given a view with format {:?} (sample type {:?})",
        binding,
        layout_sample_type,
        view_format,
        view_sample_type
    )]
    InvalidTextureSampleType {
        binding: u32,
        layout_sample_type: wgt::TextureSampleType,
        view_format: wgt::TextureFormat,
        view_sample_type: wgt::TextureSampleType,
    },
    #[error("Texture binding {binding} expects dimension = {layout_dimension:?}, but given a view with dimension = {view_dimension:?}")]
    InvalidTextureDimension {
        binding: u32,
        layout_dimension: wgt::TextureViewDimension,
        view_dimension: wgt::TextureViewDimension,
    },
    #[error("Texture binding {binding} is given a view with dimension = {view_dimension:?}, but the texture was created with texture_binding_view_dimension = {texture_binding_view_dimension:?}")]
    InvalidTextureBindingViewDimension {
        binding: u32,
        view_dimension: wgt::TextureViewDimension,
        texture_binding_view_dimension: wgt::TextureViewDimension,
    },
    #[error("Storage texture binding {binding} expects format = {layout_format:?}, but given a view with format = {view_format:?}")]
    InvalidStorageTextureFormat {
        binding: u32,
        layout_format: wgt::TextureFormat,
        view_format: wgt::TextureFormat,
    },
    #[error("Storage texture bindings must have a single mip level, but given a view with mip_level_count = {mip_level_count:?} at binding {binding}")]
    InvalidStorageTextureMipLevelCount { binding: u32, mip_level_count: u32 },
    #[error("Storage texture bindings must have an identity swizzle, but given a view with swizzle = {swizzle:?}")]
    InvalidStorageTextureSwizzle {
        swizzle: wgt::TextureComponentSwizzle,
    },
    #[error("External texture bindings must have a single mip level, but given a view with mip_level_count = {mip_level_count:?} at binding {binding}")]
    InvalidExternalTextureMipLevelCount { binding: u32, mip_level_count: u32 },
    #[error("External texture bindings must have a format of `rgba8unorm`, `bgra8unorm`, or `rgba16float, but given a view with format = {format:?} at binding {binding}")]
    InvalidExternalTextureFormat {
        binding: u32,
        format: wgt::TextureFormat,
    },
    #[error("Sampler binding {binding} expects comparison = {layout_cmp}, but given a sampler with comparison = {sampler_cmp}")]
    WrongSamplerComparison {
        binding: u32,
        layout_cmp: bool,
        sampler_cmp: bool,
    },
    #[error("Sampler binding {binding} expects filtering = {layout_flt}, but given a sampler with filtering = {sampler_flt}")]
    WrongSamplerFiltering {
        binding: u32,
        layout_flt: bool,
        sampler_flt: bool,
    },
    #[error("TLAS binding {binding} is required to support vertex returns but is missing flag AccelerationStructureFlags::ALLOW_RAY_HIT_VERTEX_RETURN")]
    MissingTLASVertexReturn { binding: u32 },
    #[error("Bound texture views can not have both depth and stencil aspects enabled")]
    DepthStencilAspect,
    #[error(transparent)]
    ResourceUsageCompatibility(#[from] ResourceUsageCompatibilityError),
    #[error(transparent)]
    InvalidResource(#[from] InvalidResourceError),
}

impl WebGpuError for CreateBindGroupError {
    fn webgpu_error_type(&self) -> ErrorType {
        match self {
            Self::Device(e) => e.webgpu_error_type(),
            Self::DestroyedResource(e) => e.webgpu_error_type(),
            Self::BindingError(e) => e.webgpu_error_type(),
            Self::MissingBufferUsage(e) => e.webgpu_error_type(),
            Self::MissingTextureUsage(e) => e.webgpu_error_type(),
            Self::ResourceUsageCompatibility(e) => e.webgpu_error_type(),
            Self::InvalidResource(e) => e.webgpu_error_type(),
            Self::BindingArrayPartialLengthMismatch { .. }
            | Self::BindingArrayLengthMismatch { .. }
            | Self::BindingArrayZeroLength
            | Self::BindingSizeTooSmall { .. }
            | Self::BindingsNumMismatch { .. }
            | Self::BindingZeroSize(_)
            | Self::DuplicateBinding(_)
            | Self::MissingBindingDeclaration(_)
            | Self::SingleBindingExpected
            | Self::UnalignedEffectiveBufferBindingSizeForStorage { .. }
            | Self::UnalignedBufferOffset(_, _, _)
            | Self::BufferRangeTooLarge { .. }
            | Self::WrongBindingType { .. }
            | Self::InvalidTextureMultisample { .. }
            | Self::InvalidTextureSampleType { .. }
            | Self::InvalidTextureDimension { .. }
            | Self::InvalidStorageTextureFormat { .. }
            | Self::InvalidStorageTextureMipLevelCount { .. }
            | Self::InvalidStorageTextureSwizzle { .. }
            | Self::WrongSamplerComparison { .. }
            | Self::WrongSamplerFiltering { .. }
            | Self::DepthStencilAspect
            | Self::MissingTLASVertexReturn { .. }
            | Self::InvalidExternalTextureMipLevelCount { .. }
            | Self::InvalidExternalTextureFormat { .. }
            | Self::InvalidTextureBindingViewDimension { .. } => ErrorType::Validation,
        }
    }
}

#[derive(Clone, Debug, Error)]
pub enum BindingZone {
    #[error("Stage {0:?}")]
    Stage(wgt::ShaderStages),
    #[error("Whole pipeline")]
    Pipeline,
}

#[derive(Clone, Debug, Error)]
#[error("Too many bindings of type {kind:?} in {zone}, limit is {limit}, count was {count}. Check the limit `{}` passed to `Adapter::request_device`", .kind.to_config_str())]
pub struct BindingTypeMaxCountError {
    pub kind: BindingTypeMaxCountErrorKind,
    pub zone: BindingZone,
    pub limit: u32,
    pub count: u32,
}

impl WebGpuError for BindingTypeMaxCountError {
    fn webgpu_error_type(&self) -> ErrorType {
        ErrorType::Validation
    }
}

#[derive(Clone, Debug)]
pub enum BindingTypeMaxCountErrorKind {
    DynamicUniformBuffers,
    DynamicStorageBuffers,
    SampledTextures,
    Samplers,
    StorageBuffers,
    StorageTextures,
    UniformBuffers,
    BindingArrayElements,
    BindingArraySamplerElements,
    BindingArrayAccelerationStructureElements,
    AccelerationStructures,
    BuffersAndAccelerationStructures,
}

impl BindingTypeMaxCountErrorKind {
    fn to_config_str(&self) -> &'static str {
        match self {
            BindingTypeMaxCountErrorKind::DynamicUniformBuffers => {
                "max_dynamic_uniform_buffers_per_pipeline_layout"
            }
            BindingTypeMaxCountErrorKind::DynamicStorageBuffers => {
                "max_dynamic_storage_buffers_per_pipeline_layout"
            }
            BindingTypeMaxCountErrorKind::SampledTextures => {
                "max_sampled_textures_per_shader_stage"
            }
            BindingTypeMaxCountErrorKind::Samplers => "max_samplers_per_shader_stage",
            BindingTypeMaxCountErrorKind::StorageBuffers => "max_storage_buffers_per_shader_stage",
            BindingTypeMaxCountErrorKind::StorageTextures => {
                "max_storage_textures_per_shader_stage"
            }
            BindingTypeMaxCountErrorKind::UniformBuffers => "max_uniform_buffers_per_shader_stage",
            BindingTypeMaxCountErrorKind::BindingArrayElements => {
                "max_binding_array_elements_per_shader_stage"
            }
            BindingTypeMaxCountErrorKind::BindingArraySamplerElements => {
                "max_binding_array_sampler_elements_per_shader_stage"
            }
            BindingTypeMaxCountErrorKind::BindingArrayAccelerationStructureElements => {
                "max_binding_array_acceleration_structure_elements_per_shader_stage"
            }
            BindingTypeMaxCountErrorKind::AccelerationStructures => {
                "max_acceleration_structures_per_shader_stage"
            }
            BindingTypeMaxCountErrorKind::BuffersAndAccelerationStructures => {
                "max_buffers_and_acceleration_structures_per_shader_stage"
            }
        }
    }
}

#[derive(Debug, Default)]
pub(crate) struct PerStageBindingTypeCounter {
    vertex: Saturating<u32>,
    fragment: Saturating<u32>,
    compute: Saturating<u32>,
    ray_generation: Saturating<u32>,
    miss: Saturating<u32>,
    any_hit: Saturating<u32>,
    closest_hit: Saturating<u32>,
}

impl PerStageBindingTypeCounter {
    pub(crate) fn add(&mut self, stage: wgt::ShaderStages, count: u32) {
        if stage.contains(wgt::ShaderStages::VERTEX) {
            self.vertex += count;
        }
        if stage.contains(wgt::ShaderStages::FRAGMENT) {
            self.fragment += count;
        }
        if stage.contains(wgt::ShaderStages::COMPUTE) {
            self.compute += count;
        }
        if stage.contains(wgt::ShaderStages::RAY_GENERATION) {
            self.ray_generation += count;
        }
        if stage.contains(wgt::ShaderStages::MISS) {
            self.miss += count;
        }
        if stage.contains(wgt::ShaderStages::ANY_HIT) {
            self.any_hit += count;
        }
        if stage.contains(wgt::ShaderStages::CLOSEST_HIT) {
            self.closest_hit += count;
        }
    }

    pub(crate) fn max(&self) -> (BindingZone, u32) {
        let max_value = self.vertex.max(
            self.fragment.max(
                self.compute.max(
                    self.ray_generation
                        .max(self.miss.max(self.any_hit.max(self.closest_hit))),
                ),
            ),
        );
        let mut stage = wgt::ShaderStages::NONE;
        if max_value == self.vertex {
            stage |= wgt::ShaderStages::VERTEX
        }
        if max_value == self.fragment {
            stage |= wgt::ShaderStages::FRAGMENT
        }
        if max_value == self.compute {
            stage |= wgt::ShaderStages::COMPUTE
        }
        if max_value == self.ray_generation {
            stage |= wgt::ShaderStages::RAY_GENERATION
        }
        if max_value == self.miss {
            stage |= wgt::ShaderStages::MISS
        }
        if max_value == self.any_hit {
            stage |= wgt::ShaderStages::ANY_HIT
        }
        if max_value == self.closest_hit {
            stage |= wgt::ShaderStages::CLOSEST_HIT
        }
        (BindingZone::Stage(stage), max_value.0)
    }

    pub(crate) fn merge(&mut self, other: &Self) {
        self.vertex += other.vertex;
        self.fragment += other.fragment;
        self.compute += other.compute;
    }

    pub(crate) fn validate(
        &self,
        limit: u32,
        kind: BindingTypeMaxCountErrorKind,
    ) -> Result<(), BindingTypeMaxCountError> {
        let (zone, count) = self.max();
        if limit < count {
            Err(BindingTypeMaxCountError {
                kind,
                zone,
                limit,
                count,
            })
        } else {
            Ok(())
        }
    }
}

#[derive(Debug, Default)]
pub(crate) struct BindingTypeMaxCountValidator {
    dynamic_uniform_buffers: u32,
    dynamic_storage_buffers: u32,
    sampled_textures: PerStageBindingTypeCounter,
    samplers: PerStageBindingTypeCounter,
    storage_buffers: PerStageBindingTypeCounter,
    storage_textures: PerStageBindingTypeCounter,
    uniform_buffers: PerStageBindingTypeCounter,
    acceleration_structures: PerStageBindingTypeCounter,
    binding_array_elements: PerStageBindingTypeCounter,
    binding_array_sampler_elements: PerStageBindingTypeCounter,
    binding_array_acceleration_structure_elements: PerStageBindingTypeCounter,
    has_bindless_array: bool,
}

impl BindingTypeMaxCountValidator {
    pub(crate) fn add_binding(&mut self, binding: &wgt::BindGroupLayoutEntry) {
        let count = binding.count.map_or(1, |count| count.get());

        if binding.count.is_some() {
            self.binding_array_elements.add(binding.visibility, count);
            self.has_bindless_array = true;

            match binding.ty {
                wgt::BindingType::Sampler(_) => {
                    self.binding_array_sampler_elements
                        .add(binding.visibility, count);
                }
                wgt::BindingType::AccelerationStructure { .. } => {
                    self.binding_array_acceleration_structure_elements
                        .add(binding.visibility, count);
                }
                _ => {}
            }
        } else {
            match binding.ty {
                wgt::BindingType::Buffer {
                    ty: wgt::BufferBindingType::Uniform,
                    has_dynamic_offset,
                    ..
                } => {
                    self.uniform_buffers.add(binding.visibility, count);
                    if has_dynamic_offset {
                        self.dynamic_uniform_buffers += count;
                    }
                }
                wgt::BindingType::Buffer {
                    ty: wgt::BufferBindingType::Storage { .. },
                    has_dynamic_offset,
                    ..
                } => {
                    self.storage_buffers.add(binding.visibility, count);
                    if has_dynamic_offset {
                        self.dynamic_storage_buffers += count;
                    }
                }
                wgt::BindingType::Sampler { .. } => {
                    self.samplers.add(binding.visibility, count);
                }
                wgt::BindingType::Texture { .. } => {
                    self.sampled_textures.add(binding.visibility, count);
                }
                wgt::BindingType::StorageTexture { .. } => {
                    self.storage_textures.add(binding.visibility, count);
                }
                wgt::BindingType::AccelerationStructure { .. } => {
                    self.acceleration_structures.add(binding.visibility, count);
                }
                wgt::BindingType::ExternalTexture => {
                    // https://www.w3.org/TR/webgpu/#gpuexternaltexture
                    // In order to account for many possible representations,
                    // the binding conservatively uses the following, for each
                    // external texture:
                    // * Three sampled textures for up to 3 planes
                    // * One additional sampled texture for a 3D LUT
                    // * One sampler to sample the LUT
                    // * One uniform buffer for metadata
                    self.sampled_textures.add(binding.visibility, count * 4);
                    self.samplers.add(binding.visibility, count);
                    self.uniform_buffers.add(binding.visibility, count);
                }
            }
        }
    }

    pub(crate) fn merge(&mut self, other: &Self) {
        self.dynamic_uniform_buffers += other.dynamic_uniform_buffers;
        self.dynamic_storage_buffers += other.dynamic_storage_buffers;
        self.sampled_textures.merge(&other.sampled_textures);
        self.samplers.merge(&other.samplers);
        self.storage_buffers.merge(&other.storage_buffers);
        self.storage_textures.merge(&other.storage_textures);
        self.uniform_buffers.merge(&other.uniform_buffers);
        self.acceleration_structures
            .merge(&other.acceleration_structures);
        self.binding_array_elements
            .merge(&other.binding_array_elements);
        self.binding_array_sampler_elements
            .merge(&other.binding_array_sampler_elements);
        self.binding_array_acceleration_structure_elements
            .merge(&other.binding_array_acceleration_structure_elements);
    }

    pub(crate) fn validate(
        &self,
        limits: &wgt::Limits,
        instance_flags: wgt::InstanceFlags,
    ) -> Result<(), BindingTypeMaxCountError> {
        if limits.max_dynamic_uniform_buffers_per_pipeline_layout < self.dynamic_uniform_buffers {
            return Err(BindingTypeMaxCountError {
                kind: BindingTypeMaxCountErrorKind::DynamicUniformBuffers,
                zone: BindingZone::Pipeline,
                limit: limits.max_dynamic_uniform_buffers_per_pipeline_layout,
                count: self.dynamic_uniform_buffers,
            });
        }
        if limits.max_dynamic_storage_buffers_per_pipeline_layout < self.dynamic_storage_buffers {
            return Err(BindingTypeMaxCountError {
                kind: BindingTypeMaxCountErrorKind::DynamicStorageBuffers,
                zone: BindingZone::Pipeline,
                limit: limits.max_dynamic_storage_buffers_per_pipeline_layout,
                count: self.dynamic_storage_buffers,
            });
        }
        self.sampled_textures.validate(
            limits.max_sampled_textures_per_shader_stage,
            BindingTypeMaxCountErrorKind::SampledTextures,
        )?;
        self.samplers.validate(
            limits.max_samplers_per_shader_stage,
            BindingTypeMaxCountErrorKind::Samplers,
        )?;
        self.storage_buffers.validate(
            limits.max_storage_buffers_per_shader_stage,
            BindingTypeMaxCountErrorKind::StorageBuffers,
        )?;
        // NOTE: We don't explicitly check `max_storage_buffers_in_vertex_stage` or
        // `max_storage_buffers_in_fragment_stage` because we don't assign different values between
        // those and `max_storage_buffers_per_shader_stage`. If this changes, this needs to be
        // fixed!
        self.storage_textures.validate(
            limits.max_storage_textures_per_shader_stage,
            BindingTypeMaxCountErrorKind::StorageTextures,
        )?;
        // NOTE: We don't explicitly check `max_storage_textures_in_vertex_stage` or
        // `max_storage_textures_in_fragment_stage` because we don't assign different values between
        // those and `max_storage_textures_per_shader_stage`. If this changes, this needs to be
        // fixed!
        self.uniform_buffers.validate(
            limits.max_uniform_buffers_per_shader_stage,
            BindingTypeMaxCountErrorKind::UniformBuffers,
        )?;
        self.binding_array_elements.validate(
            limits.max_binding_array_elements_per_shader_stage,
            BindingTypeMaxCountErrorKind::BindingArrayElements,
        )?;
        self.binding_array_sampler_elements.validate(
            limits.max_binding_array_sampler_elements_per_shader_stage,
            BindingTypeMaxCountErrorKind::BindingArraySamplerElements,
        )?;
        self.binding_array_acceleration_structure_elements
            .validate(
                limits.max_binding_array_acceleration_structure_elements_per_shader_stage,
                BindingTypeMaxCountErrorKind::BindingArrayAccelerationStructureElements,
            )?;
        self.acceleration_structures.validate(
            limits.max_acceleration_structures_per_shader_stage,
            BindingTypeMaxCountErrorKind::AccelerationStructures,
        )?;

        if !instance_flags.contains(wgt::InstanceFlags::STRICT_WEBGPU_COMPLIANCE) {
            self.buffers_and_acceleration_structures().validate(
                limits.max_buffers_and_acceleration_structures_per_shader_stage,
                BindingTypeMaxCountErrorKind::BuffersAndAccelerationStructures,
            )?;
        }

        Ok(())
    }

    fn buffers_and_acceleration_structures(&self) -> PerStageBindingTypeCounter {
        let mut buffers_and_acceleration_structures = PerStageBindingTypeCounter::default();
        buffers_and_acceleration_structures.merge(&self.uniform_buffers);
        buffers_and_acceleration_structures.merge(&self.storage_buffers);
        buffers_and_acceleration_structures.merge(&self.acceleration_structures);
        buffers_and_acceleration_structures
    }

    pub(crate) fn buffers_and_acceleration_structures_in_vertex_stage(&self) -> u32 {
        self.buffers_and_acceleration_structures().vertex.0
    }

    /// Validate that the bind group layout does not contain both a binding array and a dynamic offset array.
    ///
    /// This allows us to use `UPDATE_AFTER_BIND` on vulkan for bindless arrays. Vulkan does not allow
    /// `UPDATE_AFTER_BIND` on dynamic offset arrays. See <https://github.com/gfx-rs/wgpu/issues/6737>
    pub(crate) fn validate_binding_arrays(&self) -> Result<(), CreateBindGroupLayoutError> {
        let has_dynamic_offset_array =
            self.dynamic_uniform_buffers > 0 || self.dynamic_storage_buffers > 0;
        let has_uniform_buffer = self.uniform_buffers.max().1 > 0;
        if self.has_bindless_array && has_dynamic_offset_array {
            return Err(CreateBindGroupLayoutError::ContainsBothBindingArrayAndDynamicOffsetArray);
        }
        if self.has_bindless_array && has_uniform_buffer {
            return Err(CreateBindGroupLayoutError::ContainsBothBindingArrayAndUniformBuffer);
        }
        Ok(())
    }
}

/// Bindable resource and the slot to bind it to.
/// cbindgen:ignore
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct BindGroupEntry<
    'a,
    B = Arc<Buffer>,
    S = Arc<Sampler>,
    TV = Arc<TextureView>,
    TLAS = Arc<Tlas>,
    ET = Arc<ExternalTexture>,
> where
    [BufferBinding<B>]: ToOwned,
    [S]: ToOwned,
    [TV]: ToOwned,
    [TLAS]: ToOwned,
    <[BufferBinding<B>] as ToOwned>::Owned: fmt::Debug,
    <[S] as ToOwned>::Owned: fmt::Debug,
    <[TV] as ToOwned>::Owned: fmt::Debug,
    <[TLAS] as ToOwned>::Owned: fmt::Debug,
{
    /// Slot for which binding provides resource. Corresponds to an entry of the same
    /// binding index in the [`BindGroupLayoutDescriptor`].
    pub binding: u32,
    #[cfg_attr(
        feature = "serde",
        serde(bound(deserialize = "BindingResource<'a, B, S, TV, TLAS, ET>: Deserialize<'de>"))
    )]
    /// Resource to attach to the binding
    pub resource: BindingResource<'a, B, S, TV, TLAS, ET>,
}

/// Describes a group of bindings and the resources to be bound.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
/// cbindgen:ignore
pub struct BindGroupDescriptor<
    'a,
    BGL = Arc<BindGroupLayout>,
    B = Arc<Buffer>,
    S = Arc<Sampler>,
    TV = Arc<TextureView>,
    TLAS = Arc<Tlas>,
    ET = Arc<ExternalTexture>,
> where
    [BufferBinding<B>]: ToOwned,
    [S]: ToOwned,
    [TV]: ToOwned,
    [TLAS]: ToOwned,
    <[BufferBinding<B>] as ToOwned>::Owned: fmt::Debug,
    <[S] as ToOwned>::Owned: fmt::Debug,
    <[TV] as ToOwned>::Owned: fmt::Debug,
    <[TLAS] as ToOwned>::Owned: fmt::Debug,
    [BindGroupEntry<'a, B, S, TV, TLAS, ET>]: ToOwned,
    <[BindGroupEntry<'a, B, S, TV, TLAS, ET>] as ToOwned>::Owned: fmt::Debug,
{
    /// Debug label of the bind group.
    ///
    /// This will show up in graphics debuggers for easy identification.
    pub label: Label<'a>,
    /// The [`BindGroupLayout`] that corresponds to this bind group.
    pub layout: BGL,
    #[cfg_attr(
        feature = "serde",
        serde(bound(
            deserialize = "<[BindGroupEntry<'a, B, S, TV, TLAS, ET>] as ToOwned>::Owned: Deserialize<'de>"
        ))
    )]
    /// The resources to bind to this bind group.
    #[allow(clippy::type_complexity)]
    pub entries: Cow<'a, [BindGroupEntry<'a, B, S, TV, TLAS, ET>]>,
}

/// A buffer binding.
///
/// Corresponds to [WebGPU `GPUBufferBindingLayout`](
/// https://gpuweb.github.io/gpuweb/#dictdef-gpubufferbindinglayout).
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct BufferBindingLayout {
    /// Sub-type of the buffer binding.
    pub ty: wgt::BufferBindingType,

    /// Indicates that the binding has a dynamic offset.
    ///
    /// One offset must be passed to [`RenderPass::set_bind_group`](crate::command::RenderPass::set_bind_group)
    /// for each dynamic binding in increasing order of binding number.
    ///
    #[cfg_attr(feature = "serde", serde(default))]
    pub has_dynamic_offset: bool,

    /// The minimum size for a [`BufferBinding`] matching this entry, in bytes.
    ///
    /// If this is `Some(size)`:
    ///
    /// - When calling [`Device::create_bind_group`], the resource at this bind point
    ///   must be a [`BindingResource::Buffer`] whose effective size is at
    ///   least `size`.
    ///
    /// - When calling [`Device::create_render_pipeline`] or [`Device::create_compute_pipeline`],
    ///   `size` must be at least the [minimum buffer binding size] for the
    ///   shader module global at this bind point: large enough to hold the
    ///   global's value, along with one element of a trailing runtime-sized
    ///   array, if present.
    ///
    /// If this is `None`:
    ///
    /// - Each draw or dispatch command checks that the buffer range at this
    ///   bind point satisfies the [minimum buffer binding size].
    ///
    /// [minimum buffer binding size]: https://www.w3.org/TR/webgpu/#minimum-buffer-binding-size
    #[cfg_attr(feature = "serde", serde(default))]
    pub min_binding_size: Option<wgt::BufferSize>,
}

/// A sampler that can be used to sample a texture.
///
/// Example WGSL syntax:
/// ```rust,ignore
/// @group(0) @binding(0)
/// var s: sampler;
/// ```
///
/// Example GLSL syntax:
/// ```cpp,ignore
/// layout(binding = 0)
/// uniform sampler s;
/// ```
///
/// Corresponds to [WebGPU `GPUSamplerBindingLayout`](
/// https://gpuweb.github.io/gpuweb/#dictdef-gpusamplerbindinglayout).
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct SamplerBindingLayout {
    /// Type of a sampler binding.
    pub ty: wgt::SamplerBindingType,
}

/// A texture binding.
///
/// Example WGSL syntax:
/// ```rust,ignore
/// @group(0) @binding(0)
/// var t: texture_2d<f32>;
/// ```
///
/// Example GLSL syntax:
/// ```cpp,ignore
/// layout(binding = 0)
/// uniform texture2D t;
/// ```
///
/// Corresponds to [WebGPU `GPUTextureBindingLayout`](
/// https://gpuweb.github.io/gpuweb/#dictdef-gputexturebindinglayout).
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct TextureBindingLayout {
    /// Sample type of the texture binding.
    pub sample_type: wgt::TextureSampleType,
    /// Dimension of the texture view that is going to be sampled.
    pub view_dimension: wgt::TextureViewDimension,
    /// True if the texture has a sample count greater than 1. If this is true,
    /// the texture must be declared as `texture_multisampled_2d` or
    /// `texture_depth_multisampled_2d` in the shader, and read using `textureLoad`.
    pub multisampled: bool,
}

/// A storage texture.
///
/// Example WGSL syntax:
/// ```rust,ignore
/// @group(0) @binding(0)
/// var my_storage_image: texture_storage_2d<r32float, write>;
/// ```
///
/// Example GLSL syntax:
/// ```cpp,ignore
/// layout(set=0, binding=0, r32f) writeonly uniform image2D myStorageImage;
/// ```
/// Note that the texture format must be specified in the shader, along with the
/// access mode. For WGSL, the format must be one of the enumerants in the list
/// of [storage texel formats](https://gpuweb.github.io/gpuweb/wgsl/#storage-texel-formats).
///
/// Corresponds to [WebGPU `GPUStorageTextureBindingLayout`](
/// https://gpuweb.github.io/gpuweb/#dictdef-gpustoragetexturebindinglayout).
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct StorageTextureBindingLayout {
    /// Allowed access to this texture.
    pub access: wgt::StorageTextureAccess,
    /// Format of the texture.
    pub format: wgt::TextureFormat,
    /// Dimension of the texture view that is going to be sampled.
    pub view_dimension: wgt::TextureViewDimension,
}

/// A ray-tracing acceleration structure binding.
///
/// Example WGSL syntax:
/// ```rust,ignore
/// @group(0) @binding(0)
/// var as: acceleration_structure;
/// ```
///
/// or with vertex return enabled
/// ```rust,ignore
/// @group(0) @binding(0)
/// var as: acceleration_structure<vertex_return>;
/// ```
///
/// Example GLSL syntax:
/// ```cpp,ignore
/// layout(binding = 0)
/// uniform accelerationStructureEXT as;
/// ```
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct AccelerationStructureBindingLayout {
    /// Whether this acceleration structure can be used to
    /// create a ray query that has flag vertex return in the shader
    ///
    /// If enabled requires [`wgt::Features::EXPERIMENTAL_RAY_HIT_VERTEX_RETURN`]
    pub vertex_return: bool,
}

/// An external texture binding.
///
/// Example WGSL syntax:
/// ```rust,ignore
/// @group(0) @binding(0)
/// var t: texture_external;
/// ```
///
/// Corresponds to [WebGPU `GPUExternalTextureBindingLayout`](
/// https://gpuweb.github.io/gpuweb/#dictdef-gpuexternaltexturebindinglayout).
///
/// Requires [`wgt::Features::EXTERNAL_TEXTURE`]
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ExternalTextureBindingLayout;

/// Describes a single binding inside a bind group.
///
/// Corresponds to [WebGPU `GPUBindGroupLayoutEntry`](
/// https://gpuweb.github.io/gpuweb/#dictdef-gpubindgrouplayoutentry).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct BindGroupLayoutEntry {
    /// Binding index. Must match shader index and be unique inside a `BindGroupLayout`. A binding
    /// of index 1, would be described as `@group(0) @binding(1)` in shaders.
    pub binding: u32,
    /// Which shader stages can see this binding.
    pub visibility: wgt::ShaderStages,

    // type of binding
    #[cfg_attr(feature = "serde", serde(default))]
    pub buffer: Option<BufferBindingLayout>,
    #[cfg_attr(feature = "serde", serde(default))]
    pub sampler: Option<SamplerBindingLayout>,
    #[cfg_attr(feature = "serde", serde(default))]
    pub texture: Option<TextureBindingLayout>,
    #[cfg_attr(feature = "serde", serde(default))]
    pub storage_texture: Option<StorageTextureBindingLayout>,
    #[cfg_attr(feature = "serde", serde(default))]
    pub external_texture: Option<ExternalTextureBindingLayout>,
    #[cfg_attr(feature = "serde", serde(default))]
    pub acceleration_structure: Option<AccelerationStructureBindingLayout>,

    /// If the binding is an array of multiple resources. Corresponds to `binding_array<T>` in the shader.
    ///
    /// When this is `Some` the following validation applies:
    /// - Count must be of value 1 or greater, this corresponds to the length of the array of resources that will be bound.
    /// - When `ty == BindingType::Texture`, [`wgt::Features::TEXTURE_BINDING_ARRAY`] must be supported.
    /// - When `ty == BindingType::Sampler`, [`wgt::Features::TEXTURE_BINDING_ARRAY`] must be supported.
    /// - When `ty == BindingType::Buffer`, [`wgt::Features::BUFFER_BINDING_ARRAY`] must be supported.
    /// - When `ty == BindingType::Buffer` and `ty.ty == BufferBindingType::Storage`, [`wgt::Features::STORAGE_RESOURCE_BINDING_ARRAY`] must be supported.
    /// - When `ty == BindingType::StorageTexture`, [`wgt::Features::STORAGE_RESOURCE_BINDING_ARRAY`] must be supported.
    /// - When any binding in the group is an array, no `BindingType::Buffer` in the group may have `has_dynamic_offset == true`
    /// - When any binding in the group is an array, no `BindingType::Buffer` in the group may have `ty.ty == BufferBindingType::Uniform`.
    /// - If [`wgt::Features::PARTIALLY_BOUND_BINDING_ARRAY`] is enabled, the specified count becomes the upper bound instead.
    ///
    #[cfg_attr(feature = "serde", serde(default))]
    pub count: Option<NonZeroU32>,
}

impl From<core::convert::Infallible> for CreateBindGroupLayoutError {
    fn from(_: core::convert::Infallible) -> Self {
        unreachable!()
    }
}

impl From<wgt::BindGroupLayoutEntry> for BindGroupLayoutEntry {
    fn from(val: wgt::BindGroupLayoutEntry) -> Self {
        let wgt::BindGroupLayoutEntry {
            binding,
            visibility,
            ty,
            count,
        } = val;
        BindGroupLayoutEntry {
            binding,
            visibility,
            buffer: if let wgt::BindingType::Buffer {
                ty,
                has_dynamic_offset,
                min_binding_size,
            } = ty
            {
                Some(BufferBindingLayout {
                    ty,
                    has_dynamic_offset,
                    min_binding_size,
                })
            } else {
                None
            },
            sampler: if let wgt::BindingType::Sampler(ty) = ty {
                Some(SamplerBindingLayout { ty })
            } else {
                None
            },
            texture: if let wgt::BindingType::Texture {
                sample_type,
                view_dimension,
                multisampled,
            } = ty
            {
                Some(TextureBindingLayout {
                    sample_type,
                    view_dimension,
                    multisampled,
                })
            } else {
                None
            },
            storage_texture: if let wgt::BindingType::StorageTexture {
                access,
                format,
                view_dimension,
            } = ty
            {
                Some(StorageTextureBindingLayout {
                    access,
                    format,
                    view_dimension,
                })
            } else {
                None
            },
            external_texture: if let wgt::BindingType::ExternalTexture = ty {
                Some(ExternalTextureBindingLayout {})
            } else {
                None
            },
            acceleration_structure: if let wgt::BindingType::AccelerationStructure {
                vertex_return,
            } = ty
            {
                Some(AccelerationStructureBindingLayout { vertex_return })
            } else {
                None
            },
            count,
        }
    }
}

impl TryInto<wgt::BindGroupLayoutEntry> for BindGroupLayoutEntry {
    type Error = CreateBindGroupLayoutError;

    fn try_into(self) -> Result<wgt::BindGroupLayoutEntry, Self::Error> {
        let BindGroupLayoutEntry {
            binding,
            visibility,
            buffer,
            sampler,
            texture,
            storage_texture,
            external_texture,
            acceleration_structure,
            count,
        } = self;
        let mut binding_ty: Option<wgt::BindingType> = None;
        if let Some(BufferBindingLayout {
            ty,
            has_dynamic_offset,
            min_binding_size,
        }) = buffer
        {
            binding_ty = Some(wgt::BindingType::Buffer {
                ty,
                has_dynamic_offset,
                min_binding_size,
            });
        }
        if let Some(SamplerBindingLayout { ty }) = sampler {
            if binding_ty.is_some() {
                return Err(CreateBindGroupLayoutError::Entry {
                    binding,
                    error: BindGroupLayoutEntryError::MultipleBindingTypesProvided,
                });
            }
            binding_ty = Some(wgt::BindingType::Sampler(ty))
        }
        if let Some(TextureBindingLayout {
            sample_type,
            view_dimension,
            multisampled,
        }) = texture
        {
            if binding_ty.is_some() {
                return Err(CreateBindGroupLayoutError::Entry {
                    binding,
                    error: BindGroupLayoutEntryError::MultipleBindingTypesProvided,
                });
            }
            binding_ty = Some(wgt::BindingType::Texture {
                sample_type,
                view_dimension,
                multisampled,
            })
        }
        if let Some(StorageTextureBindingLayout {
            access,
            format,
            view_dimension,
        }) = storage_texture
        {
            if binding_ty.is_some() {
                return Err(CreateBindGroupLayoutError::Entry {
                    binding,
                    error: BindGroupLayoutEntryError::MultipleBindingTypesProvided,
                });
            }
            binding_ty = Some(wgt::BindingType::StorageTexture {
                access,
                format,
                view_dimension,
            })
        }
        if let Some(ExternalTextureBindingLayout) = external_texture {
            if binding_ty.is_some() {
                return Err(CreateBindGroupLayoutError::Entry {
                    binding,
                    error: BindGroupLayoutEntryError::MultipleBindingTypesProvided,
                });
            }
            binding_ty = Some(wgt::BindingType::ExternalTexture)
        }
        if let Some(AccelerationStructureBindingLayout { vertex_return }) = acceleration_structure {
            if binding_ty.is_some() {
                return Err(CreateBindGroupLayoutError::Entry {
                    binding,
                    error: BindGroupLayoutEntryError::MultipleBindingTypesProvided,
                });
            }
            binding_ty = Some(wgt::BindingType::AccelerationStructure { vertex_return })
        }
        Ok(wgt::BindGroupLayoutEntry {
            binding,
            visibility,
            ty: binding_ty.ok_or(CreateBindGroupLayoutError::Entry {
                binding,
                error: BindGroupLayoutEntryError::NoBindingTypesProvided,
            })?,
            count,
        })
    }
}

/// Describes a [`BindGroupLayout`].
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct BindGroupLayoutDescriptor<'a, BGLE: Copy> {
    /// Debug label of the bind group layout.
    ///
    /// This will show up in graphics debuggers for easy identification.
    pub label: Label<'a>,
    /// Array of entries in this BindGroupLayout
    pub entries: Cow<'a, [BGLE]>,
}

/// Used by [`BindGroupLayout`]. It indicates whether the BGL must be
/// used with a specific pipeline. This constraint only happens when
/// the BGLs have been derived from a pipeline without a layout.
#[derive(Clone, Debug)]
pub(crate) enum ExclusivePipeline {
    None,
    Render(Weak<RenderPipeline>),
    Compute(Weak<ComputePipeline>),
    RayTracing(Weak<RayTracingPipeline>),
}

impl From<&Arc<RenderPipeline>> for ExclusivePipeline {
    fn from(pipeline: &Arc<RenderPipeline>) -> Self {
        Self::Render(Arc::downgrade(pipeline))
    }
}

impl From<&Arc<ComputePipeline>> for ExclusivePipeline {
    fn from(pipeline: &Arc<ComputePipeline>) -> Self {
        Self::Compute(Arc::downgrade(pipeline))
    }
}

impl From<&Arc<RayTracingPipeline>> for ExclusivePipeline {
    fn from(pipeline: &Arc<RayTracingPipeline>) -> Self {
        Self::RayTracing(Arc::downgrade(pipeline))
    }
}

impl fmt::Display for ExclusivePipeline {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ExclusivePipeline::None => f.write_str("None"),
            ExclusivePipeline::Render(p) => {
                if let Some(p) = p.upgrade() {
                    p.error_ident().fmt(f)
                } else {
                    f.write_str("RenderPipeline")
                }
            }
            ExclusivePipeline::Compute(p) => {
                if let Some(p) = p.upgrade() {
                    p.error_ident().fmt(f)
                } else {
                    f.write_str("ComputePipeline")
                }
            }
            ExclusivePipeline::RayTracing(p) => {
                if let Some(p) = p.upgrade() {
                    p.error_ident().fmt(f)
                } else {
                    f.write_str("RayTracingPipeline")
                }
            }
        }
    }
}

#[derive(Debug)]
pub enum RawBindGroupLayout {
    Owning(ManuallyDrop<Box<dyn hal::DynBindGroupLayout>>),
    /// The empty BGL was created by the device and will be destroyed by the device.
    RefDeviceEmptyBGL,
}

#[derive(Debug)]
pub(crate) struct BindGroupLayoutState {
    pub(crate) raw: RawBindGroupLayout,
    /// It is very important that we know if the bind group comes from the BGL pool.
    ///
    /// If it does, then we need to remove it from the pool when we drop it.
    ///
    /// We cannot unconditionally remove from the pool, as BGLs that don't come from the pool
    /// (derived BGLs) must not be removed.
    pub(crate) origin: bgl::Origin,
    pub(crate) binding_count_validator: BindingTypeMaxCountValidator,
}

/// Bind group layout.
#[derive(Debug)]
pub struct BindGroupLayout {
    pub(crate) state: ResourceState<BindGroupLayoutState>,
    pub(crate) device: Arc<Device>,
    pub(crate) entries: bgl::EntryMap,
    /// Bindings of buffer entries without `min_binding_size`. Their sizes are checked against
    /// the shader at draw or dispatch time.
    pub(crate) late_sized_bindings: Vec<u32>,
    pub(crate) exclusive_pipeline: OnceCell<ExclusivePipeline>,
    /// The `label` from the descriptor used to create the resource.
    pub(crate) label: String,
}

impl Drop for BindGroupLayout {
    #[allow(trivial_casts)]
    fn drop(&mut self) {
        profiling::scope!("BindGroupLayout::drop");
        api_log!("BindGroupLayout::drop {:?}", self as *const _);
        #[cfg(feature = "trace")]
        {
            let mut t = self.device.trace.lock();
            if let Some(t) = t.as_mut() {
                use crate::device::trace;

                // SAFETY: All bind group layouts are constructed in Arc => are heap allocated
                t.add(trace::Action::DropBindGroupLayout(unsafe {
                    trace::to_trace(self)
                }));
            }
        }
        resource_log!("Destroy raw {}", self.error_ident());
        let ResourceState::Valid(state) = &mut self.state else {
            return;
        };
        if matches!(state.origin, bgl::Origin::Pool) {
            self.device.bgl_pool.remove(&self.entries);
        }
        match state.raw {
            RawBindGroupLayout::Owning(ref mut raw) => {
                // SAFETY: We are in the Drop impl and we don't use state.raw anymore after this point.
                let raw = unsafe { ManuallyDrop::take(raw) };
                unsafe {
                    self.device.raw().destroy_bind_group_layout(raw);
                }
            }
            RawBindGroupLayout::RefDeviceEmptyBGL => {}
        }
    }
}

crate::impl_resource_type!(BindGroupLayout);
crate::impl_labeled!(BindGroupLayout);
crate::impl_parent_device!(BindGroupLayout);
crate::impl_storage_item!(BindGroupLayout);

impl BindGroupLayout {
    pub(crate) fn try_raw(&self) -> Result<&dyn hal::DynBindGroupLayout, InvalidResourceError> {
        let ResourceState::Valid(state) = &self.state else {
            return Err(InvalidResourceError(self.error_ident()));
        };
        match &state.raw {
            RawBindGroupLayout::Owning(raw) => Ok(raw.as_ref()),
            RawBindGroupLayout::RefDeviceEmptyBGL => Ok(self.device.empty_bgl.as_ref()),
        }
    }

    pub(crate) fn state(&self) -> Result<&BindGroupLayoutState, InvalidResourceError> {
        let ResourceState::Valid(state) = &self.state else {
            return Err(InvalidResourceError(self.error_ident()));
        };
        Ok(state)
    }

    pub(crate) fn check_is_valid(self: &Arc<Self>) -> Result<(), InvalidResourceError> {
        let ResourceState::Valid(_) = &self.state else {
            return Err(InvalidResourceError(self.error_ident()));
        };
        Ok(())
    }

    fn empty(device: &Arc<Device>, exclusive_pipeline: ExclusivePipeline) -> Arc<Self> {
        Arc::new(Self {
            state: ResourceState::Valid(BindGroupLayoutState {
                raw: RawBindGroupLayout::RefDeviceEmptyBGL,
                origin: bgl::Origin::Derived,
                binding_count_validator: BindingTypeMaxCountValidator::default(),
            }),
            device: device.clone(),
            entries: bgl::EntryMap::default(),
            late_sized_bindings: Vec::new(),
            exclusive_pipeline: OnceCell::from(exclusive_pipeline),
            label: String::new(),
        })
    }

    pub fn invalid(device: &Arc<Device>, label: String) -> Arc<Self> {
        Arc::new(Self {
            state: ResourceState::Invalid,
            device: device.clone(),
            entries: bgl::EntryMap::default(),
            late_sized_bindings: Vec::new(),
            exclusive_pipeline: OnceCell::from(ExclusivePipeline::None),
            label,
        })
    }
}

#[derive(Clone, Debug, Error)]
#[non_exhaustive]
pub enum CreatePipelineLayoutError {
    #[error(transparent)]
    Device(#[from] DeviceError),
    #[error(
        "Immediate data has range bound {size} which is not aligned to IMMEDIATE_DATA_ALIGNMENT ({})",
        wgt::IMMEDIATE_DATA_ALIGNMENT
    )]
    MisalignedImmediateSize { size: u32 },
    #[error(transparent)]
    MissingFeatures(#[from] MissingFeatures),
    #[error(
        "Immediate data has size {size} which exceeds device immediate data size limit 0..{max}"
    )]
    ImmediateRangeTooLarge { size: u32, max: u32 },
    #[error(transparent)]
    TooManyBindings(BindingTypeMaxCountError),
    #[error("Bind group layout count {actual} exceeds device bind group limit {max}")]
    TooManyGroups { actual: usize, max: usize },
    #[error(transparent)]
    InvalidResource(#[from] InvalidResourceError),
    #[error("Bind group layout at index {index} has an exclusive pipeline: {pipeline}")]
    BglHasExclusivePipeline { index: usize, pipeline: String },
}

impl WebGpuError for CreatePipelineLayoutError {
    fn webgpu_error_type(&self) -> ErrorType {
        match self {
            Self::Device(e) => e.webgpu_error_type(),
            Self::MissingFeatures(e) => e.webgpu_error_type(),
            Self::InvalidResource(e) => e.webgpu_error_type(),
            Self::TooManyBindings(e) => e.webgpu_error_type(),
            Self::MisalignedImmediateSize { .. }
            | Self::ImmediateRangeTooLarge { .. }
            | Self::TooManyGroups { .. }
            | Self::BglHasExclusivePipeline { .. } => ErrorType::Validation,
        }
    }
}

#[derive(Clone, Debug, Error)]
#[non_exhaustive]
pub enum ImmediateUploadError {
    #[error(
        "Provided immediate data start offset {start_offset} overruns the range with a size of {immediate_size}"
    )]
    StartOffsetOverrun {
        start_offset: u32,
        immediate_size: u32,
    },
    #[error(
        "Provided immediate data start offset {0} does not respect \
        `IMMEDIATE_DATA_ALIGNMENT` ({ida})",
        ida = wgt::IMMEDIATE_DATA_ALIGNMENT
    )]
    StartOffsetUnaligned(u32),
    #[error(
        "Provided immediate data byte size {0} does not respect \
        `IMMEDIATE_DATA_ALIGNMENT` ({ida})",
        ida = wgt::IMMEDIATE_DATA_ALIGNMENT
    )]
    SizeUnaligned(usize),
    #[error(
        "Provided immediate data start offset {} + size {} overruns `max_immediate_size` {}",
        start_offset,
        size_bytes,
        limit
    )]
    EndOffsetBeyondLimit {
        start_offset: u32,
        size_bytes: usize,
        limit: u32,
    },
}

impl WebGpuError for ImmediateUploadError {
    fn webgpu_error_type(&self) -> ErrorType {
        ErrorType::Validation
    }
}

/// Describes a pipeline layout.
///
/// A `PipelineLayoutDescriptor` can be used to create a pipeline layout.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(bound = "BGL: Serialize"))]
/// cbindgen:ignore
pub struct PipelineLayoutDescriptor<'a, BGL = Arc<BindGroupLayout>>
where
    [Option<BGL>]: ToOwned,
    <[Option<BGL>] as ToOwned>::Owned: fmt::Debug,
{
    /// Debug label of the pipeline layout.
    ///
    /// This will show up in graphics debuggers for easy identification.
    pub label: Label<'a>,
    /// Bind groups that this pipeline uses. The first entry will provide all the bindings for
    /// "set = 0", second entry will provide all the bindings for "set = 1" etc.
    #[cfg_attr(
        feature = "serde",
        serde(bound(deserialize = "<[Option<BGL>] as ToOwned>::Owned: Deserialize<'de>"))
    )]
    pub bind_group_layouts: Cow<'a, [Option<BGL>]>,
    /// The number of bytes of immediate data that are allocated for use
    /// in the shader. The `var<immediate>`s in the shader attached to
    /// this pipeline must be equal or smaller than this size.
    ///
    /// If this value is non-zero, [`wgt::Features::IMMEDIATES`] must be enabled.
    pub immediate_size: u32,
}

#[derive(Debug)]
pub struct PipelineLayout {
    pub(crate) raw: ResourceState<Box<dyn hal::DynPipelineLayout>>,
    pub(crate) device: Arc<Device>,
    /// The `label` from the descriptor used to create the resource.
    pub(crate) label: String,
    pub(crate) bind_group_layouts: ArrayVec<Option<Arc<BindGroupLayout>>, { hal::MAX_BIND_GROUPS }>,
    pub(crate) immediate_size: u32,
    pub(crate) buffers_and_acceleration_structures_in_vertex_stage: u32,
}

impl Drop for PipelineLayout {
    #[allow(trivial_casts)]
    fn drop(&mut self) {
        profiling::scope!("PipelineLayout::drop");
        api_log!("PipelineLayout::drop {:?}", self as *const _);
        resource_log!("Destroy raw {}", self.error_ident());
        if let ResourceState::Valid(raw) = core::mem::replace(&mut self.raw, ResourceState::Invalid)
        {
            unsafe {
                self.device.raw().destroy_pipeline_layout(raw);
            }
        }
        #[cfg(feature = "trace")]
        {
            if let Some(t) = self.device.trace.lock().as_mut() {
                t.add(crate::device::trace::Action::DropPipelineLayout(unsafe {
                    crate::device::trace::to_trace(self)
                }));
            }
        }
    }
}

impl PipelineLayout {
    pub(crate) fn raw(&self) -> Result<&dyn hal::DynPipelineLayout, InvalidResourceError> {
        self.raw
            .as_ref()
            .valid()
            .map(|r| r.as_ref())
            .ok_or_else(|| InvalidResourceError(self.error_ident()))
    }

    pub(crate) fn check_valid(&self) -> Result<(), InvalidResourceError> {
        self.raw
            .as_ref()
            .valid()
            .map(|_| ())
            .ok_or_else(|| InvalidResourceError(self.error_ident()))
    }

    pub(crate) fn get_bind_group_layout(
        self: &Arc<Self>,
        index: u32,
        exclusive_pipeline_for_empty_bgl: ExclusivePipeline,
    ) -> Result<Arc<BindGroupLayout>, GetBindGroupLayoutError> {
        let max_bind_groups = self.device.limits.max_bind_groups;
        if index >= max_bind_groups {
            return Err(GetBindGroupLayoutError::IndexOutOfRange {
                index,
                max: max_bind_groups,
            });
        }
        Ok(self
            .bind_group_layouts
            .get(index as usize)
            .cloned()
            .flatten()
            .unwrap_or_else(|| {
                BindGroupLayout::empty(&self.device, exclusive_pipeline_for_empty_bgl)
            }))
    }

    pub(crate) fn get_bgl_entry(
        &self,
        group: u32,
        binding: u32,
    ) -> Option<&wgt::BindGroupLayoutEntry> {
        let bgl = self.bind_group_layouts.get(group as usize)?;
        let bgl = bgl.as_ref()?;
        bgl.entries.get(binding)
    }

    pub(crate) fn invalid(device: Arc<Device>, label: String) -> Arc<Self> {
        Arc::new(Self {
            raw: ResourceState::Invalid,
            device,
            label,
            bind_group_layouts: ArrayVec::new(),
            immediate_size: 0,
            buffers_and_acceleration_structures_in_vertex_stage: 0,
        })
    }
}

crate::impl_resource_type!(PipelineLayout);
crate::impl_labeled!(PipelineLayout);
crate::impl_parent_device!(PipelineLayout);
crate::impl_storage_item!(PipelineLayout);

#[repr(C)]
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct BufferBinding<B = Arc<Buffer>> {
    pub buffer: B,
    pub offset: wgt::BufferAddress,

    /// Size of the binding. If `None`, the binding spans from `offset` to the
    /// end of the buffer.
    ///
    /// We use `BufferAddress` to allow a size of zero on this `wgpu_core` type,
    /// because JavaScript bindings cannot readily express `Option<NonZeroU64>`.
    /// The `wgpu` API uses `Option<BufferSize>` (i.e. `NonZeroU64`) for this
    /// field.
    pub size: Option<wgt::BufferAddress>,
}

// Note: Duplicated in `wgpu-rs` as `BindingResource`
// They're different enough that it doesn't make sense to share a common type
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum BindingResource<
    'a,
    B = Arc<Buffer>,
    S = Arc<Sampler>,
    TV = Arc<TextureView>,
    TLAS = Arc<Tlas>,
    ET = Arc<ExternalTexture>,
> where
    [BufferBinding<B>]: ToOwned,
    [S]: ToOwned,
    [TV]: ToOwned,
    [TLAS]: ToOwned,
    <[BufferBinding<B>] as ToOwned>::Owned: fmt::Debug,
    <[S] as ToOwned>::Owned: fmt::Debug,
    <[TV] as ToOwned>::Owned: fmt::Debug,
    <[TLAS] as ToOwned>::Owned: fmt::Debug,
{
    Buffer(BufferBinding<B>),
    #[cfg_attr(
        feature = "serde",
        serde(bound(deserialize = "<[BufferBinding<B>] as ToOwned>::Owned: Deserialize<'de>"))
    )]
    BufferArray(Cow<'a, [BufferBinding<B>]>),
    Sampler(S),
    #[cfg_attr(
        feature = "serde",
        serde(bound(deserialize = "<[S] as ToOwned>::Owned: Deserialize<'de>"))
    )]
    SamplerArray(Cow<'a, [S]>),
    TextureView(TV),
    #[cfg_attr(
        feature = "serde",
        serde(bound(deserialize = "<[TV] as ToOwned>::Owned: Deserialize<'de>"))
    )]
    TextureViewArray(Cow<'a, [TV]>),
    AccelerationStructure(TLAS),
    #[cfg_attr(
        feature = "serde",
        serde(bound(deserialize = "<[TLAS] as ToOwned>::Owned: Deserialize<'de>"))
    )]
    AccelerationStructureArray(Cow<'a, [TLAS]>),
    ExternalTexture(ET),
}

#[derive(Clone, Debug, Error)]
#[non_exhaustive]
pub enum BindError {
    #[error(
        "Dynamic offsets not expected with null bind group at index {group}. However {actual} dynamic offset{s1} were provided.",
        s1 = if *.actual >= 2 { "s" } else { "" },
    )]
    DynamicOffsetCountNotZero { group: u32, actual: usize },
    #[error(
        "{bind_group} at index {group} expects {expected} dynamic offset{s0}, but {actual} dynamic offset{s1} {to_be} provided",
        s0 = if *.expected >= 2 { "s" } else { "" },
        s1 = if *.actual >= 2 { "s" } else { "" },
        to_be = if *.actual == 1 { "was" } else { "were" },
    )]
    MismatchedDynamicOffsetCount {
        bind_group: ResourceErrorIdent,
        group: u32,
        actual: usize,
        expected: usize,
    },
    #[error(
        "Dynamic binding index {idx} (targeting {bind_group} {group}, binding {binding}) with value {offset}, does not respect device's requested `{limit_name}` limit: {alignment}"
    )]
    UnalignedDynamicBinding {
        bind_group: ResourceErrorIdent,
        idx: usize,
        group: u32,
        binding: u32,
        offset: u32,
        alignment: u32,
        limit_name: &'static str,
    },
    #[error(
        "Dynamic binding offset index {idx} with offset {offset} would overrun the buffer bound to {bind_group} {group} -> binding {binding}. \
         Buffer size is {buffer_size} bytes, the binding binds bytes {binding_range:?}, meaning the maximum the binding can be offset is {maximum_dynamic_offset} bytes",
    )]
    DynamicBindingOutOfBounds {
        bind_group: ResourceErrorIdent,
        idx: usize,
        group: u32,
        binding: u32,
        offset: u32,
        buffer_size: wgt::BufferAddress,
        binding_range: Range<wgt::BufferAddress>,
        maximum_dynamic_offset: wgt::BufferAddress,
    },
}

impl WebGpuError for BindError {
    fn webgpu_error_type(&self) -> ErrorType {
        ErrorType::Validation
    }
}

#[derive(Debug)]
pub struct BindGroupDynamicBindingData {
    /// The index of the binding.
    ///
    /// Used for more descriptive errors.
    pub(crate) binding_idx: u32,
    /// The size of the buffer.
    ///
    /// Used for more descriptive errors.
    pub(crate) buffer_size: wgt::BufferAddress,
    /// The range that the binding covers.
    ///
    /// Used for more descriptive errors.
    pub(crate) binding_range: Range<wgt::BufferAddress>,
    /// The maximum value the dynamic offset can have before running off the end of the buffer.
    pub(crate) maximum_dynamic_offset: wgt::BufferAddress,
    /// The binding type.
    pub(crate) binding_type: wgt::BufferBindingType,
}

pub(crate) fn buffer_binding_type_alignment(
    limits: &wgt::Limits,
    binding_type: wgt::BufferBindingType,
) -> (u32, &'static str) {
    match binding_type {
        wgt::BufferBindingType::Uniform => (
            limits.min_uniform_buffer_offset_alignment,
            "min_uniform_buffer_offset_alignment",
        ),
        wgt::BufferBindingType::Storage { .. } => (
            limits.min_storage_buffer_offset_alignment,
            "min_storage_buffer_offset_alignment",
        ),
    }
}

pub(crate) fn buffer_binding_type_bounds_check_alignment(
    alignments: &hal::Alignments,
    binding_type: wgt::BufferBindingType,
) -> wgt::BufferAddress {
    match binding_type {
        wgt::BufferBindingType::Uniform => alignments.uniform_bounds_check_alignment.get(),
        wgt::BufferBindingType::Storage { .. } => wgt::COPY_BUFFER_ALIGNMENT,
    }
}

#[derive(Debug)]
pub(crate) struct BindGroupState {
    pub(crate) raw: Snatchable<Box<dyn hal::DynBindGroup>>,
}

#[derive(Debug)]
pub struct BindGroup {
    pub(crate) state: ResourceState<BindGroupState>,
    pub(crate) device: Arc<Device>,
    pub(crate) layout: Arc<BindGroupLayout>,
    /// The `label` from the descriptor used to create the resource.
    pub(crate) label: String,
    pub(crate) tracking_data: TrackingData,
    pub(crate) used: BindGroupStates,
    pub(crate) buffer_init_actions: Vec<BufferInitTrackerAction>,
    pub(crate) texture_init_actions: Vec<TextureInitTrackerAction>,
    /// INVARIANT: Sorted by binding index order.
    pub(crate) dynamic_binding_info: Vec<BindGroupDynamicBindingData>,
    /// Bound sizes of `layout.late_sized_bindings`, in the same order.
    pub(crate) late_buffer_binding_sizes: Vec<wgt::BufferSize>,
}

impl Drop for BindGroup {
    #[allow(trivial_casts)]
    fn drop(&mut self) {
        profiling::scope!("BindGroup::drop");
        api_log!("BindGroup::drop {:?}", self as *const _);
        #[cfg(feature = "trace")]
        if let Some(t) = self.device.trace.lock().as_mut() {
            use crate::device::trace::{to_trace, Action};
            t.add(Action::DropBindGroup(unsafe { to_trace(self) }));
        }
        let ResourceState::Valid(state) = &mut self.state else {
            return;
        };
        if let Some(raw) = state.raw.take() {
            resource_log!("Destroy raw {}", self.error_ident());
            unsafe {
                self.device.raw().destroy_bind_group(raw);
            }
        }
    }
}

impl BindGroup {
    pub(crate) fn try_raw<'a>(
        &'a self,
        guard: &'a SnatchGuard,
    ) -> Result<&'a dyn hal::DynBindGroup, InvalidOrDestroyedResourceError> {
        for buffer in self.used.buffers.used_resources() {
            buffer.try_raw(guard)?;
        }
        for texture in self.used.views.used_textures() {
            texture.try_raw(guard)?;
        }

        self.state()?
            .raw
            .get(guard)
            .map(|raw| raw.as_ref())
            .ok_or_else(|| DestroyedResourceError(self.error_ident()).into())
    }

    pub(crate) fn state(&self) -> Result<&BindGroupState, InvalidResourceError> {
        let ResourceState::Valid(state) = &self.state else {
            return Err(InvalidResourceError(self.error_ident()));
        };
        Ok(state)
    }

    pub(crate) fn check_is_valid(&self) -> Result<(), InvalidResourceError> {
        self.state().map(|_| ())
    }

    pub(crate) fn invalid(
        device: Arc<Device>,
        label: String,
        layout: Arc<BindGroupLayout>,
    ) -> Arc<Self> {
        Arc::new(Self {
            state: ResourceState::Invalid,
            layout,
            label,
            tracking_data: TrackingData::new(device.tracker_indices.bind_groups.clone()),
            used: BindGroupStates::new(),
            buffer_init_actions: Vec::new(),
            texture_init_actions: Vec::new(),
            dynamic_binding_info: Vec::new(),
            late_buffer_binding_sizes: Vec::new(),
            device,
        })
    }

    pub(crate) fn validate_dynamic_bindings(
        &self,
        bind_group_index: u32,
        offsets: &[wgt::DynamicOffset],
    ) -> Result<(), BindError> {
        if self.dynamic_binding_info.len() != offsets.len() {
            return Err(BindError::MismatchedDynamicOffsetCount {
                bind_group: self.error_ident(),
                group: bind_group_index,
                expected: self.dynamic_binding_info.len(),
                actual: offsets.len(),
            });
        }

        for (idx, (info, &offset)) in self
            .dynamic_binding_info
            .iter()
            .zip(offsets.iter())
            .enumerate()
        {
            let (alignment, limit_name) =
                buffer_binding_type_alignment(&self.device.limits, info.binding_type);
            if !(offset as wgt::BufferAddress).is_multiple_of(alignment as u64) {
                return Err(BindError::UnalignedDynamicBinding {
                    bind_group: self.error_ident(),
                    group: bind_group_index,
                    binding: info.binding_idx,
                    idx,
                    offset,
                    alignment,
                    limit_name,
                });
            }

            if offset as wgt::BufferAddress > info.maximum_dynamic_offset {
                return Err(BindError::DynamicBindingOutOfBounds {
                    bind_group: self.error_ident(),
                    group: bind_group_index,
                    binding: info.binding_idx,
                    idx,
                    offset,
                    buffer_size: info.buffer_size,
                    binding_range: info.binding_range.clone(),
                    maximum_dynamic_offset: info.maximum_dynamic_offset,
                });
            }
        }

        Ok(())
    }
}

crate::impl_resource_type!(BindGroup);
crate::impl_labeled!(BindGroup);
crate::impl_parent_device!(BindGroup);
crate::impl_storage_item!(BindGroup);
crate::impl_trackable!(BindGroup);

#[derive(Clone, Debug, Error)]
#[non_exhaustive]
pub enum GetBindGroupLayoutError {
    #[error("Bind group layout index {index} is greater than the device's configured `max_bind_groups` limit {max}")]
    IndexOutOfRange { index: u32, max: u32 },
    #[error(transparent)]
    InvalidResource(#[from] InvalidResourceError),
}

impl WebGpuError for GetBindGroupLayoutError {
    fn webgpu_error_type(&self) -> ErrorType {
        match self {
            Self::IndexOutOfRange { .. } => ErrorType::Validation,
            Self::InvalidResource(e) => e.webgpu_error_type(),
        }
    }
}

#[derive(Clone, Debug, Error, Eq, PartialEq)]
#[error(
    "In bind group index {group_index}, the buffer bound at binding index {binding_index} \
     is bound with size {bound_size} where the shader expects {shader_size}."
)]
pub struct LateMinBufferBindingSizeMismatch {
    pub group_index: u32,
    pub binding_index: u32,
    pub shader_size: wgt::BufferAddress,
    pub bound_size: wgt::BufferAddress,
}