1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
// Copyright (c) 2016 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.

use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::fmt;
use std::hash;
use std::hash::BuildHasherDefault;
use std::mem;
use std::ops::Range;
use std::ptr;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
use std::u64;
use fnv::FnvHasher;
use smallvec::SmallVec;

use buffer::Buffer;
use buffer::BufferSlice;
use buffer::TypedBuffer;
use buffer::traits::AccessRange as BufferAccessRange;
use command_buffer::CommandBufferPool;
use command_buffer::DrawIndirectCommand;
use command_buffer::DynamicState;
use descriptor::descriptor_set::DescriptorSetsCollection;
use descriptor::PipelineLayout;
use device::Queue;
use format::ClearValue;
use format::FormatDesc;
use format::FormatTy;
use format::PossibleFloatFormatDesc;
use framebuffer::RenderPass;
use framebuffer::RenderPassDesc;
use framebuffer::Framebuffer;
use framebuffer::Subpass;
use image::Image;
use image::ImageView;
use image::sys::Layout as ImageLayout;
use image::traits::ImageClearValue;
use image::traits::ImageContent;
use image::traits::AccessRange as ImageAccessRange;
use pipeline::ComputePipeline;
use pipeline::GraphicsPipeline;
use pipeline::input_assembly::Index;
use pipeline::vertex::Definition as VertexDefinition;
use pipeline::vertex::Source as VertexSource;
use sync::Fence;
use sync::FenceWaitError;
use sync::Semaphore;

use device::Device;
use OomError;
use SynchronizedVulkanObject;
use VulkanObject;
use VulkanPointers;
use check_errors;
use vk;

// TODO: that sucks but we have to lock everything when submitting a command buffer to a queue
//       this is because of synchronization issues when querying resources for their dependencies
lazy_static! {
    static ref GLOBAL_MUTEX: Mutex<()> = Mutex::new(());
}

/// Actual implementation of all command buffer builders.
///
/// Doesn't check whether the command type is appropriate for the command buffer type.
//
// Implementation notes.
//
// Adding a command to an `InnerCommandBufferBuilder` does not immediately add it to the
// `vk::CommandBuffer`. Instead the command is added to a list of staging commands. The reason
// for this design is that we want to minimize the number of pipeline barriers. In order to know
// what must be in a pipeline barrier, we have to be ahead of the actual commands.
//
pub struct InnerCommandBufferBuilder {
    device: Arc<Device>,
    pool: Arc<CommandBufferPool>,
    cmd: Option<vk::CommandBuffer>,

    // If true, we're inside a secondary command buffer (compute or graphics).
    is_secondary: bool,

    // If true, we're inside a secondary graphics command buffer.
    is_secondary_graphics: bool,

    // List of accesses made by this command buffer to buffers and images, exclusing the staging
    // commands and the staging render pass.
    //
    // If a buffer/image is missing in this list, that means it hasn't been used by this command
    // buffer yet and is still in its default state.
    //
    // This list is only updated by the `flush()` function.
    buffers_state: HashMap<(BufferKey, usize), InternalBufferBlockAccess, BuildHasherDefault<FnvHasher>>,
    images_state: HashMap<(ImageKey, (u32, u32)), InternalImageBlockAccess, BuildHasherDefault<FnvHasher>>,

    // List of commands that are waiting to be submitted to the Vulkan command buffer. Doesn't
    // include commands that were submitted within a render pass.
    staging_commands: Vec<Box<FnMut(&vk::DevicePointers, vk::CommandBuffer) + Send + Sync>>,

    // List of resources accesses made by the comands in `staging_commands`. Doesn't include
    // commands added to the current render pass.
    staging_required_buffer_accesses: HashMap<(BufferKey, usize), InternalBufferBlockAccess, BuildHasherDefault<FnvHasher>>,
    staging_required_image_accesses: HashMap<(ImageKey, (u32, u32)), InternalImageBlockAccess, BuildHasherDefault<FnvHasher>>,

    // List of commands that are waiting to be submitted to the Vulkan command buffer when we're
    // inside a render pass. Flushed when `end_renderpass` is called.
    render_pass_staging_commands: Vec<Box<FnMut(&vk::DevicePointers, vk::CommandBuffer) + Send + Sync>>,

    // List of resources accesses made by the current render pass. Merged with
    // `staging_required_buffer_accesses` and `staging_required_image_accesses` when
    // `end_renderpass` is called.
    render_pass_staging_required_buffer_accesses: HashMap<(BufferKey, usize), InternalBufferBlockAccess, BuildHasherDefault<FnvHasher>>,
    render_pass_staging_required_image_accesses: HashMap<(ImageKey, (u32, u32)), InternalImageBlockAccess, BuildHasherDefault<FnvHasher>>,

    // List of resources that must be kept alive because they are used by this command buffer.
    keep_alive: Vec<Arc<KeepAlive>>,

    // Current pipeline object binded to the graphics bind point. Includes all staging commands.
    current_graphics_pipeline: Option<vk::Pipeline>,

    // Current pipeline object binded to the compute bind point. Includes all staging commands.
    current_compute_pipeline: Option<vk::Pipeline>,

    // Current state of the dynamic state within the command buffer. Includes all staging commands.
    current_dynamic_state: DynamicState,
}

impl InnerCommandBufferBuilder {
    /// Creates a new builder.
    pub fn new<R>(pool: &Arc<CommandBufferPool>, secondary: bool, secondary_cont: Option<Subpass<R>>,
                  secondary_cont_fb: Option<&Arc<Framebuffer<R>>>)
                  -> Result<InnerCommandBufferBuilder, OomError>
        where R: RenderPass + 'static + Send + Sync
    {
        let device = pool.device();
        let vk = device.pointers();

        let pool_obj = pool.internal_object_guard();

        let cmd = unsafe {
            let infos = vk::CommandBufferAllocateInfo {
                sType: vk::STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
                pNext: ptr::null(),
                commandPool: *pool_obj,
                level: if secondary {
                    assert!(secondary_cont.is_some());
                    vk::COMMAND_BUFFER_LEVEL_SECONDARY
                } else {
                    vk::COMMAND_BUFFER_LEVEL_PRIMARY
                },
                // vulkan can allocate multiple command buffers at once, hence the 1
                commandBufferCount: 1,
            };

            let mut output = mem::uninitialized();
            try!(check_errors(vk.AllocateCommandBuffers(device.internal_object(), &infos,
                                                        &mut output)));
            output
        };

        let mut keep_alive = Vec::new();

        unsafe {
            // TODO: one time submit
            let flags = vk::COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT |     // TODO:
                        if secondary_cont.is_some() { vk::COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT } else { 0 };

            let (rp, sp) = if let Some(ref sp) = secondary_cont {
                keep_alive.push(sp.render_pass().clone() as Arc<_>);
                (sp.render_pass().render_pass().internal_object(), sp.index())
            } else {
                (0, 0)
            };

            let framebuffer = if let Some(fb) = secondary_cont_fb {
                keep_alive.push(fb.clone() as Arc<_>);
                fb.internal_object()
            } else {
                0
            };

            let inheritance = vk::CommandBufferInheritanceInfo {
                sType: vk::STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO,
                pNext: ptr::null(),
                renderPass: rp,
                subpass: sp,
                framebuffer: framebuffer,
                occlusionQueryEnable: 0,            // TODO:
                queryFlags: 0,          // TODO:
                pipelineStatistics: 0,          // TODO:
            };

            let infos = vk::CommandBufferBeginInfo {
                sType: vk::STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
                pNext: ptr::null(),
                flags: flags,
                pInheritanceInfo: &inheritance,
            };

            try!(check_errors(vk.BeginCommandBuffer(cmd, &infos)));
        }

        Ok(InnerCommandBufferBuilder {
            device: device.clone(),
            pool: pool.clone(),
            cmd: Some(cmd),
            is_secondary: secondary,
            is_secondary_graphics: secondary_cont.is_some(),
            buffers_state: HashMap::with_hasher(BuildHasherDefault::<FnvHasher>::default()),
            images_state: HashMap::with_hasher(BuildHasherDefault::<FnvHasher>::default()),
            staging_commands: Vec::new(),
            staging_required_buffer_accesses: HashMap::with_hasher(BuildHasherDefault::<FnvHasher>::default()),
            staging_required_image_accesses: HashMap::with_hasher(BuildHasherDefault::<FnvHasher>::default()),
            render_pass_staging_commands: Vec::new(),
            render_pass_staging_required_buffer_accesses: HashMap::with_hasher(BuildHasherDefault::<FnvHasher>::default()),
            render_pass_staging_required_image_accesses: HashMap::with_hasher(BuildHasherDefault::<FnvHasher>::default()),
            keep_alive: keep_alive,
            current_graphics_pipeline: None,
            current_compute_pipeline: None,
            current_dynamic_state: DynamicState::none(),
        })
    }

