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
use std::borrow::Borrow;
use std::hash::{Hash, Hasher};
use std::marker;
use std::ops::Deref;
use std::sync::Arc;

use fnv::FnvHasher;

use crate::buffer::{Buffer, BufferView};
use crate::image::texture_2d::{
    FloatSampledTexture2D, IntegerSampledTexture2D, ShadowSampledTexture2D,
    UnsignedIntegerSampledTexture2D,
};
use crate::image::texture_2d_array::{
    FloatSampledTexture2DArray, IntegerSampledTexture2DArray, ShadowSampledTexture2DArray,
    UnsignedIntegerSampledTexture2DArray,
};
use crate::image::texture_3d::{
    FloatSampledTexture3D, IntegerSampledTexture3D, UnsignedIntegerSampledTexture3D,
};
use crate::image::texture_cube::{
    FloatSampledTextureCube, IntegerSampledTextureCube, ShadowSampledTextureCube,
    UnsignedIntegerSampledTextureCube,
};
use crate::pipeline::interface_block::{InterfaceBlock, MemoryUnit};
use crate::pipeline::resources::resource_bindings_encoding::{
    BindGroupEncoding, BindGroupEncodingContext, ResourceBindingDescriptor,
};
use crate::pipeline::resources::resource_slot::IncompatibleInterface;
use crate::pipeline::resources::{
    BindGroupDescriptor, BindGroupEncoder, ResourceBindingsEncoding,
    ResourceBindingsEncodingContext, StaticResourceBindingsEncoder,
};

/// Represents a group of bindable resources that may be bound to a pipeline and are shared by all
/// invocations during the pipeline's execution.
///
/// See [RenderingContext::create_bind_group] for details on how a bind group is created.
///
/// More than one bind group may be bound to a pipeline, see
/// [GraphicsPipelineTaskBuilder::bind_resources] and
/// [GraphicsPipelineTaskBuilder::bind_resources_untyped] for details.
pub struct BindGroup<T> {
    pub(crate) internal: BindGroupInternal,
    _marker: marker::PhantomData<T>,
}

pub(crate) enum BindGroupInternal {
    Empty,
    NotEmpty {
        object_id: u64,
        context_id: u64,
        encoding: Arc<Vec<ResourceBindingDescriptor>>,
    },
}

impl<T> BindGroup<T>
where
    T: EncodeBindableResourceGroup,
{
    pub(crate) fn new(object_id: u64, context_id: u64, resources: T) -> Self {
        let mut encoding_context = BindGroupEncodingContext::new(context_id);
        let encoding = resources.encode_bindable_resource_group(&mut encoding_context);

        BindGroup {
            internal: BindGroupInternal::NotEmpty {
                object_id,
                context_id,
                encoding: Arc::new(encoding.bindings),
            },
            _marker: marker::PhantomData,
        }
    }
}

impl BindGroup<()> {
    pub const fn empty() -> Self {
        BindGroup {
            internal: BindGroupInternal::Empty,
            _marker: marker::PhantomData,
        }
    }
}

impl<T> PartialEq for BindGroup<T> {
    fn eq(&self, other: &Self) -> bool {
        match &self.internal {
            BindGroupInternal::Empty => {
                if let BindGroupInternal::Empty = &other.internal {
                    true
                } else {
                    false
                }
            }
            BindGroupInternal::NotEmpty { object_id, .. } => {
                if let BindGroupInternal::NotEmpty {
                    object_id: other_object_id,
                    ..
                } = &other.internal
                {
                    object_id == other_object_id
                } else {
                    false
                }
            }
        }
    }
}

impl<T> Hash for BindGroup<T> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        match &self.internal {
            BindGroupInternal::Empty => 0.hash(state),
            BindGroupInternal::NotEmpty { object_id, .. } => object_id.hash(state),
        }
    }
}

/// A minimal description of the resource binding slots used by a pipeline.
///
/// This type only contains the minimally necessary information for initializing a pipeline. See
/// also [TypedResourceBindingsLayoutDescriptor] for a type that includes information that may be
/// type checked against the resource types defined by the pipeline's shader stages.
#[derive(Clone, Debug)]
pub struct ResourceBindingsLayoutDescriptor {
    layout: Vec<LayoutElement>,
    bind_groups: usize,
}

impl ResourceBindingsLayoutDescriptor {
    /// A collection of descriptors for the bind group layouts associated with the resource bindings
    /// layout.
    ///
    /// See also [BindGroupLayout].
    pub fn bind_groups(&self) -> BindGroupLayouts {
        BindGroupLayouts { layout: self }
    }

    pub(crate) fn key(&self) -> u64 {
        let mut hasher = FnvHasher::default();

        for element in self.layout.iter() {
            match element {
                LayoutElement::Slot(descriptor) => descriptor.hash(&mut hasher),
                LayoutElement::NextBindGroup(element) => element.bind_group_index.hash(&mut hasher),
            }
        }

        hasher.finish()
    }
}

#[derive(Clone, Debug)]
enum LayoutElement {
    Slot(ResourceSlotDescriptor),
    NextBindGroup(BindGroupElement),
}

#[derive(Clone, Debug)]
struct BindGroupElement {
    bind_group_index: u32,
    len: usize,
}

/// Returned from [ResourceBindingsLayoutDescriptor::bind_groups], a collection of bind group
/// layouts associated with a [ResourceBindingsLayoutDescriptor].
#[derive(Clone, Copy)]
pub struct BindGroupLayouts<'a> {
    layout: &'a ResourceBindingsLayoutDescriptor,
}

impl<'a> BindGroupLayouts<'a> {
    /// The number of bind group layouts associated with the [ResourceBindingsLayoutDescriptor].
    pub fn len(&self) -> usize {
        self.layout.bind_groups
    }

    /// Returns an iterator of the bind group associated with the
    /// [ResourceBindingsLayoutDescriptor].
    pub fn iter(&self) -> BindGroupLayoutsIter {
        BindGroupLayoutsIter {
            layout: &self.layout.layout,
            cursor: 0,
            len: self.layout.bind_groups,
        }
    }
}

impl<'a> IntoIterator for BindGroupLayouts<'a> {
    type Item = BindGroupLayout<'a>;
    type IntoIter = BindGroupLayoutsIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        BindGroupLayoutsIter {
            layout: &self.layout.layout,
            cursor: 0,
            len: self.layout.bind_groups,
        }
    }
}

/// Returned from [BindGroupLayouts::iter], an iterator over the bind group layouts associated with
/// a [ResourceBindingsLayoutDescriptor].
pub struct BindGroupLayoutsIter<'a> {
    layout: &'a [LayoutElement],
    cursor: usize,
    len: usize,
}

