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
// Copyright (c) 2017 The vulkano developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.

// TODO: graphics pipeline params are deprecated, but are still the primary implementation in order
// to avoid duplicating code, so we hide the warnings for now
#![allow(deprecated)]

use smallvec::SmallVec;
use std::mem;
use std::ptr;
use std::sync::Arc;
use std::u32;

use descriptor::pipeline_layout::PipelineLayoutAbstract;
use device::Device;
use framebuffer::RenderPassAbstract;
use framebuffer::Subpass;
use pipeline::blend::AttachmentBlend;
use pipeline::blend::AttachmentsBlend;
use pipeline::blend::Blend;
use pipeline::blend::LogicOp;
use pipeline::depth_stencil::Compare;
use pipeline::depth_stencil::DepthBounds;
use pipeline::depth_stencil::DepthStencil;
use pipeline::graphics_pipeline::GraphicsPipeline;
use pipeline::graphics_pipeline::GraphicsPipelineCreationError;
use pipeline::graphics_pipeline::Inner as GraphicsPipelineInner;
use pipeline::input_assembly::PrimitiveTopology;
use pipeline::raster::CullMode;
use pipeline::raster::DepthBiasControl;
use pipeline::raster::FrontFace;
use pipeline::raster::PolygonMode;
use pipeline::raster::Rasterization;
use pipeline::shader::EmptyEntryPointDummy;
use pipeline::shader::GraphicsEntryPointAbstract;
use pipeline::shader::GraphicsShaderType;
use pipeline::shader::ShaderInterfaceDefMatch;
use pipeline::shader::SpecializationConstants;
use pipeline::vertex::BufferlessDefinition;
use pipeline::vertex::SingleBufferDefinition;
use pipeline::vertex::VertexDefinition;
use pipeline::viewport::Scissor;
use pipeline::viewport::Viewport;
use pipeline::viewport::ViewportsState;

use VulkanObject;
use check_errors;
use descriptor::pipeline_layout::PipelineLayoutDesc;
use descriptor::pipeline_layout::PipelineLayoutDescTweaks;
use descriptor::pipeline_layout::PipelineLayoutSuperset;
use framebuffer::RenderPassSubpassInterface;
use vk;

/// Prototype for a `GraphicsPipeline`.
// TODO: we can optimize this by filling directly the raw vk structs
pub struct GraphicsPipelineBuilder<Vdef, Vs, Vss, Tcs, Tcss, Tes, Tess, Gs, Gss, Fs, Fss, Rp> {
    vertex_input: Vdef,
    vertex_shader: Option<(Vs, Vss)>,
    input_assembly: vk::PipelineInputAssemblyStateCreateInfo,
    // Note: the `input_assembly_topology` member is temporary in order to not lose information
    // about the number of patches per primitive.
    input_assembly_topology: PrimitiveTopology,
    tessellation: Option<TessInfo<Tcs, Tcss, Tes, Tess>>,
    geometry_shader: Option<(Gs, Gss)>,
    viewport: Option<ViewportsState>,
    raster: Rasterization,
    multisample: vk::PipelineMultisampleStateCreateInfo,
    fragment_shader: Option<(Fs, Fss)>,
    depth_stencil: DepthStencil,
    blend: Blend,
    render_pass: Option<Subpass<Rp>>,
}

// Additional parameters if tessellation is used.
#[derive(Copy, Clone)]
struct TessInfo<Tcs, Tcss, Tes, Tess> {
    tessellation_control_shader: (Tcs, Tcss),
    tessellation_evaluation_shader: (Tes, Tess),
}

impl
    GraphicsPipelineBuilder<BufferlessDefinition,
                            EmptyEntryPointDummy,
                            (),
                            EmptyEntryPointDummy,
                            (),
                            EmptyEntryPointDummy,
                            (),
                            EmptyEntryPointDummy,
                            (),
                            EmptyEntryPointDummy,
                            (),
                            ()> {
    /// Builds a new empty builder.
    pub(super) fn new() -> Self {
        unsafe {
            GraphicsPipelineBuilder {
                vertex_input: BufferlessDefinition,
                vertex_shader: None,
                input_assembly: vk::PipelineInputAssemblyStateCreateInfo {
                    sType: vk::STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,
                    topology: PrimitiveTopology::TriangleList.into(),
                    ..mem::zeroed()
                },
                input_assembly_topology: PrimitiveTopology::TriangleList,
                tessellation: None,
                geometry_shader: None,
                viewport: None,
                raster: Default::default(),
                multisample: vk::PipelineMultisampleStateCreateInfo {
                    sType: vk::STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO,
                    ..mem::zeroed()
                },
                fragment_shader: None,
                depth_stencil: DepthStencil::disabled(),
                blend: Blend::pass_through(),
                render_pass: None,
            }
        }
    }
}