    /// Executes the content of another command buffer.
    ///
    /// # Safety
    ///
    /// Care must be taken to respect the rules about secondary command buffers.
    pub unsafe fn execute_commands<'a>(mut self, cb_arc: Arc<KeepAlive>,
                                       cb: &InnerCommandBuffer) -> InnerCommandBufferBuilder
    {
        debug_assert!(!self.is_secondary);
        debug_assert!(!self.is_secondary_graphics);

        // By keeping alive the secondary command buffer itself, we also keep alive all
        // the resources stored by it.
        self.keep_alive.push(cb_arc);

        // Merging the resources of the command buffer.
        if self.render_pass_staging_commands.is_empty() {
            // We're outside of a render pass.

            // Flushing if required.
            let mut conflict = false;
            for (buffer, access) in cb.buffers_state.iter() {
                if let Some(&entry) = self.staging_required_buffer_accesses.get(&buffer) {
                    if entry.write || access.write {
                        conflict = true;
                        break;
                    }
                }
            }
            for (image, access) in cb.images_state.iter() {
                if let Some(entry) = self.staging_required_image_accesses.get(&image) {
                    // TODO: should be reviewed
                    if entry.write || access.write || entry.new_layout != access.old_layout {
                        conflict = true;
                        break;
                    }
                }
            }
            if conflict {
                self.flush(false);
            }

            // Inserting in `staging_required_buffer_accesses`.
            for (buffer, access) in cb.buffers_state.iter() {
                match self.staging_required_buffer_accesses.entry(buffer.clone()) {
                    Entry::Vacant(e) => { e.insert(access.clone()); },
                    Entry::Occupied(mut entry) => {
                        let mut entry = entry.get_mut();
                        entry.stages &= access.stages;
                        entry.accesses &= access.stages;
                        entry.write = entry.write || access.write;
                    }
                }
            }

            // Inserting in `staging_required_image_accesses`.
            for (image, access) in cb.images_state.iter() {
                match self.staging_required_image_accesses.entry(image.clone()) {
                    Entry::Vacant(e) => { e.insert(access.clone()); },
                    Entry::Occupied(mut entry) => {
                        let mut entry = entry.get_mut();
                        entry.stages &= access.stages;
                        entry.accesses &= access.stages;
                        entry.write = entry.write || access.write;
                        debug_assert_eq!(entry.new_layout, access.old_layout);
                        entry.aspects |= access.aspects;
                        entry.new_layout = access.new_layout;
                    }
                }
            }

            // Adding the command to the staging commands.
            {
                let cb_cmd = cb.cmd;
                self.staging_commands.push(Box::new(move |vk, cmd| {
                    vk.CmdExecuteCommands(cmd, 1, &cb_cmd);
                }));
            }

        } else {
            // We're inside a render pass.
            for (buffer, access) in cb.buffers_state.iter() {
                // TODO: check for collisions
                self.render_pass_staging_required_buffer_accesses.insert(buffer.clone(), access.clone());
            }

            for (image, access) in cb.images_state.iter() {
                // TODO: check for collisions
                self.render_pass_staging_required_image_accesses.insert(image.clone(), access.clone());
            }

            // Adding the command to the staging commands.
            {
                let cb_cmd = cb.cmd;
                self.render_pass_staging_commands.push(Box::new(move |vk, cmd| {
                    vk.CmdExecuteCommands(cmd, 1, &cb_cmd);
                }));
            }
        }

        // Resetting the state of the command buffer.
        // The specs actually don't say anything about this, but one of the speakers at the
        // GDC 2016 conference said this was the case. Since keeping the state is purely an
        // optimization, we disable it just in case. This might be removed when things get
        // clarified.
        self.current_graphics_pipeline = None;
        self.current_compute_pipeline = None;
        self.current_dynamic_state = DynamicState::none();

        self
    }

    /// Writes data to a buffer.
    ///
    /// # Panic
    ///
    /// - Panicks if the size of `data` is not the same as the size of the buffer slice.
    /// - Panicks if the size of `data` is superior to 65536 bytes.
    /// - Panicks if the offset or size is not a multiple of 4.
    /// - Panicks if the buffer wasn't created with the right usage.
    ///
    /// # Safety
    ///
    /// - Care must be taken to respect the rules about secondary command buffers.
    ///
    pub unsafe fn update_buffer<'a, B, T, Bt>(mut self, buffer: B, data: &T)
                                              -> InnerCommandBufferBuilder
        where B: Into<BufferSlice<'a, T, Bt>>, Bt: Buffer + 'static, T: Clone + Send + Sync + 'static
    {
        debug_assert!(self.render_pass_staging_commands.is_empty());

        let buffer = buffer.into();

        assert_eq!(buffer.size(), mem::size_of_val(data));
        assert!(buffer.size() <= 65536);
        assert!(buffer.offset() % 4 == 0);
        assert!(buffer.size() % 4 == 0);
        assert!(buffer.buffer().inner_buffer().usage_transfer_dest());

        // FIXME: check queue family of the buffer

        self.add_buffer_resource_outside(buffer.buffer().clone() as Arc<_>, true,
                                         buffer.offset() .. buffer.offset() + buffer.size(),
                                         vk::PIPELINE_STAGE_TRANSFER_BIT,
                                         vk::ACCESS_TRANSFER_WRITE_BIT);

        {
            let buffer_offset = buffer.offset() as vk::DeviceSize;
            let buffer_size = buffer.size() as vk::DeviceSize;
            let buffer = buffer.buffer().inner_buffer().internal_object();
            let mut data = Some(data.clone());        // TODO: meh for Cloning, but I guess there's no other choice

            self.staging_commands.push(Box::new(move |vk, cmd| {
                let data = data.take().unwrap();
                vk.CmdUpdateBuffer(cmd, buffer, buffer_offset, buffer_size,
                                   &data as *const T as *const _);
            }));
        }

        self
    }

    /// Fills a buffer with data.
    ///
    /// # Panic
    ///
    /// - Panicks if `offset + data` is superior to the size of the buffer.
    /// - Panicks if the offset or size is not a multiple of 4.
    /// - Panicks if the buffer wasn't created with the right usage.
    /// - Panicks if the queue family doesn't support transfer operations.
    ///
    /// # Safety
    ///
    /// - Type safety is not enforced by the API.
    /// - Care must be taken to respect the rules about secondary command buffers.
    ///
    pub unsafe fn fill_buffer<B>(mut self, buffer: &Arc<B>, offset: usize,
                                 size: usize, data: u32) -> InnerCommandBufferBuilder
        where B: Buffer + 'static
    {
        debug_assert!(self.render_pass_staging_commands.is_empty());

        assert!(self.pool.queue_family().supports_transfers());
        assert!(offset + size <= buffer.size());
        assert!(offset % 4 == 0);
        assert!(size % 4 == 0);
        assert!(buffer.inner_buffer().usage_transfer_dest());

        self.add_buffer_resource_outside(buffer.clone() as Arc<_>, true, offset .. offset + size,
                                         vk::PIPELINE_STAGE_TRANSFER_BIT,
                                         vk::ACCESS_TRANSFER_WRITE_BIT);

        // FIXME: check that the queue family supports transfers
        // FIXME: check queue family of the buffer

        {
            let buffer = buffer.clone();
            self.staging_commands.push(Box::new(move |vk, cmd| {
                vk.CmdFillBuffer(cmd, buffer.inner_buffer().internal_object(),
                                 offset as vk::DeviceSize, size as vk::DeviceSize, data);
            }));
        }

        self
    }

    /// Copies data between buffers.
    ///
    /// There is no restriction for the type of queue that can perform this.
    ///
    /// # Panic
    ///
    /// - Panicks if the buffers don't belong to the same device.
    /// - Panicks if one of the buffers wasn't created with the right usage.
    ///
    /// # Safety
    ///
    /// - Type safety is not enforced by the API.
    /// - Care must be taken to respect the rules about secondary command buffers.
    ///
    // TODO: doesn't support slices
    pub unsafe fn copy_buffer<T: ?Sized + 'static, Bs, Bd>(mut self, source: &Arc<Bs>,
                                                           destination: &Arc<Bd>)
                                                           -> InnerCommandBufferBuilder
        where Bs: TypedBuffer<Content = T> + 'static, Bd: TypedBuffer<Content = T> + 'static
    {
        debug_assert!(self.render_pass_staging_commands.is_empty());

        assert_eq!(&**source.inner_buffer().device() as *const _,
                   &**destination.inner_buffer().device() as *const _);
        assert!(source.inner_buffer().usage_transfer_src());
        assert!(destination.inner_buffer().usage_transfer_dest());

        self.add_buffer_resource_outside(source.clone() as Arc<_>, false, 0 .. source.size(),
                                         vk::PIPELINE_STAGE_TRANSFER_BIT,
                                         vk::ACCESS_TRANSFER_READ_BIT);
        self.add_buffer_resource_outside(destination.clone() as Arc<_>, true, 0 .. source.size(),
                                         vk::PIPELINE_STAGE_TRANSFER_BIT,
                                         vk::ACCESS_TRANSFER_WRITE_BIT);

        {
            let source_size = source.size() as u64;     // FIXME: what is destination is too small?
            let source = source.inner_buffer().internal_object();
            let destination = destination.inner_buffer().internal_object();

            self.staging_commands.push(Box::new(move |vk, cmd| {
                let copy = vk::BufferCopy {
                    srcOffset: 0,
                    dstOffset: 0,
                    size: source_size,
                };

                vk.CmdCopyBuffer(cmd, source, destination, 1, &copy);
            }));
        }

        self
    }

    ///
    /// Note that compressed formats are not supported.
    ///
    /// # Safety
    ///
    /// - Care must be taken to respect the rules about secondary command buffers.
    ///
    pub unsafe fn clear_color_image<'a, I, V>(mut self, image: &Arc<I>, color: V)
                                              -> InnerCommandBufferBuilder
        where I: ImageClearValue<V> + 'static   // FIXME: should accept uint and int images too
    {
        debug_assert!(self.render_pass_staging_commands.is_empty());

        assert!(image.format().is_float()); // FIXME: should accept uint and int images too

        let color = image.decode(color).unwrap(); /* FIXME: error */

        {
            let image = image.inner_image().internal_object();

            self.staging_commands.push(Box::new(move |vk, cmd| {
                let color = match color {
                    ClearValue::Float(data) => vk::ClearColorValue::float32(data),
                    ClearValue::Int(data) => vk::ClearColorValue::int32(data),
                    ClearValue::Uint(data) => vk::ClearColorValue::uint32(data),
                    _ => unreachable!()   // PossibleFloatFormatDesc has been improperly implemented
                };

                let range = vk::ImageSubresourceRange {
                    aspectMask: vk::IMAGE_ASPECT_COLOR_BIT,
                    baseMipLevel: 0,        // FIXME:
                    levelCount: 1,      // FIXME:
                    baseArrayLayer: 0,      // FIXME:
                    layerCount: 1,      // FIXME:
                };

                vk.CmdClearColorImage(cmd, image, vk::IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL /* FIXME: */,
                                      &color, 1, &range);
            }));
        }

        self
    }

    /// Copies data from a buffer to a color image.
    ///
    /// This operation can be performed by any kind of queue.
    ///
    /// # Safety
    ///
    /// - Care must be taken to respect the rules about secondary command buffers.
    ///
    pub unsafe fn copy_buffer_to_color_image<'a, P, S, Sb, Img>(mut self, source: S, image: &Arc<Img>,
                                                                mip_level: u32, array_layers_range: Range<u32>,
                                                                offset: [u32; 3], extent: [u32; 3])
                                                             -> InnerCommandBufferBuilder
        where S: Into<BufferSlice<'a, [P], Sb>>, Img: ImageContent<P> + Image + 'static,
              Sb: Buffer + 'static
    {
        // FIXME: check the parameters

        debug_assert!(self.render_pass_staging_commands.is_empty());

        //assert!(image.format().is_float_or_compressed());

        let source = source.into();
        self.add_buffer_resource_outside(source.buffer().clone() as Arc<_>, false,
                                         source.offset() .. source.offset() + source.size(),
                                         vk::PIPELINE_STAGE_TRANSFER_BIT,
                                         vk::ACCESS_TRANSFER_READ_BIT);
        self.add_image_resource_outside(image.clone() as Arc<_>, mip_level .. mip_level + 1,
                                        array_layers_range.clone(), true,
                                        ImageLayout::TransferDstOptimal,
                                        vk::PIPELINE_STAGE_TRANSFER_BIT,
                                        vk::ACCESS_TRANSFER_WRITE_BIT);

        {
            let source_offset = source.offset() as vk::DeviceSize;
            let source = source.buffer().inner_buffer().internal_object();
            let image = image.inner_image().internal_object();

            self.staging_commands.push(Box::new(move |vk, cmd| {
                let region = vk::BufferImageCopy {
                    bufferOffset: source_offset,
                    bufferRowLength: 0,
                    bufferImageHeight: 0,
                    imageSubresource: vk::ImageSubresourceLayers {
                        aspectMask: vk::IMAGE_ASPECT_COLOR_BIT,
                        mipLevel: mip_level,
                        baseArrayLayer: array_layers_range.start,
                        layerCount: array_layers_range.end - array_layers_range.start,
                    },
                    imageOffset: vk::Offset3D {
                        x: offset[0] as i32,
                        y: offset[1] as i32,
                        z: offset[2] as i32,
                    },
                    imageExtent: vk::Extent3D {
                        width: extent[0],
                        height: extent[1],
                        depth: extent[2],
                    },
                };

                vk.CmdCopyBufferToImage(cmd, source, image,
                                        vk::IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL /* FIXME */,
                                        1, &region);
            }));
        }

        self
    }

    /// Copies data from a color image to a buffer.
    ///
    /// This operation can be performed by any kind of queue.
    ///
    /// # Safety
    ///
    /// - Care must be taken to respect the rules about secondary command buffers.
    ///
    pub unsafe fn copy_color_image_to_buffer<'a, P, S, Sb, Img>(mut self, dest: S, image: &Arc<Img>,
                                                                mip_level: u32, array_layers_range: Range<u32>,
                                                                offset: [u32; 3], extent: [u32; 3])
                                                             -> InnerCommandBufferBuilder
        where S: Into<BufferSlice<'a, [P], Sb>>, Img: ImageContent<P> + Image + 'static,
              Sb: Buffer + 'static
    {
        // FIXME: check the parameters

        debug_assert!(self.render_pass_staging_commands.is_empty());

        //assert!(image.format().is_float_or_compressed());

        let dest = dest.into();
        self.add_buffer_resource_outside(dest.buffer().clone() as Arc<_>, true,
                                         dest.offset() .. dest.offset() + dest.size(),
                                         vk::PIPELINE_STAGE_TRANSFER_BIT,
                                         vk::ACCESS_TRANSFER_WRITE_BIT);
        self.add_image_resource_outside(image.clone() as Arc<_>, mip_level .. mip_level + 1,
                                        array_layers_range.clone(), false,
                                        ImageLayout::TransferSrcOptimal,
                                        vk::PIPELINE_STAGE_TRANSFER_BIT,
                                        vk::ACCESS_TRANSFER_READ_BIT);

        {
            let dest_offset = dest.offset() as vk::DeviceSize;
            let dest = dest.buffer().inner_buffer().internal_object();
            let image = image.inner_image().internal_object();

            self.staging_commands.push(Box::new(move |vk, cmd| {
                let region = vk::BufferImageCopy {
                    bufferOffset: dest_offset,
                    bufferRowLength: 0,
                    bufferImageHeight: 0,
                    imageSubresource: vk::ImageSubresourceLayers {
                        aspectMask: vk::IMAGE_ASPECT_COLOR_BIT,
                        mipLevel: mip_level,
                        baseArrayLayer: array_layers_range.start,
                        layerCount: array_layers_range.end - array_layers_range.start,
                    },
                    imageOffset: vk::Offset3D {
                        x: offset[0] as i32,
                        y: offset[1] as i32,
                        z: offset[2] as i32,
                    },
                    imageExtent: vk::Extent3D {
                        width: extent[0],
                        height: extent[1],
                        depth: extent[2],
                    },
                };

                vk.CmdCopyImageToBuffer(cmd, image,
                                        vk::IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL /* FIXME */,
                                        dest, 1, &region);
            }));
        }

        self
    }

    pub unsafe fn blit<Si, Di>(mut self, source: &Arc<Si>, source_mip_level: u32,
                               source_array_layers: Range<u32>, src_coords: [Range<i32>; 3],
                               destination: &Arc<Di>, dest_mip_level: u32,
                               dest_array_layers: Range<u32>, dest_coords: [Range<i32>; 3])
                               -> InnerCommandBufferBuilder
        where Si: Image + 'static, Di: Image + 'static
    {
        // FIXME: check the parameters

        debug_assert!(self.render_pass_staging_commands.is_empty());

        assert!(source.supports_blit_source());
        assert!(destination.supports_blit_destination());

        self.add_image_resource_outside(source.clone() as Arc<_>,
                                        source_mip_level .. source_mip_level + 1,
                                        source_array_layers.clone(), false,
                                        ImageLayout::TransferSrcOptimal,
                                        vk::PIPELINE_STAGE_TRANSFER_BIT,
                                        vk::ACCESS_TRANSFER_READ_BIT);
        self.add_image_resource_outside(destination.clone() as Arc<_>,
                                        dest_mip_level .. dest_mip_level + 1,
                                        dest_array_layers.clone(), true,
                                        ImageLayout::TransferDstOptimal,
                                        vk::PIPELINE_STAGE_TRANSFER_BIT,
                                        vk::ACCESS_TRANSFER_WRITE_BIT);

        {
            let source = source.inner_image().internal_object();
            let destination = destination.inner_image().internal_object();

            self.staging_commands.push(Box::new(move |vk, cmd| {
                let region = vk::ImageBlit {
                    srcSubresource: vk::ImageSubresourceLayers {
                        aspectMask: vk::IMAGE_ASPECT_COLOR_BIT,
                        mipLevel: source_mip_level,
                        baseArrayLayer: source_array_layers.start,
                        layerCount: source_array_layers.end - source_array_layers.start,
                    },
                    srcOffsets: [
                        vk::Offset3D {
                            x: src_coords[0].start,
                            y: src_coords[1].start,
                            z: src_coords[2].start,
                        }, vk::Offset3D {
                            x: src_coords[0].end,
                            y: src_coords[1].end,
                            z: src_coords[2].end,
                        }
                    ],
                    dstSubresource: vk::ImageSubresourceLayers {
                        aspectMask: vk::IMAGE_ASPECT_COLOR_BIT,
                        mipLevel: dest_mip_level,
                        baseArrayLayer: dest_array_layers.start,
                        layerCount: dest_array_layers.end - dest_array_layers.start,
                    },
                    dstOffsets: [
                        vk::Offset3D {
                            x: dest_coords[0].start,
                            y: dest_coords[1].start,
                            z: dest_coords[2].start,
                        }, vk::Offset3D {
                            x: dest_coords[0].end,
                            y: dest_coords[1].end,
                            z: dest_coords[2].end,
                        }
                    ],
                };

                vk.CmdBlitImage(cmd, source, ImageLayout::TransferSrcOptimal as u32,
                                destination, ImageLayout::TransferDstOptimal as u32,
                                1, &region, vk::FILTER_LINEAR);
            }));
        }

        self
    }

    pub unsafe fn dispatch<Pl, L>(mut self, pipeline: &Arc<ComputePipeline<Pl>>, sets: L,
                                  dimensions: [u32; 3]) -> InnerCommandBufferBuilder
        where L: 'static + DescriptorSetsCollection + Send + Sync,
              Pl: 'static + PipelineLayout + Send + Sync
    {
        debug_assert!(self.render_pass_staging_commands.is_empty());

        self.bind_compute_pipeline_state(pipeline, sets);

        self.staging_commands.push(Box::new(move |vk, cmd| {
            vk.CmdDispatch(cmd, dimensions[0], dimensions[1], dimensions[2]);
        }));

        self
    }

    /// Calls `vkCmdDraw`.
    // FIXME: push constants
    pub unsafe fn draw<V, Pv, Pl, L, Rp, Pc>(mut self, pipeline: &Arc<GraphicsPipeline<Pv, Pl, Rp>>,
                             vertices: V, dynamic: &DynamicState,
                             sets: L, push_constants: &Pc) -> InnerCommandBufferBuilder
        where Pv: 'static + VertexSource<V>, L: DescriptorSetsCollection + Send + Sync,
              Pl: 'static + PipelineLayout + Send + Sync, Rp: 'static + Send + Sync,
              Pc: 'static + Clone + Send + Sync
    {
        // FIXME: add buffers to the resources

        self.bind_gfx_pipeline_state(pipeline, dynamic, sets, push_constants);

        let vertices = pipeline.vertex_definition().decode(vertices);

        let offsets = (0 .. vertices.0.len()).map(|_| 0).collect::<SmallVec<[_; 8]>>();
        let ids = vertices.0.map(|b| {
            assert!(b.inner_buffer().usage_vertex_buffer());
            self.add_buffer_resource_inside(b.clone(), false, 0 .. b.size(),
                                            vk::PIPELINE_STAGE_VERTEX_INPUT_BIT,
                                            vk::ACCESS_VERTEX_ATTRIBUTE_READ_BIT);
            b.inner_buffer().internal_object()
        }).collect::<SmallVec<[_; 8]>>();

        {
            let mut ids = Some(ids);
            let mut offsets = Some(offsets);
            let num_vertices = vertices.1 as u32;
            let num_instances = vertices.2 as u32;

            self.render_pass_staging_commands.push(Box::new(move |vk, cmd| {
                let ids = ids.take().unwrap();
                let offsets = offsets.take().unwrap();

                vk.CmdBindVertexBuffers(cmd, 0, ids.len() as u32, ids.as_ptr(), offsets.as_ptr());
                vk.CmdDraw(cmd, num_vertices, num_instances, 0, 0);  // FIXME: params
            }));
        }

        self
    }

    /// Calls `vkCmdDrawIndexed`.
    // FIXME: push constants
    pub unsafe fn draw_indexed<'a, V, Pv, Pl, Rp, L, I, Ib, Ibb, Pc>(mut self, pipeline: &Arc<GraphicsPipeline<Pv, Pl, Rp>>,
                                                          vertices: V, indices: Ib, dynamic: &DynamicState,
                                                          sets: L, push_constants: &Pc) -> InnerCommandBufferBuilder
        where L: DescriptorSetsCollection + Send + Sync,
              Pv: 'static + VertexSource<V>,
              Pl: 'static + PipelineLayout + Send + Sync, Rp: 'static + Send + Sync,
              Ib: Into<BufferSlice<'a, [I], Ibb>>, I: 'static + Index, Ibb: Buffer + 'static,
              Pc: 'static + Clone + Send + Sync
    {
        // FIXME: add buffers to the resources

        self.bind_gfx_pipeline_state(pipeline, dynamic, sets, push_constants);


        let indices = indices.into();

        let vertices = pipeline.vertex_definition().decode(vertices);

        let offsets = (0 .. vertices.0.len()).map(|_| 0).collect::<SmallVec<[_; 8]>>();
        let ids = vertices.0.map(|b| {
            assert!(b.inner_buffer().usage_vertex_buffer());
            self.add_buffer_resource_inside(b.clone(), false, 0 .. b.size(),
                                            vk::PIPELINE_STAGE_VERTEX_INPUT_BIT,
                                            vk::ACCESS_VERTEX_ATTRIBUTE_READ_BIT);
            b.inner_buffer().internal_object()
        }).collect::<SmallVec<[_; 8]>>();

        assert!(indices.buffer().inner_buffer().usage_index_buffer());

        self.add_buffer_resource_inside(indices.buffer().clone() as Arc<_>, false,
                                        indices.offset() .. indices.offset() + indices.size(),
                                        vk::PIPELINE_STAGE_VERTEX_INPUT_BIT,
                                        vk::ACCESS_INDEX_READ_BIT);

        {
            let mut ids = Some(ids);
            let mut offsets = Some(offsets);
            let indices_offset = indices.offset() as u64;
            let indices_len = indices.len() as u32;
            let indices_ty = I::ty() as u32;
            let indices = indices.buffer().inner_buffer().internal_object();
            let num_instances = vertices.2 as u32;

            self.render_pass_staging_commands.push(Box::new(move |vk, cmd| {
                let ids = ids.take().unwrap();
                let offsets = offsets.take().unwrap();

                vk.CmdBindIndexBuffer(cmd, indices, indices_offset, indices_ty);
                vk.CmdBindVertexBuffers(cmd, 0, ids.len() as u32, ids.as_ptr(), offsets.as_ptr());
                vk.CmdDrawIndexed(cmd, indices_len, num_instances, 0, 0, 0);  // FIXME: params
            }));
        }

        self
    }

    /// Calls `vkCmdDrawIndirect`.
    // FIXME: push constants
    pub unsafe fn draw_indirect<I, V, Pv, Pl, L, Rp, Pc>(mut self, buffer: &Arc<I>, pipeline: &Arc<GraphicsPipeline<Pv, Pl, Rp>>,
                             vertices: V, dynamic: &DynamicState,
                             sets: L, push_constants: &Pc) -> InnerCommandBufferBuilder
        where Pv: 'static + VertexSource<V>, L: DescriptorSetsCollection + Send + Sync,
              Pl: 'static + PipelineLayout + Send + Sync, Rp: 'static + Send + Sync, Pc: 'static + Clone + Send + Sync,
              I: 'static + TypedBuffer<Content = [DrawIndirectCommand]>
    {
        // FIXME: add buffers to the resources

        self.bind_gfx_pipeline_state(pipeline, dynamic, sets, push_constants);

        let vertices = pipeline.vertex_definition().decode(vertices);

        let offsets = (0 .. vertices.0.len()).map(|_| 0).collect::<SmallVec<[_; 8]>>();
        let ids = vertices.0.map(|b| {
            assert!(b.inner_buffer().usage_vertex_buffer());
            self.add_buffer_resource_inside(b.clone(), false, 0 .. b.size(),
                                            vk::PIPELINE_STAGE_VERTEX_INPUT_BIT,
                                            vk::ACCESS_VERTEX_ATTRIBUTE_READ_BIT);
            b.inner_buffer().internal_object()
        }).collect::<SmallVec<[_; 8]>>();

        self.add_buffer_resource_inside(buffer.clone(), false, 0 .. buffer.size(),
                                        vk::PIPELINE_STAGE_DRAW_INDIRECT_BIT,
                                        vk::ACCESS_INDIRECT_COMMAND_READ_BIT);

        {
            let mut ids = Some(ids);
            let mut offsets = Some(offsets);
            let buffer_internal = buffer.inner_buffer().internal_object();
            let buffer_draw_count = buffer.len() as u32;
            let buffer_size = buffer.size() as u32;

            self.render_pass_staging_commands.push(Box::new(move |vk, cmd| {
                let ids = ids.take().unwrap();
                let offsets = offsets.take().unwrap();

                vk.CmdBindVertexBuffers(cmd, 0, ids.len() as u32, ids.as_ptr(), offsets.as_ptr());
                vk.CmdDrawIndirect(cmd, buffer_internal, 0, buffer_draw_count,
                                   mem::size_of::<DrawIndirectCommand>() as u32);
            }));
        }

        self
    }

    fn bind_compute_pipeline_state<Pl, L>(&mut self, pipeline: &Arc<ComputePipeline<Pl>>, sets: L)
        where L: DescriptorSetsCollection,
              Pl: 'static + PipelineLayout + Send + Sync
    {
        unsafe {
            //assert!(sets.is_compatible_with(pipeline.layout()));

            if self.current_compute_pipeline != Some(pipeline.internal_object()) {
                self.keep_alive.push(pipeline.clone());
                let pipeline = pipeline.internal_object();
                self.staging_commands.push(Box::new(move |vk, cmd| {
                    vk.CmdBindPipeline(cmd, vk::PIPELINE_BIND_POINT_COMPUTE,
                                       pipeline);
                }));
                self.current_compute_pipeline = Some(pipeline);
            }

            let mut descriptor_sets = DescriptorSetsCollection::list(&sets).collect::<SmallVec<[_; 32]>>();

            for set in descriptor_sets.iter() {
                for &(ref img, block, layout) in set.inner_descriptor_set().images_list().iter() {
                    self.add_image_resource_outside(img.clone(), 0 .. 1 /* FIXME */, 0 .. 1 /* FIXME */,
                                                   false, layout, vk::PIPELINE_STAGE_ALL_COMMANDS_BIT /* FIXME */,
                                                   vk::ACCESS_SHADER_READ_BIT | vk::ACCESS_UNIFORM_READ_BIT /* TODO */);
                }
                for buffer in set.inner_descriptor_set().buffers_list().iter() {
                    self.add_buffer_resource_outside(buffer.clone(), false, 0 .. buffer.size() /* TODO */,
                                                    vk::PIPELINE_STAGE_ALL_COMMANDS_BIT /* FIXME */,
                                                    vk::ACCESS_SHADER_READ_BIT | vk::ACCESS_UNIFORM_READ_BIT /* TODO */);
                }
            }

            for d in descriptor_sets.iter() { self.keep_alive.push(mem::transmute(d.clone()) /* FIXME: */); }
            let mut descriptor_sets = Some(descriptor_sets.into_iter().map(|set| set.inner_descriptor_set().internal_object()).collect::<SmallVec<[_; 32]>>());

            // TODO: shouldn't rebind everything every time
            if !descriptor_sets.as_ref().unwrap().is_empty() {
                let pipeline = PipelineLayout::inner_pipeline_layout(&**pipeline.layout()).internal_object();
                self.staging_commands.push(Box::new(move |vk, cmd| {
                    let descriptor_sets = descriptor_sets.take().unwrap();
                    vk.CmdBindDescriptorSets(cmd, vk::PIPELINE_BIND_POINT_COMPUTE,
                                             pipeline, 0, descriptor_sets.len() as u32,
                                             descriptor_sets.as_ptr(), 0, ptr::null());   // FIXME: dynamic offsets
                }));
            }
        }
    }

    fn bind_gfx_pipeline_state<V, Pl, L, Rp, Pc>(&mut self, pipeline: &Arc<GraphicsPipeline<V, Pl, Rp>>,
                                                 dynamic: &DynamicState, sets: L, push_constants: &Pc)
        where V: 'static + Send + Sync, L: DescriptorSetsCollection + Send + Sync,
              Pl: 'static + PipelineLayout + Send + Sync, Rp: 'static + Send + Sync, Pc: 'static + Clone + Send + Sync
    {
        unsafe {
            //assert!(sets.is_compatible_with(pipeline.layout()));

            if self.current_graphics_pipeline != Some(pipeline.internal_object()) {
                self.keep_alive.push(pipeline.clone());
                let pipeline = pipeline.internal_object();
                self.render_pass_staging_commands.push(Box::new(move |vk, cmd| {
                    vk.CmdBindPipeline(cmd, vk::PIPELINE_BIND_POINT_GRAPHICS, pipeline);
                }));
                self.current_graphics_pipeline = Some(pipeline);
            }

            if let Some(line_width) = dynamic.line_width {
                assert!(pipeline.has_dynamic_line_width());
                // TODO: check limits
                if self.current_dynamic_state.line_width != Some(line_width) {
                    self.render_pass_staging_commands.push(Box::new(move |vk, cmd| {
                        vk.CmdSetLineWidth(cmd, line_width);
                    }));
                    self.current_dynamic_state.line_width = Some(line_width);
                }
            } else {
                assert!(!pipeline.has_dynamic_line_width());
            }

            if let Some(ref viewports) = dynamic.viewports {
                assert!(pipeline.has_dynamic_viewports());
                assert_eq!(viewports.len(), pipeline.num_viewports() as usize);
                // TODO: check limits
                // TODO: cache state?
                let mut viewports = Some(viewports.iter().map(|v| v.clone().into()).collect::<SmallVec<[_; 16]>>());
                self.render_pass_staging_commands.push(Box::new(move |vk, cmd| {
                    let viewports = viewports.take().unwrap();
                    vk.CmdSetViewport(cmd, 0, viewports.len() as u32, viewports.as_ptr());
                }));
            } else {
                assert!(!pipeline.has_dynamic_viewports());
            }

            if let Some(ref scissors) = dynamic.scissors {
                assert!(pipeline.has_dynamic_scissors());
                assert_eq!(scissors.len(), pipeline.num_viewports() as usize);
                // TODO: check limits
                // TODO: cache state?
                // TODO: allocate on stack instead (https://github.com/rust-lang/rfcs/issues/618)
                let mut scissors = Some(scissors.iter().map(|v| v.clone().into()).collect::<SmallVec<[_; 16]>>());
                self.render_pass_staging_commands.push(Box::new(move |vk, cmd| {
                    let scissors = scissors.take().unwrap();
                    vk.CmdSetScissor(cmd, 0, scissors.len() as u32, scissors.as_ptr());
                }));
            } else {
                assert!(!pipeline.has_dynamic_scissors());
            }

            let mut descriptor_sets = DescriptorSetsCollection::list(&sets).collect::<SmallVec<[_; 32]>>();
            for set in descriptor_sets.iter() {
                for &(ref img, block, layout) in set.inner_descriptor_set().images_list().iter() {
                    self.add_image_resource_inside(img.clone(), 0 .. 1 /* FIXME */, 0 .. 1 /* FIXME */,
                                                   false, layout, layout, vk::PIPELINE_STAGE_ALL_COMMANDS_BIT /* FIXME */,
                                                   vk::ACCESS_SHADER_READ_BIT | vk::ACCESS_UNIFORM_READ_BIT /* TODO */);
                }
                for buffer in set.inner_descriptor_set().buffers_list().iter() {
                    self.add_buffer_resource_inside(buffer.clone(), false, 0 .. buffer.size() /* TODO */,
                                                    vk::PIPELINE_STAGE_ALL_COMMANDS_BIT /* FIXME */,
                                                    vk::ACCESS_SHADER_READ_BIT | vk::ACCESS_UNIFORM_READ_BIT /* TODO */);
                }
            }
            for d in descriptor_sets.iter() { self.keep_alive.push(mem::transmute(d.clone()) /* FIXME: */); }
            let mut descriptor_sets = Some(descriptor_sets.into_iter().map(|set| set.inner_descriptor_set().internal_object()).collect::<SmallVec<[_; 32]>>());

            if mem::size_of_val(push_constants) >= 1 {
                let pipeline = PipelineLayout::inner_pipeline_layout(&**pipeline.layout()).internal_object();
                let size = mem::size_of_val(push_constants);
                let push_constants = push_constants.clone();
                assert!((size % 4) == 0);

                self.render_pass_staging_commands.push(Box::new(move |vk, cmd| {
                    vk.CmdPushConstants(cmd, pipeline, 0x7fffffff, 0, size as u32,
                                        &push_constants as *const Pc as *const _);
                }));
            }

            // FIXME: input attachments of descriptor sets have to be checked against input
            //        attachments of the render pass

            // TODO: shouldn't rebind everything every time
            if !descriptor_sets.as_ref().unwrap().is_empty() {
                let pipeline = PipelineLayout::inner_pipeline_layout(&**pipeline.layout()).internal_object();
                self.render_pass_staging_commands.push(Box::new(move |vk, cmd| {
                    let descriptor_sets = descriptor_sets.take().unwrap();
                    vk.CmdBindDescriptorSets(cmd, vk::PIPELINE_BIND_POINT_GRAPHICS, pipeline,
                                             0, descriptor_sets.len() as u32,
                                             descriptor_sets.as_ptr(), 0, ptr::null());   // FIXME: dynamic offsets
                }));
            }
        }
    }

    /// Calls `vkCmdBeginRenderPass`.
    ///
    /// # Panic
    ///
    /// - Panicks if the framebuffer is not compatible with the renderpass.
    ///
    /// # Safety
    ///
    /// - Care must be taken to respect the rules about secondary command buffers.
    ///
    #[inline]
    pub unsafe fn begin_renderpass<R, F>(mut self, render_pass: &Arc<R>,
                                         framebuffer: &Arc<Framebuffer<F>>,
                                         secondary_cmd_buffers: bool,
                                         clear_values: &[ClearValue]) -> InnerCommandBufferBuilder
        where R: RenderPass + 'static, F: RenderPass + 'static
    {
        debug_assert!(self.render_pass_staging_commands.is_empty());
        debug_assert!(self.render_pass_staging_required_buffer_accesses.is_empty());
        debug_assert!(self.render_pass_staging_required_image_accesses.is_empty());

        assert!(framebuffer.is_compatible_with(render_pass));

        self.keep_alive.push(framebuffer.clone() as Arc<_>);
        self.keep_alive.push(render_pass.clone() as Arc<_>);

        let clear_values = clear_values.iter().map(|value| {
            match *value {
                ClearValue::None => vk::ClearValue::color({
                    vk::ClearColorValue::float32([0.0, 0.0, 0.0, 0.0])
                }),
                ClearValue::Float(data) => vk::ClearValue::color(vk::ClearColorValue::float32(data)),
                ClearValue::Int(data) => vk::ClearValue::color(vk::ClearColorValue::int32(data)),
                ClearValue::Uint(data) => vk::ClearValue::color(vk::ClearColorValue::uint32(data)),
                ClearValue::Depth(d) => vk::ClearValue::depth_stencil({
                    vk::ClearDepthStencilValue { depth: d, stencil: 0 }
                }),
                ClearValue::Stencil(s) => vk::ClearValue::depth_stencil({
                    vk::ClearDepthStencilValue { depth: 0.0, stencil: s }
                }),
                ClearValue::DepthStencil((d, s)) => vk::ClearValue::depth_stencil({
                    vk::ClearDepthStencilValue { depth: d, stencil: s }
                }),
            }
        }).collect::<SmallVec<[_; 16]>>();

        for &(ref attachment, ref image, initial_layout, final_layout) in framebuffer.attachments() {
            self.keep_alive.push(mem::transmute(attachment.clone()) /* FIXME: */);

            let stages = vk::PIPELINE_STAGE_FRAGMENT_SHADER_BIT |
                         vk::PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT |
                         vk::PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT |
                         vk::PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; // FIXME:

            let accesses = vk::ACCESS_COLOR_ATTACHMENT_READ_BIT |
                           vk::ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
                           vk::ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
                           vk::ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
                           vk::ACCESS_INPUT_ATTACHMENT_READ_BIT;       // FIXME:

            // FIXME: parameters
            self.add_image_resource_inside(image.clone(), 0 .. 1, 0 .. 1, true,
                                           initial_layout, final_layout, stages, accesses);
        }

        {
            let mut clear_values = Some(clear_values);
            let render_pass = render_pass.render_pass().internal_object();
            let (fw, fh) = (framebuffer.width(), framebuffer.height());
            let framebuffer = framebuffer.internal_object();

            self.render_pass_staging_commands.push(Box::new(move |vk, cmd| {
                let clear_values = clear_values.take().unwrap();

                let infos = vk::RenderPassBeginInfo {
                    sType: vk::STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,
                    pNext: ptr::null(),
                    renderPass: render_pass,
                    framebuffer: framebuffer,
                    renderArea: vk::Rect2D {                // TODO: let user customize
                        offset: vk::Offset2D { x: 0, y: 0 },
                        extent: vk::Extent2D {
                            width: fw,
                            height: fh,
                        },
                    },
                    clearValueCount: clear_values.len() as u32,
                    pClearValues: clear_values.as_ptr(),
                };

                let content = if secondary_cmd_buffers {
                    vk::SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS
                } else {
                    vk::SUBPASS_CONTENTS_INLINE
                };

                vk.CmdBeginRenderPass(cmd, &infos, content);
            }));
        }

        self
    }

    #[inline]
    pub unsafe fn next_subpass(mut self, secondary_cmd_buffers: bool) -> InnerCommandBufferBuilder {
        debug_assert!(!self.render_pass_staging_commands.is_empty());

        let content = if secondary_cmd_buffers {
            vk::SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS
        } else {
            vk::SUBPASS_CONTENTS_INLINE
        };

        self.render_pass_staging_commands.push(Box::new(move |vk, cmd| {
            vk.CmdNextSubpass(cmd, content);
        }));

        self
    }

    /// Ends the current render pass by calling `vkCmdEndRenderPass`.
    ///
    /// # Safety
    ///
    /// Assumes that you're inside a render pass and that all subpasses have been processed.
    ///
    #[inline]
    pub unsafe fn end_renderpass(mut self) -> InnerCommandBufferBuilder {
        debug_assert!(!self.render_pass_staging_commands.is_empty());
        self.flush_render_pass();
        self.staging_commands.push(Box::new(move |vk, cmd| {
            vk.CmdEndRenderPass(cmd);
        }));
        self
    }

    /// Adds a buffer resource to the list of resources used by this command buffer.
    fn add_buffer_resource_outside(&mut self, buffer: Arc<Buffer>, write: bool,
                                   range: Range<usize>, stages: vk::PipelineStageFlagBits,
                                   accesses: vk::AccessFlagBits)
    {
        // Flushing if required.
        let mut conflict = false;
        for block in buffer.blocks(range.clone()) {
            let key = (BufferKey(buffer.clone()), block);
            if let Some(&entry) = self.staging_required_buffer_accesses.get(&key) {
                if entry.write || write {
                    conflict = true;
                    break;
                }
            }
        }
        if conflict {
            self.flush(false);
        }

        // Inserting in `staging_required_buffer_accesses`.
        for block in buffer.blocks(range.clone()) {
            let key = (BufferKey(buffer.clone()), block);
            match self.staging_required_buffer_accesses.entry(key) {
                Entry::Vacant(e) => {
                    e.insert(InternalBufferBlockAccess {
                        stages: stages,
                        accesses: accesses,
                        write: write,
                    });
                },
                Entry::Occupied(mut entry) => {
                    let mut entry = entry.get_mut();
                    entry.stages &= stages;
                    entry.accesses &= stages;
                    entry.write = entry.write || write;
                }
            }
        }
    }

    /// Adds an image resource to the list of resources used by this command buffer.
    fn add_image_resource_outside(&mut self, image: Arc<Image>, mipmap_levels_range: Range<u32>,
                                  array_layers_range: Range<u32>, write: bool, layout: ImageLayout,
                                  stages: vk::PipelineStageFlagBits, accesses: vk::AccessFlagBits)
    {
        // Flushing if required.
        let mut conflict = false;
        for block in image.blocks(mipmap_levels_range.clone(), array_layers_range.clone()) {
            let key = (ImageKey(image.clone()), block);
            if let Some(entry) = self.staging_required_image_accesses.get(&key) {
                // TODO: should be reviewed
                if entry.write || write || entry.new_layout != layout {
                    conflict = true;
                    break;
                }
            }
        }
        if conflict {
            self.flush(false);
        }

        // Inserting in `staging_required_image_accesses`.
        for block in image.blocks(mipmap_levels_range.clone(), array_layers_range.clone()) {
            let key = (ImageKey(image.clone()), block);
            let aspect_mask = match image.format().ty() {
                FormatTy::Float | FormatTy::Uint | FormatTy::Sint | FormatTy::Compressed => {
                    vk::IMAGE_ASPECT_COLOR_BIT
                },
                FormatTy::Depth => vk::IMAGE_ASPECT_DEPTH_BIT,
                FormatTy::Stencil => vk::IMAGE_ASPECT_STENCIL_BIT,
                FormatTy::DepthStencil => vk::IMAGE_ASPECT_DEPTH_BIT | vk::IMAGE_ASPECT_STENCIL_BIT,
            };

            match self.staging_required_image_accesses.entry(key) {
                Entry::Vacant(e) => {
                    e.insert(InternalImageBlockAccess {
                        stages: stages,
                        accesses: accesses,
                        write: write,
                        aspects: aspect_mask,
                        old_layout: layout,
                        new_layout: layout,
                    });
                },
                Entry::Occupied(mut entry) => {
                    let mut entry = entry.get_mut();
                    entry.stages &= stages;
                    entry.accesses &= stages;
                    entry.write = entry.write || write;
                    debug_assert_eq!(entry.new_layout, layout);
                    entry.aspects |= aspect_mask;
                }
            }
        }
    }

    /// Adds a buffer resource to the list of resources used by this command buffer.
    fn add_buffer_resource_inside(&mut self, buffer: Arc<Buffer>, write: bool,
                                  range: Range<usize>, stages: vk::PipelineStageFlagBits,
                                  accesses: vk::AccessFlagBits)
    {
        // TODO: check for collisions
        for block in buffer.blocks(range.clone()) {
            let key = (BufferKey(buffer.clone()), block);
            self.render_pass_staging_required_buffer_accesses.insert(key, InternalBufferBlockAccess {
                stages: stages,
                accesses: accesses,
                write: write,
            });
        }
    }

    /// Adds an image resource to the list of resources used by this command buffer.
    fn add_image_resource_inside(&mut self, image: Arc<Image>, mipmap_levels_range: Range<u32>,
                                 array_layers_range: Range<u32>, write: bool,
                                 initial_layout: ImageLayout, final_layout: ImageLayout,
                                 stages: vk::PipelineStageFlagBits, accesses: vk::AccessFlagBits)
    {
        // TODO: check for collisions
        for block in image.blocks(mipmap_levels_range.clone(), array_layers_range.clone()) {
            let key = (ImageKey(image.clone()), block);
            let aspect_mask = match image.format().ty() {
                FormatTy::Float | FormatTy::Uint | FormatTy::Sint | FormatTy::Compressed => {
                    vk::IMAGE_ASPECT_COLOR_BIT
                },
                FormatTy::Depth => vk::IMAGE_ASPECT_DEPTH_BIT,
                FormatTy::Stencil => vk::IMAGE_ASPECT_STENCIL_BIT,
                FormatTy::DepthStencil => vk::IMAGE_ASPECT_DEPTH_BIT | vk::IMAGE_ASPECT_STENCIL_BIT,
            };

            self.render_pass_staging_required_image_accesses.insert(key, InternalImageBlockAccess {
                stages: stages,
                accesses: accesses,
                write: write,
                aspects: aspect_mask,
                old_layout: initial_layout,
                new_layout: final_layout,
            });
        }
    }

    /// Flushes the staging render pass commands. Only call this before `vkCmdEndRenderPass` and
    /// before `vkEndCommandBuffer`.
    unsafe fn flush_render_pass(&mut self) {
        // Determine whether there's a conflict between the accesses done within the
        // render pass and the accesses from before the render pass.
        let mut conflict = false;
        for (key, access) in self.render_pass_staging_required_buffer_accesses.iter() {
            if let Some(ex_acc) = self.staging_required_buffer_accesses.get(&key) {
                if access.write || ex_acc.write {
                    conflict = true;
                    break;
                }
            }
        }
        if !conflict {
            for (key, access) in self.render_pass_staging_required_image_accesses.iter() {
                if let Some(ex_acc) = self.staging_required_image_accesses.get(&key) {
                    if access.write || ex_acc.write ||
                       (ex_acc.aspects & access.aspects) != ex_acc.aspects ||
                       access.old_layout != ex_acc.new_layout
                    {
                        conflict = true;
                        break;
                    }
                }
            }
        }
        if conflict {
            // Calling `flush` here means that a `vkCmdPipelineBarrier` will be inserted right
            // before the `vkCmdBeginRenderPass`.
            debug_assert!(!self.is_secondary_graphics);
            self.flush(false);
        }

        // Now merging the render pass accesses with the outter accesses.
        // Conflicts shouldn't happen since we checked above, but they are partly checked again
        // with `debug_assert`s.
        for ((buffer, block), access) in self.render_pass_staging_required_buffer_accesses.drain() {
            match self.staging_required_buffer_accesses.entry((buffer.clone(), block)) {
                Entry::Vacant(e) => { e.insert(access); },
                Entry::Occupied(mut entry) => {
                    let mut entry = entry.get_mut();
                    debug_assert!(!entry.write && !access.write);
                    entry.stages |= access.stages;
                    entry.accesses |= access.accesses;
                }
            }
        }
        for ((image, block), access) in self.render_pass_staging_required_image_accesses.drain() {
            match self.staging_required_image_accesses.entry((image.clone(), block)) {
                Entry::Vacant(e) => { e.insert(access); },
                Entry::Occupied(mut entry) => {
                    let mut entry = entry.get_mut();
                    debug_assert!(!entry.write && !access.write);
                    debug_assert_eq!(entry.new_layout, access.old_layout);
                    entry.stages |= access.stages;
                    entry.accesses |= access.accesses;
                    entry.new_layout = access.new_layout;
                }
            }
        }

        // Merging the commands as well.
        for command in self.render_pass_staging_commands.drain(..) {
            self.staging_commands.push(command);
        }
    }

    /// Flush the staging commands.
    fn flush(&mut self, ignore_empty_staging_commands: bool) {
        let cmd = self.cmd.unwrap();
        let vk = self.device.pointers();

        // If `staging_commands` is empty, that means we are doing two flushes in a row. This
        // means that a command conflicts with itself, for example a buffer reading and writing
        // simultaneously the same block.
        //
        // The `ignore_empty_staging_commands` parameter is here to ignore that check, because
        // in some situations it is legitimate to have two flushes in a row.
        //
        // TODO: handle error better
        if !ignore_empty_staging_commands {
            assert!(!self.staging_commands.is_empty(), "Invalid command detected");
        }

        // Merging the `staging_access` variables to the `state` variables,
        // and determining the list of barriers that are required and updating the resources states.
        // TODO: inefficient because multiple entries for contiguous blocks should be merged
        //       into one
        let mut buffer_barriers: SmallVec<[_; 8]> = SmallVec::new();
        let mut image_barriers: SmallVec<[_; 8]> = SmallVec::new();

        let mut src_stages = 0;
        let mut dst_stages = 0;

        for (buffer, access) in self.staging_required_buffer_accesses.drain() {
            match self.buffers_state.entry(buffer.clone()) {
                Entry::Vacant(entry) => {
                    if (buffer.0).0.host_accesses(buffer.1) && !self.is_secondary {
                        src_stages |= vk::PIPELINE_STAGE_HOST_BIT;
                        dst_stages |= access.stages;

                        let range = (buffer.0).0.block_memory_range(buffer.1);

                        debug_assert!(!self.is_secondary_graphics);
                        buffer_barriers.push(vk::BufferMemoryBarrier {
                            sType: vk::STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER,
                            pNext: ptr::null(),
                            srcAccessMask: vk::ACCESS_HOST_READ_BIT | vk::ACCESS_HOST_WRITE_BIT,
                            dstAccessMask: access.accesses,
                            srcQueueFamilyIndex: vk::QUEUE_FAMILY_IGNORED,
                            dstQueueFamilyIndex: vk::QUEUE_FAMILY_IGNORED,
                            buffer: (buffer.0).0.inner_buffer().internal_object(),
                            offset: range.start as u64,
                            size: (range.end - range.start) as u64,
                        });
                    }

                    entry.insert(access);
                },

                Entry::Occupied(mut entry) => {
                    let entry = entry.get_mut();

                    if entry.write || access.write {
                        src_stages |= entry.stages;
                        dst_stages |= access.stages;

                        let range = (buffer.0).0.block_memory_range(buffer.1);

                        debug_assert!(!self.is_secondary_graphics);
                        buffer_barriers.push(vk::BufferMemoryBarrier {
                            sType: vk::STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER,
                            pNext: ptr::null(),
                            srcAccessMask: entry.accesses,
                            dstAccessMask: access.accesses,
                            srcQueueFamilyIndex: vk::QUEUE_FAMILY_IGNORED,
                            dstQueueFamilyIndex: vk::QUEUE_FAMILY_IGNORED,
                            buffer: (buffer.0).0.inner_buffer().internal_object(),
                            offset: range.start as u64,
                            size: (range.end - range.start) as u64,
                        });

                        entry.stages = access.stages;
                        entry.accesses = access.accesses;
                    }

                    entry.write = entry.write || access.write;
                },
            }
        }

        for (image, access) in self.staging_required_image_accesses.drain() {
            match self.images_state.entry(image.clone()) {
                Entry::Vacant(entry) => {
                    // This is the first ever use of this image block in this command buffer.
                    // Therefore we need to query the image for the layout that it is going to
                    // have at the entry of this command buffer.
                    let (extern_layout, host, mem) = if !self.is_secondary {
                        (image.0).0.initial_layout(image.1, access.old_layout)
                    } else {
                        (access.old_layout, false, false)
                    };

                    let src_access = {
                        let mut v = 0;
                        if host { v |= vk::ACCESS_HOST_READ_BIT | vk::ACCESS_HOST_WRITE_BIT; }
                        if mem { v |= vk::ACCESS_MEMORY_READ_BIT | vk::ACCESS_MEMORY_WRITE_BIT; }
                        v
                    };

                    if extern_layout != access.old_layout || host || mem {
                        dst_stages |= access.stages;
                        
                        let range_mipmaps = (image.0).0.block_mipmap_levels_range(image.1);
                        let range_layers = (image.0).0.block_array_layers_range(image.1);

                        debug_assert!(!self.is_secondary_graphics);
                        image_barriers.push(vk::ImageMemoryBarrier {
                            sType: vk::STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
                            pNext: ptr::null(),
                            srcAccessMask: src_access,
                            dstAccessMask: access.accesses,
                            oldLayout: extern_layout as u32,
                            newLayout: access.old_layout as u32,
                            srcQueueFamilyIndex: vk::QUEUE_FAMILY_IGNORED,
                            dstQueueFamilyIndex: vk::QUEUE_FAMILY_IGNORED,
                            image: (image.0).0.inner_image().internal_object(),
                            subresourceRange: vk::ImageSubresourceRange {
                                aspectMask: access.aspects,
                                baseMipLevel: range_mipmaps.start,
                                levelCount: range_mipmaps.end - range_mipmaps.start,
                                baseArrayLayer: range_layers.start,
                                layerCount: range_layers.end - range_layers.start,
                            },
                        });
                    }

                    entry.insert(InternalImageBlockAccess {
                        stages: access.stages,
                        accesses: access.accesses,
                        write: access.write,
                        aspects: access.aspects,
                        old_layout: extern_layout,
                        new_layout: access.new_layout,
                    });
                },

                Entry::Occupied(mut entry) => {
                    let mut entry = entry.get_mut();

                    // TODO: not always necessary
                    src_stages |= entry.stages;
                    dst_stages |= access.stages;

                    let range_mipmaps = (image.0).0.block_mipmap_levels_range(image.1);
                    let range_layers = (image.0).0.block_array_layers_range(image.1);

                    debug_assert!(!self.is_secondary_graphics);
                    image_barriers.push(vk::ImageMemoryBarrier {
                        sType: vk::STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
                        pNext: ptr::null(),
                        srcAccessMask: entry.accesses,
                        dstAccessMask: access.accesses,
                        oldLayout: entry.new_layout as u32,
                        newLayout: access.old_layout as u32,
                        srcQueueFamilyIndex: vk::QUEUE_FAMILY_IGNORED,
                        dstQueueFamilyIndex: vk::QUEUE_FAMILY_IGNORED,
                        image: (image.0).0.inner_image().internal_object(),
                        subresourceRange: vk::ImageSubresourceRange {
                            aspectMask: access.aspects,
                            baseMipLevel: range_mipmaps.start,
                            levelCount: range_mipmaps.end - range_mipmaps.start,
                            baseArrayLayer: range_layers.start,
                            layerCount: range_layers.end - range_layers.start,
                        },
                    });

                    // TODO: incomplete
                    entry.stages = access.stages;
                    entry.accesses = access.accesses;
                    entry.new_layout = access.new_layout;
                },
            };
        }

        // Adding the pipeline barrier.
        if !buffer_barriers.is_empty() || !image_barriers.is_empty() {
            let (src_stages, dst_stages) = match (src_stages, dst_stages) {
                (0, 0) => (vk::PIPELINE_STAGE_TOP_OF_PIPE_BIT, vk::PIPELINE_STAGE_TOP_OF_PIPE_BIT),
                (src, 0) => (src, vk::PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT),
                (0, dest) => (dest, dest),
                (src, dest) => (src, dest),
            };

            debug_assert!(src_stages != 0 && dst_stages != 0);

            unsafe {
                vk.CmdPipelineBarrier(cmd, src_stages, dst_stages,
                                      vk::DEPENDENCY_BY_REGION_BIT, 0, ptr::null(),
                                      buffer_barriers.len() as u32, buffer_barriers.as_ptr(),
                                      image_barriers.len() as u32, image_barriers.as_ptr());
            }
        }

        // Now flushing all commands.
        for mut command in self.staging_commands.drain(..) {
            command(&vk, cmd);
        }
    }

    /// Finishes building the command buffer.
    pub fn build(mut self) -> Result<InnerCommandBuffer, OomError> {
        unsafe {
            self.flush_render_pass();
            self.flush(true);

            // Ensuring that each image is in its final layout. We do so by inserting elements
            // in `staging_required_image_accesses`, which lets the system think that we are
            // accessing the images, and then flushing again.
            // TODO: ideally things that don't collide should be added before the first flush,
            //       and things that collide done here
            if !self.is_secondary {
                for (image, access) in self.images_state.iter() {
                    let (final_layout, host, mem) = (image.0).0.final_layout(image.1, access.new_layout);
                    if final_layout != access.new_layout || host || mem {
                        let mut accesses = 0;
                        if host { accesses |= vk::ACCESS_HOST_READ_BIT | vk::ACCESS_HOST_WRITE_BIT; }
                        if mem { accesses |= vk::ACCESS_MEMORY_READ_BIT | vk::ACCESS_MEMORY_WRITE_BIT; }

                        self.staging_required_image_accesses.insert(image.clone(), InternalImageBlockAccess {
                            stages: vk::PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
                            accesses: accesses,
                            write: false,
                            aspects: access.aspects,
                            old_layout: final_layout,
                            new_layout: final_layout,
                        });
                    }
                }

                // Checking each buffer to see if it must be flushed to the host.
                for (buffer, access) in self.buffers_state.iter() {
                    if !(buffer.0).0.host_accesses(buffer.1) {
                        continue;
                    }

                    self.staging_required_buffer_accesses.insert(buffer.clone(), InternalBufferBlockAccess {
                        stages: vk::PIPELINE_STAGE_HOST_BIT,
                        accesses: vk::ACCESS_HOST_READ_BIT | vk::ACCESS_HOST_WRITE_BIT,
                        write: false,
                    });
                }

                self.flush(true);
            }

            debug_assert!(self.staging_required_buffer_accesses.is_empty());
            debug_assert!(self.staging_required_image_accesses.is_empty());

            let vk = self.device.pointers();
            let _ = self.pool.internal_object_guard();      // the pool needs to be synchronized
            let cmd = self.cmd.take().unwrap();

            // Ending the commands recording.
            try!(check_errors(vk.EndCommandBuffer(cmd)));

            Ok(InnerCommandBuffer {
                device: self.device.clone(),
                pool: self.pool.clone(),
                cmd: cmd,
                buffers_state: self.buffers_state.clone(),      // TODO: meh
                images_state: self.images_state.clone(),        // TODO: meh
                extern_buffers_sync: {
                    let mut map = HashMap::with_hasher(BuildHasherDefault::<FnvHasher>::default());
                    for ((buf, bl), access) in self.buffers_state.drain() {
                        let value = BufferAccessRange {
                            block: bl,
                            write: access.write,
                        };

                        match map.entry(buf) {
                            Entry::Vacant(e) => {
                                let mut v = SmallVec::new();
                                v.push(value);
                                e.insert(v);
                            },
                            Entry::Occupied(mut e) => {
                                e.get_mut().push(value);
                            },
                        }
                    }

                    map.into_iter().map(|(buf, val)| (buf.0, val)).collect()
                },
                extern_images_sync: {
                    let mut map = HashMap::with_hasher(BuildHasherDefault::<FnvHasher>::default());
                    for ((img, bl), access) in self.images_state.drain() {
                        let value = ImageAccessRange {
                            block: bl,
                            write: access.write,
                            initial_layout: access.old_layout,
                            final_layout: access.new_layout,
                        };

                        match map.entry(img) {
                            Entry::Vacant(e) => {
                                let mut v = SmallVec::new();
                                v.push(value);
                                e.insert(v);
                            },
                            Entry::Occupied(mut e) => {
                                e.get_mut().push(value);
                            },
                        }
                    }

                    map.into_iter().map(|(img, val)| (img.0, val)).collect()
                },
                keep_alive: mem::replace(&mut self.keep_alive, Vec::new()),
            })
        }
    }
}