impl<'a> Iterator for BindGroupLayoutsIter<'a> {
    type Item = BindGroupLayout<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        self.layout.get(self.cursor).map(|element| {
            if let LayoutElement::NextBindGroup(element) = element {
                let start = self.cursor as usize + 1;
                let end = start + element.len;

                self.cursor = end;
                self.len -= 1;

                BindGroupLayout {
                    slots: &self.layout[start..end],
                    bind_group_index: element.bind_group_index,
                }
            } else {
                unreachable!()
            }
        })
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.len, Some(self.len))
    }
}

impl<'a> ExactSizeIterator for BindGroupLayoutsIter<'a> {
    fn len(&self) -> usize {
        self.len
    }
}

/// Describes the layout for a bind group at a specific bind group index in a
/// [ResourceBindingsLayoutDescriptor].
pub struct BindGroupLayout<'a> {
    slots: &'a [LayoutElement],
    bind_group_index: u32,
}

impl<'a> BindGroupLayout<'a> {
    /// The bind group index for the bind group.
    pub fn bind_group_index(&self) -> u32 {
        self.bind_group_index
    }

    /// A collection of descriptors for the resource slots associated with the bind group.
    ///
    /// See also [ResourceSlotDescriptor].
    pub fn slots(&self) -> BindGroupLayoutSlots {
        BindGroupLayoutSlots { slots: self.slots }
    }
}

/// Returned from [BindGroupLayout::slots], represents the resource slots associated with the
/// bind group layout.
pub struct BindGroupLayoutSlots<'a> {
    slots: &'a [LayoutElement],
}

impl<'a> BindGroupLayoutSlots<'a> {
    /// Number of resource slots associated with the bind group layout.
    pub fn len(&self) -> usize {
        self.slots.len()
    }

    /// Returns an iterator over descriptors of the resource slots associated with the bind group
    /// layout.
    pub fn iter(&self) -> BindGroupLayoutSlotsIter {
        BindGroupLayoutSlotsIter {
            iter: self.slots.iter(),
        }
    }
}

impl<'a> IntoIterator for BindGroupLayoutSlots<'a> {
    type Item = &'a ResourceSlotDescriptor;
    type IntoIter = BindGroupLayoutSlotsIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        BindGroupLayoutSlotsIter {
            iter: self.slots.into_iter(),
        }
    }
}

/// Returned from [BindGroupLayoutSlots::iter], an iterator over the slots in the bind group layout.
pub struct BindGroupLayoutSlotsIter<'a> {
    iter: std::slice::Iter<'a, LayoutElement>,
}

impl<'a> Iterator for BindGroupLayoutSlotsIter<'a> {
    type Item = &'a ResourceSlotDescriptor;

    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next().map(|element| {
            if let LayoutElement::Slot(slot) = element {
                slot
            } else {
                unreachable!()
            }
        })
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

impl<'a> ExactSizeIterator for BindGroupLayoutSlotsIter<'a> {
    fn len(&self) -> usize {
        self.iter.len()
    }
}

/// Hint for a [ResourceBindingsLayoutDescriptorBuilder] that indicates how much memory is required
/// to accommodate the result.
///
/// See [ResourceBindingsLayoutDescriptorBuilder::new].
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct LayoutAllocationHint {
    /// The number of bind groups the layout will declare.
    pub bind_groups: usize,

    /// The total number of resource slots the layout will declare across all bind groups.
    pub total_resource_slots: usize,
}

/// Enumerates the errors that may occur when building a [ResourceBindingsLayoutDescriptor].
///
/// See [ResourceBindingsLayoutDescriptorBuilder].
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ResourceBindingsLayoutBuilderError {
    InvalidBindGroupSequence(InvalidBindGroupSequence),
    InvalidResourceSlotSequence(InvalidResourceSlotSequence),
}

impl From<InvalidBindGroupSequence> for ResourceBindingsLayoutBuilderError {
    fn from(err: InvalidBindGroupSequence) -> Self {
        ResourceBindingsLayoutBuilderError::InvalidBindGroupSequence(err)
    }
}

impl From<InvalidResourceSlotSequence> for ResourceBindingsLayoutBuilderError {
    fn from(err: InvalidResourceSlotSequence) -> Self {
        ResourceBindingsLayoutBuilderError::InvalidResourceSlotSequence(err)
    }
}

/// Error returned when adding bind groups to a [ResourceBindingsLayoutDescriptorBuilder] out of
/// order or when adding multiple bind groups that declare the same bind group index.
///
/// See [ResourceBindingsLayoutDescriptorBuilder::add_bind_group].
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct InvalidBindGroupSequence {
    pub current_index: u32,
    pub previous_index: u32,
}

/// Builds a [ResourceBindingsLayoutDescriptor].
///
/// # Example
///
/// ```
/// # use web_glitz::pipeline::resources::{ResourceBindingsLayoutBuilderError};
/// use web_glitz::pipeline::resources::{ResourceSlotDescriptor, ResourceBindingsLayoutBuilder, LayoutAllocationHint, ResourceSlotIdentifier, ResourceSlotKind};
///
/// let mut builder = ResourceBindingsLayoutBuilder::new(Some(LayoutAllocationHint {
///     bind_groups: 2,
///     total_resource_slots: 3,
/// }));
///
/// let resource_bindings_layout = builder
///     .add_bind_group(0)?
///         .add_resource_slot(ResourceSlotDescriptor {
///             slot_index: 0,
///             slot_identifier: ResourceSlotIdentifier::Static("buffer_0"),
///             slot_kind: ResourceSlotKind::UniformBuffer
///         })?
///         .finish()
///     .add_bind_group(1)?
///         .add_resource_slot(ResourceSlotDescriptor {
///             slot_index: 0,
///             slot_identifier: ResourceSlotIdentifier::Static("texture_0"),
///             slot_kind: ResourceSlotKind::SampledTexture
///         })?
///         .add_resource_slot(ResourceSlotDescriptor {
///             slot_index: 1,
///             slot_identifier: ResourceSlotIdentifier::Static("texture_1"),
///             slot_kind: ResourceSlotKind::SampledTexture
///         })?
///         .finish()
///     .finish();
/// # Ok::<(), ResourceBindingsLayoutBuilderError>(())
/// ```
///
/// Note that all bind groups must be added in increasing order of bind group index and no
/// 2 bind groups may declare the same bind group index (but bind group indices do not have to be
/// contiguous); all resource slots must be added to their respective bind groups in increaseing
/// order of slot index and no 2 resource slots within the same bind group may declare the same
/// slot index (but slot indices do not have to be contiguous).
pub struct ResourceBindingsLayoutBuilder {
    layout: Vec<LayoutElement>,
    last_bind_group_index: Option<u32>,
    bind_groups: usize,
}

impl ResourceBindingsLayoutBuilder {
    /// Creates a new [ResourceBindingsLayoutDescriptorBuilder].
    ///
    /// An optional [LayoutAllocationHint] to indicate to the builder how much memory should be
    /// allocated to accommodate the result. Note that providing an inaccurate hint will not result
    /// in any errors, but may result in more than 1 allocation or the allocation of extraneous
    /// memory.
    pub fn new(allocation_hint: Option<LayoutAllocationHint>) -> Self {
        let layout = if let Some(hint) = allocation_hint {
            Vec::with_capacity(hint.bind_groups + hint.total_resource_slots)
        } else {
            Vec::new()
        };

        ResourceBindingsLayoutBuilder {
            layout,
            last_bind_group_index: None,
            bind_groups: 0,
        }
    }

