web-glitz 0.3.0

Rusty low-level web-graphics library on top of WebGL 2.0.
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
use std::cell::Cell;
use std::cmp;
use std::hash::{Hash, Hasher};

use crate::image::format::{
    DepthRenderable, DepthStencilRenderable, FloatRenderable, IntegerRenderable, Multisamplable,
    Multisample, RenderbufferFormat, StencilRenderable, TextureFormat, UnsignedIntegerRenderable,
};
use crate::image::renderbuffer::Renderbuffer;
use crate::image::texture_2d::LevelMut as Texture2DLevelMut;
use crate::image::texture_2d_array::LevelLayerMut as Texture2DArrayLevelLayerMut;
use crate::image::texture_3d::LevelLayerMut as Texture3DLevelLayerMut;
use crate::image::texture_cube::LevelFaceMut as TextureCubeLevelFaceMut;
use crate::rendering::attachment::AttachmentData;
use crate::rendering::load_op::LoadAction;
use crate::rendering::{
    AsAttachment, AsMultisampleAttachment, ColorBufferEncoding, ColorBufferEncodingContext,
    DepthAttachment, DepthStencilAttachment, DepthStencilBufferEncoding,
    DepthStencilBufferEncodingContext, EncodeColorBuffer, EncodeDepthStencilBuffer,
    EncodeMultisampleColorBuffer, EncodeMultisampleDepthStencilBuffer, FloatAttachment,
    Framebuffer, GraphicsPipelineTarget, IntegerAttachment, LoadOp, MultisampleFramebuffer,
    RenderPass, RenderPassContext, StencilAttachment, StoreOp, UnsignedIntegerAttachment,
};
use crate::runtime::single_threaded::ObjectIdGen;
use crate::runtime::state::{AttachmentSet, DepthStencilAttachmentDescriptor, DrawBuffer};
use crate::task::{ContextId, GpuTask};

/// Marker trait for image reference types that may be attached to a [RenderTargetDescriptor] as a
/// floating point color attachment.
///
/// See [RenderTargetDescriptor::attach_color_float] for details.
pub unsafe trait AttachColorFloat: AsAttachment {}

unsafe impl<'a, T> AttachColorFloat for &'a mut T where T: AttachColorFloat {}

unsafe impl<'a, F> AttachColorFloat for Texture2DLevelMut<'a, F> where
    F: TextureFormat + FloatRenderable
{
}

unsafe impl<'a, F> AttachColorFloat for Texture2DArrayLevelLayerMut<'a, F> where
    F: TextureFormat + FloatRenderable
{
}

unsafe impl<'a, F> AttachColorFloat for Texture3DLevelLayerMut<'a, F> where
    F: TextureFormat + FloatRenderable
{
}

unsafe impl<'a, F> AttachColorFloat for TextureCubeLevelFaceMut<'a, F> where
    F: TextureFormat + FloatRenderable
{
}

unsafe impl<F> AttachColorFloat for Renderbuffer<F> where
    F: RenderbufferFormat + FloatRenderable + 'static
{
}

/// Marker trait for image reference types that may be attached to a [RenderTargetDescriptor] as an
/// integer color attachment.
///
/// See [RenderTargetDescriptor::attach_color_integer] for details.
pub unsafe trait AttachColorInteger: AsAttachment {}

unsafe impl<'a, T> AttachColorInteger for &'a mut T where T: AttachColorInteger {}

unsafe impl<'a, F> AttachColorInteger for Texture2DLevelMut<'a, F> where
    F: TextureFormat + IntegerRenderable
{
}

unsafe impl<'a, F> AttachColorInteger for Texture2DArrayLevelLayerMut<'a, F> where
    F: TextureFormat + IntegerRenderable
{
}

unsafe impl<'a, F> AttachColorInteger for Texture3DLevelLayerMut<'a, F> where
    F: TextureFormat + IntegerRenderable
{
}

unsafe impl<'a, F> AttachColorInteger for TextureCubeLevelFaceMut<'a, F> where
    F: TextureFormat + IntegerRenderable
{
}

unsafe impl<F> AttachColorInteger for Renderbuffer<F> where
    F: RenderbufferFormat + IntegerRenderable + 'static
{
}

/// Marker trait for image reference types that may be attached to a [RenderTargetDescriptor] as an
/// unsigned integer color attachment.
///
/// See [RenderTargetDescriptor::attach_color_unsigned_integer] for details.
pub unsafe trait AttachColorUnsignedInteger: AsAttachment {}

unsafe impl<'a, T> AttachColorUnsignedInteger for &'a mut T where T: AttachColorUnsignedInteger {}

unsafe impl<'a, F> AttachColorUnsignedInteger for Texture2DLevelMut<'a, F> where
    F: TextureFormat + UnsignedIntegerRenderable
{
}

unsafe impl<'a, F> AttachColorUnsignedInteger for Texture2DArrayLevelLayerMut<'a, F> where
    F: TextureFormat + UnsignedIntegerRenderable
{
}

unsafe impl<'a, F> AttachColorUnsignedInteger for Texture3DLevelLayerMut<'a, F> where
    F: TextureFormat + UnsignedIntegerRenderable
{
}

unsafe impl<'a, F> AttachColorUnsignedInteger for TextureCubeLevelFaceMut<'a, F> where
    F: TextureFormat + UnsignedIntegerRenderable
{
}

unsafe impl<F> AttachColorUnsignedInteger for Renderbuffer<F> where
    F: RenderbufferFormat + UnsignedIntegerRenderable + 'static
{
}

/// Marker trait for image reference types that may be attached to a [RenderTargetDescriptor] as a
/// depth-stencil attachment.
///
/// See [RenderTargetDescriptor::attach_depth_stencil] for details.
pub unsafe trait AttachDepthStencil: AsAttachment {}

unsafe impl<'a, T> AttachDepthStencil for &'a mut T where T: AttachDepthStencil {}

unsafe impl<'a, F> AttachDepthStencil for Texture2DLevelMut<'a, F> where
    F: TextureFormat + DepthStencilRenderable
{
}

unsafe impl<'a, F> AttachDepthStencil for Texture2DArrayLevelLayerMut<'a, F> where
    F: TextureFormat + DepthStencilRenderable
{
}

unsafe impl<'a, F> AttachDepthStencil for Texture3DLevelLayerMut<'a, F> where
    F: TextureFormat + DepthStencilRenderable
{
}

unsafe impl<'a, F> AttachDepthStencil for TextureCubeLevelFaceMut<'a, F> where
    F: TextureFormat + DepthStencilRenderable
{
}

unsafe impl<F> AttachDepthStencil for Renderbuffer<F> where
    F: RenderbufferFormat + DepthStencilRenderable + 'static
{
}

/// Marker trait for image reference types that may be attached to a [RenderTargetDescriptor] as a
/// depth attachment.
///
/// See [RenderTargetDescriptor::attach_depth] for details.
pub unsafe trait AttachDepth: AsAttachment {}

unsafe impl<'a, T> AttachDepth for &'a mut T where T: AttachDepth {}

unsafe impl<'a, F> AttachDepth for Texture2DLevelMut<'a, F> where F: TextureFormat + DepthRenderable {}

unsafe impl<'a, F> AttachDepth for Texture2DArrayLevelLayerMut<'a, F> where
    F: TextureFormat + DepthRenderable
{
}

unsafe impl<'a, F> AttachDepth for Texture3DLevelLayerMut<'a, F> where
    F: TextureFormat + DepthRenderable
{
}

unsafe impl<'a, F> AttachDepth for TextureCubeLevelFaceMut<'a, F> where
    F: TextureFormat + DepthRenderable
{
}

unsafe impl<F> AttachDepth for Renderbuffer<F> where
    F: RenderbufferFormat + DepthRenderable + 'static
{
}

/// Marker trait for image reference types that may be attached to a [RenderTargetDescriptor] as a
/// stencil attachment.
///
/// See [RenderTargetDescriptor::attach_stencil] for details.
pub unsafe trait AttachStencil: AsAttachment {}

unsafe impl<'a, T> AttachStencil for &'a mut T where T: AttachStencil {}

unsafe impl<'a, F> AttachStencil for Texture2DLevelMut<'a, F> where
    F: TextureFormat + StencilRenderable
{
}

unsafe impl<'a, F> AttachStencil for Texture2DArrayLevelLayerMut<'a, F> where
    F: TextureFormat + StencilRenderable
{
}