impl Drop for InnerCommandBufferBuilder {
    #[inline]
    fn drop(&mut self) {
        if let Some(cmd) = self.cmd {
            unsafe {
                let vk = self.device.pointers();
                vk.EndCommandBuffer(cmd);       // TODO: really needed?

                let pool = self.pool.internal_object_guard();
                vk.FreeCommandBuffers(self.device.internal_object(), *pool, 1, &cmd);
            }
        }
    }
}

/// Actual implementation of all command buffers.
pub struct InnerCommandBuffer {
    device: Arc<Device>,
    pool: Arc<CommandBufferPool>,
    cmd: vk::CommandBuffer,
    buffers_state: HashMap<(BufferKey, usize), InternalBufferBlockAccess, BuildHasherDefault<FnvHasher>>,
    images_state: HashMap<(ImageKey, (u32, u32)), InternalImageBlockAccess, BuildHasherDefault<FnvHasher>>,
    extern_buffers_sync: SmallVec<[(Arc<Buffer>, SmallVec<[BufferAccessRange; 4]>); 32]>,
    extern_images_sync: SmallVec<[(Arc<Image>, SmallVec<[ImageAccessRange; 8]>); 32]>,
    keep_alive: Vec<Arc<KeepAlive>>,
}

/// Submits the command buffer to a queue.
///
/// Queues are not thread-safe, therefore we need to get a `&mut`.
///
/// # Panic
///
/// - Panicks if the queue doesn't belong to the device this command buffer was created with.
/// - Panicks if the queue doesn't belong to the family the pool was created with.
///
pub fn submit(me: &InnerCommandBuffer, me_arc: Arc<KeepAlive>,
              queue: &Arc<Queue>) -> Result<Arc<Submission>, OomError>   // TODO: wrong error type
{
    // TODO: see comment of GLOBAL_MUTEX
    let _global_lock = GLOBAL_MUTEX.lock().unwrap();

    let vk = me.device.pointers();

    assert_eq!(queue.device().internal_object(), me.pool.device().internal_object());
    assert_eq!(queue.family().id(), me.pool.queue_family().id());

    // TODO: check if this change is okay (maybe the Arc can be omitted?) - Mixthos
    //let fence = try!(Fence::new(queue.device()));
    let fence = Arc::new(try!(Fence::raw(queue.device())));

    let mut keep_alive_semaphores = SmallVec::<[_; 8]>::new();
    let mut post_semaphores_ids = SmallVec::<[_; 8]>::new();
    let mut pre_semaphores_ids = SmallVec::<[_; 8]>::new();
    let mut pre_semaphores_stages = SmallVec::<[_; 8]>::new();

    // Each queue has a dedicated semaphore which must be signalled and waited upon by each
    // command buffer submission.
    // TODO: for now that's not true ^  as semaphores are only used once then destroyed ;
    //       waiting on https://github.com/KhronosGroup/Vulkan-Docs/issues/155
    {
        // TODO: check if this change is okay (maybe the Arc can be omitted?) - Mixthos
        //let signalled = try!(Semaphore::new(queue.device()));
        let signalled = Arc::new(try!(Semaphore::raw(queue.device())));
        let wait = unsafe { queue.dedicated_semaphore(signalled.clone()) };
        if let Some(wait) = wait {
            pre_semaphores_ids.push(wait.internal_object());
            pre_semaphores_stages.push(vk::PIPELINE_STAGE_TOP_OF_PIPE_BIT);     // TODO:
            keep_alive_semaphores.push(wait);
        }
        post_semaphores_ids.push(signalled.internal_object());
        keep_alive_semaphores.push(signalled);
    }

    // Creating additional semaphores, one for each queue transition.
    let queue_transitions_hint: u32 = 2;        // TODO: get as function parameter
    // TODO: use a pool
    let semaphores_to_signal = {
        let mut list = SmallVec::new();
        for _ in 0 .. queue_transitions_hint {
            // TODO: check if this change is okay (maybe the Arc can be omitted?) - Mixthos
            //let sem = try!(Semaphore::new(queue.device()));
            let sem = Arc::new(try!(Semaphore::raw(queue.device())));
            post_semaphores_ids.push(sem.internal_object());
            keep_alive_semaphores.push(sem.clone());
            list.push(sem);
        }
        list
    };

    // We can now create the `Submission` object.
    // We need to create it early because we pass it when calling `gpu_access`.
    let submission = Arc::new(Submission {
        fence: fence.clone(),
        queue: queue.clone(),
        guarded: Mutex::new(SubmissionGuarded {
            signalled_semaphores: semaphores_to_signal,
            signalled_queues: SmallVec::new(),
        }),
        keep_alive_cb: Mutex::new({ let mut v = SmallVec::new(); v.push(me_arc); v }),
        keep_alive_semaphores: Mutex::new(SmallVec::new()),
    });

    // List of command buffers to submit before and after the main one.
    let mut before_command_buffers: SmallVec<[_; 4]> = SmallVec::new();
    let mut after_command_buffers: SmallVec<[_; 4]> = SmallVec::new();

    {
        // There is a possibility that a parallel thread is currently submitting a command buffer to
        // another queue. Once we start invoking the `gpu_access` access functions, there is a
        // possibility the other thread detects that it depends on this one and submits its command
        // buffer before us.
        //
        // Since we need to access the content of `guarded` in our dependencies, we lock our own
        // `guarded` here to avoid being used as a dependency before being submitted.
        // TODO: this needs a new block (https://github.com/rust-lang/rfcs/issues/811)
        let _submission_lock = submission.guarded.lock().unwrap();

        // Now we determine which earlier submissions we must depend upon.
        let mut dependencies = SmallVec::<[Arc<Submission>; 6]>::new();

        // Buffers first.
        for &(ref resource, ref ranges) in me.extern_buffers_sync.iter() {
            let result = unsafe { resource.gpu_access(&mut ranges.iter().cloned(), &submission) };
            if let Some(semaphore) = result.additional_wait_semaphore {
                pre_semaphores_ids.push(semaphore.internal_object());
                pre_semaphores_stages.push(vk::PIPELINE_STAGE_TOP_OF_PIPE_BIT);     // TODO:
                keep_alive_semaphores.push(semaphore);
            }

            if let Some(semaphore) = result.additional_signal_semaphore {
                post_semaphores_ids.push(semaphore.internal_object());
                keep_alive_semaphores.push(semaphore);
            }

            dependencies.extend(result.dependencies.into_iter());
        }

        // Then images.
        for &(ref resource, ref ranges) in me.extern_images_sync.iter() {
            let result = unsafe { resource.gpu_access(&mut ranges.iter().cloned(), &submission) };

            if let Some(semaphore) = result.additional_wait_semaphore {
                pre_semaphores_ids.push(semaphore.internal_object());
                pre_semaphores_stages.push(vk::PIPELINE_STAGE_TOP_OF_PIPE_BIT);     // TODO:
                keep_alive_semaphores.push(semaphore);
            }

            if let Some(semaphore) = result.additional_signal_semaphore {
                post_semaphores_ids.push(semaphore.internal_object());
                keep_alive_semaphores.push(semaphore);
            }

            for transition in result.before_transitions {
                let cb = transition_cb(&me.pool, resource.clone(), transition.block, transition.from, transition.to).unwrap();
                before_command_buffers.push(cb.cmd);
                submission.keep_alive_cb.lock().unwrap().push(Arc::new(cb));
            }

            for transition in result.after_transitions {
                let cb = transition_cb(&me.pool, resource.clone(), transition.block, transition.from, transition.to).unwrap();
                after_command_buffers.push(cb.cmd);
                submission.keep_alive_cb.lock().unwrap().push(Arc::new(cb));
            }

            dependencies.extend(result.dependencies.into_iter());
        }

        // For each dependency, we either wait on one of its semaphores, or create a new one.
        for dependency in dependencies.iter() {
            let current_queue_id = (queue.family().id(), queue.id_within_family());

            // If we submit to the same queue as your dependency, no need to worry about this.
            if current_queue_id == (dependency.queue.family().id(),
                                    dependency.queue.id_within_family())
            {
                continue;
            }

            let mut guard = dependency.guarded.lock().unwrap();

            // If the current queue is in the list of already-signalled queue of the dependency, we
            // ignore it.
            if guard.signalled_queues.iter().find(|&&elem| elem == current_queue_id).is_some() {
                continue;
            }

            // Otherwise, try to extract a semaphore from the semaphores that were signalled by the
            // dependency.
            let semaphore = guard.signalled_semaphores.pop();
            guard.signalled_queues.push(current_queue_id);

            let semaphore = if let Some(semaphore) = semaphore {
                semaphore

            } else {
                // This path is the slow path in the case where the user gave the wrong hint about
                // the number of queue transitions.
                // The only thing left to do is submit a dummy command buffer and a dummy semaphore
                // in the source queue.
                unimplemented!()    // FIXME:
            };

            pre_semaphores_ids.push(semaphore.internal_object());
            pre_semaphores_stages.push(vk::PIPELINE_STAGE_TOP_OF_PIPE_BIT);     // TODO:
            keep_alive_semaphores.push(semaphore);

            // Note that it may look dangerous to unlock the dependency's mutex here, because the
            // queue has already been added to the list of signalled queues but the command that
            // signals the semaphore hasn't been sent yet.
            //
            // However submitting to a queue must lock the queue, which guarantees that no other
            // parallel queue submission should happen on this same queue. This means that the problem
            // is non-existing.
        }

        unsafe {
            let mut infos = SmallVec::<[_; 3]>::new();

            if !before_command_buffers.is_empty() {
                // TODO: Use try!()? - Mixthos
                let semaphore = Semaphore::new(queue.device());
                let semaphore_id = semaphore.internal_object();
                pre_semaphores_stages.push(vk::PIPELINE_STAGE_TOP_OF_PIPE_BIT);     // TODO:
                pre_semaphores_ids.push(semaphore.internal_object());
                keep_alive_semaphores.push(semaphore);

                infos.push(vk::SubmitInfo {
                    sType: vk::STRUCTURE_TYPE_SUBMIT_INFO,
                    pNext: ptr::null(),
                    waitSemaphoreCount: 0,
                    pWaitSemaphores: ptr::null(),
                    pWaitDstStageMask: ptr::null(),
                    commandBufferCount: before_command_buffers.len() as u32,
                    pCommandBuffers: before_command_buffers.as_ptr(),
                    signalSemaphoreCount: 1,
                    pSignalSemaphores: &semaphore_id,
                });
            }

            let after_semaphore = if !after_command_buffers.is_empty() {
                // TODO: Use try!()? - Mixthos
                let semaphore = Semaphore::new(queue.device());
                let semaphore_id = semaphore.internal_object();
                post_semaphores_ids.push(semaphore.internal_object());
                keep_alive_semaphores.push(semaphore);
                semaphore_id
            } else {
                0
            };

            debug_assert_eq!(pre_semaphores_ids.len(), pre_semaphores_stages.len());
            infos.push(vk::SubmitInfo {
                sType: vk::STRUCTURE_TYPE_SUBMIT_INFO,
                pNext: ptr::null(),
                waitSemaphoreCount: pre_semaphores_ids.len() as u32,
                pWaitSemaphores: pre_semaphores_ids.as_ptr(),
                pWaitDstStageMask: pre_semaphores_stages.as_ptr(),
                commandBufferCount: 1,
                pCommandBuffers: &me.cmd,
                signalSemaphoreCount: if after_command_buffers.is_empty() { post_semaphores_ids.len() as u32 } else { 1 },
                pSignalSemaphores: if after_command_buffers.is_empty() { post_semaphores_ids.as_ptr() } else { &after_semaphore },
            });

            if !after_command_buffers.is_empty() {
                let stage = vk::PIPELINE_STAGE_TOP_OF_PIPE_BIT;     // TODO:
                infos.push(vk::SubmitInfo {
                    sType: vk::STRUCTURE_TYPE_SUBMIT_INFO,
                    pNext: ptr::null(),
                    waitSemaphoreCount: 1,
                    pWaitSemaphores: &after_semaphore,
                    pWaitDstStageMask: &stage,
                    commandBufferCount: after_command_buffers.len() as u32,
                    pCommandBuffers: after_command_buffers.as_ptr(),
                    signalSemaphoreCount: post_semaphores_ids.len() as u32,
                    pSignalSemaphores: post_semaphores_ids.as_ptr(),
                });
            }

            let fence = fence.internal_object();
            try!(check_errors(vk.QueueSubmit(*queue.internal_object_guard(), infos.len() as u32,
                                             infos.as_ptr(), fence)));
        }

        // Don't forget to add all the semaphores in the list of semaphores that must be kept alive.
        {
            let mut ka_sem = submission.keep_alive_semaphores.lock().unwrap();
            *ka_sem = keep_alive_semaphores;
        }

    }

    Ok(submission)
}