    /// Adds a bind group to the layout with the given `bind_group_index`.
    ///
    /// Returns a builder that may be used to add resource slots to the bind group's layout, or
    /// returns an [InvalidBindGroupIndex] error if the `bind_group_index` is not greater than the
    /// previous bind group index (if any): bind groups must be added to the layout in ascending
    /// order of bind group index and no two bind groups may declare the same bind group index.
    pub fn add_bind_group(
        mut self,
        bind_group_index: u32,
    ) -> Result<BindGroupLayoutBuilder, InvalidBindGroupSequence> {
        if let Some(last_bind_group_index) = self.last_bind_group_index {
            if bind_group_index <= last_bind_group_index {
                return Err(InvalidBindGroupSequence {
                    current_index: bind_group_index,
                    previous_index: last_bind_group_index,
                });
            }
        }

        let start = self.layout.len();

        self.layout
            .push(LayoutElement::NextBindGroup(BindGroupElement {
                bind_group_index,
                len: 0,
            }));

        self.bind_groups += 1;

        Ok(BindGroupLayoutBuilder {
            builder: self,
            bind_group_index,
            start,
            last_slot_index: None,
        })
    }

    /// Finishes this builder and returns the resulting [ResourceBindingsLayoutDescriptor].
    pub fn finish(self) -> ResourceBindingsLayoutDescriptor {
        ResourceBindingsLayoutDescriptor {
            layout: self.layout,
            bind_groups: self.bind_groups,
        }
    }
}

/// Error returned when adding resource slots to a [BindGroupLayoutBuilder] out of order or when
/// adding multiple resource slots that declare the same slot index.
///
/// See [BindGroupLayoutBuilder::add_resource_slot].
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct InvalidResourceSlotSequence {
    pub bind_group_index: u32,
    pub current_index: u32,
    pub previous_index: u32,
}

/// Returned from [ResourceBindingsLayoutDescriptorBuilder::add_bind_group], accumulates the
/// resource slot descriptors for a bind group layout description.
pub struct BindGroupLayoutBuilder {
    builder: ResourceBindingsLayoutBuilder,
    bind_group_index: u32,
    start: usize,
    last_slot_index: Option<u32>,
}

impl BindGroupLayoutBuilder {
    /// Adds a resource slot descriptor to the bind group layout.
    ///
    /// The slot index declared by the descriptor must be greater than the previous resource slot
    /// added to this builder (if any), otherwise an [InvalidResourceSlotSequence] error is
    /// returned: all resource slots must be added to the builder in ascending order of slot index
    /// and no 2 resource slots must declare the same slot index.
    pub fn add_resource_slot(
        mut self,
        descriptor: ResourceSlotDescriptor,
    ) -> Result<Self, InvalidResourceSlotSequence> {
        if let Some(last_slot_index) = self.last_slot_index {
            if descriptor.slot_index <= last_slot_index {
                return Err(InvalidResourceSlotSequence {
                    bind_group_index: self.bind_group_index,
                    current_index: descriptor.slot_index,
                    previous_index: last_slot_index,
                });
            }
        }

        self.builder.layout.push(LayoutElement::Slot(descriptor));

        Ok(self)
    }

    /// Finishes the layout for this bind group and returns the [ResourceBindingsLayoutBuilder].
    pub fn finish(mut self) -> ResourceBindingsLayoutBuilder {
        let len = self.builder.layout.len() - self.start;

        self.builder.layout[self.start] = LayoutElement::NextBindGroup(BindGroupElement {
            bind_group_index: self.bind_group_index,
            len,
        });

        self.builder
    }
}

/// A typed description of the resource binding slots used by a pipeline.
///
/// This type includes description of the exact resource type used for each resource slot, which may
/// be checked against the resource types defined by the pipeline's shader stages.
///
/// See also [ResourceBindingsLayoutDescriptor] a descriptor that only includes the minimum of
/// information necessary to initialize a pipeline.
#[derive(Clone, Debug)]
pub struct TypedResourceBindingsLayoutDescriptor {
    bind_groups: &'static [TypedBindGroupLayoutDescriptor],
}

impl TypedResourceBindingsLayoutDescriptor {
    /// Creates a new [TypedBindGroupLayoutDescriptor] contains the specified `bind_groups`.
    ///
    /// # Unsafe
    ///
    /// The bind groups must be ordered by their bind group index (see
    /// [TypedBindGroupLayoutDescriptor::bind_group_index]) in ascending order and there must not
    /// be multiple bind groups that use the same bind group index.
    pub const unsafe fn new(bind_groups: &'static [TypedBindGroupLayoutDescriptor]) -> Self {
        TypedResourceBindingsLayoutDescriptor { bind_groups }
    }

    /// Creates a new empty [TypedResourceBindingsLayoutDescriptor] without any bind groups.
    pub const fn empty() -> Self {
        TypedResourceBindingsLayoutDescriptor { bind_groups: &[] }
    }

    /// The bind groups specified for this layout.
    pub fn bind_groups(&self) -> &[TypedBindGroupLayoutDescriptor] {
        &self.bind_groups
    }

    pub(crate) fn key(&self) -> u64 {
        let mut hasher = FnvHasher::default();

        for bind_group in self.bind_groups.iter() {
            bind_group.bind_group_index.hash(&mut hasher);

            for slot in bind_group.resource_slots.iter() {
                let minimal: ResourceSlotDescriptor = slot.clone().into();

                minimal.hash(&mut hasher)
            }
        }

        hasher.finish()
    }
}

/// Describes the resource slot layout of a bind group in a [TypedResourceBindingsLayoutDescriptor].
#[derive(Clone, Debug)]
pub struct TypedBindGroupLayoutDescriptor {
    bind_group_index: u32,
    resource_slots: &'static [TypedResourceSlotDescriptor],
}

impl TypedBindGroupLayoutDescriptor {
    /// Creates a new [TypedBindGroupLayoutDescriptor] that will use the specified
    /// `bind_group_index` and defines the specified `resource_slots`.
    ///
    /// # Unsafe
    ///
    /// The resource slots must by ordered by their slot index (see
    /// [TypedResourceSlotDescriptor::slot_index]) in ascending order and there must not be 2
    /// descriptors for the same slot index.
    pub const unsafe fn new(
        bind_group_index: u32,
        resource_slots: &'static [TypedResourceSlotDescriptor],
    ) -> Self {
        TypedBindGroupLayoutDescriptor {
            bind_group_index,
            resource_slots,
        }
    }

