DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Mercurial (cdf352f02ac4)

VCS Links

Line Code
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 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618
use auxil::FastHashMap;
use hal::format::Aspects;
use hal::range::RangeArg;
use hal::{buffer, command as com, format, image, memory, pass, pool, pso, query};
use hal::{
    DrawCount,
    IndexCount,
    IndexType,
    InstanceCount,
    VertexCount,
    VertexOffset,
    WorkGroupCount,
};

use std::borrow::Borrow;
use std::ops::Range;
use std::sync::Arc;
use std::{cmp, fmt, iter, mem, ptr};

use winapi::shared::minwindef::{FALSE, TRUE, UINT};
use winapi::shared::{dxgiformat, winerror};
use winapi::um::{d3d12, d3dcommon};
use winapi::Interface;

use native;

use root_constants::RootConstant;
use smallvec::SmallVec;
use {
    conv,
    descriptors_cpu,
    device,
    internal,
    resource as r,
    validate_line_width,
    Backend,
    Device,
    Shared,
    MAX_VERTEX_BUFFERS,
};

// Fixed size of the root signature.
// Limited by D3D12.
const ROOT_SIGNATURE_SIZE: usize = 64;

const NULL_VERTEX_BUFFER_VIEW: d3d12::D3D12_VERTEX_BUFFER_VIEW = d3d12::D3D12_VERTEX_BUFFER_VIEW {
    BufferLocation: 0,
    SizeInBytes: 0,
    StrideInBytes: 0,
};

fn get_rect(rect: &pso::Rect) -> d3d12::D3D12_RECT {
    d3d12::D3D12_RECT {
        left: rect.x as i32,
        top: rect.y as i32,
        right: (rect.x + rect.w) as i32,
        bottom: (rect.y + rect.h) as i32,
    }
}

fn div(a: u32, b: u32) -> u32 {
    (a + b - 1) / b
}

fn up_align(x: u32, alignment: u32) -> u32 {
    (x + alignment - 1) & !(alignment - 1)
}

#[derive(Clone, Debug)]
struct AttachmentClear {
    subpass_id: Option<pass::SubpassId>,
    value: Option<com::ClearValue>,
    stencil_value: Option<u32>,
}

pub struct RenderPassCache {
    render_pass: r::RenderPass,
    framebuffer: r::Framebuffer,
    target_rect: d3d12::D3D12_RECT,
    attachment_clears: Vec<AttachmentClear>,
}

impl fmt::Debug for RenderPassCache {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.write_str("RenderPassCache")
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum OcclusionQuery {
    Binary(UINT),
    Precise(UINT),
}


/// Strongly-typed root signature element
///
/// Could be removed for an unsafer variant to occupy less memory
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum RootElement {
    /// Root constant in the signature
    Constant(u32),
    /// Descriptor table, storing table offset for the current descriptor heap
    TableSrvCbvUav(u32),
    /// Descriptor table, storing table offset for the current descriptor heap
    TableSampler(u32),
    /// Root descriptors take 2 DWORDs in the root signature.
    DescriptorCbv {
        buffer: u64,
    },
    DescriptorPlaceholder,
    /// Undefined value, implementation specific
    Undefined,
}

/// Virtual data storage for the current root signature memory.
struct UserData {
    data: [RootElement; ROOT_SIGNATURE_SIZE],
    dirty_mask: u64,
}

impl fmt::Debug for UserData {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt.debug_struct("UserData")
            .field("data", &&self.data[..])
            .field("dirty_mask", &self.dirty_mask)
            .finish()
    }
}

impl UserData {
    fn new() -> Self {
        UserData {
            data: [RootElement::Undefined; ROOT_SIGNATURE_SIZE],
            dirty_mask: 0,
        }
    }

    /// Update root constant values. Changes are marked as dirty.
    fn set_constants(&mut self, offset: usize, data: &[u32]) {
        assert!(offset + data.len() <= ROOT_SIGNATURE_SIZE);
        // Each root constant occupies one DWORD
        for (i, val) in data.iter().enumerate() {
            self.data[offset + i] = RootElement::Constant(*val);
            self.dirty_mask |= 1u64 << (offset + i);
        }
    }

    /// Update descriptor table. Changes are marked as dirty.
    fn set_srv_cbv_uav_table(&mut self, offset: usize, table_start: u32) {
        assert!(offset < ROOT_SIGNATURE_SIZE);
        // A descriptor table occupies one DWORD
        self.data[offset] = RootElement::TableSrvCbvUav(table_start);
        self.dirty_mask |= 1u64 << offset;
    }

    /// Update descriptor table. Changes are marked as dirty.
    fn set_sampler_table(&mut self, offset: usize, table_start: u32) {
        assert!(offset < ROOT_SIGNATURE_SIZE);
        // A descriptor table occupies one DWORD
        self.data[offset] = RootElement::TableSampler(table_start);
        self.dirty_mask |= 1u64 << offset;
    }

    ///
    fn set_descriptor_cbv(&mut self, offset: usize, buffer: u64) {
        assert!(offset + 1 < ROOT_SIGNATURE_SIZE);
        self.data[offset] = RootElement::DescriptorCbv { buffer };
        self.data[offset + 1] = RootElement::DescriptorPlaceholder;
        self.dirty_mask |= 0b1u64 << offset;
        self.dirty_mask |= 0b1u64 << offset + 1;
    }

    fn is_dirty(&self) -> bool {
        self.dirty_mask != 0
    }

    fn is_index_dirty(&self, i: usize) -> bool {
        ((self.dirty_mask >> i) & 1) == 1
    }

    /// Clear dirty flag.
    fn clear_dirty(&mut self, i: usize) {
        self.dirty_mask &= !(1 << i);
    }

    /// Mark all entries as dirty.
    fn dirty_all(&mut self) {
        self.dirty_mask = !0;
    }
}

#[derive(Debug)]
struct PipelineCache {
    // Bound pipeline and root signature.
    // Changed on bind pipeline calls.
    pipeline: Option<(native::PipelineState, native::RootSignature)>,
    // Parameter slots of the current root signature.
    num_parameter_slots: usize,
    //
    root_constants: Vec<RootConstant>,
    // Virtualized root signature user data of the shaders
    user_data: UserData,

    // Descriptor heap gpu handle offsets
    srv_cbv_uav_start: u64,
    sampler_start: u64,
}

impl PipelineCache {
    fn new() -> Self {
        PipelineCache {
            pipeline: None,
            num_parameter_slots: 0,
            root_constants: Vec::new(),
            user_data: UserData::new(),
            srv_cbv_uav_start: 0,
            sampler_start: 0,
        }
    }

    fn bind_descriptor_sets<'a, I, J>(
        &mut self,
        layout: &r::PipelineLayout,
        first_set: usize,
        sets: I,
        offsets: J,
    ) -> [native::DescriptorHeap; 2]
    where
        I: IntoIterator,
        I::Item: Borrow<r::DescriptorSet>,
        J: IntoIterator,
        J::Item: Borrow<com::DescriptorSetOffset>,
    {
        let mut sets = sets.into_iter().peekable();
        let mut offsets = offsets.into_iter().map(|offset| *offset.borrow() as u64);

        // 'Global' GPU descriptor heaps.
        // All descriptors live in the same heaps.
        let (srv_cbv_uav_start, sampler_start, heap_srv_cbv_uav, heap_sampler) =
            if let Some(set_0) = sets.peek().map(Borrow::borrow) {
                (
                    set_0.srv_cbv_uav_gpu_start().ptr,
                    set_0.sampler_gpu_start().ptr,
                    set_0.heap_srv_cbv_uav,
                    set_0.heap_samplers,
                )
            } else {
                return [native::DescriptorHeap::null(); 2];
            };

        self.srv_cbv_uav_start = srv_cbv_uav_start;
        self.sampler_start = sampler_start;

        for (set, element) in sets.zip(layout.elements[first_set ..].iter()) {
            let set = set.borrow();

            let mut num_tables = 0;

            // Bind CBV/SRC/UAV descriptor tables
            set.first_gpu_view.map(|gpu| {
                let table = &element.table;
                assert!(table.ty.contains(r::SRV_CBV_UAV));

                // Cast is safe as offset **must** be in u32 range. Unable to
                // create heaps with more descriptors.
                let table_gpu_offset = (gpu.ptr - srv_cbv_uav_start) as u32;
                let table_offset = table.offset + num_tables;
                self.user_data
                    .set_srv_cbv_uav_table(table_offset, table_gpu_offset);
                num_tables += 1;
            });

            // Bind Sampler descriptor tables.
            set.first_gpu_sampler.map(|gpu| {
                let table = &element.table;
                assert!(table.ty.contains(r::SAMPLERS));

                // Cast is safe as offset **must** be in u32 range. Unable to
                // create heaps with more descriptors.
                let table_gpu_offset = (gpu.ptr - sampler_start) as u32;
                let table_offset = table.offset + num_tables;
                self.user_data
                    .set_sampler_table(table_offset, table_gpu_offset);
            });

            // Bind root descriptors
            // TODO: slow, can we move the dynamic descriptors into toplevel somehow during initializtion?
            //       Requires changes then in the descriptor update process.
            let mut descriptor_id = 0;
            for binding in &set.binding_infos {
                // It's not valid to modify the descriptor sets during recording -> access if safe.
                let dynamic_descriptors = unsafe { &*binding.dynamic_descriptors.get() };
                for descriptor in dynamic_descriptors {
                    let root_offset = element.descriptors[descriptor_id].offset;
                    self.user_data
                        .set_descriptor_cbv(root_offset, descriptor.gpu_buffer_location + offsets.next().unwrap());
                    descriptor_id += 1;
                }
            }
        }

        [heap_srv_cbv_uav, heap_sampler]
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum BindPoint {
    Compute,
    Graphics {
        /// Internal pipelines used for blitting, copying, etc.
        internal: bool,
    },
}

#[derive(Clone, Debug)]
struct Copy {
    footprint_offset: u64,
    footprint: image::Extent,
    row_pitch: u32,
    img_subresource: u32,
    img_offset: image::Offset,
    buf_offset: image::Offset,
    copy_extent: image::Extent,
}

pub struct CommandBuffer {
    raw: native::GraphicsCommandList,
    allocator: native::CommandAllocator,
    shared: Arc<Shared>,

    // Cache renderpasses for graphics operations
    pass_cache: Option<RenderPassCache>,
    cur_subpass: usize,

    // Cache current graphics root signature and pipeline to minimize rebinding and support two
    // bindpoints.
    gr_pipeline: PipelineCache,
    // Primitive topology of the currently bound graphics pipeline.
    // Caching required for internal graphics pipelines.
    primitive_topology: d3d12::D3D12_PRIMITIVE_TOPOLOGY,
    // Cache current compute root signature and pipeline.
    comp_pipeline: PipelineCache,
    // D3D12 only has one slot for both bindpoints. Need to rebind everything if we want to switch
    // between different bind points (ie. calling draw or dispatch).
    active_bindpoint: BindPoint,
    // Current descriptor heaps heaps (CBV/SRV/UAV and Sampler).
    // Required for resetting due to internal descriptor heaps.
    active_descriptor_heaps: [native::DescriptorHeap; 2],

    // Active queries in the command buffer.
    // Queries must begin and end in the same command buffer, which allows us to track them.
    // The query pool type on `begin_query` must differ from all currently active queries.
    // Therefore, only one query per query type can be active at the same time. Binary and precise
    // occlusion queries share one queue type in Vulkan.
    occlusion_query: Option<OcclusionQuery>,
    pipeline_stats_query: Option<UINT>,

    // Cached vertex buffer views to bind.
    // `Stride` values are not known at `bind_vertex_buffers` time because they are only stored
    // inside the pipeline state.
    vertex_bindings_remap: [Option<r::VertexBinding>; MAX_VERTEX_BUFFERS],

    vertex_buffer_views: [d3d12::D3D12_VERTEX_BUFFER_VIEW; MAX_VERTEX_BUFFERS],

    // Re-using allocation for the image-buffer copies.
    copies: Vec<Copy>,

    // D3D12 only allows setting all viewports or all scissors at once, not partial updates.
    // So we must cache the implied state for these partial updates.
    viewport_cache: SmallVec<
        [d3d12::D3D12_VIEWPORT;
            d3d12::D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE as usize],
    >,
    scissor_cache: SmallVec<
        [d3d12::D3D12_RECT;
            d3d12::D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE as usize],
    >,

    // HACK: renderdoc workaround for temporary RTVs
    rtv_pools: Vec<native::DescriptorHeap>,
    // Temporary gpu descriptor heaps (internal).
    temporary_gpu_heaps: Vec<native::DescriptorHeap>,
    // Resources that need to be alive till the end of the GPU execution.
    retained_resources: Vec<native::Resource>,
    // Parenting command pool create flags.
    //
    // Required for reset behavior.
    pool_create_flags: pool::CommandPoolCreateFlags,
}

impl fmt::Debug for CommandBuffer {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.write_str("CommandBuffer")
    }
}