impl Drop for InnerCommandBuffer {
    #[inline]
    fn drop(&mut self) {
        unsafe {
            let vk = self.device.pointers();
            let pool = self.pool.internal_object_guard();
            vk.FreeCommandBuffers(self.device.internal_object(), *pool, 1, &self.cmd);
        }
    }
}

#[must_use]
pub struct Submission {
    fence: Arc<Fence>,

    // The queue on which this was submitted.
    queue: Arc<Queue>,

    // Additional variables that are behind a mutex.
    guarded: Mutex<SubmissionGuarded>,

    // The command buffers that were submitted and that needs to be kept alive until the submission
    // is complete by the GPU.
    //
    // The fact that it is behind a `Mutex` is a hack. The list of CBs can only be known
    // after the `Submission` has been created and put in an `Arc`. Therefore we need a `Mutex`
    // in order to write this list. The list isn't accessed anymore afterwards, so it shouldn't
    // slow things down too much.
    // TODO: consider an UnsafeCell
    keep_alive_cb: Mutex<SmallVec<[Arc<KeepAlive>; 8]>>,

    // List of semaphores to keep alive while the submission hasn't finished execution.
    //
    // The fact that it is behind a `Mutex` is a hack. See `keep_alive_cb`.
    // TODO: consider an UnsafeCell
    keep_alive_semaphores: Mutex<SmallVec<[Arc<Semaphore>; 8]>>,
}