impl<Vdef, Vs, Vss, Tcs, Tcss, Tes, Tess, Gs, Gss, Fs, Fss, Rp>
    GraphicsPipelineBuilder<Vdef, Vs, Vss, Tcs, Tcss, Tes, Tess, Gs, Gss, Fs, Fss, Rp>
    where Vdef: VertexDefinition<Vs::InputDefinition>,
          Vs: GraphicsEntryPointAbstract,
          Fs: GraphicsEntryPointAbstract,
          Gs: GraphicsEntryPointAbstract,
          Tcs: GraphicsEntryPointAbstract,
          Tes: GraphicsEntryPointAbstract,
          Vss: SpecializationConstants,
          Tcss: SpecializationConstants,
          Tess: SpecializationConstants,
          Gss: SpecializationConstants,
          Fss: SpecializationConstants,
          Vs::PipelineLayout: Clone + 'static + Send + Sync, // TODO: shouldn't be required
          Fs::PipelineLayout: Clone + 'static + Send + Sync, // TODO: shouldn't be required
          Tcs::PipelineLayout: Clone + 'static + Send + Sync, // TODO: shouldn't be required
          Tes::PipelineLayout: Clone + 'static + Send + Sync, // TODO: shouldn't be required
          Gs::PipelineLayout: Clone + 'static + Send + Sync, // TODO: shouldn't be required
          Tcs::InputDefinition: ShaderInterfaceDefMatch<Vs::OutputDefinition>,
          Tes::InputDefinition: ShaderInterfaceDefMatch<Tcs::OutputDefinition>,
          Gs::InputDefinition: ShaderInterfaceDefMatch<Tes::OutputDefinition>
                                   + ShaderInterfaceDefMatch<Vs::OutputDefinition>,
          Fs::InputDefinition: ShaderInterfaceDefMatch<Gs::OutputDefinition>
                                   + ShaderInterfaceDefMatch<Tes::OutputDefinition>
                                   + ShaderInterfaceDefMatch<Vs::OutputDefinition>,
          Rp: RenderPassAbstract + RenderPassSubpassInterface<Fs::OutputDefinition>
{
    /// Builds the graphics pipeline, using an inferred a pipeline layout.
    // TODO: replace Box<PipelineLayoutAbstract> with a PipelineUnion struct without template params
    pub fn build(self, device: Arc<Device>)
                 -> Result<GraphicsPipeline<Vdef, Box<dyn PipelineLayoutAbstract + Send + Sync>, Rp>,
                           GraphicsPipelineCreationError> {
        self.with_auto_layout(device, &[])
    }

    /// Builds the graphics pipeline, using an inferred pipeline layout with some dynamic buffers.
    ///
    /// Configures the inferred layout for each descriptor `(set, binding)` in `dynamic_buffers` to accept dynamic
    /// buffers.
    pub fn with_auto_layout(self, device: Arc<Device>, dynamic_buffers: &[(usize, usize)])
                            -> Result<GraphicsPipeline<Vdef, Box<dyn PipelineLayoutAbstract + Send + Sync>, Rp>,
                                      GraphicsPipelineCreationError>
    {
        let pipeline_layout;

        if let Some(ref tess) = self.tessellation {
            if let Some(ref gs) = self.geometry_shader {
                if let Err(err) = tess.tessellation_control_shader
                    .0
                    .input()
                    .matches(self.vertex_shader.as_ref().unwrap().0.output())
                {
                    return Err(GraphicsPipelineCreationError::VertexTessControlStagesMismatch(err));
                }
                if let Err(err) = tess.tessellation_evaluation_shader
                    .0
                    .input()
                    .matches(tess.tessellation_control_shader.0.output())
                {
                    return Err(GraphicsPipelineCreationError::TessControlTessEvalStagesMismatch(err));
                }
                if let Err(err) = gs.0
                    .input()
                    .matches(tess.tessellation_evaluation_shader.0.output())
                {
                    return Err(GraphicsPipelineCreationError::TessEvalGeometryStagesMismatch(err));
                }
                if let Err(err) = self.fragment_shader
                    .as_ref()
                    .unwrap()
                    .0
                    .input()
                    .matches(gs.0.output())
                {
                    return Err(GraphicsPipelineCreationError::GeometryFragmentStagesMismatch(err));
                }

                pipeline_layout = Box::new(
                    PipelineLayoutDescTweaks::new(self.vertex_shader.as_ref().unwrap().0.layout().clone()
                          .union(self.fragment_shader.as_ref().unwrap().0.layout().clone())
                          .union(self.tessellation.as_ref().unwrap().tessellation_control_shader.0.layout().clone())    // FIXME: unwrap()
                          .union(self.tessellation.as_ref().unwrap().tessellation_evaluation_shader.0.layout().clone())    // FIXME: unwrap()
                          .union(self.geometry_shader.as_ref().unwrap().0.layout().clone()),    // FIXME: unwrap()
                          dynamic_buffers.into_iter().cloned()
                    ).build(device.clone()).unwrap()) as Box<_>; // TODO: error

            } else {
                if let Err(err) = tess.tessellation_control_shader
                    .0
                    .input()
                    .matches(self.vertex_shader.as_ref().unwrap().0.output())
                {
                    return Err(GraphicsPipelineCreationError::VertexTessControlStagesMismatch(err));
                }
                if let Err(err) = tess.tessellation_evaluation_shader
                    .0
                    .input()
                    .matches(tess.tessellation_control_shader.0.output())
                {
                    return Err(GraphicsPipelineCreationError::TessControlTessEvalStagesMismatch(err));
                }
                if let Err(err) = self.fragment_shader
                    .as_ref()
                    .unwrap()
                    .0
                    .input()
                    .matches(tess.tessellation_evaluation_shader.0.output())
                {
                    return Err(GraphicsPipelineCreationError::TessEvalFragmentStagesMismatch(err));
                }

                pipeline_layout = Box::new(
                    PipelineLayoutDescTweaks::new(self.vertex_shader.as_ref().unwrap().0.layout().clone()
                          .union(self.fragment_shader.as_ref().unwrap().0.layout().clone())
                          .union(self.tessellation.as_ref().unwrap().tessellation_control_shader.0.layout().clone())    // FIXME: unwrap()
                          .union(self.tessellation.as_ref().unwrap().tessellation_evaluation_shader.0.layout().clone()),    // FIXME: unwrap()
                          dynamic_buffers.into_iter().cloned()
                    ).build(device.clone()).unwrap()) as Box<_>; // TODO: error
            }

        } else {
            if let Some(ref geometry_shader) = self.geometry_shader {
                if let Err(err) = geometry_shader
                    .0
                    .input()
                    .matches(self.vertex_shader.as_ref().unwrap().0.output())
                {
                    return Err(GraphicsPipelineCreationError::VertexGeometryStagesMismatch(err));
                }
                if let Err(err) = self.fragment_shader
                    .as_ref()
                    .unwrap()
                    .0
                    .input()
                    .matches(geometry_shader.0.output())
                {
                    return Err(GraphicsPipelineCreationError::GeometryFragmentStagesMismatch(err));
                }

                pipeline_layout = Box::new(
                    PipelineLayoutDescTweaks::new(self.vertex_shader.as_ref().unwrap().0.layout().clone()
                          .union(self.fragment_shader.as_ref().unwrap().0.layout().clone())
                          .union(self.geometry_shader.as_ref().unwrap().0.layout().clone()),    // FIXME: unwrap()
                          dynamic_buffers.into_iter().cloned()
                    ).build(device.clone()).unwrap()) as Box<_>; // TODO: error

            } else {
                if let Err(err) = self.fragment_shader
                    .as_ref()
                    .unwrap()
                    .0
                    .input()
                    .matches(self.vertex_shader.as_ref().unwrap().0.output())
                {
                    return Err(GraphicsPipelineCreationError::VertexFragmentStagesMismatch(err));
                }

                pipeline_layout =
                    Box::new(
                        PipelineLayoutDescTweaks::new(self.vertex_shader
                              .as_ref()
                              .unwrap()
                              .0
                              .layout()
                              .clone()
                              .union(self.fragment_shader.as_ref().unwrap().0.layout().clone()),
                              dynamic_buffers.into_iter().cloned()
                        ).build(device.clone()).unwrap()) as Box<_>; // TODO: error
            }
        }

        self.with_pipeline_layout(device, pipeline_layout)
    }

    /// Builds the graphics pipeline.
    ///
    /// Does the same as `build`, except that `build` automatically builds the pipeline layout
    /// object corresponding to the union of your shaders while this function allows you to specify
    /// the pipeline layout.
    pub fn with_pipeline_layout<Pl>(mut self, device: Arc<Device>, pipeline_layout: Pl)
                                    -> Result<GraphicsPipeline<Vdef, Pl, Rp>,
                                              GraphicsPipelineCreationError>
        where Pl: PipelineLayoutAbstract
    {
        // TODO: return errors instead of panicking if missing param

        let vk = device.pointers();

        // Checking that the pipeline layout matches the shader stages.
        // TODO: more details in the errors
        PipelineLayoutSuperset::ensure_superset_of(&pipeline_layout,
                                                   self.vertex_shader
                                                       .as_ref()
                                                       .unwrap()
                                                       .0
                                                       .layout())?;
        PipelineLayoutSuperset::ensure_superset_of(&pipeline_layout,
                                                   self.fragment_shader
                                                       .as_ref()
                                                       .unwrap()
                                                       .0
                                                       .layout())?;
        if let Some(ref geometry_shader) = self.geometry_shader {
            PipelineLayoutSuperset::ensure_superset_of(&pipeline_layout,
                                                       geometry_shader.0.layout())?;
        }
        if let Some(ref tess) = self.tessellation {
            PipelineLayoutSuperset::ensure_superset_of(&pipeline_layout,
                                                       tess.tessellation_control_shader
                                                           .0
                                                           .layout())?;
            PipelineLayoutSuperset::ensure_superset_of(&pipeline_layout,
                                                       tess.tessellation_evaluation_shader
                                                           .0
                                                           .layout())?;
        }

        // Check that the subpass can accept the output of the fragment shader.
        if !RenderPassSubpassInterface::is_compatible_with(&self.render_pass
                                                               .as_ref()
                                                               .unwrap()
                                                               .render_pass(),
                                                           self.render_pass
                                                               .as_ref()
                                                               .unwrap()
                                                               .index(),
                                                           self.fragment_shader
                                                               .as_ref()
                                                               .unwrap()
                                                               .0
                                                               .output())
        {
            return Err(GraphicsPipelineCreationError::FragmentShaderRenderPassIncompatible);
        }

        // Will contain the list of dynamic states. Filled throughout this function.
        let mut dynamic_states: SmallVec<[vk::DynamicState; 8]> = SmallVec::new();

        // Creating the specialization constants of the various stages.
        let vertex_shader_specialization = {
            let spec_descriptors = Vss::descriptors();
            let constants = &self.vertex_shader.as_ref().unwrap().1;
            vk::SpecializationInfo {
                mapEntryCount: spec_descriptors.len() as u32,
                pMapEntries: spec_descriptors.as_ptr() as *const _,
                dataSize: mem::size_of_val(constants),
                pData: constants as *const Vss as *const _,
            }
        };
        let tess_shader_specialization = if let Some(ref tess) = self.tessellation {
            let tcs_spec = {
                let spec_descriptors = Tcss::descriptors();
                let constants = &tess.tessellation_control_shader.1;
                vk::SpecializationInfo {
                    mapEntryCount: spec_descriptors.len() as u32,
                    pMapEntries: spec_descriptors.as_ptr() as *const _,
                    dataSize: mem::size_of_val(constants),
                    pData: constants as *const Tcss as *const _,
                }
            };
            let tes_spec = {
                let spec_descriptors = Tess::descriptors();
                let constants = &tess.tessellation_evaluation_shader.1;
                vk::SpecializationInfo {
                    mapEntryCount: spec_descriptors.len() as u32,
                    pMapEntries: spec_descriptors.as_ptr() as *const _,
                    dataSize: mem::size_of_val(constants),
                    pData: constants as *const Tess as *const _,
                }
            };
            Some((tcs_spec, tes_spec))
        } else {
            None
        };
        let geometry_shader_specialization = if let Some(ref gs) = self.geometry_shader {
            let spec_descriptors = Gss::descriptors();
            let constants = &gs.1;
            Some(vk::SpecializationInfo {
                     mapEntryCount: spec_descriptors.len() as u32,
                     pMapEntries: spec_descriptors.as_ptr() as *const _,
                     dataSize: mem::size_of_val(constants),
                     pData: constants as *const Gss as *const _,
                 })
        } else {
            None
        };
        let fragment_shader_specialization = {
            let spec_descriptors = Fss::descriptors();
            let constants = &self.fragment_shader.as_ref().unwrap().1;
            vk::SpecializationInfo {
                mapEntryCount: spec_descriptors.len() as u32,
                pMapEntries: spec_descriptors.as_ptr() as *const _,
                dataSize: mem::size_of_val(constants),
                pData: constants as *const Fss as *const _,
            }
        };

        // List of shader stages.
        let stages = {
            let mut stages = SmallVec::<[_; 5]>::new();

            match self.vertex_shader.as_ref().unwrap().0.ty() {
                GraphicsShaderType::Vertex => {},
                _ => return Err(GraphicsPipelineCreationError::WrongShaderType),
            };

            stages.push(vk::PipelineShaderStageCreateInfo {
                            sType: vk::STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
                            pNext: ptr::null(),
                            flags: 0, // reserved
                            stage: vk::SHADER_STAGE_VERTEX_BIT,
                            module: self.vertex_shader
                                .as_ref()
                                .unwrap()
                                .0
                                .module()
                                .internal_object(),
                            pName: self.vertex_shader.as_ref().unwrap().0.name().as_ptr(),
                            pSpecializationInfo: &vertex_shader_specialization as *const _,
                        });

            match self.fragment_shader.as_ref().unwrap().0.ty() {
                GraphicsShaderType::Fragment => {},
                _ => return Err(GraphicsPipelineCreationError::WrongShaderType),
            };

            stages.push(vk::PipelineShaderStageCreateInfo {
                            sType: vk::STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
                            pNext: ptr::null(),
                            flags: 0, // reserved
                            stage: vk::SHADER_STAGE_FRAGMENT_BIT,
                            module: self.fragment_shader
                                .as_ref()
                                .unwrap()
                                .0
                                .module()
                                .internal_object(),
                            pName: self.fragment_shader.as_ref().unwrap().0.name().as_ptr(),
                            pSpecializationInfo: &fragment_shader_specialization as *const _,
                        });

            if let Some(ref gs) = self.geometry_shader {
                if !device.enabled_features().geometry_shader {
                    return Err(GraphicsPipelineCreationError::GeometryShaderFeatureNotEnabled);
                }

                stages.push(vk::PipelineShaderStageCreateInfo {
                                sType: vk::STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
                                pNext: ptr::null(),
                                flags: 0, // reserved
                                stage: vk::SHADER_STAGE_GEOMETRY_BIT,
                                module: gs.0.module().internal_object(),
                                pName: gs.0.name().as_ptr(),
                                pSpecializationInfo: geometry_shader_specialization
                                    .as_ref()
                                    .unwrap() as
                                    *const _,
                            });
            }

            if let Some(ref tess) = self.tessellation {
                // FIXME: must check that the control shader and evaluation shader are compatible

                if !device.enabled_features().tessellation_shader {
                    return Err(GraphicsPipelineCreationError::TessellationShaderFeatureNotEnabled);
                }

                match tess.tessellation_control_shader.0.ty() {
                    GraphicsShaderType::TessellationControl => {},
                    _ => return Err(GraphicsPipelineCreationError::WrongShaderType),
                };

                match tess.tessellation_evaluation_shader.0.ty() {
                    GraphicsShaderType::TessellationEvaluation => {},
                    _ => return Err(GraphicsPipelineCreationError::WrongShaderType),
                };

                stages.push(vk::PipelineShaderStageCreateInfo {
                                sType: vk::STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
                                pNext: ptr::null(),
                                flags: 0, // reserved
                                stage: vk::SHADER_STAGE_TESSELLATION_CONTROL_BIT,
                                module: tess.tessellation_control_shader
                                    .0
                                    .module()
                                    .internal_object(),
                                pName: tess.tessellation_control_shader.0.name().as_ptr(),
                                pSpecializationInfo: &tess_shader_specialization
                                    .as_ref()
                                    .unwrap()
                                    .0 as
                                    *const _,
                            });

                stages.push(vk::PipelineShaderStageCreateInfo {
                                sType: vk::STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
                                pNext: ptr::null(),
                                flags: 0, // reserved
                                stage: vk::SHADER_STAGE_TESSELLATION_EVALUATION_BIT,
                                module: tess.tessellation_evaluation_shader
                                    .0
                                    .module()
                                    .internal_object(),
                                pName: tess.tessellation_evaluation_shader.0.name().as_ptr(),
                                pSpecializationInfo: &tess_shader_specialization
                                    .as_ref()
                                    .unwrap()
                                    .1 as
                                    *const _,
                            });
            }

            stages
        };

        // Vertex bindings.
        let (binding_descriptions, attribute_descriptions) = {
            let (buffers_iter, attribs_iter) =
                self.vertex_input
                    .definition(self.vertex_shader.as_ref().unwrap().0.input())?;

            let mut binding_descriptions = SmallVec::<[_; 8]>::new();
            for (num, stride, rate) in buffers_iter {
                if stride >
                    device
                        .physical_device()
                        .limits()
                        .max_vertex_input_binding_stride() as usize
                {
                    return Err(GraphicsPipelineCreationError::MaxVertexInputBindingStrideExceeded {
                        binding: num as usize,
                        max: device.physical_device().limits().max_vertex_input_binding_stride() as usize,
                        obtained: stride,
                    });
                }

                binding_descriptions.push(vk::VertexInputBindingDescription {
                                              binding: num as u32,
                                              stride: stride as u32,
                                              inputRate: rate as u32,
                                          });
            }

            let mut attribute_descriptions = SmallVec::<[_; 8]>::new();
            for (loc, binding, info) in attribs_iter {
                // TODO: check attribute format support

                if info.offset >
                    device
                        .physical_device()
                        .limits()
                        .max_vertex_input_attribute_offset() as usize
                {
                    return Err(GraphicsPipelineCreationError::MaxVertexInputAttributeOffsetExceeded {
                        max: device.physical_device().limits().max_vertex_input_attribute_offset() as usize,
                        obtained: info.offset,
                    });
                }

                debug_assert!(binding_descriptions
                                  .iter()
                                  .find(|b| b.binding == binding)
                                  .is_some());

                attribute_descriptions.push(vk::VertexInputAttributeDescription {
                                                location: loc as u32,
                                                binding: binding as u32,
                                                format: info.format as u32,
                                                offset: info.offset as u32,
                                            });
            }

            (binding_descriptions, attribute_descriptions)
        };

        if binding_descriptions.len() >
            device
                .physical_device()
                .limits()
                .max_vertex_input_bindings() as usize
        {
            return Err(GraphicsPipelineCreationError::MaxVertexInputBindingsExceeded {
                           max: device
                               .physical_device()
                               .limits()
                               .max_vertex_input_bindings() as
                               usize,
                           obtained: binding_descriptions.len(),
                       });
        }

        if attribute_descriptions.len() >
            device
                .physical_device()
                .limits()
                .max_vertex_input_attributes() as usize
        {
            return Err(GraphicsPipelineCreationError::MaxVertexInputAttributesExceeded {
                           max: device
                               .physical_device()
                               .limits()
                               .max_vertex_input_attributes() as
                               usize,
                           obtained: attribute_descriptions.len(),
                       });
        }

        let vertex_input_state = vk::PipelineVertexInputStateCreateInfo {
            sType: vk::STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO,
            pNext: ptr::null(),
            flags: 0, // reserved
            vertexBindingDescriptionCount: binding_descriptions.len() as u32,
            pVertexBindingDescriptions: binding_descriptions.as_ptr(),
            vertexAttributeDescriptionCount: attribute_descriptions.len() as u32,
            pVertexAttributeDescriptions: attribute_descriptions.as_ptr(),
        };

        if self.input_assembly.primitiveRestartEnable != vk::FALSE &&
            !self.input_assembly_topology.supports_primitive_restart()
        {
            return Err(GraphicsPipelineCreationError::PrimitiveDoesntSupportPrimitiveRestart {
                           primitive: self.input_assembly_topology,
                       });
        }

        // TODO: should check from the tess eval shader instead of the input assembly
        if let Some(ref gs) = self.geometry_shader {
            match gs.0.ty() {
                GraphicsShaderType::Geometry(primitives) => {
                    if !primitives.matches(self.input_assembly_topology) {
                        return Err(GraphicsPipelineCreationError::TopologyNotMatchingGeometryShader);
                    }
                },
                _ => return Err(GraphicsPipelineCreationError::WrongShaderType),
            }
        }

        let tessellation = match self.input_assembly_topology {
            PrimitiveTopology::PatchList { vertices_per_patch } => {
                if self.tessellation.is_none() {
                    return Err(GraphicsPipelineCreationError::InvalidPrimitiveTopology);
                }
                if vertices_per_patch >
                    device
                        .physical_device()
                        .limits()
                        .max_tessellation_patch_size()
                {
                    return Err(GraphicsPipelineCreationError::MaxTessellationPatchSizeExceeded);
                }

                Some(vk::PipelineTessellationStateCreateInfo {
                         sType: vk::STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO,
                         pNext: ptr::null(),
                         flags: 0, // reserved,
                         patchControlPoints: vertices_per_patch,
                     })
            },
            _ => {
                if self.tessellation.is_some() {
                    return Err(GraphicsPipelineCreationError::InvalidPrimitiveTopology);
                }

                None
            },
        };

        let (vp_vp, vp_sc, vp_num) = match *self.viewport.as_ref().unwrap() {
            ViewportsState::Fixed { ref data } => (data.iter()
                                                       .map(|e| e.0.clone().into_vulkan_viewport())
                                                       .collect::<SmallVec<[vk::Viewport; 4]>>(),
                                                   data.iter()
                                                       .map(|e| e.1.clone().into_vulkan_rect())
                                                       .collect::<SmallVec<[vk::Rect2D; 4]>>(),
                                                   data.len() as u32),
            ViewportsState::DynamicViewports { ref scissors } => {
                let num = scissors.len() as u32;
                let scissors = scissors
                    .iter()
                    .map(|e| e.clone().into_vulkan_rect())
                    .collect::<SmallVec<[vk::Rect2D; 4]>>();
                dynamic_states.push(vk::DYNAMIC_STATE_VIEWPORT);
                (SmallVec::new(), scissors, num)
            },
            ViewportsState::DynamicScissors { ref viewports } => {
                let num = viewports.len() as u32;
                let viewports = viewports
                    .iter()
                    .map(|e| e.clone().into_vulkan_viewport())
                    .collect::<SmallVec<[vk::Viewport; 4]>>();
                dynamic_states.push(vk::DYNAMIC_STATE_SCISSOR);
                (viewports, SmallVec::new(), num)
            },
            ViewportsState::Dynamic { num } => {
                dynamic_states.push(vk::DYNAMIC_STATE_VIEWPORT);
                dynamic_states.push(vk::DYNAMIC_STATE_SCISSOR);
                (SmallVec::new(), SmallVec::new(), num)
            },
        };

        if vp_num > 1 && !device.enabled_features().multi_viewport {
            return Err(GraphicsPipelineCreationError::MultiViewportFeatureNotEnabled);
        }

        if vp_num > device.physical_device().limits().max_viewports() {
            return Err(GraphicsPipelineCreationError::MaxViewportsExceeded {
                           obtained: vp_num,
                           max: device.physical_device().limits().max_viewports(),
                       });
        }

        for vp in vp_vp.iter() {
            if vp.width > device.physical_device().limits().max_viewport_dimensions()[0] as f32 ||
                vp.height > device.physical_device().limits().max_viewport_dimensions()[1] as f32
            {
                return Err(GraphicsPipelineCreationError::MaxViewportDimensionsExceeded);
            }

            if vp.x < device.physical_device().limits().viewport_bounds_range()[0] ||
                vp.x + vp.width > device.physical_device().limits().viewport_bounds_range()[1] ||
                vp.y < device.physical_device().limits().viewport_bounds_range()[0] ||
                vp.y + vp.height > device.physical_device().limits().viewport_bounds_range()[1]
            {
                return Err(GraphicsPipelineCreationError::ViewportBoundsExceeded);
            }
        }

        let viewport_info = vk::PipelineViewportStateCreateInfo {
            sType: vk::STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO,
            pNext: ptr::null(),
            flags: 0, // reserved
            viewportCount: vp_num,
            pViewports: if vp_vp.is_empty() {
                ptr::null()
            } else {
                vp_vp.as_ptr()
            }, // validation layer crashes if you just pass the pointer
            scissorCount: vp_num,
            pScissors: if vp_sc.is_empty() {
                ptr::null()
            } else {
                vp_sc.as_ptr()
            }, // validation layer crashes if you just pass the pointer
        };

        if let Some(line_width) = self.raster.line_width {
            if line_width != 1.0 && !device.enabled_features().wide_lines {
                return Err(GraphicsPipelineCreationError::WideLinesFeatureNotEnabled);
            }
        } else {
            dynamic_states.push(vk::DYNAMIC_STATE_LINE_WIDTH);
        }

        let (db_enable, db_const, db_clamp, db_slope) = match self.raster.depth_bias {
            DepthBiasControl::Dynamic => {
                dynamic_states.push(vk::DYNAMIC_STATE_DEPTH_BIAS);
                (vk::TRUE, 0.0, 0.0, 0.0)
            },
            DepthBiasControl::Disabled => {
                (vk::FALSE, 0.0, 0.0, 0.0)
            },
            DepthBiasControl::Static(bias) => {
                if bias.clamp != 0.0 && !device.enabled_features().depth_bias_clamp {
                    return Err(GraphicsPipelineCreationError::DepthBiasClampFeatureNotEnabled);
                }

                (vk::TRUE, bias.constant_factor, bias.clamp, bias.slope_factor)
            },
        };

        if self.raster.depth_clamp && !device.enabled_features().depth_clamp {
            return Err(GraphicsPipelineCreationError::DepthClampFeatureNotEnabled);
        }

        if self.raster.polygon_mode != PolygonMode::Fill &&
            !device.enabled_features().fill_mode_non_solid
        {
            return Err(GraphicsPipelineCreationError::FillModeNonSolidFeatureNotEnabled);
        }

        let rasterization = vk::PipelineRasterizationStateCreateInfo {
            sType: vk::STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO,
            pNext: ptr::null(),
            flags: 0, // reserved
            depthClampEnable: if self.raster.depth_clamp {
                vk::TRUE
            } else {
                vk::FALSE
            },
            rasterizerDiscardEnable: if self.raster.rasterizer_discard {
                vk::TRUE
            } else {
                vk::FALSE
            },
            polygonMode: self.raster.polygon_mode as u32,
            cullMode: self.raster.cull_mode as u32,
            frontFace: self.raster.front_face as u32,
            depthBiasEnable: db_enable,
            depthBiasConstantFactor: db_const,
            depthBiasClamp: db_clamp,
            depthBiasSlopeFactor: db_slope,
            lineWidth: self.raster.line_width.unwrap_or(1.0),
        };

        self.multisample.rasterizationSamples = self.render_pass
            .as_ref()
            .unwrap()
            .num_samples()
            .unwrap_or(1);
        if self.multisample.sampleShadingEnable != vk::FALSE {
            debug_assert!(self.multisample.minSampleShading >= 0.0 &&
                              self.multisample.minSampleShading <= 1.0);
            if !device.enabled_features().sample_rate_shading {
                return Err(GraphicsPipelineCreationError::SampleRateShadingFeatureNotEnabled);
            }
        }
        if self.multisample.alphaToOneEnable != vk::FALSE {
            if !device.enabled_features().alpha_to_one {
                return Err(GraphicsPipelineCreationError::AlphaToOneFeatureNotEnabled);
            }
        }

        let depth_stencil = {
            let db = match self.depth_stencil.depth_bounds_test {
                DepthBounds::Disabled => (vk::FALSE, 0.0, 0.0),
                DepthBounds::Fixed(ref range) => {
                    if !device.enabled_features().depth_bounds {
                        return Err(GraphicsPipelineCreationError::DepthBoundsFeatureNotEnabled);
                    }

                    (vk::TRUE, range.start, range.end)
                },
                DepthBounds::Dynamic => {
                    if !device.enabled_features().depth_bounds {
                        return Err(GraphicsPipelineCreationError::DepthBoundsFeatureNotEnabled);
                    }

                    dynamic_states.push(vk::DYNAMIC_STATE_DEPTH_BOUNDS);

                    (vk::TRUE, 0.0, 1.0)
                },
            };

            match (self.depth_stencil.stencil_front.compare_mask,
                     self.depth_stencil.stencil_back.compare_mask) {
                (Some(_), Some(_)) => (),
                (None, None) => {
                    dynamic_states.push(vk::DYNAMIC_STATE_STENCIL_COMPARE_MASK);
                },
                _ => return Err(GraphicsPipelineCreationError::WrongStencilState),
            };

            match (self.depth_stencil.stencil_front.write_mask,
                     self.depth_stencil.stencil_back.write_mask) {
                (Some(_), Some(_)) => (),
                (None, None) => {
                    dynamic_states.push(vk::DYNAMIC_STATE_STENCIL_WRITE_MASK);
                },
                _ => return Err(GraphicsPipelineCreationError::WrongStencilState),
            };

            match (self.depth_stencil.stencil_front.reference,
                     self.depth_stencil.stencil_back.reference) {
                (Some(_), Some(_)) => (),
                (None, None) => {
                    dynamic_states.push(vk::DYNAMIC_STATE_STENCIL_REFERENCE);
                },
                _ => return Err(GraphicsPipelineCreationError::WrongStencilState),
            };

            if self.depth_stencil.depth_write &&
                !self.render_pass.as_ref().unwrap().has_writable_depth()
            {
                return Err(GraphicsPipelineCreationError::NoDepthAttachment);
            }

            if self.depth_stencil.depth_compare != Compare::Always &&
                !self.render_pass.as_ref().unwrap().has_depth()
            {
                return Err(GraphicsPipelineCreationError::NoDepthAttachment);
            }

            if (!self.depth_stencil.stencil_front.always_keep() ||
                    !self.depth_stencil.stencil_back.always_keep()) &&
                !self.render_pass.as_ref().unwrap().has_stencil()
            {
                return Err(GraphicsPipelineCreationError::NoStencilAttachment);
            }

            // FIXME: stencil writability

            vk::PipelineDepthStencilStateCreateInfo {
                sType: vk::STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO,
                pNext: ptr::null(),
                flags: 0, // reserved
                depthTestEnable: if !self.depth_stencil.depth_write &&
                    self.depth_stencil.depth_compare == Compare::Always
                {
                    vk::FALSE
                } else {
                    vk::TRUE
                },
                depthWriteEnable: if self.depth_stencil.depth_write {
                    vk::TRUE
                } else {
                    vk::FALSE
                },
                depthCompareOp: self.depth_stencil.depth_compare as u32,
                depthBoundsTestEnable: db.0,
                stencilTestEnable: if self.depth_stencil.stencil_front.always_keep() &&
                    self.depth_stencil.stencil_back.always_keep()
                {
                    vk::FALSE
                } else {
                    vk::TRUE
                },
                front: vk::StencilOpState {
                    failOp: self.depth_stencil.stencil_front.fail_op as u32,
                    passOp: self.depth_stencil.stencil_front.pass_op as u32,
                    depthFailOp: self.depth_stencil.stencil_front.depth_fail_op as u32,
                    compareOp: self.depth_stencil.stencil_front.compare as u32,
                    compareMask: self.depth_stencil
                        .stencil_front
                        .compare_mask
                        .unwrap_or(u32::MAX),
                    writeMask: self.depth_stencil
                        .stencil_front
                        .write_mask
                        .unwrap_or(u32::MAX),
                    reference: self.depth_stencil.stencil_front.reference.unwrap_or(0),
                },
                back: vk::StencilOpState {
                    failOp: self.depth_stencil.stencil_back.fail_op as u32,
                    passOp: self.depth_stencil.stencil_back.pass_op as u32,
                    depthFailOp: self.depth_stencil.stencil_back.depth_fail_op as u32,
                    compareOp: self.depth_stencil.stencil_back.compare as u32,
                    compareMask: self.depth_stencil
                        .stencil_back
                        .compare_mask
                        .unwrap_or(u32::MAX),
                    writeMask: self.depth_stencil
                        .stencil_back
                        .write_mask
                        .unwrap_or(u32::MAX),
                    reference: self.depth_stencil.stencil_back.reference.unwrap_or(0),
                },
                minDepthBounds: db.1,
                maxDepthBounds: db.2,
            }
        };

        let blend_atch: SmallVec<[vk::PipelineColorBlendAttachmentState; 8]> = {
            let num_atch = self.render_pass.as_ref().unwrap().num_color_attachments();

            match self.blend.attachments {
                AttachmentsBlend::Collective(blend) => {
                    (0 .. num_atch)
                        .map(|_| blend.clone().into_vulkan_state())
                        .collect()
                },
                AttachmentsBlend::Individual(blend) => {
                    if blend.len() != num_atch as usize {
                        return Err(GraphicsPipelineCreationError::MismatchBlendingAttachmentsCount);
                    }

                    if !device.enabled_features().independent_blend {
                        return Err(GraphicsPipelineCreationError::IndependentBlendFeatureNotEnabled);
                    }

                    blend
                        .iter()
                        .map(|b| b.clone().into_vulkan_state())
                        .collect()
                },
            }
        };

        let blend = vk::PipelineColorBlendStateCreateInfo {
            sType: vk::STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO,
            pNext: ptr::null(),
            flags: 0, // reserved
            logicOpEnable: if self.blend.logic_op.is_some() {
                if !device.enabled_features().logic_op {
                    return Err(GraphicsPipelineCreationError::LogicOpFeatureNotEnabled);
                }
                vk::TRUE
            } else {
                vk::FALSE
            },
            logicOp: self.blend.logic_op.unwrap_or(Default::default()) as u32,
            attachmentCount: blend_atch.len() as u32,
            pAttachments: blend_atch.as_ptr(),
            blendConstants: if let Some(c) = self.blend.blend_constants {
                c
            } else {
                dynamic_states.push(vk::DYNAMIC_STATE_BLEND_CONSTANTS);
                [0.0, 0.0, 0.0, 0.0]
            },
        };

        let dynamic_states = if !dynamic_states.is_empty() {
            Some(vk::PipelineDynamicStateCreateInfo {
                     sType: vk::STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO,
                     pNext: ptr::null(),
                     flags: 0, // reserved
                     dynamicStateCount: dynamic_states.len() as u32,
                     pDynamicStates: dynamic_states.as_ptr(),
                 })
        } else {
            None
        };

        let pipeline = unsafe {
            let infos = vk::GraphicsPipelineCreateInfo {
                sType: vk::STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO,
                pNext: ptr::null(),
                flags: 0, // TODO: some flags are available but none are critical
                stageCount: stages.len() as u32,
                pStages: stages.as_ptr(),
                pVertexInputState: &vertex_input_state,
                pInputAssemblyState: &self.input_assembly,
                pTessellationState: tessellation
                    .as_ref()
                    .map(|t| t as *const _)
                    .unwrap_or(ptr::null()),
                pViewportState: &viewport_info,
                pRasterizationState: &rasterization,
                pMultisampleState: &self.multisample,
                pDepthStencilState: &depth_stencil,
                pColorBlendState: &blend,
                pDynamicState: dynamic_states
                    .as_ref()
                    .map(|s| s as *const _)
                    .unwrap_or(ptr::null()),
                layout: PipelineLayoutAbstract::sys(&pipeline_layout).internal_object(),
                renderPass: self.render_pass
                    .as_ref()
                    .unwrap()
                    .render_pass()
                    .inner()
                    .internal_object(),
                subpass: self.render_pass.as_ref().unwrap().index(),
                basePipelineHandle: 0, // TODO:
                basePipelineIndex: -1, // TODO:
            };

            let mut output = mem::uninitialized();
            check_errors(vk.CreateGraphicsPipelines(device.internal_object(),
                                                    0,
                                                    1,
                                                    &infos,
                                                    ptr::null(),
                                                    &mut output))?;
            output
        };

        let (render_pass, render_pass_subpass) = self.render_pass.take().unwrap().into();

        Ok(GraphicsPipeline {
               inner: GraphicsPipelineInner {
                   device: device.clone(),
                   pipeline: pipeline,
               },
               layout: pipeline_layout,

               vertex_definition: self.vertex_input,

               render_pass: render_pass,
               render_pass_subpass: render_pass_subpass,

               dynamic_line_width: self.raster.line_width.is_none(),
               dynamic_viewport: self.viewport.as_ref().unwrap().dynamic_viewports(),
               dynamic_scissor: self.viewport.as_ref().unwrap().dynamic_scissors(),
               dynamic_depth_bias: self.raster.depth_bias.is_dynamic(),
               dynamic_depth_bounds: self.depth_stencil.depth_bounds_test.is_dynamic(),
               dynamic_stencil_compare_mask: self.depth_stencil.stencil_back.compare_mask.is_none(),
               dynamic_stencil_write_mask: self.depth_stencil.stencil_back.write_mask.is_none(),
               dynamic_stencil_reference: self.depth_stencil.stencil_back.reference.is_none(),
               dynamic_blend_constants: self.blend.blend_constants.is_none(),

               num_viewports: self.viewport.as_ref().unwrap().num_viewports(),
           })
    }

    // TODO: add build_with_cache method
}