unsafe impl<'a, F> AttachStencil for Texture3DLevelLayerMut<'a, F> where
    F: TextureFormat + StencilRenderable
{
}

unsafe impl<'a, F> AttachStencil for TextureCubeLevelFaceMut<'a, F> where
    F: TextureFormat + StencilRenderable
{
}

unsafe impl<F> AttachStencil for Renderbuffer<F> where
    F: RenderbufferFormat + StencilRenderable + 'static
{
}

/// Describes a [RenderTarget] for a [RenderPass].
///
/// Zero or more color images and zero or 1 depth-stencil image(s) may be attached to the render
/// target. Together these images define a [Framebuffer] which commands in the render pass task may
/// modify: a [RenderBuffer] will be allocated in the framebuffer for each of the attached images.
/// For each attachment, the render target must also describe how image data from the image is
/// loaded into its associated render buffer before the render pass, and how image data from the
/// render buffer is stored back into the image after the render pass.
///
/// See also [RenderingContext::create_render_target] and
/// [RenderingContext::try_create_render_target] for details on how a [RenderTargetDescriptor] may
/// be used to initialize a [RenderTarget].
///
/// # Examples
///
/// The following example constructs a [RenderTargetDescriptor] with one color attachment:
///
/// ```
/// # use web_glitz::runtime::RenderingContext;
/// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext {
/// use web_glitz::image::format::RGBA8;
/// use web_glitz::image::renderbuffer::RenderbufferDescriptor;
/// use web_glitz::rendering::{RenderTargetDescriptor, LoadOp, StoreOp};
///
/// let mut color_image = context.create_renderbuffer(&RenderbufferDescriptor{
///     format: RGBA8,
///     width: 500,
///     height: 500
/// });
///
/// let render_target_descriptor = RenderTargetDescriptor::new()
///     .attach_color_float(&mut color_image, LoadOp::Load, StoreOp::Store);
/// # }
/// ```
///
/// We attach a [Renderbuffer] as the first (and only) color attachment that stores floating point
/// pixel data. We declare a "load operation" of `LoadOp::Load` to indicate that at the start of
/// any [RenderPass] that uses this render target, the image data currently stored in the
/// renderbuffer needs to be loaded into framebuffer. A declare a "store operation" of
/// `StoreOp::Store` to indicate that at the end of the render pass, the data in the framebuffer (as
/// modified by the render pass task) needs to be stored back into the renderbuffer. See [LoadOp]
/// and [StoreOp] for details on alternative load and store operations.
///
/// The image we attach must implement [AsAttachment], as well as the [AttachColorFloat] marker
/// trait to indicate that the image's [InternalFormat] is compatible with floating point data. You
/// may attach other image types than [Renderbuffer]s; for example, we might also use a [Texture2D]
/// level:
///
/// ```
/// # use web_glitz::runtime::RenderingContext;
///
/// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext {
/// use web_glitz::image::format::RGBA8;
/// use web_glitz::image::texture_2d::Texture2DDescriptor;
/// use web_glitz::image::MipmapLevels;
/// use web_glitz::rendering::{RenderTargetDescriptor, LoadOp, StoreOp};
///
/// let mut color_image = context.try_create_texture_2d(&Texture2DDescriptor {
///     format: RGBA8,
///     width: 500,
///     height: 500,
///     levels: MipmapLevels::Complete
/// }).unwrap();
///
/// let render_target_descriptor = RenderTargetDescriptor::new()
///     .attach_color_float(color_image.base_level_mut(), LoadOp::Load, StoreOp::Store);
/// # }
/// ```
///
/// As we use [attach_color_float] to attach the image as a floating point attachment, the
/// [RenderBuffer] that is allocated for this attachment in framebuffer will store the image data as
/// float values. Any graphics pipeline that draws to the framebuffer during the render pass must
/// output float values (rather than integer or unsigned integer values).
///
/// You may also attach color images that store integer values with [attach_color_integer] if the
/// image reference implements the [AttachColorInteger] marker trait:
///
/// ```
/// # use web_glitz::runtime::RenderingContext;
/// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext {
/// use web_glitz::image::format::RGBA8I;
/// use web_glitz::image::renderbuffer::RenderbufferDescriptor;
/// use web_glitz::rendering::{RenderTargetDescriptor, LoadOp, StoreOp};
///
/// let mut color_image = context.create_renderbuffer(&RenderbufferDescriptor{
///     format: RGBA8I,
///     width: 500,
///     height: 500
/// });
///
/// let render_target_descriptor = RenderTargetDescriptor::new()
///     .attach_color_integer(&mut color_image, LoadOp::Load, StoreOp::Store);
/// # }
/// ```
///
/// Or color images that store unsigned integer values with [attach_color_unsigned_integer] if the
/// image reference implements the [AttachColorUnsignedInteger] marker trait:
///
/// ```
/// # use web_glitz::runtime::RenderingContext;
/// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext {
/// use web_glitz::image::format::RGBA8UI;
/// use web_glitz::image::renderbuffer::RenderbufferDescriptor;
/// use web_glitz::rendering::{RenderTargetDescriptor, LoadOp, StoreOp};
///
/// let mut color_image = context.create_renderbuffer(&RenderbufferDescriptor{
///     format: RGBA8UI,
///     width: 500,
///     height: 500
/// });
///
/// let render_target_descriptor = RenderTargetDescriptor::new()
///     .attach_color_unsigned_integer(&mut color_image, LoadOp::Load, StoreOp::Store);
/// # }
/// ```
///
/// It is also possible to attach multiple color images (up to 16):
///
/// ```
/// # use web_glitz::runtime::RenderingContext;
/// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext {
/// use web_glitz::image::format::{RGBA8, RGBA8I};
/// use web_glitz::image::renderbuffer::RenderbufferDescriptor;
/// use web_glitz::rendering::{RenderTargetDescriptor, LoadOp, StoreOp};
///
/// let mut color_image_0 = context.create_renderbuffer(&RenderbufferDescriptor{
///     format: RGBA8,
///     width: 500,
///     height: 500
/// });
///
/// let mut color_image_1 = context.create_renderbuffer(&RenderbufferDescriptor{
///     format: RGBA8I,
///     width: 500,
///     height: 500
/// });
///
/// let render_target_descriptor = RenderTargetDescriptor::new()
///     .attach_color_float(&mut color_image_0, LoadOp::Load, StoreOp::Store)
///     .attach_color_integer(&mut color_image_1, LoadOp::Load, StoreOp::Store);
/// # }
/// ```
///
/// The first image that is attached will be attached to the framebuffer in color slot `0`, the
/// second image will be attached in color slot `1`, etc.
///
/// Note that a rendering context does not always support up to 16 color attachments (see
/// [RenderingContext::max_color_attachments]), but always support at least 1 color attachment.
/// Therefor, if you declare a [RenderTargetDescriptor] with only a single color attachment, you may
/// use [RenderingContext::create_render_target] to obtain a [RenderTarget]; this always succeeds.
/// However, if you declare a [RenderTargetDescriptor] with more than 1 color attachment, you must
/// use [RenderingContext::try_create_render_target] instead, which may fail with an error if the
/// number of attachments you specified exceeds [RenderingContext::max_color_attachments].
///
/// Finally, you may attach a single depth-stencil image. This may be an image that stores combined
/// depth and stencil values attached with [attach_depth_stencil] if the image reference implements
/// the [AttachDepthStencil] marker trait:
///
/// ```
/// # use web_glitz::runtime::RenderingContext;
/// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext {
/// use web_glitz::image::format::Depth24Stencil8;
/// use web_glitz::image::renderbuffer::RenderbufferDescriptor;
/// use web_glitz::rendering::{RenderTargetDescriptor, LoadOp, StoreOp};
///
/// let mut depth_stencil_image = context.create_renderbuffer(&RenderbufferDescriptor{
///     format: Depth24Stencil8,
///     width: 500,
///     height: 500
/// });
///
/// let render_target_descriptor = RenderTargetDescriptor::new()
///     .attach_depth_stencil(&mut depth_stencil_image, LoadOp::Load, StoreOp::Store);
/// # }
/// ```
///
/// Or an image that stores only depth values attached with [attach_depth] if the image reference
/// implements the [AttachDepth] marker trait:
///
/// ```
/// # use web_glitz::runtime::RenderingContext;
/// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext {
/// use web_glitz::image::format::DepthComponent24;
/// use web_glitz::image::renderbuffer::RenderbufferDescriptor;
/// use web_glitz::rendering::{RenderTargetDescriptor, LoadOp, StoreOp};
///
/// let mut depth_image = context.create_renderbuffer(&RenderbufferDescriptor{
///     format: DepthComponent24,
///     width: 500,
///     height: 500
/// });
///
/// let render_target_descriptor = RenderTargetDescriptor::new()
///     .attach_depth(&mut depth_image, LoadOp::Load, StoreOp::Store);
/// # }
/// ```
///
/// Or an image that stores only stencil values attached with [attach_stencil] if the image
/// reference implements the [AttachStencil] marker trait:
///
/// ```
/// # use web_glitz::runtime::RenderingContext;
/// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext {
/// use web_glitz::image::format::StencilIndex8;
/// use web_glitz::image::renderbuffer::RenderbufferDescriptor;
/// use web_glitz::rendering::{RenderTargetDescriptor, LoadOp, StoreOp};
///
/// let mut stencil_image = context.create_renderbuffer(&RenderbufferDescriptor{
///     format: StencilIndex8,
///     width: 500,
///     height: 500
/// });
///
/// let render_target_descriptor = RenderTargetDescriptor::new()
///     .attach_stencil(&mut stencil_image, LoadOp::Load, StoreOp::Store);
/// # }
/// ```
pub struct RenderTargetDescriptor<C, Ds> {
    pub(crate) color_attachments: C,
    pub(crate) depth_stencil_attachment: Ds,
    pub(crate) color_attachment_count: u8,
    pub(crate) context_id: RenderTargetContextId,
}