    /// The bind group index used to attach the bind group.
    pub fn bind_group_index(&self) -> u32 {
        self.bind_group_index
    }

    /// The resource slots provided by the bind group.
    pub fn slots(&self) -> &[TypedResourceSlotDescriptor] {
        &self.resource_slots
    }
}

/// A resource bindings layout description attached to a type.
///
/// See also [TypedResourceBindingsLayoutDescriptor].
///
/// This trait becomes useful in combination with the [TypedResourceBindings] trait. If a
/// [TypedResourceBindingsLayout] is attached to a [GraphicsPipeline] (see
/// [GraphicsPipelineDescriptorBuilder::typed_resource_bindings_layout]), then
/// [TypedResourceBindings] with a matching [TypedResourceBindings::Layout] may be bound to the
/// pipeline without further runtime checks.
///
/// Note that [TypedResourceBindingsLayout] is safe to implement, but implementing
/// [TypedResourceBindings] is unsafe: the resource bindings encoded by a [TypedResourceBindings]
/// implementation must always be compatible with the bindings layout specified by its
/// [TypedResourceBindings::Layout], see [TypedResourceBindings] for details.
pub trait TypedResourceBindingsLayout {
    const LAYOUT: TypedResourceBindingsLayoutDescriptor;
}

macro_rules! implement_typed_resource_bindings_layout {
    ($($T:ident: $i:tt),*) => {
        #[allow(unused_parens)]
        impl<$($T),*> TypedResourceBindingsLayout for ($($T),*)
        where
            $($T: TypedBindGroupLayout),*
        {
            const LAYOUT: TypedResourceBindingsLayoutDescriptor = unsafe {
                TypedResourceBindingsLayoutDescriptor::new(&[
                    $(TypedBindGroupLayoutDescriptor::new($i, $T::LAYOUT)),*
                ])
            };
        }
    }
}

implement_typed_resource_bindings_layout!(T0: 0);
implement_typed_resource_bindings_layout!(T0: 0, T1: 1);
implement_typed_resource_bindings_layout!(T0: 0, T1: 1, T2: 2);
implement_typed_resource_bindings_layout!(T0: 0, T1: 1, T2: 2, T3: 3);
implement_typed_resource_bindings_layout!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4);
implement_typed_resource_bindings_layout!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5);
implement_typed_resource_bindings_layout!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6);
implement_typed_resource_bindings_layout!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7);
implement_typed_resource_bindings_layout!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8);
implement_typed_resource_bindings_layout!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8, T9: 9);
implement_typed_resource_bindings_layout!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8, T9: 9, T10: 10);
implement_typed_resource_bindings_layout!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8, T9: 9, T10: 10, T11: 11);
implement_typed_resource_bindings_layout!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8, T9: 9, T10: 10, T11: 11, T12: 12);
implement_typed_resource_bindings_layout!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8, T9: 9, T10: 10, T11: 11, T12: 12, T13: 13);
implement_typed_resource_bindings_layout!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8, T9: 9, T10: 10, T11: 11, T12: 12, T13: 13, T14: 14);
implement_typed_resource_bindings_layout!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8, T9: 9, T10: 10, T11: 11, T12: 12, T13: 13, T14: 14, T15: 15);

/// A description of the resource slot layout of a bind group, attached to a type.
///
/// See also [TypedResourceSlotDescriptor].
///
/// This trait becomes useful in combination with the [TypedBindableResourceGroup] and
/// [TypedResourceBindings] traits, the later of which is implemented for any tuple of [BindGroup]s
/// where each [BindGroup] holds resources that implement [TypedBindableResourceGroup]. If a
/// pipeline (or a tuple of such bind groups) declares a typed resource bindings layout, then a
/// (tuple of) bind group(s) with a matching resource layout may be safely bound to the pipeline
/// without additional runtime checks.
///
/// Note that [TypedBindGroupLayout] is safe to implement, but implementing
/// [TypedBindableResourceGroup] is unsafe: the resource bindings encoded by the
/// [TypedBindableResourceGroup] implementation must always be compatible with the bind group
/// layout specified by its [TypedBindableResourceGroup::Layout], see [TypedBindableResourceGroup]
/// for details.
pub trait TypedBindGroupLayout {
    const LAYOUT: &'static [TypedResourceSlotDescriptor];
}

/// A group of resources that may be used to encode a [BindGroup].
///
/// See also [RenderingContext::create_bind_group] for details on how a [BindGroup] is created.
///
/// This trait is implemented for any type that implements the [Resources] trait. The [Resources]
/// trait may automatically derived (see the documentation for the [Resources] trait for details).
///
/// # Example
///
/// ```
/// use web_glitz::buffer::{Buffer, BufferView};
/// use web_glitz::image::texture_2d::FloatSampledTexture2D;
/// use web_glitz::pipeline::resources::{EncodeBindableResourceGroup, BindGroupEncodingContext, BindGroupEncoding, BindGroupEncoder};
///
/// struct Resources<'a, 'b> {
///     uniform_buffer: &'a Buffer<std140::mat4x4>,
///     texture: FloatSampledTexture2D<'b>
/// }
///
/// impl<'a, 'b> EncodeBindableResourceGroup for Resources<'a, 'b> {
///     type Encoding = (
///         BufferView<'a, std140::mat4x4>,
///         FloatSampledTexture2D<'b>,
///     );
///
///     fn encode_bindable_resource_group(
///         self,
///         encoding_context: &mut BindGroupEncodingContext
///     ) -> BindGroupEncoding<Self::Encoding> {
///         BindGroupEncoder::new(encoding_context, Some(2))
///             .add_buffer_view(0, self.uniform_buffer.into())
///             .add_float_sampled_texture_2d(1, self.texture)
///             .finish()
///     }
/// }
/// ```
pub trait EncodeBindableResourceGroup {
    type Encoding;

    /// Encodes a description of the bindings for the resources in the group.
    fn encode_bindable_resource_group(
        self,
        encoding_context: &mut BindGroupEncodingContext,
    ) -> BindGroupEncoding<Self::Encoding>;
}

/// Sub-trait of [EncodeBindGroup], where a type statically describes the layout for the bind group.
///
/// A [BindGroup] for resources that implement this trait may be bound to pipeline's with a matching
/// typed resource bindings layout without additional runtime checks.
///
/// # Unsafe
///
/// Any instance of a type that implements this trait must encode a bind group (see
/// [EncodeBindGroup::encode_bind_group]) with a layout that matches the bind group layout declared
/// by [Layout].
pub unsafe trait TypedBindableResourceGroup: EncodeBindableResourceGroup {
    type Layout: TypedBindGroupLayout;
}