unsafe impl Send for CommandBuffer {}
unsafe impl Sync for CommandBuffer {}

// Insetion point for subpasses.
enum BarrierPoint {
    // Pre barriers are inserted of the beginning when switching into a new subpass.
    Pre,
    // Post barriers are applied after exectuing the user defined commands.
    Post,
}

impl CommandBuffer {
    pub(crate) fn new(
        raw: native::GraphicsCommandList,
        allocator: native::CommandAllocator,
        shared: Arc<Shared>,
        pool_create_flags: pool::CommandPoolCreateFlags,
    ) -> Self {
        CommandBuffer {
            raw,
            allocator,
            shared,
            pass_cache: None,
            cur_subpass: !0,
            gr_pipeline: PipelineCache::new(),
            primitive_topology: d3dcommon::D3D_PRIMITIVE_TOPOLOGY_UNDEFINED,
            comp_pipeline: PipelineCache::new(),
            active_bindpoint: BindPoint::Graphics { internal: false },
            active_descriptor_heaps: [native::DescriptorHeap::null(); 2],
            occlusion_query: None,
            pipeline_stats_query: None,
            vertex_bindings_remap: [None; MAX_VERTEX_BUFFERS],
            vertex_buffer_views: [NULL_VERTEX_BUFFER_VIEW; MAX_VERTEX_BUFFERS],
            copies: Vec::new(),
            viewport_cache: SmallVec::new(),
            scissor_cache: SmallVec::new(),
            rtv_pools: Vec::new(),
            temporary_gpu_heaps: Vec::new(),
            retained_resources: Vec::new(),
            pool_create_flags,
        }
    }

    pub(crate) unsafe fn destroy(&mut self) {
        self.raw.destroy();
        for heap in &self.rtv_pools {
            heap.destroy();
        }
        for heap in &self.temporary_gpu_heaps {
            heap.destroy();
        }
        for resource in &self.retained_resources {
            resource.destroy();
        }
    }

    pub(crate) unsafe fn as_raw_list(&self) -> *mut d3d12::ID3D12CommandList {
        self.raw.as_mut_ptr() as *mut _
    }

    fn reset(&mut self) {
        self.raw
            .reset(self.allocator, native::PipelineState::null());
        self.pass_cache = None;
        self.cur_subpass = !0;
        self.gr_pipeline = PipelineCache::new();
        self.primitive_topology = d3dcommon::D3D_PRIMITIVE_TOPOLOGY_UNDEFINED;
        self.comp_pipeline = PipelineCache::new();
        self.active_bindpoint = BindPoint::Graphics { internal: false };
        self.active_descriptor_heaps = [native::DescriptorHeap::null(); 2];
        self.occlusion_query = None;
        self.pipeline_stats_query = None;
        self.vertex_bindings_remap = [None; MAX_VERTEX_BUFFERS];
        self.vertex_buffer_views = [NULL_VERTEX_BUFFER_VIEW; MAX_VERTEX_BUFFERS];
        for heap in self.rtv_pools.drain(..) {
            unsafe {
                heap.destroy();
            }
        }
        for heap in self.temporary_gpu_heaps.drain(..) {
            unsafe {
                heap.destroy();
            }
        }
        for resource in self.retained_resources.drain(..) {
            unsafe {
                resource.destroy();
            }
        }
    }

    // Indicates that the pipeline slot has been overriden with an internal pipeline.
    //
    // This only invalidates the slot and the user data!
    fn set_internal_graphics_pipeline(&mut self) {
        self.active_bindpoint = BindPoint::Graphics { internal: true };
        self.gr_pipeline.user_data.dirty_all();
    }

    fn bind_descriptor_heaps(&mut self) {
        self.raw.set_descriptor_heaps(&self.active_descriptor_heaps);
    }

    fn insert_subpass_barriers(&self, insertion: BarrierPoint) {
        let state = self.pass_cache.as_ref().unwrap();
        let proto_barriers = match state.render_pass.subpasses.get(self.cur_subpass) {
            Some(subpass) => match insertion {
                BarrierPoint::Pre => &subpass.pre_barriers,
                BarrierPoint::Post => &subpass.post_barriers,
            },
            None => &state.render_pass.post_barriers,
        };

        let transition_barriers = proto_barriers
            .iter()
            .map(|barrier| {
                let mut resource_barrier = d3d12::D3D12_RESOURCE_BARRIER {
                    Type: d3d12::D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
                    Flags: barrier.flags,
                    u: unsafe { mem::zeroed() },
                };

                *unsafe { resource_barrier.u.Transition_mut() } =
                    d3d12::D3D12_RESOURCE_TRANSITION_BARRIER {
                        pResource: state.framebuffer.attachments[barrier.attachment_id]
                            .resource
                            .as_mut_ptr(),
                        Subresource: d3d12::D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
                        StateBefore: barrier.states.start,
                        StateAfter: barrier.states.end,
                    };

                resource_barrier
            })
            .collect::<Vec<_>>();

        if !transition_barriers.is_empty() {
            unsafe {
                self.raw
                    .clone()
                    .ResourceBarrier(transition_barriers.len() as _, transition_barriers.as_ptr());
            }
        }
    }

    fn bind_targets(&mut self) {
        let state = self.pass_cache.as_ref().unwrap();
        let subpass = &state.render_pass.subpasses[self.cur_subpass];

        // collect render targets
        let color_views = subpass
            .color_attachments
            .iter()
            .map(|&(id, _)| state.framebuffer.attachments[id].handle_rtv.unwrap())
            .collect::<Vec<_>>();
        let ds_view = match subpass.depth_stencil_attachment {
            Some((id, _)) => state.framebuffer.attachments[id]
                .handle_dsv
                .as_ref()
                .unwrap() as *const _,
            None => ptr::null(),
        };
        // set render targets
        unsafe {
            self.raw.OMSetRenderTargets(
                color_views.len() as UINT,
                color_views.as_ptr(),
                FALSE,
                ds_view,
            );
        }

        // performs clears for all the attachments first used in this subpass
        for (view, clear) in state
            .framebuffer
            .attachments
            .iter()
            .zip(state.attachment_clears.iter())
        {
            if clear.subpass_id != Some(self.cur_subpass) {
                continue;
            }

            if let (Some(handle), Some(cv)) = (view.handle_rtv, clear.value) {
                self.clear_render_target_view(handle, unsafe { cv.color }, &[state.target_rect]);
            }

            if let Some(handle) = view.handle_dsv {
                let depth = clear.value.map(|cv| unsafe { cv.depth_stencil.depth });
                let stencil = clear.stencil_value;

                if depth.is_some() || stencil.is_some() {
                    self.clear_depth_stencil_view(handle, depth, stencil, &[state.target_rect]);
                }
            }
        }
    }

    fn resolve_attachments(&self) {
        let state = self.pass_cache.as_ref().unwrap();
        let framebuffer = &state.framebuffer;
        let subpass = &state.render_pass.subpasses[self.cur_subpass];

        for (&(src_attachment, _), &(dst_attachment, _)) in subpass
            .color_attachments
            .iter()
            .zip(subpass.resolve_attachments.iter())
        {
            if dst_attachment == pass::ATTACHMENT_UNUSED {
                continue;
            }

            let resolve_src = state.framebuffer.attachments[src_attachment];
            let resolve_dst = state.framebuffer.attachments[dst_attachment];

            // The number of layers of the render area are given on framebuffer creation.
            for l in 0 .. framebuffer.layers {
                // Attachtments only have a single mip level by specification.
                let subresource_src = resolve_src.calc_subresource(
                    resolve_src.mip_levels.0 as _,
                    (resolve_src.layers.0 + l) as _,
                );
                let subresource_dst = resolve_dst.calc_subresource(
                    resolve_dst.mip_levels.0 as _,
                    (resolve_dst.layers.0 + l) as _,
                );

                // TODO: take width and height of render area into account.
                unsafe {
                    self.raw.ResolveSubresource(
                        resolve_dst.resource.as_mut_ptr(),
                        subresource_dst,
                        resolve_src.resource.as_mut_ptr(),
                        subresource_src,
                        resolve_dst.dxgi_format,
                    );
                }
            }
        }
    }

    fn clear_render_target_view(
        &self,
        rtv: d3d12::D3D12_CPU_DESCRIPTOR_HANDLE,
        color: com::ClearColor,
        rects: &[d3d12::D3D12_RECT],
    ) {
        let num_rects = rects.len() as _;
        let rects = if num_rects > 0 {
            rects.as_ptr()
        } else {
            ptr::null()
        };

        unsafe {
            self.raw
                .clone()
                .ClearRenderTargetView(rtv, &color.float32, num_rects, rects);
        }
    }

    fn clear_depth_stencil_view(
        &self,
        dsv: d3d12::D3D12_CPU_DESCRIPTOR_HANDLE,
        depth: Option<f32>,
        stencil: Option<u32>,
        rects: &[d3d12::D3D12_RECT],
    ) {
        let mut flags = native::ClearFlags::empty();
        if depth.is_some() {
            flags |= native::ClearFlags::DEPTH;
        }
        if stencil.is_some() {
            flags |= native::ClearFlags::STENCIL;
        }

        self.raw.clear_depth_stencil_view(
            dsv,
            flags,
            depth.unwrap_or_default(),
            stencil.unwrap_or_default() as _,
            rects,
        );
    }