impl RenderTargetDescriptor<(), ()> {
    /// Creates a new [RenderTargetDescriptor] without any attachments.
    pub fn new() -> Self {
        RenderTargetDescriptor {
            color_attachments: (),
            depth_stencil_attachment: (),
            color_attachment_count: 0,
            context_id: RenderTargetContextId::new(),
        }
    }
}

impl<C> RenderTargetDescriptor<C, ()> {
    /// Attaches an image to the depth-stencil slot that stores combined depth and stencil values.
    ///
    /// # Example
    ///
    /// ```
    /// # use web_glitz::runtime::RenderingContext;
    /// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext {
    /// use web_glitz::image::format::Depth24Stencil8;
    /// use web_glitz::image::renderbuffer::RenderbufferDescriptor;
    /// use web_glitz::rendering::{RenderTargetDescriptor, LoadOp, StoreOp};
    ///
    /// let mut depth_stencil_image = context.create_renderbuffer(&RenderbufferDescriptor{
    ///     format: Depth24Stencil8,
    ///     width: 500,
    ///     height: 500
    /// });
    ///
    /// let render_target_descriptor = RenderTargetDescriptor::new()
    ///     .attach_depth_stencil(&mut depth_stencil_image, LoadOp::Load, StoreOp::Store);
    /// # }
    /// ```
    pub fn attach_depth_stencil<Ds>(
        self,
        mut image: Ds,
        load_op: LoadOp<(f32, i32)>,
        store_op: StoreOp,
    ) -> RenderTargetDescriptor<C, DepthStencilAttachment<Ds>>
    where
        Ds: AttachDepthStencil,
    {
        let context_id = image.as_attachment().into_data().context_id;

        RenderTargetDescriptor {
            color_attachments: self.color_attachments,
            depth_stencil_attachment: DepthStencilAttachment {
                image,
                load_op,
                store_op,
            },
            color_attachment_count: self.color_attachment_count,
            context_id: self.context_id.record("depth-stencil", context_id),
        }
    }

    /// Attaches an image to the depth-stencil slot that stores depth values.
    ///
    /// # Example
    ///
    /// ```
    /// # use web_glitz::runtime::RenderingContext;
    /// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext {
    /// use web_glitz::image::format::DepthComponent24;
    /// use web_glitz::image::renderbuffer::RenderbufferDescriptor;
    /// use web_glitz::rendering::{RenderTargetDescriptor, LoadOp, StoreOp};
    ///
    /// let mut depth_image = context.create_renderbuffer(&RenderbufferDescriptor{
    ///     format: DepthComponent24,
    ///     width: 500,
    ///     height: 500
    /// });
    ///
    /// let render_target_descriptor = RenderTargetDescriptor::new()
    ///     .attach_depth(&mut depth_image, LoadOp::Load, StoreOp::Store);
    /// # }
    /// ```
    pub fn attach_depth<Ds>(
        self,
        mut image: Ds,
        load_op: LoadOp<f32>,
        store_op: StoreOp,
    ) -> RenderTargetDescriptor<C, DepthAttachment<Ds>>
    where
        Ds: AttachDepth,
    {
        let context_id = image.as_attachment().into_data().context_id;

        RenderTargetDescriptor {
            color_attachments: self.color_attachments,
            depth_stencil_attachment: DepthAttachment {
                image,
                load_op,
                store_op,
            },
            color_attachment_count: self.color_attachment_count,
            context_id: self.context_id.record("depth-stencil", context_id),
        }
    }

    /// Attaches an image to the depth-stencil slot that stores stencil values.
    ///
    /// # Example
    ///
    /// ```
    /// # use web_glitz::runtime::RenderingContext;
    /// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext {
    /// use web_glitz::image::format::StencilIndex8;
    /// use web_glitz::image::renderbuffer::RenderbufferDescriptor;
    /// use web_glitz::rendering::{RenderTargetDescriptor, LoadOp, StoreOp};
    ///
    /// let mut stencil_image = context.create_renderbuffer(&RenderbufferDescriptor{
    ///     format: StencilIndex8,
    ///     width: 500,
    ///     height: 500
    /// });
    ///
    /// let render_target_descriptor = RenderTargetDescriptor::new()
    ///     .attach_stencil(&mut stencil_image, LoadOp::Load, StoreOp::Store);
    /// # }
    /// ```
    pub fn attach_stencil<Ds>(
        self,
        mut image: Ds,
        load_op: LoadOp<i32>,
        store_op: StoreOp,
    ) -> RenderTargetDescriptor<C, StencilAttachment<Ds>>
    where
        Ds: AttachStencil,
    {
        let context_id = image.as_attachment().into_data().context_id;

        RenderTargetDescriptor {
            color_attachments: self.color_attachments,
            depth_stencil_attachment: StencilAttachment {
                image,
                load_op,
                store_op,
            },
            color_attachment_count: self.color_attachment_count,
            context_id: self.context_id.record("depth-stencil", context_id),
        }
    }
}