impl fmt::Debug for Submission {
    #[inline]
    fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        write!(fmt, "<Submission object>")      // TODO: better description
    }
}

#[derive(Debug)]
struct SubmissionGuarded {
    // Reserve of semaphores that have been signalled by this submission and that can be
    // waited upon. The semaphore must be removed from the list if it is going to be waiting upon.
    signalled_semaphores: SmallVec<[Arc<Semaphore>; 4]>,

    // Queue familiy index and queue index of each queue that got submitted a command buffer
    // that was waiting on this submission to be complete.
    //
    // If a queue is in this list, that means that all side-effects of this submission are going
    // to be visible to any further command buffer submitted to this queue. Note that this is only
    // true due to the fact that we have a per-queue semaphore (see `Queue::dedicated_semaphore`).
    signalled_queues: SmallVec<[(u32, u32); 4]>,
}

impl Submission {
    /// Returns `true` if destroying this `Submission` object would block the CPU for some time.
    #[inline]
    pub fn destroying_would_block(&self) -> bool {
        !self.finished()
    }

    /// Returns `true` if the GPU has finished executing this submission.
    #[inline]
    pub fn finished(&self) -> bool {
        self.fence.ready().unwrap_or(false)     // TODO: what to do in case of error?   
    }

    /// Waits until the submission has finished being executed by the device.
    #[inline]
    pub fn wait(&self, timeout: Duration) -> Result<(), FenceWaitError> {
        self.fence.wait(timeout)
    }