/// Encodes a description of how a set of resources is bound to a pipeline, such that the pipeline
/// may access these resources during its execution.
///
/// # Example
///
/// ```
/// use web_glitz::buffer::Buffer;
/// use web_glitz::image::texture_2d::FloatSampledTexture2D;
/// use web_glitz::pipeline::resources::{ResourceBindings, ResourceBindingsEncodingContext, ResourceBindingsEncoding, StaticResourceBindingsEncoder, BindGroup, BindGroupDescriptor};
///
/// struct Resources<T0, T1> {
///     bind_group_0: BindGroup<T0>,
///     bind_group_1: BindGroup<T1>,
/// }
///
/// impl<T0, T1> ResourceBindings for &'_ Resources<T0, T1> {
///     type BindGroups = [BindGroupDescriptor; 2];
///
///     fn encode(
///         self,
///         encoding_context: &mut ResourceBindingsEncodingContext
///     ) -> ResourceBindingsEncoding<Self::BindGroups> {
///         let encoder = StaticResourceBindingsEncoder::new(encoding_context);
///
///         let encoder = encoder.add_bind_group(0, &self.bind_group_0);
///         let encoder = encoder.add_bind_group(1, &self.bind_group_1);
///
///         encoder.finish()
///     }
/// }
/// ```
///
/// See also [StaticResourceBindingsEncoder].
///
/// Note that when multiple bindings of the same type bind to the same slot-index, then only the
/// binding that was added last will be used. However, buffer resources and texture resources belong
/// to distinct bind groups, their slot-indices do not interact.
///
/// This trait is automatically implemented for any type that derives the [Resources] trait.
pub trait ResourceBindings {
    /// Type that describes the collection of bindings.
    type BindGroups: Borrow<[BindGroupDescriptor]> + 'static;

    /// Encodes a description of how this set of resources is bound to a pipeline.
    fn encode(
        self,
        encoding_context: &mut ResourceBindingsEncodingContext,
    ) -> ResourceBindingsEncoding<Self::BindGroups>;
}

impl ResourceBindings for () {
    type BindGroups = [BindGroupDescriptor; 0];

    fn encode(
        self,
        encoding_context: &mut ResourceBindingsEncodingContext,
    ) -> ResourceBindingsEncoding<Self::BindGroups> {
        ResourceBindingsEncoding::empty(encoding_context)
    }
}

macro_rules! implement_resource_bindings {
    ($n:tt, $($T:ident: $i:tt),*) => {
        #[allow(unused_parens)]
        impl<$($T),*> ResourceBindings for ($(&'_ BindGroup<$T>),*) {
            type BindGroups = [BindGroupDescriptor; $n];

            fn encode(self, encoding_context: &mut ResourceBindingsEncodingContext) -> ResourceBindingsEncoding<Self::BindGroups> {
                let encoder = StaticResourceBindingsEncoder::new(encoding_context);

                #[allow(unused_parens, non_snake_case)]
                let ($($T),*) = self;

                $(let encoder = encoder.add_bind_group($i, $T);)*

                encoder.finish()
            }
        }
    }
}

implement_resource_bindings!(1, T0: 0);
implement_resource_bindings!(2, T0: 0, T1: 1);
implement_resource_bindings!(3, T0: 0, T1: 1, T2: 2);
implement_resource_bindings!(4, T0: 0, T1: 1, T2: 2, T3: 3);
implement_resource_bindings!(5, T0: 0, T1: 1, T2: 2, T3: 3, T4: 4);
implement_resource_bindings!(6, T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5);
implement_resource_bindings!(7, T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6);
implement_resource_bindings!(8, T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7);
implement_resource_bindings!(9, T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8);
implement_resource_bindings!(10, T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8, T9: 9);
implement_resource_bindings!(11, T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8, T9: 9, T10: 10);
implement_resource_bindings!(12, T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8, T9: 9, T10: 10, T11: 11);
implement_resource_bindings!(13, T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8, T9: 9, T10: 10, T11: 11, T12: 12);
implement_resource_bindings!(14, T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8, T9: 9, T10: 10, T11: 11, T12: 12, T13: 13);
implement_resource_bindings!(15, T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8, T9: 9, T10: 10, T11: 11, T12: 12, T13: 13, T14: 14);
implement_resource_bindings!(16, T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8, T9: 9, T10: 10, T11: 11, T12: 12, T13: 13, T14: 14, T15: 15);

/// Sub-trait of [ResourceBindings], where a type statically describes its resource bindings layout.
///
/// Resource bindings that implement this trait may be bound to graphics pipelines with a matching
/// [TypedResourceBindingsLayout] without further runtime checks.
///
/// # Unsafe
///
/// This trait must only by implemented for [ResourceBindings] types if the recourse bindings
/// encoding for any instance of the the type is guaranteed to compatible with the resource slots
/// on a pipeline that matches the [Layout].
pub unsafe trait TypedResourceBindings: ResourceBindings {
    /// A type statically associated with a resource bindings layout with which the encoding of
    /// any instance of these [TypedResourceBindings] is compatible.
    type Layout: TypedResourceBindingsLayout;
}

unsafe impl TypedResourceBindings for () {
    type Layout = ();
}

macro_rules! impl_typed_resource_bindings {
    ($($T:ident),*) => {
        #[allow(unused_parens)]
        unsafe impl<$($T),*> TypedResourceBindings for ($(&'_ BindGroup<$T>),*)
        where
            $($T: TypedBindableResourceGroup),*
        {
            #[allow(unused_parens)]
            type Layout = ($($T::Layout),*);
        }
    }
}

impl_typed_resource_bindings!(T0);
impl_typed_resource_bindings!(T0, T1);
impl_typed_resource_bindings!(T0, T1, T2);
impl_typed_resource_bindings!(T0, T1, T2, T3);
impl_typed_resource_bindings!(T0, T1, T2, T3, T4);
impl_typed_resource_bindings!(T0, T1, T2, T3, T4, T5);
impl_typed_resource_bindings!(T0, T1, T2, T3, T4, T5, T6);
impl_typed_resource_bindings!(T0, T1, T2, T3, T4, T5, T6, T7);
impl_typed_resource_bindings!(T0, T1, T2, T3, T4, T5, T6, T7, T8);
impl_typed_resource_bindings!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9);
impl_typed_resource_bindings!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10);
impl_typed_resource_bindings!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11);
impl_typed_resource_bindings!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12);
impl_typed_resource_bindings!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13);
impl_typed_resource_bindings!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14);
impl_typed_resource_bindings!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15);

/// Identifies a resource slot in a pipeline.
#[derive(Clone, Debug)]
pub enum ResourceSlotIdentifier {
    Static(&'static str),
    Dynamic(String),
}

impl From<&'static str> for ResourceSlotIdentifier {
    fn from(value: &'static str) -> Self {
        ResourceSlotIdentifier::Static(value)
    }
}