macro_rules! impl_attach_render_target_color {
    ($count:tt, $label:tt, $($C:ident),*) => {
        impl<$($C,)* Ds> RenderTargetDescriptor<($($C,)*), Ds> {
            /// Attaches an image that stores floating point values to the next color slot.
            ///
            /// # Example
            ///
            /// ```
            /// # use web_glitz::runtime::RenderingContext;
            /// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext {
            /// use web_glitz::image::format::RGBA8;
            /// use web_glitz::image::renderbuffer::RenderbufferDescriptor;
            /// use web_glitz::rendering::{RenderTargetDescriptor, LoadOp, StoreOp};
            ///
            /// let mut color_image = context.create_renderbuffer(&RenderbufferDescriptor{
            ///     format: RGBA8,
            ///     width: 500,
            ///     height: 500
            /// });
            ///
            /// let render_target_descriptor = RenderTargetDescriptor::new()
            ///     .attach_color_float(&mut color_image, LoadOp::Load, StoreOp::Store);
            /// # }
            /// ```
            pub fn attach_color_float<C>(self, mut image: C, load_op: LoadOp<[f32; 4]>, store_op: StoreOp) -> RenderTargetDescriptor<($($C,)* FloatAttachment<C>,), Ds> where C: AttachColorFloat {
                let context_id = image.as_attachment().into_data().context_id;

                #[allow(non_snake_case)]
                let ($($C,)*) = self.color_attachments;

                RenderTargetDescriptor {
                    color_attachments: ($($C,)* FloatAttachment {
                        image,
                        load_op,
                        store_op
                    },),
                    depth_stencil_attachment: self.depth_stencil_attachment,
                    color_attachment_count: $count,
                    context_id: self.context_id.record($label, context_id)
                }
            }

            /// Attaches an image that stores integer values to the next color slot.
            ///
            /// # Example
            ///
            /// ```
            /// # use web_glitz::runtime::RenderingContext;
            /// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext {
            /// use web_glitz::image::format::RGBA8I;
            /// use web_glitz::image::renderbuffer::RenderbufferDescriptor;
            /// use web_glitz::rendering::{RenderTargetDescriptor, LoadOp, StoreOp};
            ///
            /// let mut color_image = context.create_renderbuffer(&RenderbufferDescriptor{
            ///     format: RGBA8I,
            ///     width: 500,
            ///     height: 500
            /// });
            ///
            /// let render_target_descriptor = RenderTargetDescriptor::new()
            ///     .attach_color_integer(&mut color_image, LoadOp::Load, StoreOp::Store);
            /// # }
            /// ```
            pub fn attach_color_integer<C>(self, mut image: C, load_op: LoadOp<[i32; 4]>, store_op: StoreOp) -> RenderTargetDescriptor<($($C,)* IntegerAttachment<C>,), Ds> where C: AttachColorInteger {
                let context_id = image.as_attachment().into_data().context_id;

                #[allow(non_snake_case)]
                let ($($C,)*) = self.color_attachments;

                RenderTargetDescriptor {
                    color_attachments: ($($C,)* IntegerAttachment {
                        image,
                        load_op,
                        store_op
                    },),
                    depth_stencil_attachment: self.depth_stencil_attachment,
                    color_attachment_count: $count,
                    context_id: self.context_id.record($label, context_id)
                }
            }

            /// Attaches an image that stores integer values to the next color slot.
            ///
            /// # Example
            ///
            /// ```
            /// # use web_glitz::runtime::RenderingContext;
            /// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext {
            /// use web_glitz::image::format::RGBA8UI;
            /// use web_glitz::image::renderbuffer::RenderbufferDescriptor;
            /// use web_glitz::rendering::{RenderTargetDescriptor, LoadOp, StoreOp};
            ///
            /// let mut color_image = context.create_renderbuffer(&RenderbufferDescriptor{
            ///     format: RGBA8UI,
            ///     width: 500,
            ///     height: 500
            /// });
            ///
            /// let render_target_descriptor = RenderTargetDescriptor::new()
            ///     .attach_color_unsigned_integer(&mut color_image, LoadOp::Load, StoreOp::Store);
            /// # }
            /// ```
            pub fn attach_color_unsigned_integer<C>(self, mut image: C, load_op: LoadOp<[u32; 4]>, store_op: StoreOp) -> RenderTargetDescriptor<($($C,)* UnsignedIntegerAttachment<C>,), Ds> where C: AttachColorUnsignedInteger {
                let context_id = image.as_attachment().into_data().context_id;

                #[allow(non_snake_case)]
                let ($($C,)*) = self.color_attachments;

                RenderTargetDescriptor {
                    color_attachments: ($($C,)* UnsignedIntegerAttachment {
                        image,
                        load_op,
                        store_op
                    },),
                    depth_stencil_attachment: self.depth_stencil_attachment,
                    color_attachment_count: $count,
                    context_id: self.context_id.record($label, context_id)
                }
            }
        }
    }
}

impl_attach_render_target_color!(1, "color 0",);
impl_attach_render_target_color!(2, "color 1", C0);
impl_attach_render_target_color!(3, "color 2", C0, C1);
impl_attach_render_target_color!(4, "color 3", C0, C1, C2);
impl_attach_render_target_color!(5, "color 4", C0, C1, C2, C3);
impl_attach_render_target_color!(6, "color 5", C0, C1, C2, C3, C4);
impl_attach_render_target_color!(7, "color 6", C0, C1, C2, C3, C4, C5);
impl_attach_render_target_color!(8, "color 7", C0, C1, C2, C3, C4, C5, C6);
impl_attach_render_target_color!(9, "color 8", C0, C1, C2, C3, C4, C5, C6, C7);
impl_attach_render_target_color!(10, "color 9", C0, C1, C2, C3, C4, C5, C6, C7, C8);
impl_attach_render_target_color!(11, "color 10", C0, C1, C2, C3, C4, C5, C6, C7, C8, C9);
impl_attach_render_target_color!(12, "color 11", C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10);
impl_attach_render_target_color!(13, "color 12", C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11);
impl_attach_render_target_color!(
    14, "color 13", C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12
);
impl_attach_render_target_color!(
    15, "color 14", C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13
);
impl_attach_render_target_color!(
    16, "color 15", C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14
);

/// Marker trait for multisample image reference types that may be attached to a
/// [MultisampleRenderTargetDescriptor] as a floating point color attachment.
///
/// See [MultisampleRenderTargetDescriptor::attach_color_float] for details.
pub unsafe trait AttachMultisampleColorFloat: AsMultisampleAttachment {}

unsafe impl<'a, T> AttachMultisampleColorFloat for &'a mut T where T: AttachMultisampleColorFloat {}

unsafe impl<F> AttachMultisampleColorFloat for Renderbuffer<Multisample<F>> where
    F: RenderbufferFormat + Multisamplable + FloatRenderable + 'static
{
}

/// Marker trait for multisample image reference types that may be attached to a
/// [MultisampleRenderTargetDescriptor] as a depth-stencil attachment.
///
/// See [MultisampleRenderTargetDescriptor::attach_depth_stencil] for details.
pub unsafe trait AttachMultisampleDepthStencil: AsMultisampleAttachment {}

unsafe impl<'a, T> AttachMultisampleDepthStencil for &'a mut T where T: AttachMultisampleDepthStencil
{}

unsafe impl<F> AttachMultisampleDepthStencil for Renderbuffer<Multisample<F>> where
    F: RenderbufferFormat + Multisamplable + DepthStencilRenderable + 'static
{
}

/// Marker trait for multisample image reference types that may be attached to a
/// [MultisampleRenderTargetDescriptor] as a depth attachment.
///
/// See [MultisampleRenderTargetDescriptor::attach_depth] for details.
pub unsafe trait AttachMultisampleDepth: AsMultisampleAttachment {}

unsafe impl<'a, T> AttachMultisampleDepth for &'a mut T where T: AttachMultisampleDepth {}

unsafe impl<F> AttachMultisampleDepth for Renderbuffer<Multisample<F>> where
    F: RenderbufferFormat + Multisamplable + DepthRenderable + 'static
{
}

/// Describes a [MultisampleRenderTarget] for a [RenderPass].
///
/// Similar to a [RenderTargetDescriptor], except in that when you initially create the descriptor,
/// you must specify the sampling grid size the render target will use:
///
/// ```
/// # use web_glitz::runtime::RenderingContext;
/// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext {
/// use web_glitz::rendering::MultisampleRenderTargetDescriptor;
///
/// let render_target_descriptor = MultisampleRenderTargetDescriptor::new(4);
/// # }
/// ```
///
/// Attaching an image that uses a different sampling grid size will cause a panic:
///
/// ```
/// # use web_glitz::runtime::RenderingContext;
/// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext {
/// use web_glitz::image::format::{Multisample, RGBA8};
/// use web_glitz::image::renderbuffer::RenderbufferDescriptor;
/// use web_glitz::rendering::{MultisampleRenderTargetDescriptor, LoadOp, StoreOp};
///
/// let mut color_image = context.try_create_multisample_renderbuffer(&RenderbufferDescriptor {
///     format: Multisample(RGBA8, 16),
///     width: 500,
///     height: 500
/// }).unwrap();
///
/// # let render_target_descriptor = MultisampleRenderTargetDescriptor::new(4);
///
/// render_target_descriptor.attach_color_float(&mut color_image, LoadOp::Load, StoreOp::Store);
///
/// // Panic! The descriptor expects images that use sampling gride of size 4, but we're trying to
/// // attach an image that uses a sampling grid size of 16!
/// # }
/// ```
///
/// In all other ways, constructing a [MultisampleRenderTargetDescriptor] is the same as
/// constructing a [RenderTargetDescriptor]; please refer to the documentation for
/// [RenderTargetDescriptor] for more examples and details on the attachment types.
pub struct MultisampleRenderTargetDescriptor<C, Ds> {
    pub(crate) color_attachments: C,
    pub(crate) depth_stencil_attachment: Ds,
    pub(crate) samples: u8,
    pub(crate) color_attachment_count: u8,
    pub(crate) context_id: RenderTargetContextId,
}