    /// Returns the `queue` the command buffers were submitted to.
    #[inline]
    pub fn queue(&self) -> &Arc<Queue> {
        &self.queue
    }
}

impl Drop for Submission {
    #[inline]
    fn drop(&mut self) {
        let timeout = Duration::new(u64::MAX / 1_000_000_000, (u64::MAX % 1_000_000_000) as u32);
        match self.fence.wait(timeout) {
            Ok(_) => (),
            Err(FenceWaitError::DeviceLostError) => (),
            Err(FenceWaitError::Timeout) => panic!(),       // The driver has some sort of problem.
            Err(FenceWaitError::OomError(_)) => panic!(),   // What else to do here?
        }

        // TODO: return `signalled_semaphores` to the semaphore pools
    }
}

pub trait KeepAlive: 'static + Send + Sync {}
impl<T> KeepAlive for T where T: 'static + Send + Sync {}

#[derive(Clone)]
struct BufferKey(Arc<Buffer>);

impl PartialEq for BufferKey {
    #[inline]
    fn eq(&self, other: &BufferKey) -> bool {
        &*self.0 as *const Buffer == &*other.0 as *const Buffer
    }
}

impl Eq for BufferKey {}

impl hash::Hash for BufferKey {
    #[inline]
    fn hash<H>(&self, state: &mut H) where H: hash::Hasher {
        let ptr = &*self.0 as *const Buffer as *const () as usize;
        hash::Hash::hash(&ptr, state)
    }
}