    fn set_graphics_bind_point(&mut self) {
        match self.active_bindpoint {
            BindPoint::Compute => {
                // Switch to graphics bind point
                let (pipeline, _) = self
                    .gr_pipeline
                    .pipeline
                    .expect("No graphics pipeline bound");
                self.raw.set_pipeline_state(pipeline);
            }
            BindPoint::Graphics { internal: true } => {
                // Switch to graphics bind point
                let (pipeline, signature) = self
                    .gr_pipeline
                    .pipeline
                    .expect("No graphics pipeline bound");
                self.raw.set_pipeline_state(pipeline);
                self.raw.set_graphics_root_signature(signature);
                self.bind_descriptor_heaps();
            }
            BindPoint::Graphics { internal: false } => {}
        }

        self.active_bindpoint = BindPoint::Graphics { internal: false };
        let cmd_buffer = &mut self.raw;

        // Flush root signature data
        Self::flush_user_data(
            &mut self.gr_pipeline,
            |slot, data| unsafe {
                cmd_buffer.clone().SetGraphicsRoot32BitConstants(
                    slot,
                    data.len() as _,
                    data.as_ptr() as *const _,
                    0,
                )
            },
            |slot, gpu| cmd_buffer.set_graphics_root_descriptor_table(slot, gpu),
            |slot, buffer| cmd_buffer.set_graphics_root_constant_buffer_view(slot, buffer),
        );
    }

    fn set_compute_bind_point(&mut self) {
        match self.active_bindpoint {
            BindPoint::Graphics { internal } => {
                // Switch to compute bind point
                let (pipeline, _) = self
                    .comp_pipeline
                    .pipeline
                    .expect("No compute pipeline bound");

                self.raw.set_pipeline_state(pipeline);

                self.active_bindpoint = BindPoint::Compute;

                if internal {
                    self.bind_descriptor_heaps();
                    // Rebind the graphics root signature as we come from an internal graphics.
                    // Issuing a draw call afterwards would hide the information that we internally
                    // changed the graphics root signature.
                    if let Some((_, signature)) = self.gr_pipeline.pipeline {
                        self.raw.set_graphics_root_signature(signature);
                    }
                }
            }
            BindPoint::Compute => {} // Nothing to do
        }

        let cmd_buffer = &mut self.raw;
        Self::flush_user_data(
            &mut self.comp_pipeline,
            |slot, data| unsafe {
                cmd_buffer.clone().SetComputeRoot32BitConstants(
                    slot,
                    data.len() as _,
                    data.as_ptr() as *const _,
                    0,
                )
            },
            |slot, gpu| cmd_buffer.set_compute_root_descriptor_table(slot, gpu),
            |slot, buffer| cmd_buffer.set_compute_root_constant_buffer_view(slot, buffer),
        );
    }

    fn flush_user_data<F, G, H>(
        pipeline: &mut PipelineCache,
        mut constants_update: F,
        mut table_update: G,
        mut descriptor_cbv_update: H,
    ) where
        F: FnMut(u32, &[u32]),
        G: FnMut(u32, d3d12::D3D12_GPU_DESCRIPTOR_HANDLE),
        H: FnMut(u32, d3d12::D3D12_GPU_VIRTUAL_ADDRESS),
    {
        let user_data = &mut pipeline.user_data;
        if !user_data.is_dirty() {
            return;
        }

        let num_root_constant = pipeline.root_constants.len();
        let mut cur_index = 0;
        // TODO: opt: Only set dirty root constants?
        for (i, root_constant) in pipeline.root_constants.iter().enumerate() {
            let num_constants = (root_constant.range.end - root_constant.range.start) as usize;
            let mut data = Vec::new();
            for c in cur_index .. cur_index + num_constants {
                data.push(match user_data.data[c] {
                    RootElement::Constant(v) => v,
                    _ => {
                        warn!(
                            "Unset or mismatching root constant at index {:?} ({:?})",
                            c, user_data.data[c]
                        );
                        0
                    }
                });
                user_data.clear_dirty(c);
            }
            constants_update(i as _, &data);
            cur_index += num_constants;
        }

        // Flush descriptor tables & root descriptors
        // Index in the user data array where tables are starting
        let table_start = pipeline
            .root_constants
            .iter()
            .fold(0, |sum, c| sum + c.range.end - c.range.start) as usize;

        for i in num_root_constant .. pipeline.num_parameter_slots {
            let table_index = i - num_root_constant + table_start;
            if user_data.is_index_dirty(table_index) {
                match user_data.data[table_index] {
                    RootElement::TableSrvCbvUav(offset) => {
                        let gpu = d3d12::D3D12_GPU_DESCRIPTOR_HANDLE { ptr: pipeline.srv_cbv_uav_start + offset as u64 };
                        table_update(i as _, gpu);
                        user_data.clear_dirty(table_index);
                    }
                    RootElement::TableSampler(offset) => {
                        let gpu = d3d12::D3D12_GPU_DESCRIPTOR_HANDLE { ptr: pipeline.sampler_start + offset as u64 };
                        table_update(i as _, gpu);
                        user_data.clear_dirty(table_index);
                    }
                    RootElement::DescriptorCbv { buffer } => {
                        debug_assert!(user_data.is_index_dirty(table_index + 1));
                        debug_assert_eq!(user_data.data[table_index + 1], RootElement::DescriptorPlaceholder);

                        descriptor_cbv_update(i as _, buffer);

                        user_data.clear_dirty(table_index);
                        user_data.clear_dirty(table_index + 1); // skip placeholder
                    }
                    other => {
                        error!(
                            "Unexpected user data element in the root signature ({:?})",
                            (table_index, other)
                        );
                        continue;
                    }
                };
            }
        }
    }

    fn transition_barrier(
        transition: d3d12::D3D12_RESOURCE_TRANSITION_BARRIER,
    ) -> d3d12::D3D12_RESOURCE_BARRIER {
        let mut barrier = d3d12::D3D12_RESOURCE_BARRIER {
            Type: d3d12::D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
            Flags: d3d12::D3D12_RESOURCE_BARRIER_FLAG_NONE,
            u: unsafe { mem::zeroed() },
        };

        *unsafe { barrier.u.Transition_mut() } = transition;
        barrier
    }

    fn split_buffer_copy(copies: &mut Vec<Copy>, r: &com::BufferImageCopy, image: &r::ImageBound) {
        let buffer_width = if r.buffer_width == 0 {
            r.image_extent.width
        } else {
            r.buffer_width
        };
        let buffer_height = if r.buffer_height == 0 {
            r.image_extent.height
        } else {
            r.buffer_height
        };
        let image_extent_aligned = image::Extent {
            width: up_align(r.image_extent.width, image.block_dim.0 as _),
            height: up_align(r.image_extent.height, image.block_dim.1 as _),
            depth: r.image_extent.depth,
        };
        let row_pitch = div(buffer_width, image.block_dim.0 as _) * image.bytes_per_block as u32;
        let slice_pitch = div(buffer_height, image.block_dim.1 as _) * row_pitch;
        let is_pitch_aligned = row_pitch % d3d12::D3D12_TEXTURE_DATA_PITCH_ALIGNMENT == 0;

        for layer in r.image_layers.layers.clone() {
            let img_subresource = image.calc_subresource(r.image_layers.level as _, layer as _, 0);
            let layer_relative = (layer - r.image_layers.layers.start) as u32;
            let layer_offset = r.buffer_offset as u64
                + (layer_relative * slice_pitch * r.image_extent.depth) as u64;
            let aligned_offset =
                layer_offset & !(d3d12::D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT as u64 - 1);
            if layer_offset == aligned_offset && is_pitch_aligned {
                // trivial case: everything is aligned, ready for copying
                copies.push(Copy {
                    footprint_offset: aligned_offset,
                    footprint: image_extent_aligned,
                    row_pitch,
                    img_subresource,
                    img_offset: r.image_offset,
                    buf_offset: image::Offset::ZERO,
                    copy_extent: image_extent_aligned,
                });
            } else if is_pitch_aligned {
                // buffer offset is not aligned
                let row_pitch_texels =
                    row_pitch / image.bytes_per_block as u32 * image.block_dim.0 as u32;
                let gap = (layer_offset - aligned_offset) as i32;
                let buf_offset = image::Offset {
                    x: (gap % row_pitch as i32) / image.bytes_per_block as i32
                        * image.block_dim.0 as i32,
                    y: (gap % slice_pitch as i32) / row_pitch as i32 * image.block_dim.1 as i32,
                    z: gap / slice_pitch as i32,
                };
                let footprint = image::Extent {
                    width: buf_offset.x as u32 + image_extent_aligned.width,
                    height: buf_offset.y as u32 + image_extent_aligned.height,
                    depth: buf_offset.z as u32 + image_extent_aligned.depth,
                };
                if r.image_extent.width + buf_offset.x as u32 <= row_pitch_texels {
                    // we can map it to the aligned one and adjust the offsets accordingly
                    copies.push(Copy {
                        footprint_offset: aligned_offset,
                        footprint,
                        row_pitch,
                        img_subresource,
                        img_offset: r.image_offset,
                        buf_offset,
                        copy_extent: image_extent_aligned,
                    });
                } else {
                    // split the copy region into 2 that suffice the previous condition
                    assert!(buf_offset.x as u32 <= row_pitch_texels);
                    let half = row_pitch_texels - buf_offset.x as u32;
                    assert!(half <= r.image_extent.width);

                    copies.push(Copy {
                        footprint_offset: aligned_offset,
                        footprint: image::Extent {
                            width: row_pitch_texels,
                            ..footprint
                        },
                        row_pitch,
                        img_subresource,
                        img_offset: r.image_offset,
                        buf_offset,
                        copy_extent: image::Extent {
                            width: half,
                            ..r.image_extent
                        },
                    });
                    copies.push(Copy {
                        footprint_offset: aligned_offset,
                        footprint: image::Extent {
                            width: image_extent_aligned.width - half,
                            height: footprint.height + image.block_dim.1 as u32,
                            depth: footprint.depth,
                        },
                        row_pitch,
                        img_subresource,
                        img_offset: image::Offset {
                            x: r.image_offset.x + half as i32,
                            ..r.image_offset
                        },
                        buf_offset: image::Offset {
                            x: 0,
                            y: buf_offset.y + image.block_dim.1 as i32,
                            z: buf_offset.z,
                        },
                        copy_extent: image::Extent {
                            width: image_extent_aligned.width - half,
                            ..image_extent_aligned
                        },
                    });
                }
            } else {
                // worst case: row by row copy
                for z in 0 .. r.image_extent.depth {
                    for y in 0 .. image_extent_aligned.height / image.block_dim.1 as u32 {
                        // an image row starts non-aligned
                        let row_offset = layer_offset
                            + z as u64 * slice_pitch as u64
                            + y as u64 * row_pitch as u64;
                        let aligned_offset = row_offset
                            & !(d3d12::D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT as u64 - 1);
                        let next_aligned_offset =
                            aligned_offset + d3d12::D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT as u64;
                        let cut_row_texels = (next_aligned_offset - row_offset)
                            / image.bytes_per_block as u64
                            * image.block_dim.0 as u64;
                        let cut_width =
                            cmp::min(image_extent_aligned.width, cut_row_texels as image::Size);
                        let gap_texels = (row_offset - aligned_offset) as image::Size
                            / image.bytes_per_block as image::Size
                            * image.block_dim.0 as image::Size;
                        // this is a conservative row pitch that should be compatible with both copies
                        let max_unaligned_pitch =
                            (r.image_extent.width + gap_texels) * image.bytes_per_block as u32;
                        let row_pitch = (max_unaligned_pitch
                            | (d3d12::D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1))
                            + 1;

                        copies.push(Copy {
                            footprint_offset: aligned_offset,
                            footprint: image::Extent {
                                width: cut_width + gap_texels,
                                height: image.block_dim.1 as _,
                                depth: 1,
                            },
                            row_pitch,
                            img_subresource,
                            img_offset: image::Offset {
                                x: r.image_offset.x,
                                y: r.image_offset.y + image.block_dim.1 as i32 * y as i32,
                                z: r.image_offset.z + z as i32,
                            },
                            buf_offset: image::Offset {
                                x: gap_texels as i32,
                                y: 0,
                                z: 0,
                            },
                            copy_extent: image::Extent {
                                width: cut_width,
                                height: image.block_dim.1 as _,
                                depth: 1,
                            },
                        });

                        // and if it crosses a pitch alignment - we copy the rest separately
                        if cut_width >= image_extent_aligned.width {
                            continue;
                        }
                        let leftover = image_extent_aligned.width - cut_width;

                        copies.push(Copy {
                            footprint_offset: next_aligned_offset,
                            footprint: image::Extent {
                                width: leftover,
                                height: image.block_dim.1 as _,
                                depth: 1,
                            },
                            row_pitch,
                            img_subresource,
                            img_offset: image::Offset {
                                x: r.image_offset.x + cut_width as i32,
                                y: r.image_offset.y + y as i32 * image.block_dim.1 as i32,
                                z: r.image_offset.z + z as i32,
                            },
                            buf_offset: image::Offset::ZERO,
                            copy_extent: image::Extent {
                                width: leftover,
                                height: image.block_dim.1 as _,
                                depth: 1,
                            },
                        });
                    }
                }
            }
        }
    }