impl MultisampleRenderTargetDescriptor<(), ()> {
    /// Creates a new [MultisampleRenderTargetDescriptor] that expects it attachments to use a
    /// sampling grid size of `samples`.
    pub fn new(samples: u8) -> Self {
        MultisampleRenderTargetDescriptor {
            color_attachments: (),
            depth_stencil_attachment: (),
            samples,
            color_attachment_count: 0,
            context_id: RenderTargetContextId::new(),
        }
    }
}

impl<C> MultisampleRenderTargetDescriptor<C, ()> {
    /// Attaches an image to the depth-stencil slot that stores combined depth and stencil values.
    ///
    /// # Example
    ///
    /// ```
    /// # use web_glitz::runtime::RenderingContext;
    /// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext {
    /// use web_glitz::image::format::{Depth24Stencil8, Multisample};
    /// use web_glitz::image::renderbuffer::RenderbufferDescriptor;
    /// use web_glitz::rendering::{MultisampleRenderTargetDescriptor, LoadOp, StoreOp};
    ///
    /// let mut depth_stencil_image = context.try_create_multisample_renderbuffer(&RenderbufferDescriptor {
    ///     format: Multisample(Depth24Stencil8, 4),
    ///     width: 500,
    ///     height: 500
    /// }).unwrap();
    ///
    /// let render_target_descriptor = MultisampleRenderTargetDescriptor::new(4)
    ///     .attach_depth_stencil(&mut depth_stencil_image, LoadOp::Load, StoreOp::Store);
    /// # }
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the sampling grid size used by the `image` does not match the sampling grid size
    /// specified for this [MultisampleRenderTargetDescriptor] (see
    /// [MultisampleRenderTargetDescriptor::new]).
    pub fn attach_depth_stencil<Ds>(
        self,
        mut image: Ds,
        load_op: LoadOp<(f32, i32)>,
        store_op: StoreOp,
    ) -> MultisampleRenderTargetDescriptor<C, DepthStencilAttachment<Ds>>
    where
        Ds: AttachMultisampleDepthStencil,
    {
        let attachment = image.as_multisample_attachment();
        let image_samples = attachment.samples();
        let context_id = attachment.into_data().context_id;

        if image_samples != self.samples {
            panic!(
                "Descriptor expects {} samples, but image uses {} samples",
                self.samples, image_samples
            );
        }

        MultisampleRenderTargetDescriptor {
            color_attachments: self.color_attachments,
            depth_stencil_attachment: DepthStencilAttachment {
                image,
                load_op,
                store_op,
            },
            samples: self.samples,
            color_attachment_count: self.color_attachment_count,
            context_id: self.context_id.record("depth-stencil", context_id),
        }
    }

    /// Attaches an image to the depth-stencil slot that stores combined depth and stencil values.
    ///
    /// # Example
    ///
    /// ```
    /// # use web_glitz::runtime::RenderingContext;
    /// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext {
    /// use web_glitz::image::format::{DepthComponent24, Multisample};
    /// use web_glitz::image::renderbuffer::RenderbufferDescriptor;
    /// use web_glitz::rendering::{MultisampleRenderTargetDescriptor, LoadOp, StoreOp};
    ///
    /// let mut depth_image = context.try_create_multisample_renderbuffer(&RenderbufferDescriptor {
    ///     format: Multisample(DepthComponent24, 4),
    ///     width: 500,
    ///     height: 500
    /// }).unwrap();
    ///
    /// let render_target_descriptor = MultisampleRenderTargetDescriptor::new(4)
    ///     .attach_depth(&mut depth_image, LoadOp::Load, StoreOp::Store);
    /// # }
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the sampling grid size used by the `image` does not match the sampling grid size
    /// specified for this [MultisampleRenderTargetDescriptor] (see
    /// [MultisampleRenderTargetDescriptor::new]).
    pub fn attach_depth<Ds>(
        self,
        mut image: Ds,
        load_op: LoadOp<f32>,
        store_op: StoreOp,
    ) -> MultisampleRenderTargetDescriptor<C, DepthAttachment<Ds>>
    where
        Ds: AttachMultisampleDepth,
    {
        let attachment = image.as_multisample_attachment();
        let image_samples = attachment.samples();
        let context_id = attachment.into_data().context_id;

        if image_samples != self.samples {
            panic!(
                "Descriptor expects {} samples, but image uses {} samples",
                self.samples, image_samples
            );
        }

        MultisampleRenderTargetDescriptor {
            color_attachments: self.color_attachments,
            depth_stencil_attachment: DepthAttachment {
                image,
                load_op,
                store_op,
            },
            samples: self.samples,
            color_attachment_count: self.color_attachment_count,
            context_id: self.context_id.record("depth-stencil", context_id),
        }
    }
}

macro_rules! impl_attach_multisample_render_target_color {
    ($count:tt, $label:tt, $($C:ident),*) => {
        impl<$($C,)* Ds> MultisampleRenderTargetDescriptor<($($C,)*), Ds> {
            /// Attaches an image that stores floating point values to the next color slot.
            ///
            /// # Example
            ///
            /// ```
            /// # use web_glitz::runtime::RenderingContext;
            /// # fn wrapper<Rc>(context: &Rc) where Rc: RenderingContext {
            /// use web_glitz::image::format::{Multisample, RGBA8};
            /// use web_glitz::image::renderbuffer::RenderbufferDescriptor;
            /// use web_glitz::rendering::{MultisampleRenderTargetDescriptor, LoadOp, StoreOp};
            ///
            /// let mut color_image = context.try_create_multisample_renderbuffer(&RenderbufferDescriptor{
            ///     format: Multisample(RGBA8, 4),
            ///     width: 500,
            ///     height: 500
            /// }).unwrap();
            ///
            /// let render_target_descriptor = MultisampleRenderTargetDescriptor::new(4)
            ///     .attach_color_float(&mut color_image, LoadOp::Load, StoreOp::Store);
            /// # }
            /// ```
            ///
            /// # Panics
            ///
            /// Panics if the sampling grid size used by the `image` does not match the sampling
            /// grid size specified for this [MultisampleRenderTargetDescriptor] (see
            /// [MultisampleRenderTargetDescriptor::new]).
            pub fn attach_color_float<C>(
                self,
                mut image: C,
                load_op: LoadOp<[f32; 4]>,
                store_op: StoreOp
            ) -> MultisampleRenderTargetDescriptor<($($C,)* FloatAttachment<C>,), Ds>
                where C: AttachMultisampleColorFloat
            {
                let attachment = image.as_multisample_attachment();
                let image_samples = attachment.samples();
                let context_id = attachment.into_data().context_id;

                if image_samples != self.samples {
                    panic!(
                        "Descriptor expects {} samples, but image uses {} samples",
                        self.samples,
                        image_samples
                    );
                }

                #[allow(non_snake_case)]
                let ($($C,)*) = self.color_attachments;

                MultisampleRenderTargetDescriptor {
                    color_attachments: ($($C,)* FloatAttachment {
                        image,
                        load_op,
                        store_op
                    },),
                    depth_stencil_attachment: self.depth_stencil_attachment,
                    samples: self.samples,
                    color_attachment_count: $count,
                    context_id: self.context_id.record($label, context_id)
                }
            }
        }
    }
}

impl_attach_multisample_render_target_color!(1, "color 0",);
impl_attach_multisample_render_target_color!(2, "color 1", C0);
impl_attach_multisample_render_target_color!(3, "color 2", C0, C1);
impl_attach_multisample_render_target_color!(4, "color 3", C0, C1, C2);
impl_attach_multisample_render_target_color!(5, "color 4", C0, C1, C2, C3);
impl_attach_multisample_render_target_color!(6, "color 5", C0, C1, C2, C3, C4);
impl_attach_multisample_render_target_color!(7, "color 6", C0, C1, C2, C3, C4, C5);
impl_attach_multisample_render_target_color!(8, "color 7", C0, C1, C2, C3, C4, C5, C6);
impl_attach_multisample_render_target_color!(9, "color 8", C0, C1, C2, C3, C4, C5, C6, C7);
impl_attach_multisample_render_target_color!(10, "color 9", C0, C1, C2, C3, C4, C5, C6, C7, C8);
impl_attach_multisample_render_target_color!(
    11, "color 10", C0, C1, C2, C3, C4, C5, C6, C7, C8, C9
);
impl_attach_multisample_render_target_color!(
    12, "color 11", C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10
);
impl_attach_multisample_render_target_color!(
    13, "color 12", C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11
);
impl_attach_multisample_render_target_color!(
    14, "color 13", C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12
);
impl_attach_multisample_render_target_color!(
    15, "color 14", C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13
);
impl_attach_multisample_render_target_color!(
    16, "color 15", C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14
);