impl From<String> for ResourceSlotIdentifier {
    fn from(value: String) -> Self {
        ResourceSlotIdentifier::Dynamic(value)
    }
}

impl PartialEq for ResourceSlotIdentifier {
    fn eq(&self, other: &Self) -> bool {
        self.deref() == other.deref()
    }
}

impl Hash for ResourceSlotIdentifier {
    fn hash<H: Hasher>(&self, state: &mut H) {
        let as_str: &str = self.deref();

        as_str.hash(state);
    }
}

impl Deref for ResourceSlotIdentifier {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        match self {
            ResourceSlotIdentifier::Static(s) => s,
            ResourceSlotIdentifier::Dynamic(s) => s,
        }
    }
}

/// Describes a single resource slot in a pipeline.
///
/// See also [ResourceBindingsLayoutDescriptor].
#[derive(Clone, Hash, PartialEq, Debug)]
pub struct ResourceSlotDescriptor {
    /// The identifier for the slot.
    pub slot_identifier: ResourceSlotIdentifier,

    /// The index of the slot.
    pub slot_index: u32,

    /// The kind of resource slot.
    pub slot_kind: ResourceSlotKind,
}

impl From<TypedResourceSlotDescriptor> for ResourceSlotDescriptor {
    fn from(descriptor: TypedResourceSlotDescriptor) -> Self {
        let TypedResourceSlotDescriptor {
            slot_identifier,
            slot_index,
            slot_type,
        } = descriptor;

        ResourceSlotDescriptor {
            slot_identifier,
            slot_index,
            slot_kind: slot_type.into(),
        }
    }
}

/// Enumerates the different kinds of resource slots a pipeline can define.
///
/// See also [ResourceSlotDescriptor].
#[derive(Clone, Copy, Hash, PartialEq, Debug)]
pub enum ResourceSlotKind {
    // A WebGPU version would add `has_dynamic_offset`.
    UniformBuffer,
    // A WebGPU version would add `dimensionality`, `component_type` and `is_multisampled`.
    SampledTexture,
}

impl ResourceSlotKind {
    /// Whether or not this is a uniform buffer slot.
    pub fn is_uniform_buffer(&self) -> bool {
        if let ResourceSlotKind::UniformBuffer = self {
            true
        } else {
            false
        }
    }

    /// Whether or not this is a sampled-texture slot.
    pub fn is_sampled_texture(&self) -> bool {
        if let ResourceSlotKind::UniformBuffer = self {
            true
        } else {
            false
        }
    }
}

impl From<ResourceSlotType> for ResourceSlotKind {
    fn from(slot_type: ResourceSlotType) -> Self {
        match slot_type {
            ResourceSlotType::UniformBuffer(_) => ResourceSlotKind::UniformBuffer,
            ResourceSlotType::SampledTexture(_) => ResourceSlotKind::SampledTexture,
        }
    }
}

/// Describes a single resource slot in a pipeline and its type.
///
/// See also [TypedResourceBindingsLayoutDescriptor].
#[derive(Clone, PartialEq, Debug)]
pub struct TypedResourceSlotDescriptor {
    /// The identifier for the slot.
    pub slot_identifier: ResourceSlotIdentifier,

    /// The index of the slot.
    pub slot_index: u32,

    /// The type of the slot.
    pub slot_type: ResourceSlotType,
}