    fn set_vertex_buffers(&mut self) {
        let cmd_buffer = &mut self.raw;
        let vbs_remap = &self.vertex_bindings_remap;
        let vbs = &self.vertex_buffer_views;
        let mut last_end_slot = 0;
        loop {
            let start_offset = match vbs_remap[last_end_slot ..]
                .iter()
                .position(|remap| remap.is_some())
            {
                Some(offset) => offset,
                None => break,
            };

            let start_slot = last_end_slot + start_offset;
            let buffers = vbs_remap[start_slot ..]
                .iter()
                .take_while(|x| x.is_some())
                .filter_map(|mapping| {
                    let mapping = mapping.unwrap();
                    let view = vbs[mapping.mapped_binding];
                    // Skip bindings that don't make sense. Since this function is called eagerly,
                    // we expect it to be called with all the valid inputs prior to drawing.
                    view.SizeInBytes.checked_sub(mapping.offset).map(|size| {
                        d3d12::D3D12_VERTEX_BUFFER_VIEW {
                            BufferLocation: view.BufferLocation + mapping.offset as u64,
                            SizeInBytes: size,
                            StrideInBytes: mapping.stride,
                        }
                    })
                })
                .collect::<SmallVec<[_; MAX_VERTEX_BUFFERS]>>();

            if buffers.is_empty() {
                last_end_slot = start_slot + 1;
            } else {
                let num_views = buffers.len();
                unsafe {
                    cmd_buffer.IASetVertexBuffers(
                        start_slot as _,
                        num_views as _,
                        buffers.as_ptr(),
                    );
                }
                last_end_slot = start_slot + num_views;
            }
        }
    }

    fn fill_texture_barries(
        target: &r::ImageBound,
        states: Range<d3d12::D3D12_RESOURCE_STATES>,
        range: &image::SubresourceRange,
        list: &mut impl Extend<d3d12::D3D12_RESOURCE_BARRIER>,
    ) {
        let mut bar =
            Self::transition_barrier(d3d12::D3D12_RESOURCE_TRANSITION_BARRIER {
                pResource: target.resource.as_mut_ptr(),
                Subresource: d3d12::D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
                StateBefore: states.start,
                StateAfter: states.end,
            });

        if *range == target.to_subresource_range(range.aspects) {
            // Only one barrier if it affects the whole image.
            list.extend(iter::once(bar));
        } else {
            // Generate barrier for each layer/level combination.
            for level in range.levels.clone() {
                for layer in range.layers.clone() {
                    unsafe {
                        let transition_barrier = &mut *bar.u.Transition_mut();
                        transition_barrier.Subresource =
                            target.calc_subresource(level as _, layer as _, 0);
                    }
                    list.extend(iter::once(bar));
                }
            }
        }
    }
}

impl com::CommandBuffer<Backend> for CommandBuffer {
    unsafe fn begin(
        &mut self,
        _flags: com::CommandBufferFlags,
        _info: com::CommandBufferInheritanceInfo<Backend>,
    ) {
        // TODO: Implement flags and secondary command buffers (bundles).
        if self
            .pool_create_flags
            .contains(pool::CommandPoolCreateFlags::RESET_INDIVIDUAL)
        {
            // Command buffer has reset semantics now and doesn't require to be in `Initial` state.
            self.allocator.Reset();
        }
        self.reset();
    }

    unsafe fn finish(&mut self) {
        self.raw.Close();
    }

    unsafe fn reset(&mut self, _release_resources: bool) {
        // Ensure that we have a bijective relation between list and allocator.
        // This allows to modify the allocator here. Using `reset` requires this by specification.
        assert!(self
            .pool_create_flags
            .contains(pool::CommandPoolCreateFlags::RESET_INDIVIDUAL));

        // TODO: `release_resources` should recreate the allocator to give back all memory.
        self.allocator.Reset();
        self.reset();
    }

    unsafe fn begin_render_pass<T>(
        &mut self,
        render_pass: &r::RenderPass,
        framebuffer: &r::Framebuffer,
        target_rect: pso::Rect,
        clear_values: T,
        _first_subpass: com::SubpassContents,
    ) where
        T: IntoIterator,
        T::Item: Borrow<com::ClearValue>,
    {
        assert_eq!(framebuffer.attachments.len(), render_pass.attachments.len());
        // Make sure that no subpass works with Present as intermediate layout.
        // This wouldn't make much sense, and proceeding with this constraint
        // allows the state transitions generated from subpass dependencies
        // to ignore the layouts completely.
        assert!(!render_pass.subpasses.iter().any(|sp| sp
            .color_attachments
            .iter()
            .chain(sp.depth_stencil_attachment.iter())
            .chain(sp.input_attachments.iter())
            .any(|aref| aref.1 == image::Layout::Present)));

        let mut clear_iter = clear_values.into_iter();
        let attachment_clears = render_pass
            .attachments
            .iter()
            .enumerate()
            .map(|(i, attachment)| {
                let cv = if attachment.has_clears() {
                    Some(*clear_iter.next().unwrap().borrow())
                } else {
                    None
                };

                AttachmentClear {
                    subpass_id: render_pass.subpasses.iter().position(|sp| sp.is_using(i)),
                    value: if attachment.ops.load == pass::AttachmentLoadOp::Clear {
                        assert!(cv.is_some());
                        cv
                    } else {
                        None
                    },
                    stencil_value: if attachment.stencil_ops.load == pass::AttachmentLoadOp::Clear {
                        Some(cv.unwrap().depth_stencil.stencil)
                    } else {
                        None
                    },
                }
            })
            .collect();

        self.pass_cache = Some(RenderPassCache {
            render_pass: render_pass.clone(),
            framebuffer: framebuffer.clone(),
            target_rect: get_rect(&target_rect),
            attachment_clears,
        });
        self.cur_subpass = 0;
        self.insert_subpass_barriers(BarrierPoint::Pre);
        self.bind_targets();
    }

    unsafe fn next_subpass(&mut self, _contents: com::SubpassContents) {
        self.insert_subpass_barriers(BarrierPoint::Post);
        self.resolve_attachments();

        self.cur_subpass += 1;
        self.insert_subpass_barriers(BarrierPoint::Pre);
        self.bind_targets();
    }

    unsafe fn end_render_pass(&mut self) {
        self.insert_subpass_barriers(BarrierPoint::Post);
        self.resolve_attachments();

        self.cur_subpass = !0;
        self.insert_subpass_barriers(BarrierPoint::Pre);
        self.pass_cache = None;
    }