/// Describes a target for rendering operations.
///
/// A [RenderTarget] is used to create [RenderPass] tasks, see below.
///
/// A render target consists of a collection of references to renderable images, from which image
/// data may be loaded into [Framebuffer] memory, then modified by rendering commands as part of a
/// [RenderPass], and then the modified image data may be stored back into the images. These images
/// are said to be "attached" to the render target and are referred to as its "attachments".
///
/// A [RenderTarget] may be initialized from a [RenderTargetDescriptor] with
/// [RenderingContext::create_render_target] if the descriptor declares only a single color
/// attachment, or with [RenderingContext::try_create_render_target] if the descriptor declares
/// multiple color attachments, which may fail with an error if the number of color attachments
/// exceeds [RenderingContext::max_color_attachments].
///
/// Note that the [RenderTarget] holds on to exclusive references to the images attached to it; this
/// prevents you from accidentally also binding these images as pipeline resources within the
/// [RenderPass] (attempting to read from an image while it is loaded in the framebuffer is
/// undefined behavior).
///
/// [RenderTarget]s are cheap to create (their creation does not involve any interaction with the
/// GPU backend). You are encouraged to create ephemeral [RenderTarget]s every time you want to
/// define a [RenderPass], rather than attempting to keep a [RenderTarget] alive (which is
/// cumbersome as this will keep exclusive borrows to each of the attached images alive for the
/// lifetime of the [RenderTarget]).
///
/// # Creating a render pass
///
/// A new render pass can be created by calling [create_render_pass], passing it a function that
/// takes a [Framebuffer] as its input and returns a render pass task:
///
/// ```
/// # use web_glitz::runtime::RenderingContext;
/// # fn wrapper<Rc>(
/// #     context: &Rc,
/// # )
/// # where
/// #     Rc: RenderingContext,
/// # {
/// use web_glitz::image::Region2D;
/// use web_glitz::image::format::RGBA8;
/// use web_glitz::image::renderbuffer::RenderbufferDescriptor;
/// use web_glitz::rendering::{LoadOp, StoreOp, RenderTargetDescriptor};
///
/// let mut color_image = context.create_renderbuffer(&RenderbufferDescriptor{
///     format: RGBA8,
///     width: 500,
///     height: 500
/// });
///
/// let render_target_descriptor = RenderTargetDescriptor::new()
///     .attach_color_float(&mut color_image, LoadOp::Load, StoreOp::Store);
///
/// //  Mark our render target as `mut`, as `create_render_pass` requires a `&mut` reference.
/// let mut render_target = context.create_render_target(render_target_descriptor);
///
/// let render_pass = render_target.create_render_pass(|framebuffer| {
///     // Return a task that modifies the framebuffer, see the documentation for the
///     // `Framebuffer` type for details. For this example, we'll clear the first (and only) color
///     // attachment to "opaque red".
///     framebuffer.color.0.clear_command([1.0, 0.0, 0.0, 1.0], Region2D::Fill)
/// });
/// # }
/// ```
///
/// Rendering output buffers will be allocated in the framebuffer for each of the color images
/// attached to the render target (if any) and for the depth-stencil image attached to the render
/// target (if any).
///
/// The function must return a [GpuTask] that can be executed in a [RenderPassContext]. This
/// function will receive a reference to the framebuffer representation associated with the
/// render target. It may use this reference to construct commands that make up that task, see
/// [Framebuffer] for details.
///
/// At the start of the render pass, the [LoadOp]s associated with each of the images attached to
/// the render target will be performed to initialize the framebuffer. Then the task returned from
/// the function is executed, which may modify the contents of the framebuffer. Finally, the
/// [StoreOp]s associated with each of the images attached to the render target will be performed to
/// store the (modified) contents of the framebuffer back to these images.
pub struct RenderTarget<C, Ds> {
    pub(crate) color_attachments: C,
    pub(crate) depth_stencil_attachment: Ds,
    pub(crate) object_id: u64,
    pub(crate) context_id: u64,
    pub(crate) render_pass_id_gen: ObjectIdGen,
}

impl<C, Ds> PartialEq for RenderTarget<C, Ds> {
    fn eq(&self, other: &Self) -> bool {
        self.object_id == other.object_id
    }
}

impl<C, Ds> Hash for RenderTarget<C, Ds> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.object_id.hash(state);
    }
}

pub struct MultisampleRenderTarget<C, Ds> {
    pub(crate) color_attachments: C,
    pub(crate) depth_stencil_attachment: Ds,
    pub(crate) samples: u8,
    pub(crate) object_id: u64,
    pub(crate) context_id: u64,
    pub(crate) render_pass_id_gen: ObjectIdGen,
}

impl<C, Ds> PartialEq for MultisampleRenderTarget<C, Ds> {
    fn eq(&self, other: &Self) -> bool {
        self.object_id == other.object_id
    }
}

impl<C, Ds> Hash for MultisampleRenderTarget<C, Ds> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.object_id.hash(state);
    }
}