/// Enumerates the slot types for a [TypedResourceSlotDescriptor].
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum ResourceSlotType {
    /// A uniform buffer slot and its memory layout as a collection of [MemoryUnit]s.
    // A WebGPU version would add `has_dynamic_offset`.
    UniformBuffer(&'static [MemoryUnit]),
    /// A sampled-texture slot and it's [SampledTextureType].
    // A WebGPU version would add `dimensionality`, `component_type` and `is_multisampled`.
    SampledTexture(SampledTextureType),
}

/// Enumerates the types available for sampled-texture resource slot.
#[derive(Clone, Copy, Hash, PartialEq, Debug)]
pub enum SampledTextureType {
    FloatSampler2D,
    IntegerSampler2D,
    UnsignedIntegerSampler2D,
    FloatSampler2DArray,
    IntegerSampler2DArray,
    UnsignedIntegerSampler2DArray,
    FloatSampler3D,
    IntegerSampler3D,
    UnsignedIntegerSampler3D,
    FloatSamplerCube,
    IntegerSamplerCube,
    UnsignedIntegerSamplerCube,
    Sampler2DShadow,
    Sampler2DArrayShadow,
    SamplerCubeShadow,
}

/// Provides a group of resources (uniform block buffers, sampled textures) that can initialize a
/// [BindGroup].
///
/// See [RendinderingContext::create_bind_group] for details on how a [BindGroup] is created.
///
/// The resulting bind group may be bound to a pipeline, such that all pipeline invokations may
/// access these resources when the pipeline is executed. See
/// [GraphicsPipelineTaskBuilder::bind_resources] for details on how bind groups are bound to a
/// pipeline.
///
/// This type acts as an automatically derivable trait for a [TypedBindableResourceGroup] type that
/// acts as its own [TypedBindGroupLayout]. This trait is only intended to be derived automatically;
/// if your set of resources cannot be adequatly described by automatically deriving this trait,
/// rather than manually implementing this trait, instead consider manually implementing the
/// [TypedBindableResourceGroup] and [TypedBindGroupLayout] traits separately.
///
/// Note that a [BindGroup] may also be initialized from an untyped [BindableResourceGroup]. The
/// resulting bind group will be untyped and binding it to a pipeline is unsafe: you are responsible
/// for ensuring that the resources you bind match the resources expected by the shader stages of
/// the pipeline, see [GraphicsPipelineTaskBuilder::bind_resources_untyped] for details.
///
/// # Usage
///
/// The programmable stages of a pipeline may require access to various resources during pipeline
/// execution. To this end, the code for a programmable stage may define slots for such resources
/// (e.g. uniform  blocks, texture samplers):
///
/// ```glsl
/// #version 300 es
///
/// uniform sampler2D some_texture;
///
/// uniform sampler2DArray some_other_texture;
///
/// layout(std140) uniform SomeUniformBlock {
///     vec4 some_uniform;
///     mat4 some_other_uniform;
/// };
///
/// main () {
///     ...
/// }
/// ```
///
/// Note that GLSL ES 3.0 does not allow you to define your own explicit bind groups. Instead, bind
/// groups are implicitly defined for each kind of resource:
///
/// - Uniform buffers: this bind group uses bind group index `0`.
/// - Sampled textures: this bind group uses bind group index `1`.
///
/// This trait may be safely derived automatically on a type to define how specific resource
/// instances should be bound to the pipeline:
///
/// ```
/// # #![feature(const_fn, const_loop, const_if_match, const_ptr_offset_from, const_transmute, ptr_offset_from)]
/// use web_glitz::image::texture_2d::FloatSampledTexture2D;
/// use web_glitz::image::texture_2d_array::FloatSampledTexture2DArray;
/// use web_glitz::buffer::Buffer;
///
/// #[derive(web_glitz::derive::Resources)]
/// struct BufferResources<'a> {
///     #[resource(binding=0, name="SomeUniformBlock")]
///     some_uniform_block: &'a Buffer<SomeUniformBlock>,
/// }
///
/// #[derive(web_glitz::derive::Resources)]
/// struct TextureResources<'a> {
///     #[resource(binding=0)]
///     some_texture: FloatSampledTexture2D<'a>,
///
///     #[resource(binding=1, name="some_other_texture")]
///     second_texture: FloatSampledTexture2DArray<'a>,
/// }
///
/// #[std140::repr_std140]
/// #[derive(web_glitz::derive::InterfaceBlock)]
/// struct SomeUniformBlock {
///     some_uniform: std140::vec4,
///     some_other_uniform: std140::mat4x4
/// }
/// ```
///
/// Any field marked with a `#[resource(...)]` attribute defines a resource binding; unmarked fields
/// are ignored when initializing a bind group.
///
/// A `#[resource(...)]` attribute must always declare a `binding` index; for a texture this should
/// be a positive integer that is smaller than the [RenderingContext::max_texture_resource_index] of
/// the [RenderingContext] with which you intend to use the [Resources] (hardware dependent, at
/// least `32`); for a uniform buffer this should be a positive integer that is smaller than the
/// [RenderingContext::max_buffer_resource_index] for the [RenderingContext] with which you intend
/// to use the [Resources] (hardware dependent, at least `24`).
///
/// If the field name does not match the resource name used in the shader code, then the attribute
/// should also declare a `name` with a string that does match the resource name used in the shader
/// code; if the field name does match the name used in the shader, then `name` may be omitted.
///
/// The field's type must implement [Resource]; marking a field that does not implement [Resource]
/// with `#[resource(...)]` will result in a compilation error. If multiple `#[resource(...)]`
/// fields are defined, then all fields must declare a unique `binding` index; 2 or more
/// `#[resource(...)]` fields with the same `binding` index will also result in a compilation error.
pub unsafe trait Resources {
    type Encoding;

    const LAYOUT: &'static [TypedResourceSlotDescriptor];

    fn encode_bind_group(
        self,
        encoding_context: &mut BindGroupEncodingContext,
    ) -> BindGroupEncoding<Self::Encoding>;
}

impl<T> TypedBindGroupLayout for T
where
    T: Resources,
{
    const LAYOUT: &'static [TypedResourceSlotDescriptor] = T::LAYOUT;
}

impl<T> EncodeBindableResourceGroup for T
where
    T: Resources,
{
    type Encoding = T::Encoding;

    fn encode_bindable_resource_group(
        self,
        encoding_context: &mut BindGroupEncodingContext,
    ) -> BindGroupEncoding<Self::Encoding> {
        <T as Resources>::encode_bind_group(self, encoding_context)
    }
}

unsafe impl<T> TypedBindableResourceGroup for T
where
    T: Resources,
{
    type Layout = T;
}

impl TypedBindGroupLayout for () {
    const LAYOUT: &'static [TypedResourceSlotDescriptor] = &[];
}

impl EncodeBindableResourceGroup for () {
    type Encoding = ();

    fn encode_bindable_resource_group(
        self,
        encoding_context: &mut BindGroupEncodingContext,
    ) -> BindGroupEncoding<()> {
        BindGroupEncoding::empty(encoding_context)
    }
}

unsafe impl TypedBindableResourceGroup for () {
    type Layout = ();
}

/// Error returned when a [ResourceBindingsLayoutDescriptor] or
/// [TypedResourceBindingsLayoutDescriptor] does not match resource slots declared in a pipeline's
/// shader stages.
#[derive(Debug)]
pub enum IncompatibleResources {
    MissingBindGroup(u32),
    MissingResource(ResourceSlotIdentifier),
    ResourceTypeMismatch(ResourceSlotIdentifier),
    IncompatibleInterface(ResourceSlotIdentifier, IncompatibleInterface),
    SlotBindingMismatch { expected: usize, actual: usize },
}

/// Trait implemented for types that can be bound to a pipeline as a resource.
///
/// When automatically deriving the [Resources] trait, fields marked with `#[resource(...)]` must
/// implement this trait.
pub unsafe trait Resource {
    type Encoding;

    const TYPE: ResourceSlotType;

    /// Encodes a binding for this resource at the specified `slot_index`.
    fn encode<E>(
        self,
        slot_index: u32,
        encoder: BindGroupEncoder<E>,
    ) -> BindGroupEncoder<(Self::Encoding, E)>;
}

unsafe impl<'a, T> Resource for &'a Buffer<T>
where
    T: InterfaceBlock,
{
    type Encoding = BufferView<'a, T>;

    const TYPE: ResourceSlotType = ResourceSlotType::UniformBuffer(T::MEMORY_UNITS);

    fn encode<E>(
        self,
        slot_index: u32,
        encoder: BindGroupEncoder<E>,
    ) -> BindGroupEncoder<(Self::Encoding, E)> {
        encoder.add_buffer_view(slot_index, self.into())
    }
}

unsafe impl<'a, T> Resource for BufferView<'a, T>
where
    T: InterfaceBlock,
{
    type Encoding = Self;

    const TYPE: ResourceSlotType = ResourceSlotType::UniformBuffer(T::MEMORY_UNITS);

    fn encode<E>(
        self,
        slot_index: u32,
        encoder: BindGroupEncoder<E>,
    ) -> BindGroupEncoder<(Self::Encoding, E)> {
        encoder.add_buffer_view(slot_index, self)
    }
}

unsafe impl<'a> Resource for FloatSampledTexture2D<'a> {
    type Encoding = Self;

    const TYPE: ResourceSlotType =
        ResourceSlotType::SampledTexture(SampledTextureType::FloatSampler2D);

    fn encode<E>(
        self,
        slot_index: u32,
        encoder: BindGroupEncoder<E>,
    ) -> BindGroupEncoder<(Self::Encoding, E)> {
        encoder.add_float_sampled_texture_2d(slot_index, self)
    }
}

unsafe impl<'a> Resource for FloatSampledTexture2DArray<'a> {
    type Encoding = Self;

    const TYPE: ResourceSlotType =
        ResourceSlotType::SampledTexture(SampledTextureType::FloatSampler2DArray);

    fn encode<E>(
        self,
        slot_index: u32,
        encoder: BindGroupEncoder<E>,
    ) -> BindGroupEncoder<(Self::Encoding, E)> {
        encoder.add_float_sampled_texture_2d_array(slot_index, self)
    }
}

unsafe impl<'a> Resource for FloatSampledTexture3D<'a> {
    type Encoding = Self;

    const TYPE: ResourceSlotType =
        ResourceSlotType::SampledTexture(SampledTextureType::FloatSampler3D);

    fn encode<E>(
        self,
        slot_index: u32,
        encoder: BindGroupEncoder<E>,
    ) -> BindGroupEncoder<(Self::Encoding, E)> {
        encoder.add_float_sampled_texture_3d(slot_index, self)
    }
}

unsafe impl<'a> Resource for FloatSampledTextureCube<'a> {
    type Encoding = Self;

    const TYPE: ResourceSlotType =
        ResourceSlotType::SampledTexture(SampledTextureType::FloatSamplerCube);

    fn encode<E>(
        self,
        slot_index: u32,
        encoder: BindGroupEncoder<E>,
    ) -> BindGroupEncoder<(Self::Encoding, E)> {
        encoder.add_float_sampled_texture_cube(slot_index, self)
    }
}

unsafe impl<'a> Resource for IntegerSampledTexture2D<'a> {
    type Encoding = Self;

    const TYPE: ResourceSlotType =
        ResourceSlotType::SampledTexture(SampledTextureType::IntegerSampler2D);

    fn encode<E>(
        self,
        slot_index: u32,
        encoder: BindGroupEncoder<E>,
    ) -> BindGroupEncoder<(Self::Encoding, E)> {
        encoder.add_integer_sampled_texture_2d(slot_index, self)
    }
}

unsafe impl<'a> Resource for IntegerSampledTexture2DArray<'a> {
    type Encoding = Self;

    const TYPE: ResourceSlotType =
        ResourceSlotType::SampledTexture(SampledTextureType::IntegerSampler2DArray);

    fn encode<E>(
        self,
        slot_index: u32,
        encoder: BindGroupEncoder<E>,
    ) -> BindGroupEncoder<(Self::Encoding, E)> {
        encoder.add_integer_sampled_texture_2d_array(slot_index, self)
    }
}

unsafe impl<'a> Resource for IntegerSampledTexture3D<'a> {
    type Encoding = Self;

    const TYPE: ResourceSlotType =
        ResourceSlotType::SampledTexture(SampledTextureType::IntegerSampler3D);

    fn encode<E>(
        self,
        slot_index: u32,
        encoder: BindGroupEncoder<E>,
    ) -> BindGroupEncoder<(Self::Encoding, E)> {
        encoder.add_integer_sampled_texture_3d(slot_index, self)
    }
}

unsafe impl<'a> Resource for IntegerSampledTextureCube<'a> {
    type Encoding = Self;

    const TYPE: ResourceSlotType =
        ResourceSlotType::SampledTexture(SampledTextureType::IntegerSamplerCube);

    fn encode<E>(
        self,
        slot_index: u32,
        encoder: BindGroupEncoder<E>,
    ) -> BindGroupEncoder<(Self::Encoding, E)> {
        encoder.add_integer_sampled_texture_cube(slot_index, self)
    }
}

unsafe impl<'a> Resource for UnsignedIntegerSampledTexture2D<'a> {
    type Encoding = Self;

    const TYPE: ResourceSlotType =
        ResourceSlotType::SampledTexture(SampledTextureType::UnsignedIntegerSampler2D);

    fn encode<E>(
        self,
        slot_index: u32,
        encoder: BindGroupEncoder<E>,
    ) -> BindGroupEncoder<(Self::Encoding, E)> {
        encoder.add_unsigned_integer_sampled_texture_2d(slot_index, self)
    }
}

unsafe impl<'a> Resource for UnsignedIntegerSampledTexture2DArray<'a> {
    type Encoding = Self;

    const TYPE: ResourceSlotType =
        ResourceSlotType::SampledTexture(SampledTextureType::UnsignedIntegerSampler2DArray);

    fn encode<E>(
        self,
        slot_index: u32,
        encoder: BindGroupEncoder<E>,
    ) -> BindGroupEncoder<(Self::Encoding, E)> {
        encoder.add_unsigned_integer_sampled_texture_2d_array(slot_index, self)
    }
}

unsafe impl<'a> Resource for UnsignedIntegerSampledTexture3D<'a> {
    type Encoding = Self;

    const TYPE: ResourceSlotType =
        ResourceSlotType::SampledTexture(SampledTextureType::UnsignedIntegerSampler3D);

    fn encode<E>(
        self,
        slot_index: u32,
        encoder: BindGroupEncoder<E>,
    ) -> BindGroupEncoder<(Self::Encoding, E)> {
        encoder.add_unsigned_integer_sampled_texture_3d(slot_index, self)
    }
}

unsafe impl<'a> Resource for UnsignedIntegerSampledTextureCube<'a> {
    type Encoding = Self;

    const TYPE: ResourceSlotType =
        ResourceSlotType::SampledTexture(SampledTextureType::UnsignedIntegerSamplerCube);

    fn encode<E>(
        self,
        slot_index: u32,
        encoder: BindGroupEncoder<E>,
    ) -> BindGroupEncoder<(Self::Encoding, E)> {
        encoder.add_unsigned_integer_sampled_texture_cube(slot_index, self)
    }
}

unsafe impl<'a> Resource for ShadowSampledTexture2D<'a> {
    type Encoding = Self;

    const TYPE: ResourceSlotType =
        ResourceSlotType::SampledTexture(SampledTextureType::Sampler2DShadow);

    fn encode<E>(
        self,
        slot_index: u32,
        encoder: BindGroupEncoder<E>,
    ) -> BindGroupEncoder<(Self::Encoding, E)> {
        encoder.add_shadow_sampled_texture_2d(slot_index, self)
    }
}

unsafe impl<'a> Resource for ShadowSampledTexture2DArray<'a> {
    type Encoding = Self;

    const TYPE: ResourceSlotType =
        ResourceSlotType::SampledTexture(SampledTextureType::Sampler2DArrayShadow);

    fn encode<E>(
        self,
        slot_index: u32,
        encoder: BindGroupEncoder<E>,
    ) -> BindGroupEncoder<(Self::Encoding, E)> {
        encoder.add_shadow_sampled_texture_2d_array(slot_index, self)
    }
}

unsafe impl<'a> Resource for ShadowSampledTextureCube<'a> {
    type Encoding = Self;

    const TYPE: ResourceSlotType =
        ResourceSlotType::SampledTexture(SampledTextureType::SamplerCubeShadow);

    fn encode<E>(
        self,
        slot_index: u32,
        encoder: BindGroupEncoder<E>,
    ) -> BindGroupEncoder<(Self::Encoding, E)> {
        encoder.add_shadow_sampled_texture_cube(slot_index, self)
    }
}