    unsafe fn pipeline_barrier<'a, T>(
        &mut self,
        _stages: Range<pso::PipelineStage>,
        _dependencies: memory::Dependencies,
        barriers: T,
    ) where
        T: IntoIterator,
        T::Item: Borrow<memory::Barrier<'a, Backend>>,
    {
        let mut raw_barriers = SmallVec::<[_; 4]>::new();

        // transition barriers
        for barrier in barriers {
            match *barrier.borrow() {
                memory::Barrier::AllBuffers(_) | memory::Barrier::AllImages(_) => {
                    // Aliasing barrier with NULL resource is the closest we can get to
                    // a global memory barrier in Vulkan.
                    // Was suggested by a Microsoft representative as well as some of the IHVs.
                    let mut bar = d3d12::D3D12_RESOURCE_BARRIER {
                        Type: d3d12::D3D12_RESOURCE_BARRIER_TYPE_UAV,
                        Flags: d3d12::D3D12_RESOURCE_BARRIER_FLAG_NONE,
                        u: mem::zeroed(),
                    };
                    *bar.u.UAV_mut() = d3d12::D3D12_RESOURCE_UAV_BARRIER {
                        pResource: ptr::null_mut(),
                    };
                    raw_barriers.push(bar);
                }
                memory::Barrier::Buffer {
                    ref states,
                    target,
                    ref families,
                    ..
                } => {
                    // TODO: Implement queue family ownership transitions for dx12
                    if let Some(f) = families {
                        if f.start.0 != f.end.0 {
                            unimplemented!("Queue family resource ownership transitions are not implemented for DX12 (attempted transition from queue family {} to {}", f.start.0, f.end.0);
                        }
                    }
                    let state_src = conv::map_buffer_resource_state(states.start);
                    let state_dst = conv::map_buffer_resource_state(states.end);

                    if state_src == state_dst {
                        continue;
                    }

                    let target = target.expect_bound();
                    let bar = Self::transition_barrier(d3d12::D3D12_RESOURCE_TRANSITION_BARRIER {
                        pResource: target.resource.as_mut_ptr(),
                        Subresource: d3d12::D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
                        StateBefore: state_src,
                        StateAfter: state_dst,
                    });

                    raw_barriers.push(bar);
                }
                memory::Barrier::Image {
                    ref states,
                    target,
                    ref families,
                    ref range,
                } => {
                    // TODO: Implement queue family ownership transitions for dx12
                    if let Some(f) = families {
                        if f.start.0 != f.end.0 {
                            unimplemented!("Queue family resource ownership transitions are not implemented for DX12 (attempted transition from queue family {} to {}", f.start.0, f.end.0);
                        }
                    }
                    let state_src = conv::map_image_resource_state(states.start.0, states.start.1);
                    let state_dst = conv::map_image_resource_state(states.end.0, states.end.1);

                    if state_src == state_dst {
                        continue;
                    }

                    let target = target.expect_bound();
                    Self::fill_texture_barries(target, state_src .. state_dst, range, &mut raw_barriers);
                }
            }
        }

        // UAV barriers
        //
        // TODO: Currently always add a global UAV barrier.
        //       WAR only requires an execution barrier but D3D12 seems to need
        //       a UAV barrier for this according to docs. Can we make this better?
        {
            let mut barrier = d3d12::D3D12_RESOURCE_BARRIER {
                Type: d3d12::D3D12_RESOURCE_BARRIER_TYPE_UAV,
                Flags: d3d12::D3D12_RESOURCE_BARRIER_FLAG_NONE,
                u: mem::zeroed(),
            };
            *barrier.u.UAV_mut() = d3d12::D3D12_RESOURCE_UAV_BARRIER {
                pResource: ptr::null_mut(),
            };
            raw_barriers.push(barrier);
        }

        // Alias barriers
        //
        // TODO: Optimize, don't always add an alias barrier
        {
            let mut barrier = d3d12::D3D12_RESOURCE_BARRIER {
                Type: d3d12::D3D12_RESOURCE_BARRIER_TYPE_ALIASING,
                Flags: d3d12::D3D12_RESOURCE_BARRIER_FLAG_NONE,
                u: mem::zeroed(),
            };
            *barrier.u.Aliasing_mut() = d3d12::D3D12_RESOURCE_ALIASING_BARRIER {
                pResourceBefore: ptr::null_mut(),
                pResourceAfter: ptr::null_mut(),
            };
            raw_barriers.push(barrier);
        }

        self.raw
            .ResourceBarrier(raw_barriers.len() as _, raw_barriers.as_ptr());
    }

    unsafe fn clear_image<T>(
        &mut self,
        image: &r::Image,
        layout: image::Layout,
        value: com::ClearValue,
        subresource_ranges: T,
    ) where
        T: IntoIterator,
        T::Item: Borrow<image::SubresourceRange>,
    {
        let image = image.expect_bound();
        let base_state = conv::map_image_resource_state(image::Access::TRANSFER_WRITE, layout);
        let mut raw_barriers = SmallVec::<[_; 4]>::new();

        for subresource_range in subresource_ranges {
            let sub = subresource_range.borrow();
            if sub.levels.end != 1 {
                warn!("Clearing non-zero mipmap levels is not supported yet");
            }
            let target_state = if sub.aspects.contains(Aspects::COLOR) {
                d3d12::D3D12_RESOURCE_STATE_RENDER_TARGET
            } else {
                d3d12::D3D12_RESOURCE_STATE_DEPTH_WRITE
            };

            // Transition into a renderable state. We don't expect `*AttachmentOptimal`
            // here since this would be invalid.
            raw_barriers.clear();
            Self::fill_texture_barries(image, base_state .. target_state, sub, &mut raw_barriers);
            self.raw
                .ResourceBarrier(raw_barriers.len() as _, raw_barriers.as_ptr());

            for layer in sub.layers.clone() {
                if sub.aspects.contains(Aspects::COLOR) {
                    let rtv = image.clear_cv[layer as usize];
                    self.clear_render_target_view(rtv, value.color, &[]);
                }
                if sub.aspects.contains(Aspects::DEPTH) {
                    let dsv = image.clear_dv[layer as usize];
                    self.clear_depth_stencil_view(dsv, Some(value.depth_stencil.depth), None, &[]);
                }
                if sub.aspects.contains(Aspects::STENCIL) {
                    let dsv = image.clear_sv[layer as usize];
                    self.clear_depth_stencil_view(
                        dsv,
                        None,
                        Some(value.depth_stencil.stencil as _),
                        &[],
                    );
                }
            }

            // Transition back into the old state.
            raw_barriers.clear();
            Self::fill_texture_barries(image, target_state .. base_state, sub, &mut raw_barriers);
            self.raw
                .ResourceBarrier(raw_barriers.len() as _, raw_barriers.as_ptr());
        }
    }

    unsafe fn clear_attachments<T, U>(&mut self, clears: T, rects: U)
    where
        T: IntoIterator,
        T::Item: Borrow<com::AttachmentClear>,
        U: IntoIterator,
        U::Item: Borrow<pso::ClearRect>,
    {
        let pass_cache = match self.pass_cache {
            Some(ref cache) => cache,
            None => panic!("`clear_attachments` can only be called inside a renderpass"),
        };
        let sub_pass = &pass_cache.render_pass.subpasses[self.cur_subpass];

        let clear_rects: SmallVec<[pso::ClearRect; 4]> = rects
            .into_iter()
            .map(|rect| rect.borrow().clone())
            .collect();

        let device = self.shared.service_pipes.device;

        for clear in clears {
            match *clear.borrow() {
                com::AttachmentClear::Color { index, value } => {
                    let attachment = {
                        let rtv_id = sub_pass.color_attachments[index];
                        pass_cache.framebuffer.attachments[rtv_id.0]
                    };

                    let mut rtv_pool = descriptors_cpu::HeapLinear::new(
                        device,
                        native::DescriptorHeapType::Rtv,
                        clear_rects.len(),
                    );

                    for clear_rect in &clear_rects {
                        assert!(attachment.layers.0 + clear_rect.layers.end <= attachment.layers.1);
                        let rect = [get_rect(&clear_rect.rect)];

                        let view_info = device::ViewInfo {
                            resource: attachment.resource,
                            kind: attachment.kind,
                            caps: image::ViewCapabilities::empty(),
                            view_kind: image::ViewKind::D2Array,
                            format: attachment.dxgi_format,
                            component_mapping: device::IDENTITY_MAPPING,
                            range: image::SubresourceRange {
                                aspects: Aspects::COLOR,
                                levels: attachment.mip_levels.0 .. attachment.mip_levels.1,
                                layers: attachment.layers.0 + clear_rect.layers.start
                                    .. attachment.layers.0 + clear_rect.layers.end,
                            },
                        };
                        let rtv = rtv_pool.alloc_handle();
                        Device::view_image_as_render_target_impl(device, rtv, view_info).unwrap();
                        self.clear_render_target_view(rtv, value.into(), &rect);
                    }

                    rtv_pool.destroy();
                }
                com::AttachmentClear::DepthStencil { depth, stencil } => {
                    let attachment = {
                        let dsv_id = sub_pass.depth_stencil_attachment.unwrap();
                        pass_cache.framebuffer.attachments[dsv_id.0]
                    };

                    let mut dsv_pool = descriptors_cpu::HeapLinear::new(
                        device,
                        native::DescriptorHeapType::Dsv,
                        clear_rects.len(),
                    );

                    for clear_rect in &clear_rects {
                        assert!(attachment.layers.0 + clear_rect.layers.end <= attachment.layers.1);
                        let rect = [get_rect(&clear_rect.rect)];

                        let view_info = device::ViewInfo {
                            resource: attachment.resource,
                            kind: attachment.kind,
                            caps: image::ViewCapabilities::empty(),
                            view_kind: image::ViewKind::D2Array,
                            format: attachment.dxgi_format,
                            component_mapping: device::IDENTITY_MAPPING,
                            range: image::SubresourceRange {
                                aspects: if depth.is_some() {
                                    Aspects::DEPTH
                                } else {
                                    Aspects::empty()
                                } | if stencil.is_some() {
                                    Aspects::STENCIL
                                } else {
                                    Aspects::empty()
                                },
                                levels: attachment.mip_levels.0 .. attachment.mip_levels.1,
                                layers: attachment.layers.0 + clear_rect.layers.start
                                    .. attachment.layers.0 + clear_rect.layers.end,
                            },
                        };
                        let dsv = dsv_pool.alloc_handle();
                        Device::view_image_as_depth_stencil_impl(device, dsv, view_info).unwrap();
                        self.clear_depth_stencil_view(dsv, depth, stencil, &rect);
                    }

                    dsv_pool.destroy();
                }
            }
        }
    }

    unsafe fn resolve_image<T>(
        &mut self,
        src: &r::Image,
        _src_layout: image::Layout,
        dst: &r::Image,
        _dst_layout: image::Layout,
        regions: T,
    ) where
        T: IntoIterator,
        T::Item: Borrow<com::ImageResolve>,
    {
        let src = src.expect_bound();
        let dst = dst.expect_bound();
        assert_eq!(src.descriptor.Format, dst.descriptor.Format);

        {
            // Insert barrier for `COPY_DEST` to `RESOLVE_DEST` as we only expose
            // `TRANSFER_WRITE` which is used for all copy commands.
            let transition_barrier =
                Self::transition_barrier(d3d12::D3D12_RESOURCE_TRANSITION_BARRIER {
                    pResource: dst.resource.as_mut_ptr(),
                    Subresource: d3d12::D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, // TODO: only affected ranges
                    StateBefore: d3d12::D3D12_RESOURCE_STATE_COPY_DEST,
                    StateAfter: d3d12::D3D12_RESOURCE_STATE_RESOLVE_DEST,
                });
            self.raw.ResourceBarrier(1, &transition_barrier);
        }

        for region in regions {
            let r = region.borrow();
            for layer in 0 .. r.extent.depth as UINT {
                self.raw.ResolveSubresource(
                    src.resource.as_mut_ptr(),
                    src.calc_subresource(
                        r.src_subresource.level as UINT,
                        r.src_subresource.layers.start as UINT + layer,
                        0,
                    ),
                    dst.resource.as_mut_ptr(),
                    dst.calc_subresource(
                        r.dst_subresource.level as UINT,
                        r.dst_subresource.layers.start as UINT + layer,
                        0,
                    ),
                    src.descriptor.Format,
                );
            }
        }

        {
            // Insert barrier for back transition from `RESOLVE_DEST` to `COPY_DEST`.
            let transition_barrier =
                Self::transition_barrier(d3d12::D3D12_RESOURCE_TRANSITION_BARRIER {
                    pResource: dst.resource.as_mut_ptr(),
                    Subresource: d3d12::D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, // TODO: only affected ranges
                    StateBefore: d3d12::D3D12_RESOURCE_STATE_RESOLVE_DEST,
                    StateAfter: d3d12::D3D12_RESOURCE_STATE_COPY_DEST,
                });
            self.raw.ResourceBarrier(1, &transition_barrier);
        }
    }

    unsafe fn blit_image<T>(
        &mut self,
        src: &r::Image,
        _src_layout: image::Layout,
        dst: &r::Image,
        _dst_layout: image::Layout,
        filter: image::Filter,
        regions: T,
    ) where
        T: IntoIterator,
        T::Item: Borrow<com::ImageBlit>,
    {
        let device = self.shared.service_pipes.device.clone();
        let src = src.expect_bound();
        let dst = dst.expect_bound();

        // TODO: Resource barriers for src.
        // TODO: depth or stencil images not supported so far

        // TODO: only supporting 2D images
        match (src.kind, dst.kind) {
            (image::Kind::D2(..), image::Kind::D2(..)) => {}
            _ => unimplemented!(),
        }

        // Descriptor heap for the current blit, only storing the src image
        let (srv_heap, _) = device.create_descriptor_heap(
            1,
            native::DescriptorHeapType::CbvSrvUav,
            native::DescriptorHeapFlags::SHADER_VISIBLE,
            0,
        );
        let srv_desc = Device::build_image_as_shader_resource_desc(&device::ViewInfo {
            resource: src.resource,
            kind: src.kind,
            caps: src.view_caps,
            view_kind: image::ViewKind::D2Array, // TODO
            format: src.default_view_format.unwrap(),
            component_mapping: device::IDENTITY_MAPPING,
            range: image::SubresourceRange {
                aspects: format::Aspects::COLOR, // TODO
                levels: 0 .. src.descriptor.MipLevels as _,
                layers: 0 .. src.kind.num_layers(),
            },
        })
        .unwrap();
        device.CreateShaderResourceView(
            src.resource.as_mut_ptr(),
            &srv_desc,
            srv_heap.start_cpu_descriptor(),
        );
        self.raw.set_descriptor_heaps(&[srv_heap]);
        self.temporary_gpu_heaps.push(srv_heap);

        let filter = match filter {
            image::Filter::Nearest => d3d12::D3D12_FILTER_MIN_MAG_MIP_POINT,
            image::Filter::Linear => d3d12::D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT,
        };

        struct Instance {
            rtv: d3d12::D3D12_CPU_DESCRIPTOR_HANDLE,
            viewport: d3d12::D3D12_VIEWPORT,
            data: internal::BlitData,
        };
        let mut instances = FastHashMap::<internal::BlitKey, Vec<Instance>>::default();
        let mut barriers = Vec::new();

        for region in regions {
            let r = region.borrow();

            let first_layer = r.dst_subresource.layers.start;
            let num_layers = r.dst_subresource.layers.end - first_layer;

            // WORKAROUND: renderdoc crashes if we destroy the pool too early
            let rtv_pool = Device::create_descriptor_heap_impl(
                device,
                native::DescriptorHeapType::Rtv,
                false,
                num_layers as _,
            );
            self.rtv_pools.push(rtv_pool.raw.clone());

            let key = match r.dst_subresource.aspects {
                format::Aspects::COLOR => {
                    let format = dst.default_view_format.unwrap();
                    // Create RTVs of the dst image for the miplevel of the current region
                    for i in 0 .. num_layers {
                        let mut desc = d3d12::D3D12_RENDER_TARGET_VIEW_DESC {
                            Format: format,
                            ViewDimension: d3d12::D3D12_RTV_DIMENSION_TEXTURE2DARRAY,
                            u: mem::zeroed(),
                        };

                        *desc.u.Texture2DArray_mut() = d3d12::D3D12_TEX2D_ARRAY_RTV {
                            MipSlice: r.dst_subresource.level as _,
                            FirstArraySlice: (i + first_layer) as u32,
                            ArraySize: 1,
                            PlaneSlice: 0, // TODO
                        };

                        let view = rtv_pool.at(i as _, 0).cpu;
                        device.CreateRenderTargetView(dst.resource.as_mut_ptr(), &desc, view);
                    }

                    (format, filter)
                }
                _ => unimplemented!(),
            };

            // Take flipping into account
            let viewport = d3d12::D3D12_VIEWPORT {
                TopLeftX: cmp::min(r.dst_bounds.start.x, r.dst_bounds.end.x) as _,
                TopLeftY: cmp::min(r.dst_bounds.start.y, r.dst_bounds.end.y) as _,
                Width: (r.dst_bounds.end.x - r.dst_bounds.start.x).abs() as _,
                Height: (r.dst_bounds.end.y - r.dst_bounds.start.y).abs() as _,
                MinDepth: 0.0,
                MaxDepth: 1.0,
            };

            let list = instances.entry(key).or_insert(Vec::new());

            for i in 0 .. num_layers {
                let src_layer = r.src_subresource.layers.start + i;
                // Screen space triangle blitting
                let data = {
                    // Image extents, layers are treated as depth
                    let (sx, dx) = if r.dst_bounds.start.x > r.dst_bounds.end.x {
                        (
                            r.src_bounds.end.x,
                            r.src_bounds.start.x - r.src_bounds.end.x,
                        )
                    } else {
                        (
                            r.src_bounds.start.x,
                            r.src_bounds.end.x - r.src_bounds.start.x,
                        )
                    };
                    let (sy, dy) = if r.dst_bounds.start.y > r.dst_bounds.end.y {
                        (
                            r.src_bounds.end.y,
                            r.src_bounds.start.y - r.src_bounds.end.y,
                        )
                    } else {
                        (
                            r.src_bounds.start.y,
                            r.src_bounds.end.y - r.src_bounds.start.y,
                        )
                    };
                    let image::Extent { width, height, .. } =
                        src.kind.level_extent(r.src_subresource.level);

                    internal::BlitData {
                        src_offset: [sx as f32 / width as f32, sy as f32 / height as f32],
                        src_extent: [dx as f32 / width as f32, dy as f32 / height as f32],
                        layer: src_layer as f32,
                        level: r.src_subresource.level as _,
                    }
                };

                list.push(Instance {
                    rtv: rtv_pool.at(i as _, 0).cpu,
                    viewport,
                    data,
                });

                barriers.push(Self::transition_barrier(
                    d3d12::D3D12_RESOURCE_TRANSITION_BARRIER {
                        pResource: dst.resource.as_mut_ptr(),
                        Subresource: dst.calc_subresource(
                            r.dst_subresource.level as _,
                            (first_layer + i) as _,
                            0,
                        ),
                        StateBefore: d3d12::D3D12_RESOURCE_STATE_COPY_DEST,
                        StateAfter: d3d12::D3D12_RESOURCE_STATE_RENDER_TARGET,
                    },
                ));
            }
        }

        // pre barriers
        self.raw
            .ResourceBarrier(barriers.len() as _, barriers.as_ptr());
        // execute blits
        self.set_internal_graphics_pipeline();
        for (key, list) in instances {
            let blit = self.shared.service_pipes.get_blit_2d_color(key);
            self.raw
                .IASetPrimitiveTopology(d3dcommon::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
            self.raw.set_pipeline_state(blit.pipeline);
            self.raw.set_graphics_root_signature(blit.signature);
            self.raw
                .set_graphics_root_descriptor_table(0, srv_heap.start_gpu_descriptor());
            for inst in list {
                let scissor = d3d12::D3D12_RECT {
                    left: inst.viewport.TopLeftX as _,
                    top: inst.viewport.TopLeftY as _,
                    right: (inst.viewport.TopLeftX + inst.viewport.Width) as _,
                    bottom: (inst.viewport.TopLeftY + inst.viewport.Height) as _,
                };
                self.raw.RSSetViewports(1, &inst.viewport);
                self.raw.RSSetScissorRects(1, &scissor);
                self.raw.SetGraphicsRoot32BitConstants(
                    1,
                    (mem::size_of::<internal::BlitData>() / 4) as _,
                    &inst.data as *const _ as *const _,
                    0,
                );
                self.raw.OMSetRenderTargets(1, &inst.rtv, TRUE, ptr::null());
                self.raw.draw(3, 1, 0, 0);
            }
        }
        // post barriers
        for bar in &mut barriers {
            let transition = bar.u.Transition_mut();
            mem::swap(&mut transition.StateBefore, &mut transition.StateAfter);
        }
        self.raw
            .ResourceBarrier(barriers.len() as _, barriers.as_ptr());

        // Reset states
        self.raw
            .RSSetViewports(self.viewport_cache.len() as _, self.viewport_cache.as_ptr());
        self.raw
            .RSSetScissorRects(self.scissor_cache.len() as _, self.scissor_cache.as_ptr());
        if self.primitive_topology != d3dcommon::D3D_PRIMITIVE_TOPOLOGY_UNDEFINED {
            self.raw.IASetPrimitiveTopology(self.primitive_topology);
        }
    }

    unsafe fn bind_index_buffer(&mut self, ibv: buffer::IndexBufferView<Backend>) {
        let buffer = ibv.buffer.expect_bound();
        let format = match ibv.index_type {
            IndexType::U16 => dxgiformat::DXGI_FORMAT_R16_UINT,
            IndexType::U32 => dxgiformat::DXGI_FORMAT_R32_UINT,
        };
        let location = buffer.resource.gpu_virtual_address();
        self.raw.set_index_buffer(
            location + ibv.offset,
            (buffer.requirements.size - ibv.offset) as u32,
            format,
        );
    }

    unsafe fn bind_vertex_buffers<I, T>(&mut self, first_binding: pso::BufferIndex, buffers: I)
    where
        I: IntoIterator<Item = (T, buffer::Offset)>,
        T: Borrow<r::Buffer>,
    {
        assert!(first_binding as usize <= MAX_VERTEX_BUFFERS);

        for (view, (buffer, offset)) in self.vertex_buffer_views[first_binding as _ ..]
            .iter_mut()
            .zip(buffers)
        {
            let b = buffer.borrow().expect_bound();
            let base = (*b.resource).GetGPUVirtualAddress();
            view.BufferLocation = base + offset;
            view.SizeInBytes = (b.requirements.size - offset) as u32;
        }
        self.set_vertex_buffers();
    }

    unsafe fn set_viewports<T>(&mut self, first_viewport: u32, viewports: T)
    where
        T: IntoIterator,
        T::Item: Borrow<pso::Viewport>,
    {
        let viewports = viewports
            .into_iter()
            .map(|viewport| {
                let viewport = viewport.borrow();
                d3d12::D3D12_VIEWPORT {
                    TopLeftX: viewport.rect.x as _,
                    TopLeftY: viewport.rect.y as _,
                    Width: viewport.rect.w as _,
                    Height: viewport.rect.h as _,
                    MinDepth: viewport.depth.start,
                    MaxDepth: viewport.depth.end,
                }
            })
            .enumerate();

        for (i, viewport) in viewports {
            if i + first_viewport as usize >= self.viewport_cache.len() {
                self.viewport_cache.push(viewport);
            } else {
                self.viewport_cache[i + first_viewport as usize] = viewport;
            }
        }

        self.raw
            .RSSetViewports(self.viewport_cache.len() as _, self.viewport_cache.as_ptr());
    }

    unsafe fn set_scissors<T>(&mut self, first_scissor: u32, scissors: T)
    where
        T: IntoIterator,
        T::Item: Borrow<pso::Rect>,
    {
        let rects = scissors
            .into_iter()
            .map(|rect| get_rect(rect.borrow()))
            .enumerate();

        for (i, rect) in rects {
            if i + first_scissor as usize >= self.scissor_cache.len() {
                self.scissor_cache.push(rect);
            } else {
                self.scissor_cache[i + first_scissor as usize] = rect;
            }
        }

        self.raw
            .RSSetScissorRects(self.scissor_cache.len() as _, self.scissor_cache.as_ptr())
    }

    unsafe fn set_blend_constants(&mut self, color: pso::ColorValue) {
        self.raw.set_blend_factor(color);
    }

    unsafe fn set_stencil_reference(&mut self, faces: pso::Face, value: pso::StencilValue) {
        assert!(!faces.is_empty());

        if !faces.is_all() {
            warn!(
                "Stencil ref values set for both faces but only one was requested ({})",
                faces.bits(),
            );
        }

        self.raw.set_stencil_reference(value as _);
    }

    unsafe fn set_stencil_read_mask(&mut self, _faces: pso::Face, _value: pso::StencilValue) {
        unimplemented!();
    }

    unsafe fn set_stencil_write_mask(&mut self, _faces: pso::Face, _value: pso::StencilValue) {
        unimplemented!();
    }

    unsafe fn set_depth_bounds(&mut self, bounds: Range<f32>) {
        let (cmd_list1, hr) = self.raw.cast::<d3d12::ID3D12GraphicsCommandList1>();
        if winerror::SUCCEEDED(hr) {
            cmd_list1.OMSetDepthBounds(bounds.start, bounds.end);
            cmd_list1.destroy();
        } else {
            warn!("Depth bounds test is not supported");
        }
    }

    unsafe fn set_line_width(&mut self, width: f32) {
        validate_line_width(width);
    }

    unsafe fn set_depth_bias(&mut self, _depth_bias: pso::DepthBias) {
        unimplemented!()
    }

    unsafe fn bind_graphics_pipeline(&mut self, pipeline: &r::GraphicsPipeline) {
        match self.gr_pipeline.pipeline {
            Some((_, signature)) if signature == pipeline.signature => {
                // Same root signature, nothing to do
            }
            _ => {
                self.raw.set_graphics_root_signature(pipeline.signature);
                self.gr_pipeline.num_parameter_slots = pipeline.num_parameter_slots;
                self.gr_pipeline.root_constants = pipeline.constants.clone();
                // All slots need to be rebound internally on signature change.
                self.gr_pipeline.user_data.dirty_all();
            }
        }
        self.raw.set_pipeline_state(pipeline.raw);
        self.raw.IASetPrimitiveTopology(pipeline.topology);
        self.primitive_topology = pipeline.topology;

        self.active_bindpoint = BindPoint::Graphics { internal: false };
        self.gr_pipeline.pipeline = Some((pipeline.raw, pipeline.signature));
        self.vertex_bindings_remap = pipeline.vertex_bindings;

        self.set_vertex_buffers();

        if let Some(ref vp) = pipeline.baked_states.viewport {
            self.set_viewports(0, iter::once(vp));
        }
        if let Some(ref rect) = pipeline.baked_states.scissor {
            self.set_scissors(0, iter::once(rect));
        }
        if let Some(color) = pipeline.baked_states.blend_color {
            self.set_blend_constants(color);
        }
        if let Some(ref bounds) = pipeline.baked_states.depth_bounds {
            self.set_depth_bounds(bounds.clone());
        }
    }

    unsafe fn bind_graphics_descriptor_sets<'a, I, J>(
        &mut self,
        layout: &r::PipelineLayout,
        first_set: usize,
        sets: I,
        offsets: J,
    ) where
        I: IntoIterator,
        I::Item: Borrow<r::DescriptorSet>,
        J: IntoIterator,
        J::Item: Borrow<com::DescriptorSetOffset>,
    {
        self.active_descriptor_heaps = self
            .gr_pipeline
            .bind_descriptor_sets(layout, first_set, sets, offsets);
        self.bind_descriptor_heaps();
    }

    unsafe fn bind_compute_pipeline(&mut self, pipeline: &r::ComputePipeline) {
        match self.comp_pipeline.pipeline {
            Some((_, signature)) if signature == pipeline.signature => {
                // Same root signature, nothing to do
            }
            _ => {
                self.raw.set_compute_root_signature(pipeline.signature);
                self.comp_pipeline.num_parameter_slots = pipeline.num_parameter_slots;
                self.comp_pipeline.root_constants = pipeline.constants.clone();
                // All slots need to be rebound internally on signature change.
                self.comp_pipeline.user_data.dirty_all();
            }
        }
        self.raw.set_pipeline_state(pipeline.raw);

        self.active_bindpoint = BindPoint::Compute;
        self.comp_pipeline.pipeline = Some((pipeline.raw, pipeline.signature));
    }

    unsafe fn bind_compute_descriptor_sets<I, J>(
        &mut self,
        layout: &r::PipelineLayout,
        first_set: usize,
        sets: I,
        offsets: J,
    ) where
        I: IntoIterator,
        I::Item: Borrow<r::DescriptorSet>,
        J: IntoIterator,
        J::Item: Borrow<com::DescriptorSetOffset>,
    {
        self.active_descriptor_heaps = self
            .comp_pipeline
            .bind_descriptor_sets(layout, first_set, sets, offsets);
        self.bind_descriptor_heaps();
    }

    unsafe fn dispatch(&mut self, count: WorkGroupCount) {
        self.set_compute_bind_point();
        self.raw.dispatch(count);
    }

    unsafe fn dispatch_indirect(&mut self, buffer: &r::Buffer, offset: buffer::Offset) {
        let buffer = buffer.expect_bound();
        self.set_compute_bind_point();
        self.raw.ExecuteIndirect(
            self.shared.signatures.dispatch.as_mut_ptr(),
            1,
            buffer.resource.as_mut_ptr(),
            offset,
            ptr::null_mut(),
            0,
        );
    }

    unsafe fn fill_buffer<R>(&mut self, buffer: &r::Buffer, range: R, _data: u32)
    where
        R: RangeArg<buffer::Offset>,
    {
        let buffer = buffer.expect_bound();
        assert!(
            buffer.clear_uav.is_some(),
            "Buffer needs to be created with usage `TRANSFER_DST`"
        );
        let bytes_per_unit = 4;
        let start = *range.start().unwrap_or(&0) as i32;
        let end = *range.end().unwrap_or(&(buffer.requirements.size as u64)) as i32;
        if start % 4 != 0 || end % 4 != 0 {
            warn!("Fill buffer bounds have to be multiples of 4");
        }
        let _rect = d3d12::D3D12_RECT {
            left: start / bytes_per_unit,
            top: 0,
            right: end / bytes_per_unit,
            bottom: 1,
        };

        // Insert barrier for `COPY_DEST` to `UNORDERED_ACCESS` as we use
        // `TRANSFER_WRITE` for all clear commands.
        let pre_barrier = Self::transition_barrier(d3d12::D3D12_RESOURCE_TRANSITION_BARRIER {
            pResource: buffer.resource.as_mut_ptr(),
            Subresource: d3d12::D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
            StateBefore: d3d12::D3D12_RESOURCE_STATE_COPY_DEST,
            StateAfter: d3d12::D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
        });
        self.raw.ResourceBarrier(1, &pre_barrier);

        error!("fill_buffer currently unimplemented");
        // TODO: GPU handle must be in the current heap. Atm we use a CPU descriptor heap for allocation
        //       which is not shader visible.
        /*
        let handle = buffer.clear_uav.unwrap();
        unsafe {
            self.raw.ClearUnorderedAccessViewUint(
                handle.gpu,
                handle.cpu,
                buffer.resource,
                &[data as UINT; 4],
                1,
                &rect as *const _,
            );
        }
        */

        let post_barrier = Self::transition_barrier(d3d12::D3D12_RESOURCE_TRANSITION_BARRIER {
            pResource: buffer.resource.as_mut_ptr(),
            Subresource: d3d12::D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
            StateBefore: d3d12::D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
            StateAfter: d3d12::D3D12_RESOURCE_STATE_COPY_DEST,
        });
        self.raw.ResourceBarrier(1, &post_barrier);
    }

    unsafe fn update_buffer(&mut self, _buffer: &r::Buffer, _offset: buffer::Offset, _data: &[u8]) {
        unimplemented!()
    }

    unsafe fn copy_buffer<T>(&mut self, src: &r::Buffer, dst: &r::Buffer, regions: T)
    where
        T: IntoIterator,
        T::Item: Borrow<com::BufferCopy>,
    {
        let src = src.expect_bound();
        let dst = dst.expect_bound();
        // copy each region
        for region in regions {
            let region = region.borrow();
            self.raw.CopyBufferRegion(
                dst.resource.as_mut_ptr(),
                region.dst as _,
                src.resource.as_mut_ptr(),
                region.src as _,
                region.size as _,
            );
        }

        // TODO: Optimization: Copy whole resource if possible
    }

    unsafe fn copy_image<T>(
        &mut self,
        src: &r::Image,
        _: image::Layout,
        dst: &r::Image,
        _: image::Layout,
        regions: T,
    ) where
        T: IntoIterator,
        T::Item: Borrow<com::ImageCopy>,
    {
        let src = src.expect_bound();
        let dst = dst.expect_bound();
        let mut src_image = d3d12::D3D12_TEXTURE_COPY_LOCATION {
            pResource: src.resource.as_mut_ptr(),
            Type: d3d12::D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
            u: mem::zeroed(),
        };
        let mut dst_image = d3d12::D3D12_TEXTURE_COPY_LOCATION {
            pResource: dst.resource.as_mut_ptr(),
            Type: d3d12::D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
            u: mem::zeroed(),
        };

        let device = self.shared.service_pipes.device.clone();
        let src_desc = src.surface_type.desc();
        let dst_desc = dst.surface_type.desc();
        assert_eq!(src_desc.bits, dst_desc.bits);
        //Note: Direct3D 10.1 enables copies between prestructured-typed textures
        // and block-compressed textures of the same bit widths.
        let do_alias = src.surface_type != dst.surface_type
            && src_desc.is_compressed() == dst_desc.is_compressed();

        if do_alias {
            // D3D12 only permits changing the channel type for copies,
            // similarly to how it allows the views to be created.

            // create an aliased resource to the source
            let mut alias = native::Resource::null();
            let desc = d3d12::D3D12_RESOURCE_DESC {
                Format: dst.descriptor.Format,
                ..src.descriptor.clone()
            };
            let (heap_ptr, offset) = match src.place {
                r::Place::SwapChain => {
                    error!("Unable to copy from a swapchain image with format conversion: {:?} -> {:?}",
                        src.descriptor.Format, dst.descriptor.Format);
                    return;
                }
                r::Place::Heap { ref raw, offset } => (raw.as_mut_ptr(), offset),
            };
            assert_eq!(
                winerror::S_OK,
                device.CreatePlacedResource(
                    heap_ptr,
                    offset,
                    &desc,
                    d3d12::D3D12_RESOURCE_STATE_COMMON,
                    ptr::null(),
                    &d3d12::ID3D12Resource::uuidof(),
                    alias.mut_void(),
                )
            );
            src_image.pResource = alias.as_mut_ptr();
            self.retained_resources.push(alias);

            // signal the aliasing transition
            let sub_barrier = d3d12::D3D12_RESOURCE_ALIASING_BARRIER {
                pResourceBefore: src.resource.as_mut_ptr(),
                pResourceAfter: src_image.pResource,
            };
            let mut barrier = d3d12::D3D12_RESOURCE_BARRIER {
                Type: d3d12::D3D12_RESOURCE_BARRIER_TYPE_ALIASING,
                Flags: d3d12::D3D12_RESOURCE_BARRIER_FLAG_NONE,
                u: mem::zeroed(),
            };
            *barrier.u.Aliasing_mut() = sub_barrier;
            self.raw.ResourceBarrier(1, &barrier as *const _);
        }

        for region in regions {
            let r = region.borrow();
            debug_assert_eq!(
                r.src_subresource.layers.len(),
                r.dst_subresource.layers.len()
            );
            let src_box = d3d12::D3D12_BOX {
                left: r.src_offset.x as _,
                top: r.src_offset.y as _,
                right: (r.src_offset.x + r.extent.width as i32) as _,
                bottom: (r.src_offset.y + r.extent.height as i32) as _,
                front: r.src_offset.z as _,
                back: (r.src_offset.z + r.extent.depth as i32) as _,
            };

            for (src_layer, dst_layer) in r
                .src_subresource
                .layers
                .clone()
                .zip(r.dst_subresource.layers.clone())
            {
                *src_image.u.SubresourceIndex_mut() =
                    src.calc_subresource(r.src_subresource.level as _, src_layer as _, 0);
                *dst_image.u.SubresourceIndex_mut() =
                    dst.calc_subresource(r.dst_subresource.level as _, dst_layer as _, 0);
                self.raw.CopyTextureRegion(
                    &dst_image,
                    r.dst_offset.x as _,
                    r.dst_offset.y as _,
                    r.dst_offset.z as _,
                    &src_image,
                    &src_box,
                );
            }
        }

        if do_alias {
            // signal the aliasing transition - back to the original
            let sub_barrier = d3d12::D3D12_RESOURCE_ALIASING_BARRIER {
                pResourceBefore: src_image.pResource,
                pResourceAfter: src.resource.as_mut_ptr(),
            };
            let mut barrier = d3d12::D3D12_RESOURCE_BARRIER {
                Type: d3d12::D3D12_RESOURCE_BARRIER_TYPE_ALIASING,
                Flags: d3d12::D3D12_RESOURCE_BARRIER_FLAG_NONE,
                u: mem::zeroed(),
            };
            *barrier.u.Aliasing_mut() = sub_barrier;
            self.raw.ResourceBarrier(1, &barrier as *const _);
        }
    }

    unsafe fn copy_buffer_to_image<T>(
        &mut self,
        buffer: &r::Buffer,
        image: &r::Image,
        _: image::Layout,
        regions: T,
    ) where
        T: IntoIterator,
        T::Item: Borrow<com::BufferImageCopy>,
    {
        let buffer = buffer.expect_bound();
        let image = image.expect_bound();
        assert!(self.copies.is_empty());

        for region in regions {
            let r = region.borrow();
            Self::split_buffer_copy(&mut self.copies, r, image);
        }

        if self.copies.is_empty() {
            return;
        }

        let mut src = d3d12::D3D12_TEXTURE_COPY_LOCATION {
            pResource: buffer.resource.as_mut_ptr(),
            Type: d3d12::D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
            u: mem::zeroed(),
        };
        let mut dst = d3d12::D3D12_TEXTURE_COPY_LOCATION {
            pResource: image.resource.as_mut_ptr(),
            Type: d3d12::D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
            u: mem::zeroed(),
        };

        for c in self.copies.drain(..) {
            let src_box = d3d12::D3D12_BOX {
                left: c.buf_offset.x as u32,
                top: c.buf_offset.y as u32,
                right: c.buf_offset.x as u32 + c.copy_extent.width,
                bottom: c.buf_offset.y as u32 + c.copy_extent.height,
                front: c.buf_offset.z as u32,
                back: c.buf_offset.z as u32 + c.copy_extent.depth,
            };
            let footprint = d3d12::D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
                Offset: c.footprint_offset,
                Footprint: d3d12::D3D12_SUBRESOURCE_FOOTPRINT {
                    Format: image.descriptor.Format,
                    Width: c.footprint.width,
                    Height: c.footprint.height,
                    Depth: c.footprint.depth,
                    RowPitch: c.row_pitch,
                },
            };
            *src.u.PlacedFootprint_mut() = footprint;
            *dst.u.SubresourceIndex_mut() = c.img_subresource;
            self.raw.CopyTextureRegion(
                &dst,
                c.img_offset.x as _,
                c.img_offset.y as _,
                c.img_offset.z as _,
                &src,
                &src_box,
            );
        }
    }

    unsafe fn copy_image_to_buffer<T>(
        &mut self,
        image: &r::Image,
        _: image::Layout,
        buffer: &r::Buffer,
        regions: T,
    ) where
        T: IntoIterator,
        T::Item: Borrow<com::BufferImageCopy>,
    {
        let image = image.expect_bound();
        let buffer = buffer.expect_bound();
        assert!(self.copies.is_empty());

        for region in regions {
            let r = region.borrow();
            Self::split_buffer_copy(&mut self.copies, r, image);
        }

        if self.copies.is_empty() {
            return;
        }

        let mut src = d3d12::D3D12_TEXTURE_COPY_LOCATION {
            pResource: image.resource.as_mut_ptr(),
            Type: d3d12::D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
            u: mem::zeroed(),
        };
        let mut dst = d3d12::D3D12_TEXTURE_COPY_LOCATION {
            pResource: buffer.resource.as_mut_ptr(),
            Type: d3d12::D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
            u: mem::zeroed(),
        };

        for c in self.copies.drain(..) {
            let src_box = d3d12::D3D12_BOX {
                left: c.img_offset.x as u32,
                top: c.img_offset.y as u32,
                right: c.img_offset.x as u32 + c.copy_extent.width,
                bottom: c.img_offset.y as u32 + c.copy_extent.height,
                front: c.img_offset.z as u32,
                back: c.img_offset.z as u32 + c.copy_extent.depth,
            };
            let footprint = d3d12::D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
                Offset: c.footprint_offset,
                Footprint: d3d12::D3D12_SUBRESOURCE_FOOTPRINT {
                    Format: image.descriptor.Format,
                    Width: c.footprint.width,
                    Height: c.footprint.height,
                    Depth: c.footprint.depth,
                    RowPitch: c.row_pitch,
                },
            };
            *dst.u.PlacedFootprint_mut() = footprint;
            *src.u.SubresourceIndex_mut() = c.img_subresource;
            self.raw.CopyTextureRegion(
                &dst,
                c.buf_offset.x as _,
                c.buf_offset.y as _,
                c.buf_offset.z as _,
                &src,
                &src_box,
            );
        }
    }

    unsafe fn draw(&mut self, vertices: Range<VertexCount>, instances: Range<InstanceCount>) {
        self.set_graphics_bind_point();
        self.raw.draw(
            vertices.end - vertices.start,
            instances.end - instances.start,
            vertices.start,
            instances.start,
        );
    }

    unsafe fn draw_indexed(
        &mut self,
        indices: Range<IndexCount>,
        base_vertex: VertexOffset,
        instances: Range<InstanceCount>,
    ) {
        self.set_graphics_bind_point();
        self.raw.draw_indexed(
            indices.end - indices.start,
            instances.end - instances.start,
            indices.start,
            base_vertex,
            instances.start,
        );
    }

    unsafe fn draw_indirect(
        &mut self,
        buffer: &r::Buffer,
        offset: buffer::Offset,
        draw_count: DrawCount,
        stride: u32,
    ) {
        assert_eq!(stride, 16);
        let buffer = buffer.expect_bound();
        self.set_graphics_bind_point();
        self.raw.ExecuteIndirect(
            self.shared.signatures.draw.as_mut_ptr(),
            draw_count,
            buffer.resource.as_mut_ptr(),
            offset,
            ptr::null_mut(),
            0,
        );
    }

    unsafe fn draw_indexed_indirect(
        &mut self,
        buffer: &r::Buffer,
        offset: buffer::Offset,
        draw_count: DrawCount,
        stride: u32,
    ) {
        assert_eq!(stride, 20);
        let buffer = buffer.expect_bound();
        self.set_graphics_bind_point();
        self.raw.ExecuteIndirect(
            self.shared.signatures.draw_indexed.as_mut_ptr(),
            draw_count,
            buffer.resource.as_mut_ptr(),
            offset,
            ptr::null_mut(),
            0,
        );
    }

    unsafe fn set_event(&mut self, _: &(), _: pso::PipelineStage) {
        unimplemented!()
    }

    unsafe fn reset_event(&mut self, _: &(), _: pso::PipelineStage) {
        unimplemented!()
    }

    unsafe fn wait_events<'a, I, J>(&mut self, _: I, _: Range<pso::PipelineStage>, _: J)
    where
        I: IntoIterator,
        I::Item: Borrow<()>,
        J: IntoIterator,
        J::Item: Borrow<memory::Barrier<'a, Backend>>,
    {
        unimplemented!()
    }

    unsafe fn begin_query(&mut self, query: query::Query<Backend>, flags: query::ControlFlags) {
        let query_ty = match query.pool.ty {
            native::QueryHeapType::Occlusion => {
                if flags.contains(query::ControlFlags::PRECISE) {
                    self.occlusion_query = Some(OcclusionQuery::Precise(query.id));
                    d3d12::D3D12_QUERY_TYPE_OCCLUSION
                } else {
                    // Default to binary occlusion as it might be faster due to early depth/stencil
                    // tests.
                    self.occlusion_query = Some(OcclusionQuery::Binary(query.id));
                    d3d12::D3D12_QUERY_TYPE_BINARY_OCCLUSION
                }
            }
            native::QueryHeapType::Timestamp => panic!("Timestap queries are issued via "),
            native::QueryHeapType::PipelineStatistics => {
                self.pipeline_stats_query = Some(query.id);
                d3d12::D3D12_QUERY_TYPE_PIPELINE_STATISTICS
            }
            _ => unreachable!(),
        };

        self.raw
            .BeginQuery(query.pool.raw.as_mut_ptr(), query_ty, query.id);
    }

    unsafe fn end_query(&mut self, query: query::Query<Backend>) {
        let id = query.id;
        let query_ty = match query.pool.ty {
            native::QueryHeapType::Occlusion
                if self.occlusion_query == Some(OcclusionQuery::Precise(id)) =>
            {
                self.occlusion_query = None;
                d3d12::D3D12_QUERY_TYPE_OCCLUSION
            }
            native::QueryHeapType::Occlusion
                if self.occlusion_query == Some(OcclusionQuery::Binary(id)) =>
            {
                self.occlusion_query = None;
                d3d12::D3D12_QUERY_TYPE_BINARY_OCCLUSION
            }
            native::QueryHeapType::PipelineStatistics
                if self.pipeline_stats_query == Some(id) =>
            {
                self.pipeline_stats_query = None;
                d3d12::D3D12_QUERY_TYPE_PIPELINE_STATISTICS
            }
            _ => panic!("Missing `begin_query` call for query: {:?}", query),
        };

        self.raw.EndQuery(query.pool.raw.as_mut_ptr(), query_ty, id);
    }

    unsafe fn reset_query_pool(&mut self, _pool: &r::QueryPool, _queries: Range<query::Id>) {
        // Nothing to do here
        // vkCmdResetQueryPool sets the queries to `unavailable` but the specification
        // doesn't state an affect on the `active` state. Every queries at the end of the command
        // buffer must be made inactive, which can only be done with EndQuery.
        // Therefore, every `begin_query` must follow a `end_query` state, the resulting values
        // after calling are undefined.
    }

    unsafe fn copy_query_pool_results(
        &mut self,
        _pool: &r::QueryPool,
        _queries: Range<query::Id>,
        _buffer: &r::Buffer,
        _offset: buffer::Offset,
        _stride: buffer::Offset,
        _flags: query::ResultFlags,
    ) {
        unimplemented!()
    }

    unsafe fn write_timestamp(&mut self, _: pso::PipelineStage, query: query::Query<Backend>) {
        self.raw.EndQuery(
            query.pool.raw.as_mut_ptr(),
            d3d12::D3D12_QUERY_TYPE_TIMESTAMP,
            query.id,
        );
    }

    unsafe fn push_graphics_constants(
        &mut self,
        _layout: &r::PipelineLayout,
        _stages: pso::ShaderStageFlags,
        offset: u32,
        constants: &[u32],
    ) {
        assert!(offset % 4 == 0);
        self.gr_pipeline
            .user_data
            .set_constants(offset as usize / 4, constants);
    }

    unsafe fn push_compute_constants(
        &mut self,
        _layout: &r::PipelineLayout,
        offset: u32,
        constants: &[u32],
    ) {
        assert!(offset % 4 == 0);
        self.comp_pipeline
            .user_data
            .set_constants(offset as usize / 4, constants);
    }

    unsafe fn execute_commands<'a, T, I>(&mut self, cmd_buffers: I)
    where
        T: 'a + Borrow<CommandBuffer>,
        I: IntoIterator<Item = &'a T>,
    {
        for _cmd_buf in cmd_buffers {
            error!("TODO: execute_commands");
        }
    }
}