#[derive(Copy, Clone, Debug)]
struct InternalBufferBlockAccess {
    // Stages in which the resource is used.
    // Note that this field can have different semantics depending on where this struct is used.
    // For example it can be the stages since the latest barrier instead of just the stages.
    stages: vk::PipelineStageFlagBits,

    // The way this resource is accessed.
    // Just like `stages`, this has different semantics depending on the usage of this struct.
    accesses: vk::AccessFlagBits,

    write: bool,
}

#[derive(Clone)]
struct ImageKey(Arc<Image>);

impl PartialEq for ImageKey {
    #[inline]
    fn eq(&self, other: &ImageKey) -> bool {
        &*self.0 as *const Image == &*other.0 as *const Image
    }
}

impl Eq for ImageKey {}

impl hash::Hash for ImageKey {
    #[inline]
    fn hash<H>(&self, state: &mut H) where H: hash::Hasher {
        let ptr = &*self.0 as *const Image as *const () as usize;
        hash::Hash::hash(&ptr, state)
    }
}

#[derive(Copy, Clone, Debug)]
struct InternalImageBlockAccess {
    // Stages in which the resource is used.
    // Note that this field can have different semantics depending on where this struct is used.
    // For example it can be the stages since the latest barrier instead of just the stages.
    stages: vk::PipelineStageFlagBits,