impl<Vdef, Vs, Vss, Tcs, Tcss, Tes, Tess, Gs, Gss, Fs, Fss, Rp>
    GraphicsPipelineBuilder<Vdef, Vs, Vss, Tcs, Tcss, Tes, Tess, Gs, Gss, Fs, Fss, Rp> {
    // TODO: add pipeline derivate system

    /// Sets the vertex input.
    #[inline]
    pub fn vertex_input<T>(
        self, vertex_input: T)
        -> GraphicsPipelineBuilder<T, Vs, Vss, Tcs, Tcss, Tes, Tess, Gs, Gss, Fs, Fss, Rp> {
        GraphicsPipelineBuilder {
            vertex_input: vertex_input,
            vertex_shader: self.vertex_shader,
            input_assembly: self.input_assembly,
            input_assembly_topology: self.input_assembly_topology,
            tessellation: self.tessellation,
            geometry_shader: self.geometry_shader,
            viewport: self.viewport,
            raster: self.raster,
            multisample: self.multisample,
            fragment_shader: self.fragment_shader,
            depth_stencil: self.depth_stencil,
            blend: self.blend,
            render_pass: self.render_pass,
        }
    }

    /// Sets the vertex input to a single vertex buffer.
    ///
    /// You will most likely need to explicitly specify the template parameter to the type of a
    /// vertex.
    #[inline]
    pub fn vertex_input_single_buffer<V>(self)
                                         -> GraphicsPipelineBuilder<SingleBufferDefinition<V>,
                                                                    Vs,
                                                                    Vss,
                                                                    Tcs,
                                                                    Tcss,
                                                                    Tes,
                                                                    Tess,
                                                                    Gs,
                                                                    Gss,
                                                                    Fs,
                                                                    Fss,
                                                                    Rp> {
        self.vertex_input(SingleBufferDefinition::<V>::new())
    }

    /// Sets the vertex shader to use.
    // TODO: correct specialization constants
    #[inline]
    pub fn vertex_shader<Vs2, Vss2>(
        self, shader: Vs2, specialization_constants: Vss2)
        -> GraphicsPipelineBuilder<Vdef, Vs2, Vss2, Tcs, Tcss, Tes, Tess, Gs, Gss, Fs, Fss, Rp>
        where Vs2: GraphicsEntryPointAbstract<SpecializationConstants = Vss2>,
              Vss2: SpecializationConstants
    {
        GraphicsPipelineBuilder {
            vertex_input: self.vertex_input,
            vertex_shader: Some((shader, specialization_constants)),
            input_assembly: self.input_assembly,
            input_assembly_topology: self.input_assembly_topology,
            tessellation: self.tessellation,
            geometry_shader: self.geometry_shader,
            viewport: self.viewport,
            raster: self.raster,
            multisample: self.multisample,
            fragment_shader: self.fragment_shader,
            depth_stencil: self.depth_stencil,
            blend: self.blend,
            render_pass: self.render_pass,
        }
    }

    /// Sets whether primitive restart if enabled.
    #[inline]
    pub fn primitive_restart(mut self, enabled: bool) -> Self {
        self.input_assembly.primitiveRestartEnable = if enabled {
            vk::TRUE
        } else {
            vk::FALSE
        };

        self
    }

    /// Sets the topology of the primitives that are expected by the pipeline.
    #[inline]
    pub fn primitive_topology(mut self, topology: PrimitiveTopology) -> Self {
        self.input_assembly_topology = topology;
        self.input_assembly.topology = topology.into();
        self
    }

    /// Sets the topology of the primitives to a list of points.
    ///
    /// > **Note**: This is equivalent to
    /// > `self.primitive_topology(PrimitiveTopology::PointList)`.
    #[inline]
    pub fn point_list(self) -> Self {
        self.primitive_topology(PrimitiveTopology::PointList)
    }

    /// Sets the topology of the primitives to a list of lines.
    ///
    /// > **Note**: This is equivalent to
    /// > `self.primitive_topology(PrimitiveTopology::LineList)`.
    #[inline]
    pub fn line_list(self) -> Self {
        self.primitive_topology(PrimitiveTopology::LineList)
    }

    /// Sets the topology of the primitives to a line strip.
    ///
    /// > **Note**: This is equivalent to
    /// > `self.primitive_topology(PrimitiveTopology::LineStrip)`.
    #[inline]
    pub fn line_strip(self) -> Self {
        self.primitive_topology(PrimitiveTopology::LineStrip)
    }

    /// Sets the topology of the primitives to a list of triangles. Note that this is the default.
    ///
    /// > **Note**: This is equivalent to
    /// > `self.primitive_topology(PrimitiveTopology::TriangleList)`.
    #[inline]
    pub fn triangle_list(self) -> Self {
        self.primitive_topology(PrimitiveTopology::TriangleList)
    }

    /// Sets the topology of the primitives to a triangle strip.
    ///
    /// > **Note**: This is equivalent to
    /// > `self.primitive_topology(PrimitiveTopology::TriangleStrip)`.
    #[inline]
    pub fn triangle_strip(self) -> Self {
        self.primitive_topology(PrimitiveTopology::TriangleStrip)
    }

    /// Sets the topology of the primitives to a fan of triangles.
    ///
    /// > **Note**: This is equivalent to
    /// > `self.primitive_topology(PrimitiveTopology::TriangleFan)`.
    #[inline]
    pub fn triangle_fan(self) -> Self {
        self.primitive_topology(PrimitiveTopology::TriangleFan)
    }

    /// Sets the topology of the primitives to a list of lines with adjacency information.
    ///
    /// > **Note**: This is equivalent to
    /// > `self.primitive_topology(PrimitiveTopology::LineListWithAdjacency)`.
    #[inline]
    pub fn line_list_with_adjacency(self) -> Self {
        self.primitive_topology(PrimitiveTopology::LineListWithAdjacency)
    }

    /// Sets the topology of the primitives to a line strip with adjacency information.
    ///
    /// > **Note**: This is equivalent to
    /// > `self.primitive_topology(PrimitiveTopology::LineStripWithAdjacency)`.
    #[inline]
    pub fn line_strip_with_adjacency(self) -> Self {
        self.primitive_topology(PrimitiveTopology::LineStripWithAdjacency)
    }

    /// Sets the topology of the primitives to a list of triangles with adjacency information.
    ///
    /// > **Note**: This is equivalent to
    /// > `self.primitive_topology(PrimitiveTopology::TriangleListWithAdjacency)`.
    #[inline]
    pub fn triangle_list_with_adjacency(self) -> Self {
        self.primitive_topology(PrimitiveTopology::TriangleListWithAdjacency)
    }

    /// Sets the topology of the primitives to a triangle strip with adjacency information`
    ///
    /// > **Note**: This is equivalent to
    /// > `self.primitive_topology(PrimitiveTopology::TriangleStripWithAdjacency)`.
    #[inline]
    pub fn triangle_strip_with_adjacency(self) -> Self {
        self.primitive_topology(PrimitiveTopology::TriangleStripWithAdjacency)
    }

    /// Sets the topology of the primitives to a list of patches. Can only be used and must be used
    /// with a tessellation shader.
    ///
    /// > **Note**: This is equivalent to
    /// > `self.primitive_topology(PrimitiveTopology::PatchList { vertices_per_patch })`.
    #[inline]
    pub fn patch_list(self, vertices_per_patch: u32) -> Self {
        self.primitive_topology(PrimitiveTopology::PatchList { vertices_per_patch })
    }

    /// Sets the tessellation shaders to use.
    // TODO: correct specialization constants
    #[inline]
    pub fn tessellation_shaders<Tcs2, Tcss2, Tes2, Tess2>(
        self, tessellation_control_shader: Tcs2,
        tessellation_control_shader_spec_constants: Tcss2, tessellation_evaluation_shader: Tes2,
        tessellation_evaluation_shader_spec_constants: Tess2)
        -> GraphicsPipelineBuilder<Vdef, Vs, Vss, Tcs2, Tcss2, Tes2, Tess2, Gs, Gss, Fs, Fss, Rp>
        where Tcs2: GraphicsEntryPointAbstract<SpecializationConstants = Tcss2>,
              Tes2: GraphicsEntryPointAbstract<SpecializationConstants = Tess2>,
              Tcss2: SpecializationConstants,
              Tess2: SpecializationConstants
    {
        GraphicsPipelineBuilder {
            vertex_input: self.vertex_input,
            vertex_shader: self.vertex_shader,
            input_assembly: self.input_assembly,
            input_assembly_topology: self.input_assembly_topology,
            tessellation: Some(TessInfo {
                                   tessellation_control_shader:
                                       (tessellation_control_shader,
                                        tessellation_control_shader_spec_constants),
                                   tessellation_evaluation_shader:
                                       (tessellation_evaluation_shader,
                                        tessellation_evaluation_shader_spec_constants),
                               }),
            geometry_shader: self.geometry_shader,
            viewport: self.viewport,
            raster: self.raster,
            multisample: self.multisample,
            fragment_shader: self.fragment_shader,
            depth_stencil: self.depth_stencil,
            blend: self.blend,
            render_pass: self.render_pass,
        }
    }

    /// Sets the tessellation shaders stage as disabled. This is the default.
    #[inline]
    pub fn tessellation_shaders_disabled(mut self) -> Self {
        self.tessellation = None;
        self
    }

    /// Sets the geometry shader to use.
    // TODO: correct specialization constants
    #[inline]
    pub fn geometry_shader<Gs2, Gss2>(
        self, shader: Gs2, specialization_constants: Gss2)
        -> GraphicsPipelineBuilder<Vdef, Vs, Vss, Tcs, Tcss, Tes, Tess, Gs2, Gss2, Fs, Fss, Rp>
        where Gs2: GraphicsEntryPointAbstract<SpecializationConstants = Gss2>,
              Gss2: SpecializationConstants
    {
        GraphicsPipelineBuilder {
            vertex_input: self.vertex_input,
            vertex_shader: self.vertex_shader,
            input_assembly: self.input_assembly,
            input_assembly_topology: self.input_assembly_topology,
            tessellation: self.tessellation,
            geometry_shader: Some((shader, specialization_constants)),
            viewport: self.viewport,
            raster: self.raster,
            multisample: self.multisample,
            fragment_shader: self.fragment_shader,
            depth_stencil: self.depth_stencil,
            blend: self.blend,
            render_pass: self.render_pass,
        }
    }

    /// Sets the geometry shader stage as disabled. This is the default.
    #[inline]
    pub fn geometry_shader_disabled(mut self) -> Self {
        self.geometry_shader = None;
        self
    }

    /// Sets the viewports to some value, and the scissor boxes to boxes that always cover the
    /// whole viewport.
    #[inline]
    pub fn viewports<I>(self, viewports: I) -> Self
        where I: IntoIterator<Item = Viewport>
    {
        self.viewports_scissors(viewports.into_iter().map(|v| (v, Scissor::irrelevant())))
    }

    /// Sets the characteristics of viewports and scissor boxes in advance.
    #[inline]
    pub fn viewports_scissors<I>(mut self, viewports: I) -> Self
        where I: IntoIterator<Item = (Viewport, Scissor)>
    {
        self.viewport = Some(ViewportsState::Fixed { data: viewports.into_iter().collect() });
        self
    }

    /// Sets the scissor boxes to some values, and viewports to dynamic. The viewports will
    /// need to be set before drawing.
    #[inline]
    pub fn viewports_dynamic_scissors_fixed<I>(mut self, scissors: I) -> Self
        where I: IntoIterator<Item = Scissor>
    {
        self.viewport =
            Some(ViewportsState::DynamicViewports { scissors: scissors.into_iter().collect() });
        self
    }

    /// Sets the viewports to dynamic, and the scissor boxes to boxes that always cover the whole
    /// viewport. The viewports will need to be set before drawing.
    #[inline]
    pub fn viewports_dynamic_scissors_irrelevant(mut self, num: u32) -> Self {
        self.viewport = Some(ViewportsState::DynamicViewports {
                                 scissors: (0 .. num).map(|_| Scissor::irrelevant()).collect(),
                             });
        self
    }

    /// Sets the viewports to some values, and scissor boxes to dynamic. The scissor boxes will
    /// need to be set before drawing.
    #[inline]
    pub fn viewports_fixed_scissors_dynamic<I>(mut self, viewports: I) -> Self
        where I: IntoIterator<Item = Viewport>
    {
        self.viewport =
            Some(ViewportsState::DynamicScissors { viewports: viewports.into_iter().collect() });
        self
    }

    /// Sets the viewports and scissor boxes to dynamic. They will both need to be set before
    /// drawing.
    #[inline]
    pub fn viewports_scissors_dynamic(mut self, num: u32) -> Self {
        self.viewport = Some(ViewportsState::Dynamic { num: num });
        self
    }

    /// If true, then the depth value of the vertices will be clamped to the range `[0.0 ; 1.0]`.
    /// If false, fragments whose depth is outside of this range will be discarded before the
    /// fragment shader even runs.
    #[inline]
    pub fn depth_clamp(mut self, clamp: bool) -> Self {
        self.raster.depth_clamp = clamp;
        self
    }

    // TODO: this won't work correctly
    /*/// Disables the fragment shader stage.
    #[inline]
    pub fn rasterizer_discard(mut self) -> Self {
        self.rasterization.rasterizer_discard. = true;
        self
    }*/

    /// Sets the front-facing faces to counter-clockwise faces. This is the default.
    ///
    /// Triangles whose vertices are oriented counter-clockwise on the screen will be considered
    /// as facing their front. Otherwise they will be considered as facing their back.
    #[inline]
    pub fn front_face_counter_clockwise(mut self) -> Self {
        self.raster.front_face = FrontFace::CounterClockwise;
        self
    }

    /// Sets the front-facing faces to clockwise faces.
    ///
    /// Triangles whose vertices are oriented clockwise on the screen will be considered
    /// as facing their front. Otherwise they will be considered as facing their back.
    #[inline]
    pub fn front_face_clockwise(mut self) -> Self {
        self.raster.front_face = FrontFace::Clockwise;
        self
    }

    /// Sets backface culling as disabled. This is the default.
    #[inline]
    pub fn cull_mode_disabled(mut self) -> Self {
        self.raster.cull_mode = CullMode::None;
        self
    }

    /// Sets backface culling to front faces. The front faces (as chosen with the `front_face_*`
    /// methods) will be discarded by the GPU when drawing.
    #[inline]
    pub fn cull_mode_front(mut self) -> Self {
        self.raster.cull_mode = CullMode::Front;
        self
    }

    /// Sets backface culling to back faces. Faces that are not facing the front (as chosen with
    /// the `front_face_*` methods) will be discarded by the GPU when drawing.
    #[inline]
    pub fn cull_mode_back(mut self) -> Self {
        self.raster.cull_mode = CullMode::Back;
        self
    }

    /// Sets backface culling to both front and back faces. All the faces will be discarded.
    ///
    /// > **Note**: This option exists for the sake of completeness. It has no known practical
    /// > usage.
    #[inline]
    pub fn cull_mode_front_and_back(mut self) -> Self {
        self.raster.cull_mode = CullMode::FrontAndBack;
        self
    }

    /// Sets the polygon mode to "fill". This is the default.
    #[inline]
    pub fn polygon_mode_fill(mut self) -> Self {
        self.raster.polygon_mode = PolygonMode::Fill;
        self
    }

    /// Sets the polygon mode to "line". Triangles will each be turned into three lines.
    #[inline]
    pub fn polygon_mode_line(mut self) -> Self {
        self.raster.polygon_mode = PolygonMode::Line;
        self
    }

    /// Sets the polygon mode to "point". Triangles and lines will each be turned into three points.
    #[inline]
    pub fn polygon_mode_point(mut self) -> Self {
        self.raster.polygon_mode = PolygonMode::Point;
        self
    }

    /// Sets the width of the lines, if the GPU needs to draw lines. The default is `1.0`.
    #[inline]
    pub fn line_width(mut self, value: f32) -> Self {
        self.raster.line_width = Some(value);
        self
    }

    /// Sets the width of the lines as dynamic, which means that you will need to set this value
    /// when drawing.
    #[inline]
    pub fn line_width_dynamic(mut self) -> Self {
        self.raster.line_width = None;
        self
    }

    // TODO: missing DepthBiasControl

    /// Disables sample shading. The fragment shader will only be run once per fragment (ie. per
    /// pixel) and not once by sample. The output will then be copied in all of the covered
    /// samples.
    ///
    /// Sample shading is disabled by default.
    #[inline]
    pub fn sample_shading_disabled(mut self) -> Self {
        self.multisample.sampleShadingEnable = vk::FALSE;
        self
    }

    /// Enables sample shading. The fragment shader will be run once per sample at the borders of
    /// the object you're drawing.
    ///
    /// Enabling sampling shading requires the `sample_rate_shading` feature to be enabled on the
    /// device.
    ///
    /// The `min_fract` parameter is the minimum fraction of samples shading. For example if its
    /// value is 0.5, then the fragment shader will run for at least half of the samples. The other
    /// half of the samples will get their values determined automatically.
    ///
    /// Sample shading is disabled by default.
    ///
    /// # Panic
    ///
    /// - Panics if `min_fract` is not between 0.0 and 1.0.
    ///
    #[inline]
    pub fn sample_shading_enabled(mut self, min_fract: f32) -> Self {
        assert!(min_fract >= 0.0 && min_fract <= 1.0);
        self.multisample.sampleShadingEnable = vk::TRUE;
        self.multisample.minSampleShading = min_fract;
        self
    }

    // TODO: doc
    pub fn alpha_to_coverage_disabled(mut self) -> Self {
        self.multisample.alphaToCoverageEnable = vk::FALSE;
        self
    }

    // TODO: doc
    pub fn alpha_to_coverage_enabled(mut self) -> Self {
        self.multisample.alphaToCoverageEnable = vk::TRUE;
        self
    }

    /// Disables alpha-to-one.
    ///
    /// Alpha-to-one is disabled by default.
    #[inline]
    pub fn alpha_to_one_disabled(mut self) -> Self {
        self.multisample.alphaToOneEnable = vk::FALSE;
        self
    }

    /// Enables alpha-to-one. The alpha component of the first color output of the fragment shader
    /// will be replaced by the value `1.0`.
    ///
    /// Enabling alpha-to-one requires the `alpha_to_one` feature to be enabled on the device.
    ///
    /// Alpha-to-one is disabled by default.
    #[inline]
    pub fn alpha_to_one_enabled(mut self) -> Self {
        self.multisample.alphaToOneEnable = vk::TRUE;
        self
    }

    // TODO: rasterizationSamples and pSampleMask

    /// Sets the fragment shader to use.
    ///
    /// The fragment shader is run once for each pixel that is covered by each primitive.
    // TODO: correct specialization constants
    #[inline]
    pub fn fragment_shader<Fs2, Fss2>(
        self, shader: Fs2, specialization_constants: Fss2)
        -> GraphicsPipelineBuilder<Vdef, Vs, Vss, Tcs, Tcss, Tes, Tess, Gs, Gss, Fs2, Fss2, Rp>
        where Fs2: GraphicsEntryPointAbstract<SpecializationConstants = Fss2>,
              Fss2: SpecializationConstants
    {
        GraphicsPipelineBuilder {
            vertex_input: self.vertex_input,
            vertex_shader: self.vertex_shader,
            input_assembly: self.input_assembly,
            input_assembly_topology: self.input_assembly_topology,
            tessellation: self.tessellation,
            geometry_shader: self.geometry_shader,
            viewport: self.viewport,
            raster: self.raster,
            multisample: self.multisample,
            fragment_shader: Some((shader, specialization_constants)),
            depth_stencil: self.depth_stencil,
            blend: self.blend,
            render_pass: self.render_pass,
        }
    }

    /// Sets the depth/stencil configuration. This function may be removed in the future.
    #[inline]
    pub fn depth_stencil(mut self, depth_stencil: DepthStencil) -> Self {
        self.depth_stencil = depth_stencil;
        self
    }

    /// Sets the depth/stencil tests as disabled.
    ///
    /// > **Note**: This is a shortcut for all the other `depth_*` and `depth_stencil_*` methods
    /// > of the builder.
    #[inline]
    pub fn depth_stencil_disabled(mut self) -> Self {
        self.depth_stencil = DepthStencil::disabled();
        self
    }

    /// Sets the depth/stencil tests as a simple depth test and no stencil test.
    ///
    /// > **Note**: This is a shortcut for setting the depth test to `Less`, the depth write Into
    /// > ` true` and disable the stencil test.
    #[inline]
    pub fn depth_stencil_simple_depth(mut self) -> Self {
        self.depth_stencil = DepthStencil::simple_depth_test();
        self
    }

    /// Sets whether the depth buffer will be written.
    #[inline]
    pub fn depth_write(mut self, write: bool) -> Self {
        self.depth_stencil.depth_write = write;
        self
    }

    // TODO: missing tons of depth-stencil stuff


    #[inline]
    pub fn blend_collective(mut self, blend: AttachmentBlend) -> Self {
        self.blend.attachments = AttachmentsBlend::Collective(blend);
        self
    }

    #[inline]
    pub fn blend_individual<I>(mut self, blend: I) -> Self
        where I: IntoIterator<Item = AttachmentBlend>
    {
        self.blend.attachments = AttachmentsBlend::Individual(blend.into_iter().collect());
        self
    }

    /// Each fragment shader output will have its value directly written to the framebuffer
    /// attachment. This is the default.
    #[inline]
    pub fn blend_pass_through(self) -> Self {
        self.blend_collective(AttachmentBlend::pass_through())
    }

    #[inline]
    pub fn blend_alpha_blending(self) -> Self {
        self.blend_collective(AttachmentBlend::alpha_blending())
    }

    #[inline]
    pub fn blend_logic_op(mut self, logic_op: LogicOp) -> Self {
        self.blend.logic_op = Some(logic_op);
        self
    }

    /// Sets the logic operation as disabled. This is the default.
    #[inline]
    pub fn blend_logic_op_disabled(mut self) -> Self {
        self.blend.logic_op = None;
        self
    }

    /// Sets the blend constant. The default is `[0.0, 0.0, 0.0, 0.0]`.
    ///
    /// The blend constant is used for some blending calculations. It is irrelevant otherwise.
    #[inline]
    pub fn blend_constants(mut self, constants: [f32; 4]) -> Self {
        self.blend.blend_constants = Some(constants);
        self
    }

    /// Sets the blend constant value as dynamic. Its value will need to be set before drawing.
    ///
    /// The blend constant is used for some blending calculations. It is irrelevant otherwise.
    #[inline]
    pub fn blend_constants_dynamic(mut self) -> Self {
        self.blend.blend_constants = None;
        self
    }

    /// Sets the render pass subpass to use.
    #[inline]
    pub fn render_pass<Rp2>(
        self, subpass: Subpass<Rp2>)
        -> GraphicsPipelineBuilder<Vdef, Vs, Vss, Tcs, Tcss, Tes, Tess, Gs, Gss, Fs, Fss, Rp2> {
        GraphicsPipelineBuilder {
            vertex_input: self.vertex_input,
            vertex_shader: self.vertex_shader,
            input_assembly: self.input_assembly,
            input_assembly_topology: self.input_assembly_topology,
            tessellation: self.tessellation,
            geometry_shader: self.geometry_shader,
            viewport: self.viewport,
            raster: self.raster,
            multisample: self.multisample,
            fragment_shader: self.fragment_shader,
            depth_stencil: self.depth_stencil,
            blend: self.blend,
            render_pass: Some(subpass),
        }
    }
}