macro_rules! impl_create_render_pass {
    ($C0:ident $(,$C:ident)*) => {
        #[allow(unused_parens)]
        impl<$C0 $(,$C)*> RenderTarget<($C0, $($C,)*), ()>
        where
            $C0: EncodeColorBuffer, $($C: EncodeColorBuffer,)*
        {
            /// Creates a new [RenderPass] that will output to this [RenderTarget].
            ///
            /// The `f` function will receive a reference to a [Framebuffer] with a buffer layout
            /// that matches the [RenderTarget]'s attachment layout.
            ///
            /// For details and examples on defining render passes, please refer to the struct
            /// documentation for [RenderTarget].
            ///
            /// # Panics
            ///
            /// Panics if the render pass context ID associated with the task returned from `f` does
            /// not match the ID generated for this render pass (the task returned from `f` must not
            /// contain commands that were created for a different render pass).
            #[allow(non_snake_case, unused_mut, unused_parens)]
            pub fn create_render_pass<F, T>(&mut self, f: F) -> RenderPass<T>
                where
                    F: FnOnce(&Framebuffer<($C0::Buffer, $($C::Buffer,)*), ()>) -> T,
                    T: GpuTask<RenderPassContext>
            {
                let id = self.render_pass_id_gen.next();

                let mut render_target = CustomRenderTargetData {
                    load_ops: [LoadAction::Load; 17],
                    store_ops: [StoreOp::Store; 17],
                    color_count: 0,
                    color_attachments: [
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                    ],
                    depth_stencil_attachment: DepthStencilAttachmentDescriptor::None,
                };

                let ($C0, $($C,)*) = &mut self.color_attachments;

                let mut context = ColorBufferEncodingContext {
                    render_pass_id: id,
                    buffer_index: 0,
                };

                let $C0 = $C0.encode_color_buffer(&mut context);

                let mut width = $C0.image.width;
                let mut height = $C0.image.height;

                let $C0 = {
                    let ColorBufferEncoding {
                        load_action,
                        store_op,
                        image,
                        buffer,
                        ..
                    } = $C0;

                    render_target.load_ops[0] = load_action;
                    render_target.store_ops[0] = store_op;
                    render_target.color_attachments[0] = Some(image);

                    buffer
                };

                let mut color_count = 1;

                $(
                    let mut context = ColorBufferEncodingContext {
                        render_pass_id: id,
                        buffer_index: color_count as i32,
                    };

                    let $C = $C.encode_color_buffer(&mut context);

                    width = cmp::min(width, $C.image.width);
                    height = cmp::min(height, $C.image.height);

                    let $C = {
                        let ColorBufferEncoding {
                            load_action,
                            store_op,
                            image,
                            buffer,
                            ..
                        } = $C;

                        render_target.load_ops[color_count] = load_action;
                        render_target.store_ops[color_count] = store_op;
                        render_target.color_attachments[color_count] = Some(image);

                        buffer
                    };

                    color_count += 1;
                )*

                render_target.color_count = color_count;

                let task = f(&Framebuffer {
                    color: ($C0, $($C,)*),
                    depth_stencil: (),
                    pipeline_target: GraphicsPipelineTarget {
                        dimensions: Some((width, height)),
                        context_id: self.context_id,
                        render_pass_id: id,
                        last_pipeline_task_id: Cell::new(0),
                    }
                });

                if let ContextId::Id(render_pass_id) = task.context_id() {
                    if render_pass_id != id {
                        panic!("The render pass task belongs to a different render pass.")
                    }
                }

                RenderPass {
                    id,
                    context_id: self.context_id,
                    render_target: RenderTargetData::Custom(render_target),
                    task
                }
            }
        }

        #[allow(unused_parens)]
        impl<$C0 $(,$C)*> MultisampleRenderTarget<($C0, $($C,)*), ()>
        where
            $C0: EncodeMultisampleColorBuffer $(,$C: EncodeMultisampleColorBuffer)*
        {
            /// Creates a new [RenderPass] that will output to this [MultisampleRenderTarget].
            ///
            /// The `f` function will receive a reference to a [MultisampleFramebuffer] with a
            /// buffer layout that matches the [MultisampleRenderTarget]'s attachment layout.
            ///
            /// For details and examples on defining render passes, please refer to the struct
            /// documentation for [RenderTarget].
            ///
            /// # Panics
            ///
            /// Panics if the render pass context ID associated with the task returned from `f` does
            /// not match the ID generated for this render pass (the task returned from `f` must not
            /// contain commands that were created for a different render pass).
            #[allow(non_snake_case, unused_mut, unused_parens)]
            pub fn create_render_pass<F, T>(&mut self, f: F) -> RenderPass<T>
                where
                    F: FnOnce(&MultisampleFramebuffer<($C0::Buffer, $($C::Buffer,)*), ()>) -> T,
                    T: GpuTask<RenderPassContext>
            {
                let id = self.render_pass_id_gen.next();

                let mut render_target = CustomRenderTargetData {
                    load_ops: [LoadAction::Load; 17],
                    store_ops: [StoreOp::Store; 17],
                    color_count: 0,
                    color_attachments: [
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                    ],
                    depth_stencil_attachment: DepthStencilAttachmentDescriptor::None,
                };

                let ($C0, $($C,)*) = &mut self.color_attachments;

                let mut context = ColorBufferEncodingContext {
                    render_pass_id: id,
                    buffer_index: 0,
                };

                let $C0 = $C0.encode_multisample_color_buffer(&mut context);

                let mut width = $C0.image.width;
                let mut height = $C0.image.height;

                let $C0 = {
                    let ColorBufferEncoding {
                        load_action,
                        store_op,
                        image,
                        buffer,
                        ..
                    } = $C0;

                    render_target.load_ops[0] = load_action;
                    render_target.store_ops[0] = store_op;
                    render_target.color_attachments[0] = Some(image);

                    buffer
                };

                let mut color_count = 1;

                $(
                    let mut context = ColorBufferEncodingContext {
                        render_pass_id: id,
                        buffer_index: color_count as i32,
                    };

                    let $C = $C.encode_multisample_color_buffer(&mut context);

                    width = cmp::min(width, $C.image.width);
                    height = cmp::min(height, $C.image.height);

                    let $C = {
                        let ColorBufferEncoding {
                            load_action,
                            store_op,
                            image,
                            buffer,
                            ..
                        } = $C;

                        render_target.load_ops[color_count] = load_action;
                        render_target.store_ops[color_count] = store_op;
                        render_target.color_attachments[color_count] = Some(image);

                        buffer
                    };

                    color_count += 1;
                )*

                render_target.color_count = color_count;

                let task = f(&MultisampleFramebuffer {
                    color: ($C0, $($C,)*),
                    depth_stencil: (),
                    samples: self.samples,
                    pipeline_target: GraphicsPipelineTarget {
                        dimensions: Some((width, height)),
                        context_id: self.context_id,
                        render_pass_id: id,
                        last_pipeline_task_id: Cell::new(0),
                    }
                });

                if let ContextId::Id(render_pass_id) = task.context_id() {
                    if render_pass_id != id {
                        panic!("The render pass task belongs to a different render pass.")
                    }
                }

                RenderPass {
                    id,
                    context_id: self.context_id,
                    render_target: RenderTargetData::Custom(render_target),
                    task
                }
            }
        }
    }
}

impl_create_render_pass!(C0);
impl_create_render_pass!(C0, C1);
impl_create_render_pass!(C0, C1, C2);
impl_create_render_pass!(C0, C1, C2, C3);
impl_create_render_pass!(C0, C1, C2, C3, C4);
impl_create_render_pass!(C0, C1, C2, C3, C4, C5);
impl_create_render_pass!(C0, C1, C2, C3, C4, C5, C6);
impl_create_render_pass!(C0, C1, C2, C3, C4, C5, C6, C7);
impl_create_render_pass!(C0, C1, C2, C3, C4, C5, C6, C7, C8);
impl_create_render_pass!(C0, C1, C2, C3, C4, C5, C6, C7, C8, C9);
impl_create_render_pass!(C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10);
impl_create_render_pass!(C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11);
impl_create_render_pass!(C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12);
impl_create_render_pass!(C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13);
impl_create_render_pass!(C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14);
impl_create_render_pass!(C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15);