    // The way this resource is accessed.
    // Just like `stages`, this has different semantics depending on the usage of this struct.
    accesses: vk::AccessFlagBits,

    write: bool,
    aspects: vk::ImageAspectFlags,
    old_layout: ImageLayout,
    new_layout: ImageLayout,
}

/// Builds an `InnerCommandBuffer` whose only purpose is to transition an image between two
/// layouts.
fn transition_cb(pool: &Arc<CommandBufferPool>, image: Arc<Image>, block: (u32, u32),
                 old_layout: ImageLayout, new_layout: ImageLayout)
                 -> Result<InnerCommandBuffer, OomError>
{
    let device = pool.device();
    let vk = device.pointers();
    let pool_obj = pool.internal_object_guard();

    let cmd = unsafe {
        let infos = vk::CommandBufferAllocateInfo {
            sType: vk::STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
            pNext: ptr::null(),
            commandPool: *pool_obj,
            level: vk::COMMAND_BUFFER_LEVEL_PRIMARY,
            commandBufferCount: 1,
        };

        let mut output = mem::uninitialized();
        try!(check_errors(vk.AllocateCommandBuffers(device.internal_object(), &infos,
                                                    &mut output)));
        output
    };

    unsafe {
        let infos = vk::CommandBufferBeginInfo {
            sType: vk::STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
            pNext: ptr::null(),
            flags: vk::COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
            pInheritanceInfo: ptr::null(),
        };

        // TODO: leak if this returns an err
        try!(check_errors(vk.BeginCommandBuffer(cmd, &infos)));

        let range_mipmaps = image.block_mipmap_levels_range(block);
        let range_layers = image.block_array_layers_range(block);
        let aspect_mask = match image.format().ty() {
            FormatTy::Float | FormatTy::Uint | FormatTy::Sint | FormatTy::Compressed => {
                vk::IMAGE_ASPECT_COLOR_BIT
            },
            FormatTy::Depth => vk::IMAGE_ASPECT_DEPTH_BIT,
            FormatTy::Stencil => vk::IMAGE_ASPECT_STENCIL_BIT,
            FormatTy::DepthStencil => vk::IMAGE_ASPECT_DEPTH_BIT | vk::IMAGE_ASPECT_STENCIL_BIT,
        };

        let barrier = vk::ImageMemoryBarrier {
            sType: vk::STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
            pNext: ptr::null(),
            srcAccessMask: 0,      // TODO: ?
            dstAccessMask: 0x0001ffff,      // TODO: ?
            oldLayout: old_layout as u32,
            newLayout: new_layout as u32,
            srcQueueFamilyIndex: vk::QUEUE_FAMILY_IGNORED,
            dstQueueFamilyIndex: vk::QUEUE_FAMILY_IGNORED,
            image: image.inner_image().internal_object(),
            subresourceRange: vk::ImageSubresourceRange {
                aspectMask: aspect_mask,
                baseMipLevel: range_mipmaps.start,
                levelCount: range_mipmaps.end - range_mipmaps.start,
                baseArrayLayer: range_layers.start,
                layerCount: range_layers.end - range_layers.start,
            },
        };

        vk.CmdPipelineBarrier(cmd, vk::PIPELINE_STAGE_ALL_COMMANDS_BIT,
                              vk::PIPELINE_STAGE_ALL_COMMANDS_BIT, vk::DEPENDENCY_BY_REGION_BIT,
                              0, ptr::null(), 0, ptr::null(), 1, &barrier);

        // TODO: leak if this returns an err
        try!(check_errors(vk.EndCommandBuffer(cmd)));
    }

    Ok(InnerCommandBuffer {
        device: device.clone(),
        pool: pool.clone(),
        cmd: cmd,
        buffers_state: HashMap::with_hasher(BuildHasherDefault::<FnvHasher>::default()),
        images_state: HashMap::with_hasher(BuildHasherDefault::<FnvHasher>::default()),
        extern_buffers_sync: SmallVec::new(),
        extern_images_sync: SmallVec::new(),
        keep_alive: Vec::new(),
    })
}