impl<Vdef, Vs, Vss, Tcs, Tcss, Tes, Tess, Gs, Gss, Fs, Fss, Rp> Clone
    for GraphicsPipelineBuilder<Vdef, Vs, Vss, Tcs, Tcss, Tes, Tess, Gs, Gss, Fs, Fss, Rp>
    where Vdef: Clone,
          Vs: Clone,
          Vss: Clone,
          Tcs: Clone,
          Tcss: Clone,
          Tes: Clone,
          Tess: Clone,
          Gs: Clone,
          Gss: Clone,
          Fs: Clone,
          Fss: Clone,
          Rp: Clone
{
    fn clone(&self) -> Self {
        GraphicsPipelineBuilder {
            vertex_input: self.vertex_input.clone(),
            vertex_shader: self.vertex_shader.clone(),
            input_assembly: unsafe { ptr::read(&self.input_assembly) },
            input_assembly_topology: self.input_assembly_topology,
            tessellation: self.tessellation.clone(),
            geometry_shader: self.geometry_shader.clone(),
            viewport: self.viewport.clone(),
            raster: self.raster.clone(),
            multisample: vk::PipelineMultisampleStateCreateInfo {
                sType: self.multisample.sType,
                pNext: self.multisample.pNext,
                flags: self.multisample.flags,
                rasterizationSamples: self.multisample.rasterizationSamples,
                sampleShadingEnable: self.multisample.sampleShadingEnable,
                minSampleShading: self.multisample.minSampleShading,
                pSampleMask: self.multisample.pSampleMask,
                alphaToCoverageEnable: self.multisample.alphaToCoverageEnable,
                alphaToOneEnable: self.multisample.alphaToOneEnable,
            },
            fragment_shader: self.fragment_shader.clone(),
            depth_stencil: self.depth_stencil.clone(),
            blend: self.blend.clone(),
            render_pass: self.render_pass.clone(),
        }
    }
}