macro_rules! impl_create_render_pass_depth_stencil {
    ($($C:ident),*) => {
        #[allow(unused_parens)]
        impl<$($C,)* Ds> RenderTarget<($($C,)*), Ds>
        where
            $($C: EncodeColorBuffer,)*
            Ds: EncodeDepthStencilBuffer
        {
            /// Creates a new [RenderPass] that will output to this [RenderTarget].
            ///
            /// The `f` function will receive a reference to a [Framebuffer] with a buffer layout
            /// that matches the [RenderTarget]'s attachment layout.
            ///
            /// For details and examples on defining render passes, please refer to the struct
            /// documentation for [RenderTarget].
            ///
            /// # Panics
            ///
            /// Panics if the render pass context ID associated with the task returned from `f` does
            /// not match the ID generated for this render pass (the task returned from `f` must not
            /// contain commands that were created for a different render pass).
            #[allow(non_snake_case, unused_parens)]
            pub fn create_render_pass<F, T>(&mut self, f: F) -> RenderPass<T>
                where
                    F: FnOnce(&Framebuffer<($($C::Buffer,)*), Ds::Buffer>) -> T,
                    T: GpuTask<RenderPassContext>
            {
                let id = self.render_pass_id_gen.next();

                let mut context = DepthStencilBufferEncodingContext {
                    render_pass_id: id,
                };

                let DepthStencilBufferEncoding {
                    load_action,
                    store_op,
                    depth_stencil_type,
                    image,
                    buffer,
                    ..
                } = self.depth_stencil_attachment.encode_depth_stencil_buffer(&mut context);

                #[allow(unused_mut)]
                let mut width = image.width;

                #[allow(unused_mut)]
                let mut height = image.height;

                let mut render_target = CustomRenderTargetData {
                    load_ops: [LoadAction::Load; 17],
                    store_ops: [StoreOp::Store; 17],
                    color_count: 0,
                    color_attachments: [
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                    ],
                    depth_stencil_attachment: depth_stencil_type.descriptor(image),
                };

                render_target.load_ops[16] = load_action;
                render_target.store_ops[16] = store_op;

                let ($($C,)*) = &mut self.color_attachments;

                #[allow(unused_mut)]
                let mut color_count = 0;

                $(
                    let mut context = ColorBufferEncodingContext {
                        render_pass_id: id,
                        buffer_index: color_count as i32,
                    };

                    let $C = $C.encode_color_buffer(&mut context);

                    width = cmp::min(width, $C.image.width);
                    height = cmp::min(height, $C.image.height);

                    let $C = {
                        let ColorBufferEncoding {
                            load_action,
                            store_op,
                            image,
                            buffer,
                            ..
                        } = $C;

                        render_target.load_ops[color_count] = load_action;
                        render_target.store_ops[color_count] = store_op;
                        render_target.color_attachments[color_count] = Some(image);

                        buffer
                    };

                    color_count += 1;
                )*

                render_target.color_count = color_count;

                let task = f(&Framebuffer {
                    color: ($($C,)*),
                    depth_stencil: buffer,
                    pipeline_target: GraphicsPipelineTarget {
                        dimensions: Some((width, height)),
                        context_id: self.context_id,
                        render_pass_id: id,
                        last_pipeline_task_id: Cell::new(0),
                    }
                });

                if let ContextId::Id(render_pass_id) = task.context_id() {
                    if render_pass_id != id {
                        panic!("The render pass task belongs to a different render pass.")
                    }
                }

                RenderPass {
                    id,
                    context_id: self.context_id,
                    render_target: RenderTargetData::Custom(render_target),
                    task
                }
            }
        }

        #[allow(unused_parens)]
        impl<$($C,)* Ds> MultisampleRenderTarget<($($C,)*), Ds>
        where
            $($C: EncodeMultisampleColorBuffer,)*
            Ds: EncodeMultisampleDepthStencilBuffer
        {
            /// Creates a new [RenderPass] that will output to this [MultisampleRenderTarget].
            ///
            /// The `f` function will receive a reference to a [MultisampleFramebuffer] with a
            /// buffer layout that matches the [MultisampleRenderTarget]'s attachment layout.
            ///
            /// For details and examples on defining render passes, please refer to the struct
            /// documentation for [RenderTarget].
            ///
            /// # Panics
            ///
            /// Panics if the render pass context ID associated with the task returned from `f` does
            /// not match the ID generated for this render pass (the task returned from `f` must not
            /// contain commands that were created for a different render pass).
            #[allow(non_snake_case, unused_parens)]
            pub fn create_render_pass<F, T>(&mut self, f: F) -> RenderPass<T>
                where
                    F: FnOnce(&MultisampleFramebuffer<($($C::Buffer,)*), Ds::Buffer>) -> T,
                    T: GpuTask<RenderPassContext>
            {
                let id = self.render_pass_id_gen.next();

                let mut context = DepthStencilBufferEncodingContext {
                    render_pass_id: id,
                };

                let DepthStencilBufferEncoding {
                    load_action,
                    store_op,
                    depth_stencil_type,
                    image,
                    buffer,
                    ..
                } = self.depth_stencil_attachment.encode_multisample_depth_stencil_buffer(&mut context);

                #[allow(unused_mut)]
                let mut width = image.width;

                #[allow(unused_mut)]
                let mut height = image.height;

                let mut render_target = CustomRenderTargetData {
                    load_ops: [LoadAction::Load; 17],
                    store_ops: [StoreOp::Store; 17],
                    color_count: 0,
                    color_attachments: [
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                    ],
                    depth_stencil_attachment: depth_stencil_type.descriptor(image),
                };

                render_target.load_ops[16] = load_action;
                render_target.store_ops[16] = store_op;

                let ($($C,)*) = &mut self.color_attachments;

                #[allow(unused_mut)]
                let mut color_count = 0;

                $(
                    let mut context = ColorBufferEncodingContext {
                        render_pass_id: id,
                        buffer_index: color_count as i32,
                    };

                    let $C = $C.encode_multisample_color_buffer(&mut context);

                    width = cmp::min(width, $C.image.width);
                    height = cmp::min(height, $C.image.height);

                    let $C = {
                        let ColorBufferEncoding {
                            load_action,
                            store_op,
                            image,
                            buffer,
                            ..
                        } = $C;

                        render_target.load_ops[color_count] = load_action;
                        render_target.store_ops[color_count] = store_op;
                        render_target.color_attachments[color_count] = Some(image);

                        buffer
                    };

                    color_count += 1;
                )*

                render_target.color_count = color_count;

                let task = f(&MultisampleFramebuffer {
                    color: ($($C,)*),
                    depth_stencil: buffer,
                    samples: self.samples,
                    pipeline_target : GraphicsPipelineTarget {
                        dimensions: Some((width, height)),
                        context_id: self.context_id,
                        render_pass_id: id,
                        last_pipeline_task_id: Cell::new(0),
                    }
                });

                if let ContextId::Id(render_pass_id) = task.context_id() {
                    if render_pass_id != id {
                        panic!("The render pass task belongs to a different render pass.")
                    }
                }

                RenderPass {
                    id,
                    context_id: self.context_id,
                    render_target: RenderTargetData::Custom(render_target),
                    task
                }
            }
        }
    }
}

impl_create_render_pass_depth_stencil!();
impl_create_render_pass_depth_stencil!(C0);
impl_create_render_pass_depth_stencil!(C0, C1);
impl_create_render_pass_depth_stencil!(C0, C1, C2);
impl_create_render_pass_depth_stencil!(C0, C1, C2, C3);
impl_create_render_pass_depth_stencil!(C0, C1, C2, C3, C4);
impl_create_render_pass_depth_stencil!(C0, C1, C2, C3, C4, C5);
impl_create_render_pass_depth_stencil!(C0, C1, C2, C3, C4, C5, C6);
impl_create_render_pass_depth_stencil!(C0, C1, C2, C3, C4, C5, C6, C7);
impl_create_render_pass_depth_stencil!(C0, C1, C2, C3, C4, C5, C6, C7, C8);
impl_create_render_pass_depth_stencil!(C0, C1, C2, C3, C4, C5, C6, C7, C8, C9);
impl_create_render_pass_depth_stencil!(C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10);
impl_create_render_pass_depth_stencil!(C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11);
impl_create_render_pass_depth_stencil!(C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12);
impl_create_render_pass_depth_stencil!(C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13);
impl_create_render_pass_depth_stencil!(
    C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14
);
impl_create_render_pass_depth_stencil!(
    C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15
);

pub(crate) enum RenderTargetContextId {
    Any,
    Single(&'static str, u64),
    Mixed {
        first: (&'static str, u64),
        second: &'static str,
    },
}

impl RenderTargetContextId {
    pub(crate) fn new() -> Self {
        RenderTargetContextId::Any
    }

    pub(crate) fn record(self, label: &'static str, context_id: u64) -> Self {
        match self {
            RenderTargetContextId::Any => RenderTargetContextId::Single(label, context_id),
            RenderTargetContextId::Single(first_label, first_id) => {
                if context_id != first_id {
                    RenderTargetContextId::Mixed {
                        first: (first_label, first_id),
                        second: label,
                    }
                } else {
                    self
                }
            }
            _ => self,
        }
    }

    pub(crate) fn verify(&self, context_id: u64) {
        match self {
            RenderTargetContextId::Single(label, id) => {
                if context_id != *id {
                    panic!("The {} attachment belongs to a different context.", label)
                }
            }
            RenderTargetContextId::Mixed {
                first: (first_label, first_id),
                second: second_label,
            } => {
                if context_id != *first_id {
                    panic!(
                        "The {} attachment belongs to a different context.",
                        first_label
                    )
                } else {
                    panic!(
                        "The {} attachment belongs to a different context.",
                        second_label
                    )
                }
            }
            _ => (),
        }
    }
}

#[derive(Clone)]
pub(crate) enum RenderTargetData {
    Default,
    Custom(CustomRenderTargetData),
}

#[derive(Clone)]
pub(crate) struct CustomRenderTargetData {
    pub(crate) load_ops: [LoadAction; 17],
    pub(crate) store_ops: [StoreOp; 17],
    pub(crate) color_count: usize,
    pub(crate) color_attachments: [Option<AttachmentData>; 16],
    pub(crate) depth_stencil_attachment: DepthStencilAttachmentDescriptor,
}

impl CustomRenderTargetData {
    pub(crate) fn draw_buffers(&self) -> &[DrawBuffer] {
        const DRAW_BUFFERS_SEQUENTIAL: [DrawBuffer; 16] = [
            DrawBuffer::Color0,
            DrawBuffer::Color1,
            DrawBuffer::Color2,
            DrawBuffer::Color3,
            DrawBuffer::Color4,
            DrawBuffer::Color5,
            DrawBuffer::Color6,
            DrawBuffer::Color7,
            DrawBuffer::Color8,
            DrawBuffer::Color9,
            DrawBuffer::Color10,
            DrawBuffer::Color11,
            DrawBuffer::Color12,
            DrawBuffer::Color13,
            DrawBuffer::Color14,
            DrawBuffer::Color15,
        ];

        &DRAW_BUFFERS_SEQUENTIAL[0..self.color_count]
    }
}

impl Hash for CustomRenderTargetData {
    fn hash<H>(&self, hasher: &mut H)
    where
        H: Hasher,
    {
        self.color_attachments().hash(hasher);
        self.depth_stencil_attachment().hash(hasher);
    }
}

impl AttachmentSet for CustomRenderTargetData {
    fn color_attachments(&self) -> &[Option<AttachmentData>] {
        &self.color_attachments[0..self.color_count]
    }

    fn depth_stencil_attachment(&self) -> &DepthStencilAttachmentDescriptor {
        &self.depth_stencil_attachment
    }
}