Hash :
68a5baeb
Author :
Date :
2020-09-23T22:13:03
Revert "Vulkan: Implement a SharedResourceUse pool" This reverts commit de335c16855f11d1f0a6f0b37bee30c8a09a6c1d. Reason for revert: Might actually regress CPU overhead perf. Unsure but it's possible the reported perf improvement was due to variance. Original change's description: > Vulkan: Implement a SharedResourceUse pool > > When adding a Resource to the ResourceUseList of ContextVk > we constructed a new SharedResourceUse object for tracking > and update of the Resource's Serial. We would then delete > it after releasing the resource. This incurs repeated > memory operation costs. > > Instead we now allocate a pool of SharedResourceUse objects > and acquire and release from this pool as needed. > > VTune profile of the Manhattan 30 offscreen benchmark > shows the CPU occupancy of bufferRead decrease from an > average of 0.9% -> 0.6% and imageRead decreases from > an average of 0.4% -> 0.3%. The bottleneck for both > these methods is the retain() method that leverages > the new SharedResourceUse pool. > > Bug: angleproject:4950 > Change-Id: Ib4f67c6f101d4b2de118014546e6cc14ad108703 > Reviewed-on: https://chromium-review.googlesource.com/c/angle/angle/+/2396597 > Reviewed-by: Shahbaz Youssefi <syoussefi@chromium.org> > Reviewed-by: Jamie Madill <jmadill@chromium.org> > Commit-Queue: Mohan Maiya <m.maiya@samsung.com> TBR=syoussefi@chromium.org,jmadill@chromium.org,m.maiya@samsung.com # Not skipping CQ checks because original CL landed > 1 day ago. Bug: angleproject:4950 Change-Id: I40081551c3db67d6e55182fea40119946ed16ac3 Reviewed-on: https://chromium-review.googlesource.com/c/angle/angle/+/2426479 Reviewed-by: Jamie Madill <jmadill@chromium.org> Commit-Queue: Jamie Madill <jmadill@chromium.org>
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 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828
//
// Copyright 2018 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// vk_helpers:
// Helper utilitiy classes that manage Vulkan resources.
#include "libANGLE/renderer/vulkan/vk_helpers.h"
#include "common/utilities.h"
#include "image_util/loadimage.h"
#include "libANGLE/Context.h"
#include "libANGLE/renderer/renderer_utils.h"
#include "libANGLE/renderer/vulkan/BufferVk.h"
#include "libANGLE/renderer/vulkan/ContextVk.h"
#include "libANGLE/renderer/vulkan/DisplayVk.h"
#include "libANGLE/renderer/vulkan/FramebufferVk.h"
#include "libANGLE/renderer/vulkan/RenderTargetVk.h"
#include "libANGLE/renderer/vulkan/RendererVk.h"
#include "libANGLE/renderer/vulkan/vk_utils.h"
#include "libANGLE/trace.h"
namespace rx
{
namespace vk
{
namespace
{
// ANGLE_robust_resource_initialization requires color textures to be initialized to zero.
constexpr VkClearColorValue kRobustInitColorValue = {{0, 0, 0, 0}};
// When emulating a texture, we want the emulated channels to be 0, with alpha 1.
constexpr VkClearColorValue kEmulatedInitColorValue = {{0, 0, 0, 1.0f}};
// ANGLE_robust_resource_initialization requires depth to be initialized to 1 and stencil to 0.
// We are fine with these values for emulated depth/stencil textures too.
constexpr VkClearDepthStencilValue kRobustInitDepthStencilValue = {1.0f, 0};
constexpr VkBufferUsageFlags kLineLoopDynamicBufferUsage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT |
VK_BUFFER_USAGE_TRANSFER_DST_BIT |
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
constexpr int kLineLoopDynamicBufferInitialSize = 1024 * 1024;
constexpr VkBufferUsageFlags kLineLoopDynamicIndirectBufferUsage =
VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT |
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
constexpr int kLineLoopDynamicIndirectBufferInitialSize = sizeof(VkDrawIndirectCommand) * 16;
constexpr angle::PackedEnumMap<PipelineStage, VkPipelineStageFlagBits> kPipelineStageFlagBitMap = {
{PipelineStage::TopOfPipe, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT},
{PipelineStage::DrawIndirect, VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT},
{PipelineStage::VertexInput, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT},
{PipelineStage::VertexShader, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT},
{PipelineStage::GeometryShader, VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT},
{PipelineStage::TransformFeedback, VK_PIPELINE_STAGE_TRANSFORM_FEEDBACK_BIT_EXT},
{PipelineStage::EarlyFragmentTest, VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT},
{PipelineStage::FragmentShader, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT},
{PipelineStage::LateFragmentTest, VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT},
{PipelineStage::ColorAttachmentOutput, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT},
{PipelineStage::ComputeShader, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT},
{PipelineStage::Transfer, VK_PIPELINE_STAGE_TRANSFER_BIT},
{PipelineStage::BottomOfPipe, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT},
{PipelineStage::Host, VK_PIPELINE_STAGE_HOST_BIT}};
constexpr size_t kDefaultPoolAllocatorPageSize = 16 * 1024;
struct ImageMemoryBarrierData
{
char name[40];
// The Vk layout corresponding to the ImageLayout key.
VkImageLayout layout;
// The stage in which the image is used (or Bottom/Top if not using any specific stage). Unless
// Bottom/Top (Bottom used for transition to and Top used for transition from), the two values
// should match.
VkPipelineStageFlags dstStageMask;
VkPipelineStageFlags srcStageMask;
// Access mask when transitioning into this layout.
VkAccessFlags dstAccessMask;
// Access mask when transitioning out from this layout. Note that source access mask never
// needs a READ bit, as WAR hazards don't need memory barriers (just execution barriers).
VkAccessFlags srcAccessMask;
// Read or write.
ResourceAccess type;
// CommandBufferHelper tracks an array of PipelineBarriers. This indicates which array element
// this should be merged into. Right now we track individual barrier for every PipelineStage. If
// layout has a single stage mask bit, we use that stage as index. If layout has multiple stage
// mask bits, we pick the lowest stage as the index since it is the first stage that needs
// barrier.
PipelineStage barrierIndex;
};
constexpr VkPipelineStageFlags kAllShadersPipelineStageFlags =
VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT |
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
// clang-format off
constexpr angle::PackedEnumMap<ImageLayout, ImageMemoryBarrierData> kImageMemoryBarrierData = {
{
ImageLayout::Undefined,
ImageMemoryBarrierData{
"Undefined",
VK_IMAGE_LAYOUT_UNDEFINED,
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
// Transition to: we don't expect to transition into Undefined.
0,
// Transition from: there's no data in the image to care about.
0,
ResourceAccess::ReadOnly,
PipelineStage::InvalidEnum,
},
},
{
ImageLayout::ExternalPreInitialized,
ImageMemoryBarrierData{
"ExternalPreInitialized",
VK_IMAGE_LAYOUT_PREINITIALIZED,
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
// Transition to: we don't expect to transition into PreInitialized.
0,
// Transition from: all writes must finish before barrier.
VK_ACCESS_MEMORY_WRITE_BIT,
ResourceAccess::ReadOnly,
PipelineStage::InvalidEnum,
},
},
{
ImageLayout::ExternalShadersReadOnly,
ImageMemoryBarrierData{
"ExternalShadersReadOnly",
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
// Transition to: all reads must happen after barrier.
VK_ACCESS_SHADER_READ_BIT,
// Transition from: RAR and WAR don't need memory barrier.
0,
ResourceAccess::ReadOnly,
// In case of multiple destination stages, We barrier the earliest stage
PipelineStage::TopOfPipe,
},
},
{
ImageLayout::ExternalShadersWrite,
ImageMemoryBarrierData{
"ExternalShadersWrite",
VK_IMAGE_LAYOUT_GENERAL,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
// Transition to: all reads and writes must happen after barrier.
VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT,
// Transition from: all writes must finish before barrier.
VK_ACCESS_SHADER_WRITE_BIT,
ResourceAccess::Write,
// In case of multiple destination stages, We barrier the earliest stage
PipelineStage::TopOfPipe,
},
},
{
ImageLayout::TransferSrc,
ImageMemoryBarrierData{
"TransferSrc",
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT,
// Transition to: all reads must happen after barrier.
VK_ACCESS_TRANSFER_READ_BIT,
// Transition from: RAR and WAR don't need memory barrier.
0,
ResourceAccess::ReadOnly,
PipelineStage::Transfer,
},
},
{
ImageLayout::TransferDst,
ImageMemoryBarrierData{
"TransferDst",
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT,
// Transition to: all writes must happen after barrier.
VK_ACCESS_TRANSFER_WRITE_BIT,
// Transition from: all writes must finish before barrier.
VK_ACCESS_TRANSFER_WRITE_BIT,
ResourceAccess::Write,
PipelineStage::Transfer,
},
},
{
ImageLayout::VertexShaderReadOnly,
ImageMemoryBarrierData{
"VertexShaderReadOnly",
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_VERTEX_SHADER_BIT,
VK_PIPELINE_STAGE_VERTEX_SHADER_BIT,
// Transition to: all reads must happen after barrier.
VK_ACCESS_SHADER_READ_BIT,
// Transition from: RAR and WAR don't need memory barrier.
0,
ResourceAccess::ReadOnly,
PipelineStage::VertexShader,
},
},
{
ImageLayout::VertexShaderWrite,
ImageMemoryBarrierData{
"VertexShaderWrite",
VK_IMAGE_LAYOUT_GENERAL,
VK_PIPELINE_STAGE_VERTEX_SHADER_BIT,
VK_PIPELINE_STAGE_VERTEX_SHADER_BIT,
// Transition to: all reads and writes must happen after barrier.
VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT,
// Transition from: all writes must finish before barrier.
VK_ACCESS_SHADER_WRITE_BIT,
ResourceAccess::Write,
PipelineStage::VertexShader,
},
},
{
ImageLayout::GeometryShaderReadOnly,
ImageMemoryBarrierData{
"GeometryShaderReadOnly",
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT,
VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT,
// Transition to: all reads must happen after barrier.
VK_ACCESS_SHADER_READ_BIT,
// Transition from: RAR and WAR don't need memory barrier.
0,
ResourceAccess::ReadOnly,
PipelineStage::GeometryShader,
},
},
{
ImageLayout::GeometryShaderWrite,
ImageMemoryBarrierData{
"GeometryShaderWrite",
VK_IMAGE_LAYOUT_GENERAL,
VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT,
VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT,
// Transition to: all reads and writes must happen after barrier.
VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT,
// Transition from: all writes must finish before barrier.
VK_ACCESS_SHADER_WRITE_BIT,
ResourceAccess::Write,
PipelineStage::GeometryShader,
},
},
{
ImageLayout::FragmentShaderReadOnly,
ImageMemoryBarrierData{
"FragmentShaderReadOnly",
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
// Transition to: all reads must happen after barrier.
VK_ACCESS_SHADER_READ_BIT,
// Transition from: RAR and WAR don't need memory barrier.
0,
ResourceAccess::ReadOnly,
PipelineStage::FragmentShader,
},
},
{
ImageLayout::FragmentShaderWrite,
ImageMemoryBarrierData{
"FragmentShaderWrite",
VK_IMAGE_LAYOUT_GENERAL,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
// Transition to: all reads and writes must happen after barrier.
VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT,
// Transition from: all writes must finish before barrier.
VK_ACCESS_SHADER_WRITE_BIT,
ResourceAccess::Write,
PipelineStage::FragmentShader,
},
},
{
ImageLayout::ComputeShaderReadOnly,
ImageMemoryBarrierData{
"ComputeShaderReadOnly",
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
// Transition to: all reads must happen after barrier.
VK_ACCESS_SHADER_READ_BIT,
// Transition from: RAR and WAR don't need memory barrier.
0,
ResourceAccess::ReadOnly,
PipelineStage::ComputeShader,
},
},
{
ImageLayout::ComputeShaderWrite,
ImageMemoryBarrierData{
"ComputeShaderWrite",
VK_IMAGE_LAYOUT_GENERAL,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
// Transition to: all reads and writes must happen after barrier.
VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT,
// Transition from: all writes must finish before barrier.
VK_ACCESS_SHADER_WRITE_BIT,
ResourceAccess::Write,
PipelineStage::ComputeShader,
},
},
{
ImageLayout::AllGraphicsShadersReadOnly,
ImageMemoryBarrierData{
"AllGraphicsShadersReadOnly",
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
kAllShadersPipelineStageFlags,
kAllShadersPipelineStageFlags,
// Transition to: all reads must happen after barrier.
VK_ACCESS_SHADER_READ_BIT,
// Transition from: RAR and WAR don't need memory barrier.
0,
ResourceAccess::ReadOnly,
// In case of multiple destination stages, We barrier the earliest stage
PipelineStage::VertexShader,
},
},
{
ImageLayout::AllGraphicsShadersWrite,
ImageMemoryBarrierData{
"AllGraphicsShadersWrite",
VK_IMAGE_LAYOUT_GENERAL,
kAllShadersPipelineStageFlags,
kAllShadersPipelineStageFlags,
// Transition to: all reads and writes must happen after barrier.
VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT,
// Transition from: all writes must finish before barrier.
VK_ACCESS_SHADER_WRITE_BIT,
ResourceAccess::Write,
// In case of multiple destination stages, We barrier the earliest stage
PipelineStage::VertexShader,
},
},
{
ImageLayout::ColorAttachment,
ImageMemoryBarrierData{
"ColorAttachment",
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
// Transition to: all reads and writes must happen after barrier.
VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
// Transition from: all writes must finish before barrier.
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
ResourceAccess::Write,
PipelineStage::ColorAttachmentOutput,
},
},
{
ImageLayout::DepthStencilReadOnly,
ImageMemoryBarrierData{
"DepthStencilReadOnly",
VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL,
kAllShadersPipelineStageFlags | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT,
kAllShadersPipelineStageFlags | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
// Transition to: all reads must happen after barrier.
VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT,
// Transition from: RAR and WAR don't need memory barrier.
0,
ResourceAccess::ReadOnly,
PipelineStage::EarlyFragmentTest,
},
},
{
ImageLayout::DepthStencilAttachment,
ImageMemoryBarrierData{
"DepthStencilAttachment",
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT,
VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
// Transition to: all reads and writes must happen after barrier.
VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
// Transition from: all writes must finish before barrier.
VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
ResourceAccess::Write,
PipelineStage::EarlyFragmentTest,
},
},
{
ImageLayout::Present,
ImageMemoryBarrierData{
"Present",
VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
// transition to: vkQueuePresentKHR automatically performs the appropriate memory barriers:
//
// > Any writes to memory backing the images referenced by the pImageIndices and
// > pSwapchains members of pPresentInfo, that are available before vkQueuePresentKHR
// > is executed, are automatically made visible to the read access performed by the
// > presentation engine.
0,
// Transition from: RAR and WAR don't need memory barrier.
0,
ResourceAccess::ReadOnly,
PipelineStage::BottomOfPipe,
},
},
};
// clang-format on
VkImageCreateFlags GetImageCreateFlags(gl::TextureType textureType)
{
switch (textureType)
{
case gl::TextureType::CubeMap:
return VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT;
case gl::TextureType::_3D:
return VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT;
default:
return 0;
}
}
void HandlePrimitiveRestart(ContextVk *contextVk,
gl::DrawElementsType glIndexType,
GLsizei indexCount,
const uint8_t *srcPtr,
uint8_t *outPtr)
{
switch (glIndexType)
{
case gl::DrawElementsType::UnsignedByte:
if (contextVk->getFeatures().supportsIndexTypeUint8.enabled)
{
CopyLineLoopIndicesWithRestart<uint8_t, uint8_t>(indexCount, srcPtr, outPtr);
}
else
{
CopyLineLoopIndicesWithRestart<uint8_t, uint16_t>(indexCount, srcPtr, outPtr);
}
break;
case gl::DrawElementsType::UnsignedShort:
CopyLineLoopIndicesWithRestart<uint16_t, uint16_t>(indexCount, srcPtr, outPtr);
break;
case gl::DrawElementsType::UnsignedInt:
CopyLineLoopIndicesWithRestart<uint32_t, uint32_t>(indexCount, srcPtr, outPtr);
break;
default:
UNREACHABLE();
}
}
bool HasBothDepthAndStencilAspects(VkImageAspectFlags aspectFlags)
{
constexpr VkImageAspectFlags kDepthStencilAspects =
VK_IMAGE_ASPECT_STENCIL_BIT | VK_IMAGE_ASPECT_DEPTH_BIT;
return (aspectFlags & kDepthStencilAspects) == kDepthStencilAspects;
}
uint32_t GetImageLayerCountForView(const ImageHelper &image)
{
// Depth > 1 means this is a 3D texture and depth is our layer count
return image.getExtents().depth > 1 ? image.getExtents().depth : image.getLayerCount();
}
void ReleaseImageViews(ImageViewVector *imageViewVector, std::vector<GarbageObject> *garbage)
{
for (ImageView &imageView : *imageViewVector)
{
if (imageView.valid())
{
garbage->emplace_back(GetGarbage(&imageView));
}
}
imageViewVector->clear();
}
void DestroyImageViews(ImageViewVector *imageViewVector, VkDevice device)
{
for (ImageView &imageView : *imageViewVector)
{
imageView.destroy(device);
}
imageViewVector->clear();
}
ImageView *GetLevelImageView(ImageViewVector *imageViews, LevelIndex levelVk, uint32_t levelCount)
{
// Lazily allocate the storage for image views. We allocate the full level count because we
// don't want to trigger any std::vector reallocations. Reallocations could invalidate our
// view pointers.
if (imageViews->empty())
{
imageViews->resize(levelCount);
}
ASSERT(imageViews->size() > levelVk.get());
return &(*imageViews)[levelVk.get()];
}
// Special rules apply to VkBufferImageCopy with depth/stencil. The components are tightly packed
// into a depth or stencil section of the destination buffer. See the spec:
// https://www.khronos.org/registry/vulkan/specs/1.1-extensions/man/html/VkBufferImageCopy.html
const angle::Format &GetDepthStencilImageToBufferFormat(const angle::Format &imageFormat,
VkImageAspectFlagBits copyAspect)
{
if (copyAspect == VK_IMAGE_ASPECT_STENCIL_BIT)
{
ASSERT(imageFormat.id == angle::FormatID::D24_UNORM_S8_UINT ||
imageFormat.id == angle::FormatID::D32_FLOAT_S8X24_UINT ||
imageFormat.id == angle::FormatID::S8_UINT);
return angle::Format::Get(angle::FormatID::S8_UINT);
}
ASSERT(copyAspect == VK_IMAGE_ASPECT_DEPTH_BIT);
switch (imageFormat.id)
{
case angle::FormatID::D16_UNORM:
return imageFormat;
case angle::FormatID::D24_UNORM_X8_UINT:
return imageFormat;
case angle::FormatID::D24_UNORM_S8_UINT:
return angle::Format::Get(angle::FormatID::D24_UNORM_X8_UINT);
case angle::FormatID::D32_FLOAT:
return imageFormat;
case angle::FormatID::D32_FLOAT_S8X24_UINT:
return angle::Format::Get(angle::FormatID::D32_FLOAT);
default:
UNREACHABLE();
return imageFormat;
}
}
VkClearValue GetRobustResourceClearValue(const Format &format)
{
VkClearValue clearValue;
if (format.intendedFormat().hasDepthOrStencilBits())
{
clearValue.depthStencil = kRobustInitDepthStencilValue;
}
else
{
clearValue.color =
format.hasEmulatedImageChannels() ? kEmulatedInitColorValue : kRobustInitColorValue;
}
return clearValue;
}
#if !defined(ANGLE_PLATFORM_MACOS) && !defined(ANGLE_PLATFORM_ANDROID)
bool IsExternalQueueFamily(uint32_t queueFamilyIndex)
{
return queueFamilyIndex == VK_QUEUE_FAMILY_EXTERNAL ||
queueFamilyIndex == VK_QUEUE_FAMILY_FOREIGN_EXT;
}
#endif
bool IsShaderReadOnlyLayout(const ImageMemoryBarrierData &imageLayout)
{
return imageLayout.layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
}
} // anonymous namespace
// This is an arbitrary max. We can change this later if necessary.
uint32_t DynamicDescriptorPool::mMaxSetsPerPool = 128;
VkImageLayout ConvertImageLayoutToVkImageLayout(ImageLayout imageLayout)
{
return kImageMemoryBarrierData[imageLayout].layout;
}
// PackedClearValuesArray implementation
PackedClearValuesArray::PackedClearValuesArray() : mValues{} {}
PackedClearValuesArray::~PackedClearValuesArray() = default;
PackedClearValuesArray::PackedClearValuesArray(const PackedClearValuesArray &other) = default;
PackedClearValuesArray &PackedClearValuesArray::operator=(const PackedClearValuesArray &rhs) =
default;
void PackedClearValuesArray::store(PackedAttachmentIndex index,
VkImageAspectFlags aspectFlags,
const VkClearValue &clearValue)
{
ASSERT(aspectFlags != 0);
if (aspectFlags != VK_IMAGE_ASPECT_STENCIL_BIT)
{
storeNoDepthStencil(index, clearValue);
}
}
void PackedClearValuesArray::storeNoDepthStencil(PackedAttachmentIndex index,
const VkClearValue &clearValue)
{
mValues[index.get()] = clearValue;
}
// CommandBufferHelper implementation.
CommandBufferHelper::CommandBufferHelper()
: mPipelineBarriers(),
mPipelineBarrierMask(),
mCounter(0),
mClearValues{},
mRenderPassStarted(false),
mForceIndividualBarriers(false),
mTransformFeedbackCounterBuffers{},
mValidTransformFeedbackBufferCount(0),
mRebindTransformFeedbackBuffers(false),
mIsRenderPassCommandBuffer(false),
mDepthStartAccess(ResourceAccess::Unused),
mStencilStartAccess(ResourceAccess::Unused),
mDepthCmdSizeInvalidated(kInfiniteCmdSize),
mDepthCmdSizeDisabled(kInfiniteCmdSize),
mStencilCmdSizeInvalidated(kInfiniteCmdSize),
mStencilCmdSizeDisabled(kInfiniteCmdSize),
mDepthStencilAttachmentIndex(kAttachmentIndexInvalid)
{}
CommandBufferHelper::~CommandBufferHelper()
{
mFramebuffer.setHandle(VK_NULL_HANDLE);
}
void CommandBufferHelper::initialize(bool isRenderPassCommandBuffer)
{
ASSERT(mUsedBuffers.empty());
constexpr size_t kInitialBufferCount = 128;
mUsedBuffers.ensureCapacity(kInitialBufferCount);
mAllocator.initialize(kDefaultPoolAllocatorPageSize, 1);
// Push a scope into the pool allocator so we can easily free and re-init on reset()
mAllocator.push();
mCommandBuffer.initialize(&mAllocator);
mIsRenderPassCommandBuffer = isRenderPassCommandBuffer;
}
bool CommandBufferHelper::usesBuffer(const BufferHelper &buffer) const
{
return mUsedBuffers.contains(buffer.getBufferSerial().getValue());
}
bool CommandBufferHelper::usesBufferForWrite(const BufferHelper &buffer) const
{
BufferAccess access;
if (!mUsedBuffers.get(buffer.getBufferSerial().getValue(), &access))
{
return false;
}
return access == BufferAccess::Write;
}
void CommandBufferHelper::bufferRead(ResourceUseList *resourceUseList,
VkAccessFlags readAccessType,
PipelineStage readStage,
BufferHelper *buffer)
{
buffer->retain(resourceUseList);
VkPipelineStageFlagBits stageBits = kPipelineStageFlagBitMap[readStage];
if (buffer->recordReadBarrier(readAccessType, stageBits, &mPipelineBarriers[readStage]))
{
mPipelineBarrierMask.set(readStage);
}
ASSERT(!usesBufferForWrite(*buffer));
if (!mUsedBuffers.contains(buffer->getBufferSerial().getValue()))
{
mUsedBuffers.insert(buffer->getBufferSerial().getValue(), BufferAccess::Read);
}
}
void CommandBufferHelper::bufferWrite(ResourceUseList *resourceUseList,
VkAccessFlags writeAccessType,
PipelineStage writeStage,
AliasingMode aliasingMode,
BufferHelper *buffer)
{
buffer->retain(resourceUseList);
VkPipelineStageFlagBits stageBits = kPipelineStageFlagBitMap[writeStage];
if (buffer->recordWriteBarrier(writeAccessType, stageBits, &mPipelineBarriers[writeStage]))
{
mPipelineBarrierMask.set(writeStage);
}
// Storage buffers are special. They can alias one another in a shader.
// We support aliasing by not tracking storage buffers. This works well with the GL API
// because storage buffers are required to be externally synchronized.
// Compute / XFB emulation buffers are not allowed to alias.
if (aliasingMode == AliasingMode::Disallowed)
{
ASSERT(!usesBuffer(*buffer));
mUsedBuffers.insert(buffer->getBufferSerial().getValue(), BufferAccess::Write);
}
}
void CommandBufferHelper::imageRead(ResourceUseList *resourceUseList,
VkImageAspectFlags aspectFlags,
ImageLayout imageLayout,
ImageHelper *image)
{
image->retain(resourceUseList);
if (image->isReadBarrierNecessary(imageLayout))
{
PipelineStage barrierIndex = kImageMemoryBarrierData[imageLayout].barrierIndex;
ASSERT(barrierIndex != PipelineStage::InvalidEnum);
PipelineBarrier *barrier = &mPipelineBarriers[barrierIndex];
if (image->updateLayoutAndBarrier(aspectFlags, imageLayout, barrier))
{
mPipelineBarrierMask.set(barrierIndex);
}
}
if (mIsRenderPassCommandBuffer)
{
// As noted in the header we don't support multiple read layouts for Images.
// We allow duplicate uses in the RP to accomodate for normal GL sampler usage.
if (!usesImageInRenderPass(*image))
{
mRenderPassUsedImages.insert(image->getImageSerial().getValue());
}
}
}
void CommandBufferHelper::imageWrite(ResourceUseList *resourceUseList,
VkImageAspectFlags aspectFlags,
ImageLayout imageLayout,
AliasingMode aliasingMode,
ImageHelper *image)
{
image->retain(resourceUseList);
image->onWrite();
// Write always requires a barrier
PipelineStage barrierIndex = kImageMemoryBarrierData[imageLayout].barrierIndex;
ASSERT(barrierIndex != PipelineStage::InvalidEnum);
PipelineBarrier *barrier = &mPipelineBarriers[barrierIndex];
if (image->updateLayoutAndBarrier(aspectFlags, imageLayout, barrier))
{
mPipelineBarrierMask.set(barrierIndex);
}
if (mIsRenderPassCommandBuffer)
{
// When used as a storage image we allow for aliased writes.
if (aliasingMode == AliasingMode::Disallowed)
{
ASSERT(!usesImageInRenderPass(*image));
}
if (!usesImageInRenderPass(*image))
{
mRenderPassUsedImages.insert(image->getImageSerial().getValue());
}
}
}
bool CommandBufferHelper::onDepthAccess(ResourceAccess access)
{
// Update the access for optimizing this render pass's loadOp
UpdateAccess(&mDepthStartAccess, access);
ASSERT((mRenderPassDesc.getDepthStencilAccess() != ResourceAccess::ReadOnly) ||
mDepthStartAccess != ResourceAccess::Write);
// Update the invalidate state for optimizing this render pass's storeOp
return onDepthStencilAccess(access, &mDepthCmdSizeInvalidated, &mDepthCmdSizeDisabled);
}
bool CommandBufferHelper::onStencilAccess(ResourceAccess access)
{
// Update the access for optimizing this render pass's loadOp
UpdateAccess(&mStencilStartAccess, access);
// Update the invalidate state for optimizing this render pass's stencilStoreOp
return onDepthStencilAccess(access, &mStencilCmdSizeInvalidated, &mStencilCmdSizeDisabled);
}
bool CommandBufferHelper::onDepthStencilAccess(ResourceAccess access,
uint32_t *cmdCountInvalidated,
uint32_t *cmdCountDisabled)
{
if (*cmdCountInvalidated == kInfiniteCmdSize)
{
// If never invalidated or no longer invalidated, return early.
return false;
}
if (access == vk::ResourceAccess::Write)
{
// Drawing to this attachment is being enabled. Assume that drawing will immediately occur
// after this attachment is enabled, and that means that the attachment will no longer be
// invalidated.
*cmdCountInvalidated = kInfiniteCmdSize;
*cmdCountDisabled = kInfiniteCmdSize;
// Return true to indicate that the store op should remain STORE and that mContentDefined
// should be set to true;
return true;
}
else
{
// Drawing to this attachment is being disabled.
if (hasWriteAfterInvalidate(*cmdCountInvalidated, *cmdCountDisabled))
{
// The attachment was previously drawn while enabled, and so is no longer invalidated.
*cmdCountInvalidated = kInfiniteCmdSize;
*cmdCountDisabled = kInfiniteCmdSize;
// Return true to indicate that the store op should remain STORE and that
// mContentDefined should be set to true;
return true;
}
else
{
// Get the latest CmdSize at the start of being disabled. At the end of the render
// pass, cmdCountDisabled is <= the actual command buffer size, and so it's compared
// with cmdCountInvalidated. If the same, the attachment is still invalidated.
*cmdCountDisabled = mCommandBuffer.getCommandSize();
return false;
}
}
}
void CommandBufferHelper::executeBarriers(ContextVk *contextVk, PrimaryCommandBuffer *primary)
{
// make a local copy for faster access
PipelineStagesMask mask = mPipelineBarrierMask;
if (mask.none())
{
return;
}
if (mForceIndividualBarriers)
{
// Note: ideally we could merge double barriers into a single barrier (or even completely
// eliminate them in some cases). This is a bit trickier to manage than splitting barriers
// into single calls. It should only affect Framebuffer transitions.
// TODO: Investigate merging barriers. http://anglebug.com/4976
for (PipelineStage pipelineStage : mask)
{
PipelineBarrier &barrier = mPipelineBarriers[pipelineStage];
barrier.executeIndividually(primary);
}
mForceIndividualBarriers = false;
}
else if (contextVk->getFeatures().preferAggregateBarrierCalls.enabled)
{
PipelineStagesMask::Iterator iter = mask.begin();
PipelineBarrier &barrier = mPipelineBarriers[*iter];
for (++iter; iter != mask.end(); ++iter)
{
barrier.merge(&mPipelineBarriers[*iter]);
}
barrier.execute(primary);
}
else
{
for (PipelineStage pipelineStage : mask)
{
PipelineBarrier &barrier = mPipelineBarriers[pipelineStage];
barrier.execute(primary);
}
}
mPipelineBarrierMask.reset();
}
void CommandBufferHelper::beginRenderPass(const Framebuffer &framebuffer,
const gl::Rectangle &renderArea,
const RenderPassDesc &renderPassDesc,
const AttachmentOpsArray &renderPassAttachmentOps,
const PackedAttachmentIndex depthStencilAttachmentIndex,
const PackedClearValuesArray &clearValues,
CommandBuffer **commandBufferOut)
{
ASSERT(mIsRenderPassCommandBuffer);
ASSERT(empty());
mRenderPassDesc = renderPassDesc;
mAttachmentOps = renderPassAttachmentOps;
mDepthStencilAttachmentIndex = depthStencilAttachmentIndex;
mFramebuffer.setHandle(framebuffer.getHandle());
mRenderArea = renderArea;
mClearValues = clearValues;
*commandBufferOut = &mCommandBuffer;
mForceIndividualBarriers = false;
mRenderPassStarted = true;
mCounter++;
}
void CommandBufferHelper::restartRenderPassWithReadOnlyDepth(const Framebuffer &framebuffer,
const RenderPassDesc &renderPassDesc)
{
ASSERT(mIsRenderPassCommandBuffer);
ASSERT(mRenderPassStarted);
mRenderPassDesc = renderPassDesc;
mAttachmentOps.setLayouts(mDepthStencilAttachmentIndex, ImageLayout::DepthStencilReadOnly,
ImageLayout::DepthStencilReadOnly);
mFramebuffer.setHandle(framebuffer.getHandle());
// Barrier aggregation messes up with RenderPass restarting.
mForceIndividualBarriers = true;
}
void CommandBufferHelper::endRenderPass(ContextVk *contextVk)
{
if (mDepthStencilAttachmentIndex == kAttachmentIndexInvalid)
{
return;
}
PackedAttachmentOpsDesc &dsOps = mAttachmentOps[mDepthStencilAttachmentIndex];
// Depth/Stencil buffer optimizations:
//
// First, if the attachment is invalidated, skip the store op.
if (isInvalidated(mDepthCmdSizeInvalidated, mDepthCmdSizeDisabled))
{
dsOps.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
}
if (isInvalidated(mStencilCmdSizeInvalidated, mStencilCmdSizeDisabled))
{
dsOps.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
}
// Second, if we are loading or clearing the attachment, but the attachment has not been used,
// and the data has also not been stored back into attachment, then just skip the load/clear op.
if (mDepthStartAccess == ResourceAccess::Unused &&
dsOps.storeOp == VK_ATTACHMENT_STORE_OP_DONT_CARE)
{
dsOps.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
}
if (mStencilStartAccess == ResourceAccess::Unused &&
dsOps.stencilStoreOp == VK_ATTACHMENT_STORE_OP_DONT_CARE)
{
dsOps.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
}
// Ensure we don't write to a read-only RenderPass. (ReadOnly -> !Write)
ASSERT((mRenderPassDesc.getDepthStencilAccess() != ResourceAccess::ReadOnly) ||
mDepthStartAccess != ResourceAccess::Write);
// Fill out perf counters
PerfCounters &counters = contextVk->getPerfCounters();
counters.depthClears += dsOps.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR ? 1 : 0;
counters.depthLoads += dsOps.loadOp == VK_ATTACHMENT_LOAD_OP_LOAD ? 1 : 0;
counters.depthStores += dsOps.storeOp == VK_ATTACHMENT_STORE_OP_STORE ? 1 : 0;
counters.stencilClears += dsOps.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_CLEAR ? 1 : 0;
counters.stencilLoads += dsOps.stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD ? 1 : 0;
counters.stencilStores += dsOps.stencilStoreOp == VK_ATTACHMENT_STORE_OP_STORE ? 1 : 0;
}
void CommandBufferHelper::beginTransformFeedback(size_t validBufferCount,
const VkBuffer *counterBuffers,
bool rebindBuffers)
{
ASSERT(mIsRenderPassCommandBuffer);
mValidTransformFeedbackBufferCount = static_cast<uint32_t>(validBufferCount);
mRebindTransformFeedbackBuffers = rebindBuffers;
for (size_t index = 0; index < validBufferCount; index++)
{
mTransformFeedbackCounterBuffers[index] = counterBuffers[index];
}
}
void CommandBufferHelper::endTransformFeedback()
{
ASSERT(mIsRenderPassCommandBuffer);
pauseTransformFeedback();
mValidTransformFeedbackBufferCount = 0;
}
angle::Result CommandBufferHelper::flushToPrimary(ContextVk *contextVk,
PrimaryCommandBuffer *primary)
{
ANGLE_TRACE_EVENT0("gpu.angle", "CommandBufferHelper::flushToPrimary");
ASSERT(!empty());
if (kEnableCommandStreamDiagnostics)
{
addCommandDiagnostics(contextVk);
}
// Commands that are added to primary before beginRenderPass command
executeBarriers(contextVk, primary);
if (mIsRenderPassCommandBuffer)
{
mCommandBuffer.executeQueuedResetQueryPoolCommands(primary->getHandle());
// Pull a RenderPass from the cache.
RenderPassCache &renderPassCache = contextVk->getRenderPassCache();
Serial serial = contextVk->getCurrentQueueSerial();
RenderPass *renderPass = nullptr;
ANGLE_TRY(renderPassCache.getRenderPassWithOps(contextVk, serial, mRenderPassDesc,
mAttachmentOps, &renderPass));
VkRenderPassBeginInfo beginInfo = {};
beginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
beginInfo.renderPass = renderPass->getHandle();
beginInfo.framebuffer = mFramebuffer.getHandle();
beginInfo.renderArea.offset.x = static_cast<uint32_t>(mRenderArea.x);
beginInfo.renderArea.offset.y = static_cast<uint32_t>(mRenderArea.y);
beginInfo.renderArea.extent.width = static_cast<uint32_t>(mRenderArea.width);
beginInfo.renderArea.extent.height = static_cast<uint32_t>(mRenderArea.height);
beginInfo.clearValueCount = static_cast<uint32_t>(mRenderPassDesc.attachmentCount());
beginInfo.pClearValues = mClearValues.data();
// Run commands inside the RenderPass.
primary->beginRenderPass(beginInfo, VK_SUBPASS_CONTENTS_INLINE);
mCommandBuffer.executeCommands(primary->getHandle());
primary->endRenderPass();
if (mValidTransformFeedbackBufferCount != 0)
{
// Would be better to accumulate this barrier using the command APIs.
// TODO: Clean thus up before we close http://anglebug.com/3206
VkBufferMemoryBarrier bufferBarrier = {};
bufferBarrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
bufferBarrier.pNext = nullptr;
bufferBarrier.srcAccessMask = VK_ACCESS_TRANSFORM_FEEDBACK_COUNTER_WRITE_BIT_EXT;
bufferBarrier.dstAccessMask = VK_ACCESS_TRANSFORM_FEEDBACK_COUNTER_READ_BIT_EXT;
bufferBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
bufferBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
bufferBarrier.buffer = mTransformFeedbackCounterBuffers[0];
bufferBarrier.offset = 0;
bufferBarrier.size = VK_WHOLE_SIZE;
primary->pipelineBarrier(VK_PIPELINE_STAGE_TRANSFORM_FEEDBACK_BIT_EXT,
VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT, 0u, 0u, nullptr, 1u,
&bufferBarrier, 0u, nullptr);
}
}
else
{
mCommandBuffer.executeCommands(primary->getHandle());
}
// Restart the command buffer.
reset();
return angle::Result::Continue;
}
void CommandBufferHelper::updateRenderPassForResolve(vk::Framebuffer *newFramebuffer,
const vk::RenderPassDesc &renderPassDesc)
{
ASSERT(newFramebuffer);
mFramebuffer.setHandle(newFramebuffer->getHandle());
mRenderPassDesc = renderPassDesc;
}
// Helper functions used below
char GetLoadOpShorthand(uint32_t loadOp)
{
switch (loadOp)
{
case VK_ATTACHMENT_LOAD_OP_CLEAR:
return 'C';
case VK_ATTACHMENT_LOAD_OP_LOAD:
return 'L';
default:
return 'D';
}
}
char GetStoreOpShorthand(uint32_t storeOp)
{
switch (storeOp)
{
case VK_ATTACHMENT_STORE_OP_STORE:
return 'S';
default:
return 'D';
}
}
void CommandBufferHelper::addCommandDiagnostics(ContextVk *contextVk)
{
std::ostringstream out;
out << "Memory Barrier: ";
for (PipelineBarrier &barrier : mPipelineBarriers)
{
if (!barrier.isEmpty())
{
barrier.addDiagnosticsString(out);
}
}
out << "\\l";
if (mIsRenderPassCommandBuffer)
{
size_t attachmentCount = mRenderPassDesc.attachmentCount();
size_t depthStencilAttachmentCount = mRenderPassDesc.hasDepthStencilAttachment() ? 1 : 0;
size_t colorAttachmentCount = attachmentCount - depthStencilAttachmentCount;
PackedAttachmentIndex attachmentIndexVk(0);
std::string loadOps, storeOps;
if (colorAttachmentCount > 0)
{
loadOps += " Color: ";
storeOps += " Color: ";
for (size_t i = 0; i < colorAttachmentCount; ++i)
{
loadOps += GetLoadOpShorthand(mAttachmentOps[attachmentIndexVk].loadOp);
storeOps += GetStoreOpShorthand(mAttachmentOps[attachmentIndexVk].storeOp);
++attachmentIndexVk;
}
}
if (depthStencilAttachmentCount > 0)
{
ASSERT(depthStencilAttachmentCount == 1);
loadOps += " Depth/Stencil: ";
storeOps += " Depth/Stencil: ";
loadOps += GetLoadOpShorthand(mAttachmentOps[attachmentIndexVk].loadOp);
loadOps += GetLoadOpShorthand(mAttachmentOps[attachmentIndexVk].stencilLoadOp);
storeOps += GetStoreOpShorthand(mAttachmentOps[attachmentIndexVk].storeOp);
storeOps += GetStoreOpShorthand(mAttachmentOps[attachmentIndexVk].stencilStoreOp);
}
if (attachmentCount > 0)
{
out << "LoadOp: " << loadOps << "\\l";
out << "StoreOp: " << storeOps << "\\l";
}
}
out << mCommandBuffer.dumpCommands("\\l");
contextVk->addCommandBufferDiagnostics(out.str());
}
void CommandBufferHelper::reset()
{
mAllocator.pop();
mAllocator.push();
mCommandBuffer.reset();
mUsedBuffers.clear();
if (mIsRenderPassCommandBuffer)
{
mRenderPassStarted = false;
mValidTransformFeedbackBufferCount = 0;
mRebindTransformFeedbackBuffers = false;
mDepthStartAccess = ResourceAccess::Unused;
mStencilStartAccess = ResourceAccess::Unused;
mDepthCmdSizeInvalidated = kInfiniteCmdSize;
mDepthCmdSizeDisabled = kInfiniteCmdSize;
mStencilCmdSizeInvalidated = kInfiniteCmdSize;
mStencilCmdSizeDisabled = kInfiniteCmdSize;
mDepthStencilAttachmentIndex = kAttachmentIndexInvalid;
mRenderPassUsedImages.clear();
}
// This state should never change for non-renderPass command buffer
ASSERT(mRenderPassStarted == false);
ASSERT(mValidTransformFeedbackBufferCount == 0);
ASSERT(mRebindTransformFeedbackBuffers == false);
ASSERT(mRenderPassUsedImages.empty());
}
void CommandBufferHelper::releaseToContextQueue(ContextVk *contextVk)
{
contextVk->recycleCommandBuffer(this);
}
void CommandBufferHelper::resumeTransformFeedback()
{
ASSERT(mIsRenderPassCommandBuffer);
ASSERT(isTransformFeedbackStarted());
uint32_t numCounterBuffers =
mRebindTransformFeedbackBuffers ? 0 : mValidTransformFeedbackBufferCount;
mRebindTransformFeedbackBuffers = false;
mCommandBuffer.beginTransformFeedback(numCounterBuffers,
mTransformFeedbackCounterBuffers.data());
}
void CommandBufferHelper::pauseTransformFeedback()
{
ASSERT(mIsRenderPassCommandBuffer);
ASSERT(isTransformFeedbackStarted());
mCommandBuffer.endTransformFeedback(mValidTransformFeedbackBufferCount,
mTransformFeedbackCounterBuffers.data());
}
void CommandBufferHelper::updateRenderPassColorClear(PackedAttachmentIndex colorIndexVk,
const VkClearValue &clearValue)
{
mAttachmentOps.setClearOp(colorIndexVk);
mClearValues.store(colorIndexVk, VK_IMAGE_ASPECT_COLOR_BIT, clearValue);
}
void CommandBufferHelper::updateRenderPassDepthStencilClear(VkImageAspectFlags aspectFlags,
const VkClearValue &clearValue)
{
// Don't overwrite prior clear values for individual aspects.
VkClearValue combinedClearValue = mClearValues[mDepthStencilAttachmentIndex];
if ((aspectFlags & VK_IMAGE_ASPECT_DEPTH_BIT) != 0)
{
mAttachmentOps.setClearOp(mDepthStencilAttachmentIndex);
combinedClearValue.depthStencil.depth = clearValue.depthStencil.depth;
}
if ((aspectFlags & VK_IMAGE_ASPECT_STENCIL_BIT) != 0)
{
mAttachmentOps.setClearStencilOp(mDepthStencilAttachmentIndex);
combinedClearValue.depthStencil.stencil = clearValue.depthStencil.stencil;
}
// Bypass special D/S handling. This clear values array stores values packed.
mClearValues.storeNoDepthStencil(mDepthStencilAttachmentIndex, combinedClearValue);
}
// DynamicBuffer implementation.
DynamicBuffer::DynamicBuffer()
: mUsage(0),
mHostVisible(false),
mInitialSize(0),
mBuffer(nullptr),
mNextAllocationOffset(0),
mLastFlushOrInvalidateOffset(0),
mSize(0),
mAlignment(0),
mMemoryPropertyFlags(0)
{}
DynamicBuffer::DynamicBuffer(DynamicBuffer &&other)
: mUsage(other.mUsage),
mHostVisible(other.mHostVisible),
mInitialSize(other.mInitialSize),
mBuffer(other.mBuffer),
mNextAllocationOffset(other.mNextAllocationOffset),
mLastFlushOrInvalidateOffset(other.mLastFlushOrInvalidateOffset),
mSize(other.mSize),
mAlignment(other.mAlignment),
mMemoryPropertyFlags(other.mMemoryPropertyFlags),
mInFlightBuffers(std::move(other.mInFlightBuffers))
{
other.mBuffer = nullptr;
}
void DynamicBuffer::init(RendererVk *renderer,
VkBufferUsageFlags usage,
size_t alignment,
size_t initialSize,
bool hostVisible)
{
VkMemoryPropertyFlags memoryPropertyFlags =
(hostVisible) ? VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT : VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
initWithFlags(renderer, usage, alignment, initialSize, memoryPropertyFlags);
}
void DynamicBuffer::initWithFlags(RendererVk *renderer,
VkBufferUsageFlags usage,
size_t alignment,
size_t initialSize,
VkMemoryPropertyFlags memoryPropertyFlags)
{
mUsage = usage;
mHostVisible = ((memoryPropertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0);
mMemoryPropertyFlags = memoryPropertyFlags;
// Check that we haven't overriden the initial size of the buffer in setMinimumSizeForTesting.
if (mInitialSize == 0)
{
mInitialSize = initialSize;
mSize = 0;
}
// Workaround for the mock ICD not supporting allocations greater than 0x1000.
// Could be removed if https://github.com/KhronosGroup/Vulkan-Tools/issues/84 is fixed.
if (renderer->isMockICDEnabled())
{
mSize = std::min<size_t>(mSize, 0x1000);
}
requireAlignment(renderer, alignment);
}
DynamicBuffer::~DynamicBuffer()
{
ASSERT(mBuffer == nullptr);
}
angle::Result DynamicBuffer::allocateNewBuffer(ContextVk *contextVk)
{
std::unique_ptr<BufferHelper> buffer = std::make_unique<BufferHelper>();
VkBufferCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
createInfo.flags = 0;
createInfo.size = mSize;
createInfo.usage = mUsage;
createInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
createInfo.queueFamilyIndexCount = 0;
createInfo.pQueueFamilyIndices = nullptr;
ANGLE_TRY(buffer->init(contextVk, createInfo, mMemoryPropertyFlags));
ASSERT(!mBuffer);
mBuffer = buffer.release();
return angle::Result::Continue;
}
bool DynamicBuffer::allocateFromCurrentBuffer(size_t sizeInBytes,
uint8_t **ptrOut,
VkDeviceSize *offsetOut)
{
ASSERT(ptrOut);
ASSERT(offsetOut);
size_t sizeToAllocate = roundUp(sizeInBytes, mAlignment);
angle::base::CheckedNumeric<size_t> checkedNextWriteOffset = mNextAllocationOffset;
checkedNextWriteOffset += sizeToAllocate;
if (!checkedNextWriteOffset.IsValid() || checkedNextWriteOffset.ValueOrDie() >= mSize)
{
return false;
}
ASSERT(mBuffer != nullptr);
ASSERT(mHostVisible);
ASSERT(mBuffer->getMappedMemory());
*ptrOut = mBuffer->getMappedMemory() + mNextAllocationOffset;
*offsetOut = static_cast<VkDeviceSize>(mNextAllocationOffset);
mNextAllocationOffset += static_cast<uint32_t>(sizeToAllocate);
return true;
}
angle::Result DynamicBuffer::allocateWithAlignment(ContextVk *contextVk,
size_t sizeInBytes,
size_t alignment,
uint8_t **ptrOut,
VkBuffer *bufferOut,
VkDeviceSize *offsetOut,
bool *newBufferAllocatedOut)
{
mNextAllocationOffset =
roundUp<uint32_t>(mNextAllocationOffset, static_cast<uint32_t>(alignment));
size_t sizeToAllocate = roundUp(sizeInBytes, mAlignment);
angle::base::CheckedNumeric<size_t> checkedNextWriteOffset = mNextAllocationOffset;
checkedNextWriteOffset += sizeToAllocate;
if (!checkedNextWriteOffset.IsValid() || checkedNextWriteOffset.ValueOrDie() >= mSize)
{
if (mBuffer)
{
ANGLE_TRY(flush(contextVk));
mBuffer->unmap(contextVk->getRenderer());
mInFlightBuffers.push_back(mBuffer);
mBuffer = nullptr;
}
if (sizeToAllocate > mSize)
{
mSize = std::max(mInitialSize, sizeToAllocate);
// Clear the free list since the free buffers are now too small.
for (BufferHelper *toFree : mBufferFreeList)
{
toFree->release(contextVk->getRenderer());
}
mBufferFreeList.clear();
}
// The front of the free list should be the oldest. Thus if it is in use the rest of the
// free list should be in use as well.
if (mBufferFreeList.empty() ||
mBufferFreeList.front()->isCurrentlyInUse(contextVk->getLastCompletedQueueSerial()))
{
ANGLE_TRY(allocateNewBuffer(contextVk));
}
else
{
mBuffer = mBufferFreeList.front();
mBufferFreeList.erase(mBufferFreeList.begin());
}
ASSERT(mBuffer->getSize() == mSize);
mNextAllocationOffset = 0;
mLastFlushOrInvalidateOffset = 0;
if (newBufferAllocatedOut != nullptr)
{
*newBufferAllocatedOut = true;
}
}
else if (newBufferAllocatedOut != nullptr)
{
*newBufferAllocatedOut = false;
}
ASSERT(mBuffer != nullptr);
if (bufferOut != nullptr)
{
*bufferOut = mBuffer->getBuffer().getHandle();
}
// Optionally map() the buffer if possible
if (ptrOut)
{
ASSERT(mHostVisible);
uint8_t *mappedMemory;
ANGLE_TRY(mBuffer->map(contextVk, &mappedMemory));
*ptrOut = mappedMemory + mNextAllocationOffset;
}
if (offsetOut != nullptr)
{
*offsetOut = static_cast<VkDeviceSize>(mNextAllocationOffset);
}
mNextAllocationOffset += static_cast<uint32_t>(sizeToAllocate);
return angle::Result::Continue;
}
angle::Result DynamicBuffer::flush(ContextVk *contextVk)
{
if (mHostVisible && (mNextAllocationOffset > mLastFlushOrInvalidateOffset))
{
ASSERT(mBuffer != nullptr);
ANGLE_TRY(mBuffer->flush(contextVk->getRenderer(), mLastFlushOrInvalidateOffset,
mNextAllocationOffset - mLastFlushOrInvalidateOffset));
mLastFlushOrInvalidateOffset = mNextAllocationOffset;
}
return angle::Result::Continue;
}
angle::Result DynamicBuffer::invalidate(ContextVk *contextVk)
{
if (mHostVisible && (mNextAllocationOffset > mLastFlushOrInvalidateOffset))
{
ASSERT(mBuffer != nullptr);
ANGLE_TRY(mBuffer->invalidate(contextVk->getRenderer(), mLastFlushOrInvalidateOffset,
mNextAllocationOffset - mLastFlushOrInvalidateOffset));
mLastFlushOrInvalidateOffset = mNextAllocationOffset;
}
return angle::Result::Continue;
}
void DynamicBuffer::releaseBufferListToRenderer(RendererVk *renderer,
std::vector<BufferHelper *> *buffers)
{
for (BufferHelper *toFree : *buffers)
{
toFree->release(renderer);
delete toFree;
}
buffers->clear();
}
void DynamicBuffer::destroyBufferList(RendererVk *renderer, std::vector<BufferHelper *> *buffers)
{
for (BufferHelper *toFree : *buffers)
{
toFree->destroy(renderer);
delete toFree;
}
buffers->clear();
}
void DynamicBuffer::release(RendererVk *renderer)
{
reset();
releaseBufferListToRenderer(renderer, &mInFlightBuffers);
releaseBufferListToRenderer(renderer, &mBufferFreeList);
if (mBuffer)
{
mBuffer->release(renderer);
SafeDelete(mBuffer);
}
}
void DynamicBuffer::releaseInFlightBuffersToResourceUseList(ContextVk *contextVk)
{
ResourceUseList *resourceUseList = &contextVk->getResourceUseList();
for (BufferHelper *bufferHelper : mInFlightBuffers)
{
bufferHelper->retain(resourceUseList);
// If the dynamic buffer was resized we cannot reuse the retained buffer.
if (bufferHelper->getSize() < mSize)
{
bufferHelper->release(contextVk->getRenderer());
}
else
{
mBufferFreeList.push_back(bufferHelper);
}
}
mInFlightBuffers.clear();
}
void DynamicBuffer::releaseInFlightBuffers(ContextVk *contextVk)
{
for (BufferHelper *toRelease : mInFlightBuffers)
{
// If the dynamic buffer was resized we cannot reuse the retained buffer.
if (toRelease->getSize() < mSize)
{
toRelease->release(contextVk->getRenderer());
}
else
{
mBufferFreeList.push_back(toRelease);
}
}
mInFlightBuffers.clear();
}
void DynamicBuffer::destroy(RendererVk *renderer)
{
reset();
destroyBufferList(renderer, &mInFlightBuffers);
destroyBufferList(renderer, &mBufferFreeList);
if (mBuffer)
{
mBuffer->unmap(renderer);
mBuffer->destroy(renderer);
delete mBuffer;
mBuffer = nullptr;
}
}
void DynamicBuffer::requireAlignment(RendererVk *renderer, size_t alignment)
{
ASSERT(alignment > 0);
size_t prevAlignment = mAlignment;
// If alignment was never set, initialize it with the atom size limit.
if (prevAlignment == 0)
{
prevAlignment =
static_cast<size_t>(renderer->getPhysicalDeviceProperties().limits.nonCoherentAtomSize);
ASSERT(gl::isPow2(prevAlignment));
}
// We need lcm(prevAlignment, alignment). Usually, one divides the other so std::max() could be
// used instead. Only known case where this assumption breaks is for 3-component types with
// 16- or 32-bit channels, so that's special-cased to avoid a full-fledged lcm implementation.
if (gl::isPow2(prevAlignment * alignment))
{
ASSERT(alignment % prevAlignment == 0 || prevAlignment % alignment == 0);
alignment = std::max(prevAlignment, alignment);
}
else
{
ASSERT(prevAlignment % 3 != 0 || gl::isPow2(prevAlignment / 3));
ASSERT(alignment % 3 != 0 || gl::isPow2(alignment / 3));
prevAlignment = prevAlignment % 3 == 0 ? prevAlignment / 3 : prevAlignment;
alignment = alignment % 3 == 0 ? alignment / 3 : alignment;
alignment = std::max(prevAlignment, alignment) * 3;
}
// If alignment has changed, make sure the next allocation is done at an aligned offset.
if (alignment != mAlignment)
{
mNextAllocationOffset = roundUp(mNextAllocationOffset, static_cast<uint32_t>(alignment));
}
mAlignment = alignment;
}
void DynamicBuffer::setMinimumSizeForTesting(size_t minSize)
{
// This will really only have an effect next time we call allocate.
mInitialSize = minSize;
// Forces a new allocation on the next allocate.
mSize = 0;
}
void DynamicBuffer::reset()
{
mSize = 0;
mNextAllocationOffset = 0;
mLastFlushOrInvalidateOffset = 0;
}
// DynamicShadowBuffer implementation.
DynamicShadowBuffer::DynamicShadowBuffer() : mInitialSize(0), mSize(0) {}
DynamicShadowBuffer::DynamicShadowBuffer(DynamicShadowBuffer &&other)
: mInitialSize(other.mInitialSize), mSize(other.mSize), mBuffer(std::move(other.mBuffer))
{}
void DynamicShadowBuffer::init(size_t initialSize)
{
mInitialSize = initialSize;
}
DynamicShadowBuffer::~DynamicShadowBuffer()
{
ASSERT(mBuffer.empty());
}
angle::Result DynamicShadowBuffer::allocate(size_t sizeInBytes)
{
bool result = true;
// Delete the current buffer, if any
if (!mBuffer.empty())
{
result &= mBuffer.resize(0);
}
// Cache the new size
mSize = std::max(mInitialSize, sizeInBytes);
// Allocate the buffer
result &= mBuffer.resize(mSize);
// If allocation failed, release the buffer and return error.
if (!result)
{
release();
return angle::Result::Stop;
}
return angle::Result::Continue;
}
void DynamicShadowBuffer::release()
{
reset();
if (!mBuffer.empty())
{
(void)mBuffer.resize(0);
}
}
void DynamicShadowBuffer::destroy(VkDevice device)
{
release();
}
void DynamicShadowBuffer::reset()
{
mSize = 0;
}
// DescriptorPoolHelper implementation.
DescriptorPoolHelper::DescriptorPoolHelper() : mFreeDescriptorSets(0) {}
DescriptorPoolHelper::~DescriptorPoolHelper() = default;
bool DescriptorPoolHelper::hasCapacity(uint32_t descriptorSetCount) const
{
return mFreeDescriptorSets >= descriptorSetCount;
}
angle::Result DescriptorPoolHelper::init(ContextVk *contextVk,
const std::vector<VkDescriptorPoolSize> &poolSizes,
uint32_t maxSets)
{
if (mDescriptorPool.valid())
{
// This could be improved by recycling the descriptor pool.
mDescriptorPool.destroy(contextVk->getDevice());
}
VkDescriptorPoolCreateInfo descriptorPoolInfo = {};
descriptorPoolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
descriptorPoolInfo.flags = 0;
descriptorPoolInfo.maxSets = maxSets;
descriptorPoolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size());
descriptorPoolInfo.pPoolSizes = poolSizes.data();
mFreeDescriptorSets = maxSets;
ANGLE_VK_TRY(contextVk, mDescriptorPool.init(contextVk->getDevice(), descriptorPoolInfo));
return angle::Result::Continue;
}
void DescriptorPoolHelper::destroy(VkDevice device)
{
mDescriptorPool.destroy(device);
}
void DescriptorPoolHelper::release(ContextVk *contextVk)
{
contextVk->addGarbage(&mDescriptorPool);
}
angle::Result DescriptorPoolHelper::allocateSets(ContextVk *contextVk,
const VkDescriptorSetLayout *descriptorSetLayout,
uint32_t descriptorSetCount,
VkDescriptorSet *descriptorSetsOut)
{
VkDescriptorSetAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = mDescriptorPool.getHandle();
allocInfo.descriptorSetCount = descriptorSetCount;
allocInfo.pSetLayouts = descriptorSetLayout;
ASSERT(mFreeDescriptorSets >= descriptorSetCount);
mFreeDescriptorSets -= descriptorSetCount;
ANGLE_VK_TRY(contextVk, mDescriptorPool.allocateDescriptorSets(contextVk->getDevice(),
allocInfo, descriptorSetsOut));
return angle::Result::Continue;
}
// DynamicDescriptorPool implementation.
DynamicDescriptorPool::DynamicDescriptorPool()
: mCurrentPoolIndex(0), mCachedDescriptorSetLayout(VK_NULL_HANDLE)
{}
DynamicDescriptorPool::~DynamicDescriptorPool() = default;
angle::Result DynamicDescriptorPool::init(ContextVk *contextVk,
const VkDescriptorPoolSize *setSizes,
size_t setSizeCount,
VkDescriptorSetLayout descriptorSetLayout)
{
ASSERT(setSizes);
ASSERT(setSizeCount);
ASSERT(mCurrentPoolIndex == 0);
ASSERT(mDescriptorPools.empty() ||
(mDescriptorPools.size() == 1 &&
mDescriptorPools[mCurrentPoolIndex]->get().hasCapacity(mMaxSetsPerPool)));
ASSERT(mCachedDescriptorSetLayout == VK_NULL_HANDLE);
mPoolSizes.assign(setSizes, setSizes + setSizeCount);
for (uint32_t i = 0; i < setSizeCount; ++i)
{
mPoolSizes[i].descriptorCount *= mMaxSetsPerPool;
}
mCachedDescriptorSetLayout = descriptorSetLayout;
mDescriptorPools.push_back(new RefCountedDescriptorPoolHelper());
mCurrentPoolIndex = mDescriptorPools.size() - 1;
return mDescriptorPools[mCurrentPoolIndex]->get().init(contextVk, mPoolSizes, mMaxSetsPerPool);
}
void DynamicDescriptorPool::destroy(VkDevice device)
{
for (RefCountedDescriptorPoolHelper *pool : mDescriptorPools)
{
ASSERT(!pool->isReferenced());
pool->get().destroy(device);
delete pool;
}
mDescriptorPools.clear();
mCachedDescriptorSetLayout = VK_NULL_HANDLE;
}
void DynamicDescriptorPool::release(ContextVk *contextVk)
{
for (RefCountedDescriptorPoolHelper *pool : mDescriptorPools)
{
ASSERT(!pool->isReferenced());
pool->get().release(contextVk);
delete pool;
}
mDescriptorPools.clear();
mCachedDescriptorSetLayout = VK_NULL_HANDLE;
}
angle::Result DynamicDescriptorPool::allocateSetsAndGetInfo(
ContextVk *contextVk,
const VkDescriptorSetLayout *descriptorSetLayout,
uint32_t descriptorSetCount,
RefCountedDescriptorPoolBinding *bindingOut,
VkDescriptorSet *descriptorSetsOut,
bool *newPoolAllocatedOut)
{
ASSERT(!mDescriptorPools.empty());
ASSERT(*descriptorSetLayout == mCachedDescriptorSetLayout);
*newPoolAllocatedOut = false;
if (!bindingOut->valid() || !bindingOut->get().hasCapacity(descriptorSetCount))
{
if (!mDescriptorPools[mCurrentPoolIndex]->get().hasCapacity(descriptorSetCount))
{
ANGLE_TRY(allocateNewPool(contextVk));
*newPoolAllocatedOut = true;
}
// Make sure the old binding knows the descriptor sets can still be in-use. We only need
// to update the serial when we move to a new pool. This is because we only check serials
// when we move to a new pool.
if (bindingOut->valid())
{
Serial currentSerial = contextVk->getCurrentQueueSerial();
bindingOut->get().updateSerial(currentSerial);
}
bindingOut->set(mDescriptorPools[mCurrentPoolIndex]);
}
return bindingOut->get().allocateSets(contextVk, descriptorSetLayout, descriptorSetCount,
descriptorSetsOut);
}
angle::Result DynamicDescriptorPool::allocateNewPool(ContextVk *contextVk)
{
bool found = false;
for (size_t poolIndex = 0; poolIndex < mDescriptorPools.size(); ++poolIndex)
{
if (!mDescriptorPools[poolIndex]->isReferenced() &&
!contextVk->isSerialInUse(mDescriptorPools[poolIndex]->get().getSerial()))
{
mCurrentPoolIndex = poolIndex;
found = true;
break;
}
}
if (!found)
{
mDescriptorPools.push_back(new RefCountedDescriptorPoolHelper());
mCurrentPoolIndex = mDescriptorPools.size() - 1;
static constexpr size_t kMaxPools = 99999;
ANGLE_VK_CHECK(contextVk, mDescriptorPools.size() < kMaxPools, VK_ERROR_TOO_MANY_OBJECTS);
}
return mDescriptorPools[mCurrentPoolIndex]->get().init(contextVk, mPoolSizes, mMaxSetsPerPool);
}
uint32_t DynamicDescriptorPool::GetMaxSetsPerPoolForTesting()
{
return mMaxSetsPerPool;
}
void DynamicDescriptorPool::SetMaxSetsPerPoolForTesting(uint32_t maxSetsPerPool)
{
mMaxSetsPerPool = maxSetsPerPool;
}
// DynamicallyGrowingPool implementation
template <typename Pool>
DynamicallyGrowingPool<Pool>::DynamicallyGrowingPool()
: mPoolSize(0), mCurrentPool(0), mCurrentFreeEntry(0)
{}
template <typename Pool>
DynamicallyGrowingPool<Pool>::~DynamicallyGrowingPool() = default;
template <typename Pool>
angle::Result DynamicallyGrowingPool<Pool>::initEntryPool(Context *contextVk, uint32_t poolSize)
{
ASSERT(mPools.empty() && mPoolStats.empty());
mPoolSize = poolSize;
return angle::Result::Continue;
}
template <typename Pool>
void DynamicallyGrowingPool<Pool>::destroyEntryPool()
{
mPools.clear();
mPoolStats.clear();
}
template <typename Pool>
bool DynamicallyGrowingPool<Pool>::findFreeEntryPool(ContextVk *contextVk)
{
Serial lastCompletedQueueSerial = contextVk->getLastCompletedQueueSerial();
for (size_t i = 0; i < mPools.size(); ++i)
{
if (mPoolStats[i].freedCount == mPoolSize &&
mPoolStats[i].serial <= lastCompletedQueueSerial)
{
mCurrentPool = i;
mCurrentFreeEntry = 0;
mPoolStats[i].freedCount = 0;
return true;
}
}
return false;
}
template <typename Pool>
angle::Result DynamicallyGrowingPool<Pool>::allocateNewEntryPool(ContextVk *contextVk, Pool &&pool)
{
mPools.push_back(std::move(pool));
PoolStats poolStats = {0, Serial()};
mPoolStats.push_back(poolStats);
mCurrentPool = mPools.size() - 1;
mCurrentFreeEntry = 0;
return angle::Result::Continue;
}
template <typename Pool>
void DynamicallyGrowingPool<Pool>::onEntryFreed(ContextVk *contextVk, size_t poolIndex)
{
ASSERT(poolIndex < mPoolStats.size() && mPoolStats[poolIndex].freedCount < mPoolSize);
// Take note of the current serial to avoid reallocating a query in the same pool
mPoolStats[poolIndex].serial = contextVk->getCurrentQueueSerial();
++mPoolStats[poolIndex].freedCount;
}
// DynamicQueryPool implementation
DynamicQueryPool::DynamicQueryPool() = default;
DynamicQueryPool::~DynamicQueryPool() = default;
angle::Result DynamicQueryPool::init(ContextVk *contextVk, VkQueryType type, uint32_t poolSize)
{
ANGLE_TRY(initEntryPool(contextVk, poolSize));
mQueryType = type;
ANGLE_TRY(allocateNewPool(contextVk));
return angle::Result::Continue;
}
void DynamicQueryPool::destroy(VkDevice device)
{
for (QueryPool &queryPool : mPools)
{
queryPool.destroy(device);
}
destroyEntryPool();
}
angle::Result DynamicQueryPool::allocateQuery(ContextVk *contextVk, QueryHelper *queryOut)
{
ASSERT(!queryOut->valid());
if (mCurrentFreeEntry >= mPoolSize)
{
// No more queries left in this pool, create another one.
ANGLE_TRY(allocateNewPool(contextVk));
}
uint32_t queryIndex = mCurrentFreeEntry++;
queryOut->init(this, mCurrentPool, queryIndex);
return angle::Result::Continue;
}
void DynamicQueryPool::freeQuery(ContextVk *contextVk, QueryHelper *query)
{
if (query->valid())
{
size_t poolIndex = query->mQueryPoolIndex;
ASSERT(getQueryPool(poolIndex).valid());
onEntryFreed(contextVk, poolIndex);
query->deinit();
}
}
angle::Result DynamicQueryPool::allocateNewPool(ContextVk *contextVk)
{
if (findFreeEntryPool(contextVk))
{
return angle::Result::Continue;
}
VkQueryPoolCreateInfo queryPoolInfo = {};
queryPoolInfo.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
queryPoolInfo.flags = 0;
queryPoolInfo.queryType = mQueryType;
queryPoolInfo.queryCount = mPoolSize;
queryPoolInfo.pipelineStatistics = 0;
QueryPool queryPool;
ANGLE_VK_TRY(contextVk, queryPool.init(contextVk->getDevice(), queryPoolInfo));
return allocateNewEntryPool(contextVk, std::move(queryPool));
}
// QueryHelper implementation
QueryHelper::QueryHelper() : mDynamicQueryPool(nullptr), mQueryPoolIndex(0), mQuery(0) {}
QueryHelper::~QueryHelper() {}
void QueryHelper::init(const DynamicQueryPool *dynamicQueryPool,
const size_t queryPoolIndex,
uint32_t query)
{
mDynamicQueryPool = dynamicQueryPool;
mQueryPoolIndex = queryPoolIndex;
mQuery = query;
}
void QueryHelper::deinit()
{
mDynamicQueryPool = nullptr;
mQueryPoolIndex = 0;
mQuery = 0;
mMostRecentSerial = Serial();
}
void QueryHelper::resetQueryPool(ContextVk *contextVk,
CommandBuffer *outsideRenderPassCommandBuffer)
{
const QueryPool &queryPool = getQueryPool();
outsideRenderPassCommandBuffer->resetQueryPool(queryPool.getHandle(), mQuery, 1);
}
angle::Result QueryHelper::beginQuery(ContextVk *contextVk)
{
if (contextVk->hasStartedRenderPass())
{
ANGLE_TRY(contextVk->flushCommandsAndEndRenderPass());
}
CommandBuffer &commandBuffer = contextVk->getOutsideRenderPassCommandBuffer();
const QueryPool &queryPool = getQueryPool();
commandBuffer.resetQueryPool(queryPool.getHandle(), mQuery, 1);
commandBuffer.beginQuery(queryPool.getHandle(), mQuery, 0);
mMostRecentSerial = contextVk->getCurrentQueueSerial();
return angle::Result::Continue;
}
angle::Result QueryHelper::endQuery(ContextVk *contextVk)
{
if (contextVk->hasStartedRenderPass())
{
ANGLE_TRY(contextVk->flushCommandsAndEndRenderPass());
}
CommandBuffer &commandBuffer = contextVk->getOutsideRenderPassCommandBuffer();
commandBuffer.endQuery(getQueryPool().getHandle(), mQuery);
mMostRecentSerial = contextVk->getCurrentQueueSerial();
return angle::Result::Continue;
}
void QueryHelper::beginOcclusionQuery(ContextVk *contextVk, CommandBuffer *renderPassCommandBuffer)
{
const QueryPool &queryPool = getQueryPool();
renderPassCommandBuffer->queueResetQueryPool(queryPool.getHandle(), mQuery, 1);
renderPassCommandBuffer->beginQuery(queryPool.getHandle(), mQuery, 0);
mMostRecentSerial = contextVk->getCurrentQueueSerial();
}
void QueryHelper::endOcclusionQuery(ContextVk *contextVk, CommandBuffer *renderPassCommandBuffer)
{
renderPassCommandBuffer->endQuery(getQueryPool().getHandle(), mQuery);
mMostRecentSerial = contextVk->getCurrentQueueSerial();
}
angle::Result QueryHelper::flushAndWriteTimestamp(ContextVk *contextVk)
{
if (contextVk->hasStartedRenderPass())
{
ANGLE_TRY(contextVk->flushCommandsAndEndRenderPass());
}
CommandBuffer &commandBuffer = contextVk->getOutsideRenderPassCommandBuffer();
writeTimestamp(contextVk, &commandBuffer);
return angle::Result::Continue;
}
void QueryHelper::writeTimestampToPrimary(ContextVk *contextVk, PrimaryCommandBuffer *primary)
{
// Note that commands may not be flushed at this point.
const QueryPool &queryPool = getQueryPool();
primary->resetQueryPool(queryPool, mQuery, 1);
primary->writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, queryPool, mQuery);
mMostRecentSerial = contextVk->getCurrentQueueSerial();
}
void QueryHelper::writeTimestamp(ContextVk *contextVk, CommandBuffer *commandBuffer)
{
const QueryPool &queryPool = getQueryPool();
commandBuffer->resetQueryPool(queryPool.getHandle(), mQuery, 1);
commandBuffer->writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, queryPool.getHandle(),
mQuery);
mMostRecentSerial = contextVk->getCurrentQueueSerial();
}
bool QueryHelper::hasPendingWork(ContextVk *contextVk)
{
// If the renderer has a queue serial higher than the stored one, the command buffers that
// recorded this query have already been submitted, so there is no pending work.
return mMostRecentSerial.valid() && (mMostRecentSerial == contextVk->getCurrentQueueSerial());
}
angle::Result QueryHelper::getUint64ResultNonBlocking(ContextVk *contextVk,
uint64_t *resultOut,
bool *availableOut)
{
ASSERT(valid());
VkResult result;
// Ensure that we only wait if we have inserted a query in command buffer. Otherwise you will
// wait forever and trigger GPU timeout.
if (mMostRecentSerial.valid())
{
VkDevice device = contextVk->getDevice();
constexpr VkQueryResultFlags kFlags = VK_QUERY_RESULT_64_BIT;
result = getQueryPool().getResults(device, mQuery, 1, sizeof(uint64_t), resultOut,
sizeof(uint64_t), kFlags);
}
else
{
result = VK_SUCCESS;
*resultOut = 0;
}
if (result == VK_NOT_READY)
{
*availableOut = false;
return angle::Result::Continue;
}
else
{
ANGLE_VK_TRY(contextVk, result);
*availableOut = true;
}
return angle::Result::Continue;
}
angle::Result QueryHelper::getUint64Result(ContextVk *contextVk, uint64_t *resultOut)
{
ASSERT(valid());
if (mMostRecentSerial.valid())
{
VkDevice device = contextVk->getDevice();
constexpr VkQueryResultFlags kFlags = VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT;
ANGLE_VK_TRY(contextVk, getQueryPool().getResults(device, mQuery, 1, sizeof(uint64_t),
resultOut, sizeof(uint64_t), kFlags));
}
else
{
*resultOut = 0;
}
return angle::Result::Continue;
}
// DynamicSemaphorePool implementation
DynamicSemaphorePool::DynamicSemaphorePool() = default;
DynamicSemaphorePool::~DynamicSemaphorePool() = default;
angle::Result DynamicSemaphorePool::init(ContextVk *contextVk, uint32_t poolSize)
{
ANGLE_TRY(initEntryPool(contextVk, poolSize));
ANGLE_TRY(allocateNewPool(contextVk));
return angle::Result::Continue;
}
void DynamicSemaphorePool::destroy(VkDevice device)
{
for (auto &semaphorePool : mPools)
{
for (Semaphore &semaphore : semaphorePool)
{
semaphore.destroy(device);
}
}
destroyEntryPool();
}
angle::Result DynamicSemaphorePool::allocateSemaphore(ContextVk *contextVk,
SemaphoreHelper *semaphoreOut)
{
ASSERT(!semaphoreOut->getSemaphore());
if (mCurrentFreeEntry >= mPoolSize)
{
// No more queries left in this pool, create another one.
ANGLE_TRY(allocateNewPool(contextVk));
}
semaphoreOut->init(mCurrentPool, &mPools[mCurrentPool][mCurrentFreeEntry++]);
return angle::Result::Continue;
}
void DynamicSemaphorePool::freeSemaphore(ContextVk *contextVk, SemaphoreHelper *semaphore)
{
if (semaphore->getSemaphore())
{
onEntryFreed(contextVk, semaphore->getSemaphorePoolIndex());
semaphore->deinit();
}
}
angle::Result DynamicSemaphorePool::allocateNewPool(ContextVk *contextVk)
{
if (findFreeEntryPool(contextVk))
{
return angle::Result::Continue;
}
std::vector<Semaphore> newPool(mPoolSize);
for (Semaphore &semaphore : newPool)
{
ANGLE_VK_TRY(contextVk, semaphore.init(contextVk->getDevice()));
}
// This code is safe as long as the growth of the outer vector in vector<vector<T>> is done by
// moving the inner vectors, making sure references to the inner vector remain intact.
Semaphore *assertMove = mPools.size() > 0 ? mPools[0].data() : nullptr;
ANGLE_TRY(allocateNewEntryPool(contextVk, std::move(newPool)));
ASSERT(assertMove == nullptr || assertMove == mPools[0].data());
return angle::Result::Continue;
}
// SemaphoreHelper implementation
SemaphoreHelper::SemaphoreHelper() : mSemaphorePoolIndex(0), mSemaphore(0) {}
SemaphoreHelper::~SemaphoreHelper() {}
SemaphoreHelper::SemaphoreHelper(SemaphoreHelper &&other)
: mSemaphorePoolIndex(other.mSemaphorePoolIndex), mSemaphore(other.mSemaphore)
{
other.mSemaphore = nullptr;
}
SemaphoreHelper &SemaphoreHelper::operator=(SemaphoreHelper &&other)
{
std::swap(mSemaphorePoolIndex, other.mSemaphorePoolIndex);
std::swap(mSemaphore, other.mSemaphore);
return *this;
}
void SemaphoreHelper::init(const size_t semaphorePoolIndex, const Semaphore *semaphore)
{
mSemaphorePoolIndex = semaphorePoolIndex;
mSemaphore = semaphore;
}
void SemaphoreHelper::deinit()
{
mSemaphorePoolIndex = 0;
mSemaphore = nullptr;
}
// LineLoopHelper implementation.
LineLoopHelper::LineLoopHelper(RendererVk *renderer)
{
// We need to use an alignment of the maximum size we're going to allocate, which is
// VK_INDEX_TYPE_UINT32. When we switch from a drawElement to a drawArray call, the allocations
// can vary in size. According to the Vulkan spec, when calling vkCmdBindIndexBuffer: 'The
// sum of offset and the address of the range of VkDeviceMemory object that is backing buffer,
// must be a multiple of the type indicated by indexType'.
mDynamicIndexBuffer.init(renderer, kLineLoopDynamicBufferUsage, sizeof(uint32_t),
kLineLoopDynamicBufferInitialSize, true);
mDynamicIndirectBuffer.init(renderer, kLineLoopDynamicIndirectBufferUsage, sizeof(uint32_t),
kLineLoopDynamicIndirectBufferInitialSize, true);
}
LineLoopHelper::~LineLoopHelper() = default;
angle::Result LineLoopHelper::getIndexBufferForDrawArrays(ContextVk *contextVk,
uint32_t clampedVertexCount,
GLint firstVertex,
BufferHelper **bufferOut,
VkDeviceSize *offsetOut)
{
uint32_t *indices = nullptr;
size_t allocateBytes = sizeof(uint32_t) * (static_cast<size_t>(clampedVertexCount) + 1);
mDynamicIndexBuffer.releaseInFlightBuffers(contextVk);
ANGLE_TRY(mDynamicIndexBuffer.allocate(contextVk, allocateBytes,
reinterpret_cast<uint8_t **>(&indices), nullptr,
offsetOut, nullptr));
*bufferOut = mDynamicIndexBuffer.getCurrentBuffer();
// Note: there could be an overflow in this addition.
uint32_t unsignedFirstVertex = static_cast<uint32_t>(firstVertex);
uint32_t vertexCount = (clampedVertexCount + unsignedFirstVertex);
for (uint32_t vertexIndex = unsignedFirstVertex; vertexIndex < vertexCount; vertexIndex++)
{
*indices++ = vertexIndex;
}
*indices = unsignedFirstVertex;
// Since we are not using the VK_MEMORY_PROPERTY_HOST_COHERENT_BIT flag when creating the
// device memory in the StreamingBuffer, we always need to make sure we flush it after
// writing.
ANGLE_TRY(mDynamicIndexBuffer.flush(contextVk));
return angle::Result::Continue;
}
angle::Result LineLoopHelper::getIndexBufferForElementArrayBuffer(ContextVk *contextVk,
BufferVk *elementArrayBufferVk,
gl::DrawElementsType glIndexType,
int indexCount,
intptr_t elementArrayOffset,
BufferHelper **bufferOut,
VkDeviceSize *bufferOffsetOut,
uint32_t *indexCountOut)
{
if (glIndexType == gl::DrawElementsType::UnsignedByte ||
contextVk->getState().isPrimitiveRestartEnabled())
{
ANGLE_TRACE_EVENT0("gpu.angle", "LineLoopHelper::getIndexBufferForElementArrayBuffer");
void *srcDataMapping = nullptr;
ANGLE_TRY(elementArrayBufferVk->mapImpl(contextVk, &srcDataMapping));
ANGLE_TRY(streamIndices(contextVk, glIndexType, indexCount,
static_cast<const uint8_t *>(srcDataMapping) + elementArrayOffset,
bufferOut, bufferOffsetOut, indexCountOut));
ANGLE_TRY(elementArrayBufferVk->unmapImpl(contextVk));
return angle::Result::Continue;
}
*indexCountOut = indexCount + 1;
uint32_t *indices = nullptr;
size_t unitSize = contextVk->getVkIndexTypeSize(glIndexType);
size_t allocateBytes = unitSize * (indexCount + 1) + 1;
mDynamicIndexBuffer.releaseInFlightBuffers(contextVk);
ANGLE_TRY(mDynamicIndexBuffer.allocate(contextVk, allocateBytes,
reinterpret_cast<uint8_t **>(&indices), nullptr,
bufferOffsetOut, nullptr));
*bufferOut = mDynamicIndexBuffer.getCurrentBuffer();
VkDeviceSize sourceOffset = static_cast<VkDeviceSize>(elementArrayOffset);
uint64_t unitCount = static_cast<VkDeviceSize>(indexCount);
angle::FixedVector<VkBufferCopy, 3> copies = {
{sourceOffset, *bufferOffsetOut, unitCount * unitSize},
{sourceOffset, *bufferOffsetOut + unitCount * unitSize, unitSize},
};
if (contextVk->getRenderer()->getFeatures().extraCopyBufferRegion.enabled)
copies.push_back({sourceOffset, *bufferOffsetOut + (unitCount + 1) * unitSize, 1});
ANGLE_TRY(elementArrayBufferVk->copyToBufferImpl(
contextVk, *bufferOut, static_cast<uint32_t>(copies.size()), copies.data()));
ANGLE_TRY(mDynamicIndexBuffer.flush(contextVk));
return angle::Result::Continue;
}
angle::Result LineLoopHelper::streamIndices(ContextVk *contextVk,
gl::DrawElementsType glIndexType,
GLsizei indexCount,
const uint8_t *srcPtr,
BufferHelper **bufferOut,
VkDeviceSize *bufferOffsetOut,
uint32_t *indexCountOut)
{
size_t unitSize = contextVk->getVkIndexTypeSize(glIndexType);
uint8_t *indices = nullptr;
uint32_t numOutIndices = indexCount + 1;
if (contextVk->getState().isPrimitiveRestartEnabled())
{
numOutIndices = GetLineLoopWithRestartIndexCount(glIndexType, indexCount, srcPtr);
}
*indexCountOut = numOutIndices;
size_t allocateBytes = unitSize * numOutIndices;
ANGLE_TRY(mDynamicIndexBuffer.allocate(contextVk, allocateBytes,
reinterpret_cast<uint8_t **>(&indices), nullptr,
bufferOffsetOut, nullptr));
*bufferOut = mDynamicIndexBuffer.getCurrentBuffer();
if (contextVk->getState().isPrimitiveRestartEnabled())
{
HandlePrimitiveRestart(contextVk, glIndexType, indexCount, srcPtr, indices);
}
else
{
if (contextVk->shouldConvertUint8VkIndexType(glIndexType))
{
// If vulkan doesn't support uint8 index types, we need to emulate it.
VkIndexType indexType = contextVk->getVkIndexType(glIndexType);
ASSERT(indexType == VK_INDEX_TYPE_UINT16);
uint16_t *indicesDst = reinterpret_cast<uint16_t *>(indices);
for (int i = 0; i < indexCount; i++)
{
indicesDst[i] = srcPtr[i];
}
indicesDst[indexCount] = srcPtr[0];
}
else
{
memcpy(indices, srcPtr, unitSize * indexCount);
memcpy(indices + unitSize * indexCount, srcPtr, unitSize);
}
}
ANGLE_TRY(mDynamicIndexBuffer.flush(contextVk));
return angle::Result::Continue;
}
angle::Result LineLoopHelper::streamIndicesIndirect(ContextVk *contextVk,
gl::DrawElementsType glIndexType,
BufferHelper *indexBuffer,
BufferHelper *indirectBuffer,
VkDeviceSize indirectBufferOffset,
BufferHelper **indexBufferOut,
VkDeviceSize *indexBufferOffsetOut,
BufferHelper **indirectBufferOut,
VkDeviceSize *indirectBufferOffsetOut)
{
size_t unitSize = contextVk->getVkIndexTypeSize(glIndexType);
size_t allocateBytes = static_cast<size_t>(indexBuffer->getSize() + unitSize);
if (contextVk->getState().isPrimitiveRestartEnabled())
{
// If primitive restart, new index buffer is 135% the size of the original index buffer. The
// smallest lineloop with primitive restart is 3 indices (point 1, point 2 and restart
// value) when converted to linelist becomes 4 vertices. Expansion of 4/3. Any larger
// lineloops would have less overhead and require less extra space. Any incomplete
// primitives can be dropped or left incomplete and thus not increase the size of the
// destination index buffer. Since we don't know the number of indices being used we'll use
// the size of the index buffer as allocated as the index count.
size_t numInputIndices = static_cast<size_t>(indexBuffer->getSize() / unitSize);
size_t numNewInputIndices = ((numInputIndices * 4) / 3) + 1;
allocateBytes = static_cast<size_t>(numNewInputIndices * unitSize);
}
mDynamicIndexBuffer.releaseInFlightBuffers(contextVk);
mDynamicIndirectBuffer.releaseInFlightBuffers(contextVk);
ANGLE_TRY(mDynamicIndexBuffer.allocate(contextVk, allocateBytes, nullptr, nullptr,
indexBufferOffsetOut, nullptr));
*indexBufferOut = mDynamicIndexBuffer.getCurrentBuffer();
ANGLE_TRY(mDynamicIndirectBuffer.allocate(contextVk, sizeof(VkDrawIndexedIndirectCommand),
nullptr, nullptr, indirectBufferOffsetOut, nullptr));
*indirectBufferOut = mDynamicIndirectBuffer.getCurrentBuffer();
BufferHelper *destIndexBuffer = mDynamicIndexBuffer.getCurrentBuffer();
BufferHelper *destIndirectBuffer = mDynamicIndirectBuffer.getCurrentBuffer();
// Copy relevant section of the source into destination at allocated offset. Note that the
// offset returned by allocate() above is in bytes. As is the indices offset pointer.
UtilsVk::ConvertLineLoopIndexIndirectParameters params = {};
params.indirectBufferOffset = static_cast<uint32_t>(indirectBufferOffset);
params.dstIndirectBufferOffset = static_cast<uint32_t>(*indirectBufferOffsetOut);
params.dstIndexBufferOffset = static_cast<uint32_t>(*indexBufferOffsetOut);
params.indicesBitsWidth = static_cast<uint32_t>(unitSize * 8);
ANGLE_TRY(contextVk->getUtils().convertLineLoopIndexIndirectBuffer(
contextVk, indirectBuffer, destIndirectBuffer, destIndexBuffer, indexBuffer, params));
return angle::Result::Continue;
}
angle::Result LineLoopHelper::streamArrayIndirect(ContextVk *contextVk,
size_t vertexCount,
BufferHelper *arrayIndirectBuffer,
VkDeviceSize arrayIndirectBufferOffset,
BufferHelper **indexBufferOut,
VkDeviceSize *indexBufferOffsetOut,
BufferHelper **indexIndirectBufferOut,
VkDeviceSize *indexIndirectBufferOffsetOut)
{
auto unitSize = sizeof(uint32_t);
size_t allocateBytes = static_cast<size_t>((vertexCount + 1) * unitSize);
mDynamicIndexBuffer.releaseInFlightBuffers(contextVk);
mDynamicIndirectBuffer.releaseInFlightBuffers(contextVk);
ANGLE_TRY(mDynamicIndexBuffer.allocate(contextVk, allocateBytes, nullptr, nullptr,
indexBufferOffsetOut, nullptr));
*indexBufferOut = mDynamicIndexBuffer.getCurrentBuffer();
ANGLE_TRY(mDynamicIndirectBuffer.allocate(contextVk, sizeof(VkDrawIndexedIndirectCommand),
nullptr, nullptr, indexIndirectBufferOffsetOut,
nullptr));
*indexIndirectBufferOut = mDynamicIndirectBuffer.getCurrentBuffer();
BufferHelper *destIndexBuffer = mDynamicIndexBuffer.getCurrentBuffer();
BufferHelper *destIndirectBuffer = mDynamicIndirectBuffer.getCurrentBuffer();
// Copy relevant section of the source into destination at allocated offset. Note that the
// offset returned by allocate() above is in bytes. As is the indices offset pointer.
UtilsVk::ConvertLineLoopArrayIndirectParameters params = {};
params.indirectBufferOffset = static_cast<uint32_t>(arrayIndirectBufferOffset);
params.dstIndirectBufferOffset = static_cast<uint32_t>(*indexIndirectBufferOffsetOut);
params.dstIndexBufferOffset = static_cast<uint32_t>(*indexBufferOffsetOut);
ANGLE_TRY(contextVk->getUtils().convertLineLoopArrayIndirectBuffer(
contextVk, arrayIndirectBuffer, destIndirectBuffer, destIndexBuffer, params));
return angle::Result::Continue;
}
void LineLoopHelper::release(ContextVk *contextVk)
{
mDynamicIndexBuffer.release(contextVk->getRenderer());
mDynamicIndirectBuffer.release(contextVk->getRenderer());
}
void LineLoopHelper::destroy(RendererVk *renderer)
{
mDynamicIndexBuffer.destroy(renderer);
mDynamicIndirectBuffer.destroy(renderer);
}
// static
void LineLoopHelper::Draw(uint32_t count, uint32_t baseVertex, CommandBuffer *commandBuffer)
{
// Our first index is always 0 because that's how we set it up in createIndexBuffer*.
commandBuffer->drawIndexedBaseVertex(count, baseVertex);
}
// PipelineBarrier implementation.
void PipelineBarrier::addDiagnosticsString(std::ostringstream &out) const
{
if (mMemoryBarrierSrcAccess != 0 || mMemoryBarrierDstAccess != 0)
{
out << "Src: 0x" << std::hex << mMemoryBarrierSrcAccess << " → Dst: 0x" << std::hex
<< mMemoryBarrierDstAccess << std::endl;
}
}
// BufferHelper implementation.
BufferHelper::BufferHelper()
: mMemoryPropertyFlags{},
mSize(0),
mMappedMemory(nullptr),
mViewFormat(nullptr),
mCurrentQueueFamilyIndex(std::numeric_limits<uint32_t>::max()),
mCurrentWriteAccess(0),
mCurrentReadAccess(0),
mCurrentWriteStages(0),
mCurrentReadStages(0),
mSerial()
{}
BufferHelper::~BufferHelper() = default;
angle::Result BufferHelper::init(ContextVk *contextVk,
const VkBufferCreateInfo &requestedCreateInfo,
VkMemoryPropertyFlags memoryPropertyFlags)
{
RendererVk *renderer = contextVk->getRenderer();
mSerial = renderer->getResourceSerialFactory().generateBufferSerial();
mSize = requestedCreateInfo.size;
VkBufferCreateInfo modifiedCreateInfo;
const VkBufferCreateInfo *createInfo = &requestedCreateInfo;
if (renderer->getFeatures().padBuffersToMaxVertexAttribStride.enabled)
{
const VkDeviceSize maxVertexAttribStride = renderer->getMaxVertexAttribStride();
ASSERT(maxVertexAttribStride);
modifiedCreateInfo = requestedCreateInfo;
modifiedCreateInfo.size += maxVertexAttribStride;
createInfo = &modifiedCreateInfo;
}
VkMemoryPropertyFlags requiredFlags =
(memoryPropertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);
VkMemoryPropertyFlags preferredFlags =
(memoryPropertyFlags & (~VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT));
const Allocator &allocator = renderer->getAllocator();
bool persistentlyMapped = renderer->getFeatures().persistentlyMappedBuffers.enabled;
// Check that the allocation is not too large.
uint32_t memoryTypeIndex = 0;
ANGLE_VK_TRY(contextVk, allocator.findMemoryTypeIndexForBufferInfo(
*createInfo, requiredFlags, preferredFlags, persistentlyMapped,
&memoryTypeIndex));
VkDeviceSize heapSize =
renderer->getMemoryProperties().getHeapSizeForMemoryType(memoryTypeIndex);
ANGLE_VK_CHECK(contextVk, createInfo->size <= heapSize, VK_ERROR_OUT_OF_DEVICE_MEMORY);
ANGLE_VK_TRY(contextVk, allocator.createBuffer(*createInfo, requiredFlags, preferredFlags,
persistentlyMapped, &memoryTypeIndex, &mBuffer,
&mAllocation));
allocator.getMemoryTypeProperties(memoryTypeIndex, &mMemoryPropertyFlags);
mCurrentQueueFamilyIndex = renderer->getQueueFamilyIndex();
if (renderer->getFeatures().allocateNonZeroMemory.enabled)
{
// This memory can't be mapped, so the buffer must be marked as a transfer destination so we
// can use a staging resource to initialize it to a non-zero value. If the memory is
// mappable we do the initialization in AllocateBufferMemory.
if ((mMemoryPropertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0 &&
(requestedCreateInfo.usage & VK_BUFFER_USAGE_TRANSFER_DST_BIT) != 0)
{
ANGLE_TRY(initializeNonZeroMemory(contextVk, createInfo->size));
}
else if ((mMemoryPropertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0)
{
// Can map the memory.
// Pick an arbitrary value to initialize non-zero memory for sanitization.
constexpr int kNonZeroInitValue = 55;
ANGLE_TRY(InitMappableAllocation(contextVk, allocator, &mAllocation, mSize,
kNonZeroInitValue, mMemoryPropertyFlags));
}
}
return angle::Result::Continue;
}
angle::Result BufferHelper::initializeNonZeroMemory(Context *context, VkDeviceSize size)
{
// Staging buffer memory is non-zero-initialized in 'init'.
StagingBuffer stagingBuffer;
ANGLE_TRY(stagingBuffer.init(context, size, StagingUsage::Both));
RendererVk *renderer = context->getRenderer();
PrimaryCommandBuffer commandBuffer;
ANGLE_TRY(renderer->getCommandBufferOneOff(context, &commandBuffer));
// Queue a DMA copy.
VkBufferCopy copyRegion = {};
copyRegion.srcOffset = 0;
copyRegion.dstOffset = 0;
copyRegion.size = size;
commandBuffer.copyBuffer(stagingBuffer.getBuffer(), mBuffer, 1, ©Region);
ANGLE_VK_TRY(context, commandBuffer.end());
Serial serial;
ANGLE_TRY(renderer->queueSubmitOneOff(context, std::move(commandBuffer),
egl::ContextPriority::Medium, nullptr, &serial));
stagingBuffer.collectGarbage(renderer, serial);
mUse.updateSerialOneOff(serial);
return angle::Result::Continue;
}
void BufferHelper::destroy(RendererVk *renderer)
{
VkDevice device = renderer->getDevice();
unmap(renderer);
mSize = 0;
mViewFormat = nullptr;
mBuffer.destroy(device);
mBufferView.destroy(device);
mAllocation.destroy(renderer->getAllocator());
}
void BufferHelper::release(RendererVk *renderer)
{
unmap(renderer);
mSize = 0;
mViewFormat = nullptr;
renderer->collectGarbageAndReinit(&mUse, &mBuffer, &mBufferView, &mAllocation);
}
angle::Result BufferHelper::copyFromBuffer(ContextVk *contextVk,
BufferHelper *srcBuffer,
uint32_t regionCount,
const VkBufferCopy *copyRegions)
{
ANGLE_TRY(contextVk->onBufferTransferRead(srcBuffer));
ANGLE_TRY(contextVk->onBufferTransferWrite(this));
CommandBuffer &commandBuffer = contextVk->getOutsideRenderPassCommandBuffer();
commandBuffer.copyBuffer(srcBuffer->getBuffer(), mBuffer, regionCount, copyRegions);
return angle::Result::Continue;
}
angle::Result BufferHelper::initBufferView(ContextVk *contextVk, const Format &format)
{
ASSERT(format.valid());
if (mBufferView.valid())
{
ASSERT(mViewFormat->vkBufferFormat == format.vkBufferFormat);
return angle::Result::Continue;
}
VkBufferViewCreateInfo viewCreateInfo = {};
viewCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO;
viewCreateInfo.buffer = mBuffer.getHandle();
viewCreateInfo.format = format.vkBufferFormat;
viewCreateInfo.offset = 0;
viewCreateInfo.range = mSize;
ANGLE_VK_TRY(contextVk, mBufferView.init(contextVk->getDevice(), viewCreateInfo));
mViewFormat = &format;
return angle::Result::Continue;
}
angle::Result BufferHelper::mapImpl(ContextVk *contextVk)
{
ANGLE_VK_TRY(contextVk,
mAllocation.map(contextVk->getRenderer()->getAllocator(), &mMappedMemory));
return angle::Result::Continue;
}
void BufferHelper::unmap(RendererVk *renderer)
{
if (mMappedMemory)
{
mAllocation.unmap(renderer->getAllocator());
mMappedMemory = nullptr;
}
}
angle::Result BufferHelper::flush(RendererVk *renderer, VkDeviceSize offset, VkDeviceSize size)
{
bool hostVisible = mMemoryPropertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
bool hostCoherent = mMemoryPropertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
if (hostVisible && !hostCoherent)
{
mAllocation.flush(renderer->getAllocator(), offset, size);
}
return angle::Result::Continue;
}
angle::Result BufferHelper::invalidate(RendererVk *renderer, VkDeviceSize offset, VkDeviceSize size)
{
bool hostVisible = mMemoryPropertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
bool hostCoherent = mMemoryPropertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
if (hostVisible && !hostCoherent)
{
mAllocation.invalidate(renderer->getAllocator(), offset, size);
}
return angle::Result::Continue;
}
void BufferHelper::changeQueue(uint32_t newQueueFamilyIndex, CommandBuffer *commandBuffer)
{
VkBufferMemoryBarrier bufferMemoryBarrier = {};
bufferMemoryBarrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
bufferMemoryBarrier.srcAccessMask = 0;
bufferMemoryBarrier.dstAccessMask = 0;
bufferMemoryBarrier.srcQueueFamilyIndex = mCurrentQueueFamilyIndex;
bufferMemoryBarrier.dstQueueFamilyIndex = newQueueFamilyIndex;
bufferMemoryBarrier.buffer = mBuffer.getHandle();
bufferMemoryBarrier.offset = 0;
bufferMemoryBarrier.size = VK_WHOLE_SIZE;
commandBuffer->bufferBarrier(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, &bufferMemoryBarrier);
mCurrentQueueFamilyIndex = newQueueFamilyIndex;
}
void BufferHelper::acquireFromExternal(ContextVk *contextVk,
uint32_t externalQueueFamilyIndex,
uint32_t rendererQueueFamilyIndex,
CommandBuffer *commandBuffer)
{
mCurrentQueueFamilyIndex = externalQueueFamilyIndex;
changeQueue(rendererQueueFamilyIndex, commandBuffer);
}
void BufferHelper::releaseToExternal(ContextVk *contextVk,
uint32_t rendererQueueFamilyIndex,
uint32_t externalQueueFamilyIndex,
CommandBuffer *commandBuffer)
{
ASSERT(mCurrentQueueFamilyIndex == rendererQueueFamilyIndex);
changeQueue(externalQueueFamilyIndex, commandBuffer);
}
bool BufferHelper::isReleasedToExternal() const
{
#if !defined(ANGLE_PLATFORM_MACOS) && !defined(ANGLE_PLATFORM_ANDROID)
return IsExternalQueueFamily(mCurrentQueueFamilyIndex);
#else
// TODO(anglebug.com/4635): Implement external memory barriers on Mac/Android.
return false;
#endif
}
bool BufferHelper::recordReadBarrier(VkAccessFlags readAccessType,
VkPipelineStageFlags readStage,
PipelineBarrier *barrier)
{
bool barrierModified = false;
// If there was a prior write and we are making a read that is either a new access type or from
// a new stage, we need a barrier
if (mCurrentWriteAccess != 0 && (((mCurrentReadAccess & readAccessType) != readAccessType) ||
((mCurrentReadStages & readStage) != readStage)))
{
barrier->mergeMemoryBarrier(mCurrentWriteStages, readStage, mCurrentWriteAccess,
readAccessType);
barrierModified = true;
}
// Accumulate new read usage.
mCurrentReadAccess |= readAccessType;
mCurrentReadStages |= readStage;
return barrierModified;
}
bool BufferHelper::recordWriteBarrier(VkAccessFlags writeAccessType,
VkPipelineStageFlags writeStage,
PipelineBarrier *barrier)
{
bool barrierModified = false;
// We don't need to check mCurrentReadStages here since if it is not zero, mCurrentReadAccess
// must not be zero as well. stage is finer grain than accessType.
ASSERT((!mCurrentReadStages && !mCurrentReadAccess) ||
(mCurrentReadStages && mCurrentReadAccess));
if (mCurrentReadAccess != 0 || mCurrentWriteAccess != 0)
{
barrier->mergeMemoryBarrier(mCurrentWriteStages | mCurrentReadStages, writeStage,
mCurrentWriteAccess, writeAccessType);
barrierModified = true;
}
// Reset usages on the new write.
mCurrentWriteAccess = writeAccessType;
mCurrentReadAccess = 0;
mCurrentWriteStages = writeStage;
mCurrentReadStages = 0;
return barrierModified;
}
// ImageHelper implementation.
ImageHelper::ImageHelper()
{
resetCachedProperties();
}
ImageHelper::ImageHelper(ImageHelper &&other)
: Resource(std::move(other)),
mImage(std::move(other.mImage)),
mDeviceMemory(std::move(other.mDeviceMemory)),
mImageType(other.mImageType),
mTilingMode(other.mTilingMode),
mUsage(other.mUsage),
mExtents(other.mExtents),
mFormat(other.mFormat),
mSamples(other.mSamples),
mImageSerial(other.mImageSerial),
mCurrentLayout(other.mCurrentLayout),
mCurrentQueueFamilyIndex(other.mCurrentQueueFamilyIndex),
mLastNonShaderReadOnlyLayout(other.mLastNonShaderReadOnlyLayout),
mCurrentShaderReadStageMask(other.mCurrentShaderReadStageMask),
mYuvConversionSampler(std::move(other.mYuvConversionSampler)),
mExternalFormat(other.mExternalFormat),
mBaseLevel(other.mBaseLevel),
mMaxLevel(other.mMaxLevel),
mLayerCount(other.mLayerCount),
mLevelCount(other.mLevelCount),
mStagingBuffer(std::move(other.mStagingBuffer)),
mSubresourceUpdates(std::move(other.mSubresourceUpdates)),
mCurrentSingleClearValue(std::move(other.mCurrentSingleClearValue))
{
ASSERT(this != &other);
other.resetCachedProperties();
}
ImageHelper::~ImageHelper()
{
ASSERT(!valid());
}
void ImageHelper::resetCachedProperties()
{
mImageType = VK_IMAGE_TYPE_2D;
mTilingMode = VK_IMAGE_TILING_OPTIMAL;
mUsage = 0;
mExtents = {};
mFormat = nullptr;
mSamples = 1;
mImageSerial = kInvalidImageSerial;
mCurrentLayout = ImageLayout::Undefined;
mCurrentQueueFamilyIndex = std::numeric_limits<uint32_t>::max();
mLastNonShaderReadOnlyLayout = ImageLayout::Undefined;
mCurrentShaderReadStageMask = 0;
mBaseLevel = gl::LevelIndex(0);
mMaxLevel = gl::LevelIndex(0);
mLayerCount = 0;
mLevelCount = 0;
mExternalFormat = 0;
mCurrentSingleClearValue.reset();
}
void ImageHelper::initStagingBuffer(RendererVk *renderer,
size_t imageCopyBufferAlignment,
VkBufferUsageFlags usageFlags,
size_t initialSize)
{
mStagingBuffer.init(renderer, usageFlags, imageCopyBufferAlignment, initialSize, true);
}
angle::Result ImageHelper::init(Context *context,
gl::TextureType textureType,
const VkExtent3D &extents,
const Format &format,
GLint samples,
VkImageUsageFlags usage,
gl::LevelIndex baseLevel,
gl::LevelIndex maxLevel,
uint32_t mipLevels,
uint32_t layerCount)
{
return initExternal(context, textureType, extents, format, samples, usage,
kVkImageCreateFlagsNone, ImageLayout::Undefined, nullptr, baseLevel,
maxLevel, mipLevels, layerCount);
}
angle::Result ImageHelper::initExternal(Context *context,
gl::TextureType textureType,
const VkExtent3D &extents,
const Format &format,
GLint samples,
VkImageUsageFlags usage,
VkImageCreateFlags additionalCreateFlags,
ImageLayout initialLayout,
const void *externalImageCreateInfo,
gl::LevelIndex baseLevel,
gl::LevelIndex maxLevel,
uint32_t mipLevels,
uint32_t layerCount)
{
ASSERT(!valid());
mImageType = gl_vk::GetImageType(textureType);
mExtents = extents;
mFormat = &format;
mSamples = std::max(samples, 1);
mImageSerial = context->getRenderer()->getResourceSerialFactory().generateImageSerial();
mBaseLevel = baseLevel;
mMaxLevel = maxLevel;
mLevelCount = mipLevels;
mLayerCount = layerCount;
mUsage = usage;
// Validate that mLayerCount is compatible with the texture type
ASSERT(textureType != gl::TextureType::_3D || mLayerCount == 1);
ASSERT(textureType != gl::TextureType::_2DArray || mExtents.depth == 1);
ASSERT(textureType != gl::TextureType::External || mLayerCount == 1);
ASSERT(textureType != gl::TextureType::Rectangle || mLayerCount == 1);
ASSERT(textureType != gl::TextureType::CubeMap || mLayerCount == gl::kCubeFaceCount);
VkImageCreateInfo imageInfo = {};
imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
imageInfo.pNext = externalImageCreateInfo;
imageInfo.flags = GetImageCreateFlags(textureType) | additionalCreateFlags;
imageInfo.imageType = mImageType;
imageInfo.format = format.vkImageFormat;
imageInfo.extent = mExtents;
imageInfo.mipLevels = mipLevels;
imageInfo.arrayLayers = mLayerCount;
imageInfo.samples = gl_vk::GetSamples(mSamples);
imageInfo.tiling = mTilingMode;
imageInfo.usage = mUsage;
imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
imageInfo.queueFamilyIndexCount = 0;
imageInfo.pQueueFamilyIndices = nullptr;
imageInfo.initialLayout = ConvertImageLayoutToVkImageLayout(initialLayout);
mCurrentLayout = initialLayout;
mYuvConversionSampler.reset();
mExternalFormat = 0;
ANGLE_VK_TRY(context, mImage.init(context->getDevice(), imageInfo));
stageClearIfEmulatedFormat(context);
return angle::Result::Continue;
}
void ImageHelper::releaseImage(RendererVk *renderer)
{
renderer->collectGarbageAndReinit(&mUse, &mImage, &mDeviceMemory);
mImageSerial = kInvalidImageSerial;
}
void ImageHelper::releaseStagingBuffer(RendererVk *renderer)
{
// Remove updates that never made it to the texture.
for (SubresourceUpdate &update : mSubresourceUpdates)
{
update.release(renderer);
}
mStagingBuffer.release(renderer);
mSubresourceUpdates.clear();
mCurrentSingleClearValue.reset();
}
void ImageHelper::resetImageWeakReference()
{
mImage.reset();
mImageSerial = kInvalidImageSerial;
}
angle::Result ImageHelper::initializeNonZeroMemory(Context *context, VkDeviceSize size)
{
const angle::Format &angleFormat = mFormat->actualImageFormat();
bool isCompressedFormat = angleFormat.isBlock;
RendererVk *renderer = context->getRenderer();
PrimaryCommandBuffer commandBuffer;
ANGLE_TRY(renderer->getCommandBufferOneOff(context, &commandBuffer));
// Queue a DMA copy.
barrierImpl(getAspectFlags(), ImageLayout::TransferDst, mCurrentQueueFamilyIndex,
&commandBuffer);
StagingBuffer stagingBuffer;
if (isCompressedFormat)
{
// If format is compressed, set its contents through buffer copies.
// The staging buffer memory is non-zero-initialized in 'init'.
ANGLE_TRY(stagingBuffer.init(context, size, StagingUsage::Write));
for (LevelIndex level(0); level < LevelIndex(mLevelCount); ++level)
{
VkBufferImageCopy copyRegion = {};
gl_vk::GetExtent(getLevelExtents(level), ©Region.imageExtent);
copyRegion.imageSubresource.aspectMask = getAspectFlags();
copyRegion.imageSubresource.layerCount = mLayerCount;
// If image has depth and stencil, copy to each individually per Vulkan spec.
bool hasBothDepthAndStencil = isCombinedDepthStencilFormat();
if (hasBothDepthAndStencil)
{
copyRegion.imageSubresource.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
}
commandBuffer.copyBufferToImage(stagingBuffer.getBuffer().getHandle(), mImage,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©Region);
if (hasBothDepthAndStencil)
{
copyRegion.imageSubresource.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
commandBuffer.copyBufferToImage(stagingBuffer.getBuffer().getHandle(), mImage,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1,
©Region);
}
}
}
else
{
// Otherwise issue clear commands.
VkImageSubresourceRange subresource = {};
subresource.aspectMask = getAspectFlags();
subresource.baseMipLevel = 0;
subresource.levelCount = mLevelCount;
subresource.baseArrayLayer = 0;
subresource.layerCount = mLayerCount;
// Arbitrary value to initialize the memory with. Note: the given uint value, reinterpreted
// as float is about 0.7.
constexpr uint32_t kInitValue = 0x3F345678;
constexpr float kInitValueFloat = 0.12345f;
if ((subresource.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) != 0)
{
VkClearColorValue clearValue;
clearValue.uint32[0] = kInitValue;
clearValue.uint32[1] = kInitValue;
clearValue.uint32[2] = kInitValue;
clearValue.uint32[3] = kInitValue;
commandBuffer.clearColorImage(mImage, getCurrentLayout(), clearValue, 1, &subresource);
}
else
{
VkClearDepthStencilValue clearValue;
clearValue.depth = kInitValueFloat;
clearValue.stencil = kInitValue;
commandBuffer.clearDepthStencilImage(mImage, getCurrentLayout(), clearValue, 1,
&subresource);
}
}
ANGLE_VK_TRY(context, commandBuffer.end());
Serial serial;
ANGLE_TRY(renderer->queueSubmitOneOff(context, std::move(commandBuffer),
egl::ContextPriority::Medium, nullptr, &serial));
if (isCompressedFormat)
{
stagingBuffer.collectGarbage(renderer, serial);
}
mUse.updateSerialOneOff(serial);
return angle::Result::Continue;
}
angle::Result ImageHelper::initMemory(Context *context,
const MemoryProperties &memoryProperties,
VkMemoryPropertyFlags flags)
{
// TODO(jmadill): Memory sub-allocation. http://anglebug.com/2162
VkDeviceSize size;
ANGLE_TRY(AllocateImageMemory(context, flags, &flags, nullptr, &mImage, &mDeviceMemory, &size));
mCurrentQueueFamilyIndex = context->getRenderer()->getQueueFamilyIndex();
RendererVk *renderer = context->getRenderer();
if (renderer->getFeatures().allocateNonZeroMemory.enabled)
{
// Can't map the memory. Use a staging resource.
if ((flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0)
{
ANGLE_TRY(initializeNonZeroMemory(context, size));
}
}
return angle::Result::Continue;
}
angle::Result ImageHelper::initExternalMemory(
Context *context,
const MemoryProperties &memoryProperties,
const VkMemoryRequirements &memoryRequirements,
const VkSamplerYcbcrConversionCreateInfo *samplerYcbcrConversionCreateInfo,
const void *extraAllocationInfo,
uint32_t currentQueueFamilyIndex,
VkMemoryPropertyFlags flags)
{
// TODO(jmadill): Memory sub-allocation. http://anglebug.com/2162
ANGLE_TRY(AllocateImageMemoryWithRequirements(context, flags, memoryRequirements,
extraAllocationInfo, &mImage, &mDeviceMemory));
mCurrentQueueFamilyIndex = currentQueueFamilyIndex;
#ifdef VK_USE_PLATFORM_ANDROID_KHR
if (samplerYcbcrConversionCreateInfo)
{
const VkExternalFormatANDROID *vkExternalFormat =
reinterpret_cast<const VkExternalFormatANDROID *>(
samplerYcbcrConversionCreateInfo->pNext);
ASSERT(vkExternalFormat->sType == VK_STRUCTURE_TYPE_EXTERNAL_FORMAT_ANDROID);
mExternalFormat = vkExternalFormat->externalFormat;
ANGLE_TRY(context->getRenderer()->getYuvConversionCache().getYuvConversion(
context, mExternalFormat, *samplerYcbcrConversionCreateInfo, &mYuvConversionSampler));
}
#endif
return angle::Result::Continue;
}
angle::Result ImageHelper::initImageView(Context *context,
gl::TextureType textureType,
VkImageAspectFlags aspectMask,
const gl::SwizzleState &swizzleMap,
ImageView *imageViewOut,
LevelIndex baseMipLevelVk,
uint32_t levelCount)
{
return initLayerImageView(context, textureType, aspectMask, swizzleMap, imageViewOut,
baseMipLevelVk, levelCount, 0, mLayerCount);
}
angle::Result ImageHelper::initLayerImageView(Context *context,
gl::TextureType textureType,
VkImageAspectFlags aspectMask,
const gl::SwizzleState &swizzleMap,
ImageView *imageViewOut,
LevelIndex baseMipLevelVk,
uint32_t levelCount,
uint32_t baseArrayLayer,
uint32_t layerCount) const
{
return initLayerImageViewImpl(context, textureType, aspectMask, swizzleMap, imageViewOut,
baseMipLevelVk, levelCount, baseArrayLayer, layerCount,
mFormat->vkImageFormat, nullptr);
}
angle::Result ImageHelper::initLayerImageViewImpl(
Context *context,
gl::TextureType textureType,
VkImageAspectFlags aspectMask,
const gl::SwizzleState &swizzleMap,
ImageView *imageViewOut,
LevelIndex baseMipLevelVk,
uint32_t levelCount,
uint32_t baseArrayLayer,
uint32_t layerCount,
VkFormat imageFormat,
const VkImageViewUsageCreateInfo *imageViewUsageCreateInfo) const
{
VkImageViewCreateInfo viewInfo = {};
viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
viewInfo.flags = 0;
viewInfo.image = mImage.getHandle();
viewInfo.viewType = gl_vk::GetImageViewType(textureType);
viewInfo.format = imageFormat;
if (swizzleMap.swizzleRequired() && !mYuvConversionSampler.valid())
{
viewInfo.components.r = gl_vk::GetSwizzle(swizzleMap.swizzleRed);
viewInfo.components.g = gl_vk::GetSwizzle(swizzleMap.swizzleGreen);
viewInfo.components.b = gl_vk::GetSwizzle(swizzleMap.swizzleBlue);
viewInfo.components.a = gl_vk::GetSwizzle(swizzleMap.swizzleAlpha);
}
else
{
viewInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
viewInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
viewInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
viewInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
}
viewInfo.subresourceRange.aspectMask = aspectMask;
viewInfo.subresourceRange.baseMipLevel = baseMipLevelVk.get();
viewInfo.subresourceRange.levelCount = levelCount;
viewInfo.subresourceRange.baseArrayLayer = baseArrayLayer;
viewInfo.subresourceRange.layerCount = layerCount;
viewInfo.pNext = imageViewUsageCreateInfo;
VkSamplerYcbcrConversionInfo yuvConversionInfo = {};
if (mYuvConversionSampler.valid())
{
ASSERT((context->getRenderer()->getFeatures().supportsYUVSamplerConversion.enabled));
yuvConversionInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO;
yuvConversionInfo.pNext = nullptr;
yuvConversionInfo.conversion = mYuvConversionSampler.get().getHandle();
AddToPNextChain(&viewInfo, &yuvConversionInfo);
}
ANGLE_VK_TRY(context, imageViewOut->init(context->getDevice(), viewInfo));
return angle::Result::Continue;
}
angle::Result ImageHelper::initAliasedLayerImageView(Context *context,
gl::TextureType textureType,
VkImageAspectFlags aspectMask,
const gl::SwizzleState &swizzleMap,
ImageView *imageViewOut,
LevelIndex baseMipLevelVk,
uint32_t levelCount,
uint32_t baseArrayLayer,
uint32_t layerCount,
VkImageUsageFlags imageUsageFlags,
VkFormat imageViewFormat) const
{
VkImageViewUsageCreateInfo imageViewUsageCreateInfo = {};
imageViewUsageCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO;
imageViewUsageCreateInfo.usage =
imageUsageFlags & GetMaximalImageUsageFlags(context->getRenderer(), imageViewFormat);
return initLayerImageViewImpl(context, textureType, aspectMask, swizzleMap, imageViewOut,
baseMipLevelVk, levelCount, baseArrayLayer, layerCount,
imageViewFormat, &imageViewUsageCreateInfo);
}
void ImageHelper::destroy(RendererVk *renderer)
{
VkDevice device = renderer->getDevice();
mImage.destroy(device);
mDeviceMemory.destroy(device);
mStagingBuffer.destroy(renderer);
mCurrentLayout = ImageLayout::Undefined;
mImageType = VK_IMAGE_TYPE_2D;
mLayerCount = 0;
mLevelCount = 0;
}
void ImageHelper::init2DWeakReference(Context *context,
VkImage handle,
const gl::Extents &glExtents,
const Format &format,
GLint samples)
{
ASSERT(!valid());
gl_vk::GetExtent(glExtents, &mExtents);
mFormat = &format;
mSamples = std::max(samples, 1);
mImageSerial = context->getRenderer()->getResourceSerialFactory().generateImageSerial();
mCurrentLayout = ImageLayout::Undefined;
mLayerCount = 1;
mLevelCount = 1;
mImage.setHandle(handle);
stageClearIfEmulatedFormat(context);
}
angle::Result ImageHelper::init2DStaging(Context *context,
const MemoryProperties &memoryProperties,
const gl::Extents &glExtents,
const Format &format,
VkImageUsageFlags usage,
uint32_t layerCount)
{
ASSERT(!valid());
gl_vk::GetExtent(glExtents, &mExtents);
mImageType = VK_IMAGE_TYPE_2D;
mFormat = &format;
mSamples = 1;
mImageSerial = context->getRenderer()->getResourceSerialFactory().generateImageSerial();
mLayerCount = layerCount;
mLevelCount = 1;
mCurrentLayout = ImageLayout::Undefined;
VkImageCreateInfo imageInfo = {};
imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
imageInfo.flags = 0;
imageInfo.imageType = mImageType;
imageInfo.format = format.vkImageFormat;
imageInfo.extent = mExtents;
imageInfo.mipLevels = 1;
imageInfo.arrayLayers = mLayerCount;
imageInfo.samples = gl_vk::GetSamples(mSamples);
imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
imageInfo.usage = usage;
imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
imageInfo.queueFamilyIndexCount = 0;
imageInfo.pQueueFamilyIndices = nullptr;
imageInfo.initialLayout = getCurrentLayout();
ANGLE_VK_TRY(context, mImage.init(context->getDevice(), imageInfo));
// Allocate and bind device-local memory.
VkMemoryPropertyFlags memoryPropertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
ANGLE_TRY(initMemory(context, memoryProperties, memoryPropertyFlags));
return angle::Result::Continue;
}
angle::Result ImageHelper::initImplicitMultisampledRenderToTexture(
Context *context,
const MemoryProperties &memoryProperties,
gl::TextureType textureType,
GLint samples,
const ImageHelper &resolveImage)
{
ASSERT(!valid());
ASSERT(samples > 1);
// The image is used as either color or depth/stencil attachment. Additionally, its memory is
// lazily allocated as the contents are discarded at the end of the renderpass and with tiling
// GPUs no actual backing memory is required.
//
// Note that the Vulkan image is created with or without VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT
// based on whether the memory that will be used to create the image would have
// VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT. TRANSIENT is provided if there is any memory that
// supports LAZILY_ALLOCATED. However, based on actual image requirements, such a memory may
// not be suitable for the image. We don't support such a case, which will result in the
// |initMemory| call below failing.
const bool hasLazilyAllocatedMemory = memoryProperties.hasLazilyAllocatedMemory();
const VkImageUsageFlags kMultisampledUsageFlags =
(hasLazilyAllocatedMemory ? VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT : 0) |
(resolveImage.getAspectFlags() == VK_IMAGE_ASPECT_COLOR_BIT
? VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT
: VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT);
constexpr VkImageCreateFlags kMultisampledCreateFlags = 0;
ANGLE_TRY(initExternal(context, textureType, resolveImage.getExtents(),
resolveImage.getFormat(), samples, kMultisampledUsageFlags,
kMultisampledCreateFlags, ImageLayout::Undefined, nullptr,
resolveImage.getBaseLevel(), resolveImage.getMaxLevel(),
resolveImage.getLevelCount(), resolveImage.getLayerCount()));
const VkMemoryPropertyFlags kMultisampledMemoryFlags =
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
(hasLazilyAllocatedMemory ? VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT : 0);
// If this ever fails, this code should be modified to retry creating the image without the
// TRANSIENT flag.
ANGLE_TRY(initMemory(context, memoryProperties, kMultisampledMemoryFlags));
// Remove the emulated format clear from the multisampled image if any. There is one already
// staged on the resolve image if needed.
removeStagedUpdates(context, getBaseLevel(), getMaxLevel());
return angle::Result::Continue;
}
VkImageAspectFlags ImageHelper::getAspectFlags() const
{
return GetFormatAspectFlags(mFormat->actualImageFormat());
}
bool ImageHelper::isCombinedDepthStencilFormat() const
{
return ((VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT) & getAspectFlags()) ==
(VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT);
}
VkImageLayout ImageHelper::getCurrentLayout() const
{
return ConvertImageLayoutToVkImageLayout(mCurrentLayout);
}
gl::Extents ImageHelper::getLevelExtents(LevelIndex levelVk) const
{
// Level 0 should be the size of the extents, after that every time you increase a level
// you shrink the extents by half.
uint32_t width = std::max(mExtents.width >> levelVk.get(), 1u);
uint32_t height = std::max(mExtents.height >> levelVk.get(), 1u);
uint32_t depth = std::max(mExtents.depth >> levelVk.get(), 1u);
return gl::Extents(width, height, depth);
}
gl::Extents ImageHelper::getLevelExtents2D(LevelIndex levelVk) const
{
gl::Extents extents = getLevelExtents(levelVk);
extents.depth = 1;
return extents;
}
bool ImageHelper::isDepthOrStencil() const
{
return mFormat->actualImageFormat().hasDepthOrStencilBits();
}
bool ImageHelper::isReadBarrierNecessary(ImageLayout newLayout) const
{
// If transitioning to a different layout, we need always need a barrier.
if (mCurrentLayout != newLayout)
{
return true;
}
// RAR (read-after-read) is not a hazard and doesn't require a barrier.
//
// RAW (read-after-write) hazards always require a memory barrier. This can only happen if the
// layout (same as new layout) is writable which in turn is only possible if the image is
// simultaneously bound for shader write (i.e. the layout is GENERAL).
const ImageMemoryBarrierData &layoutData = kImageMemoryBarrierData[mCurrentLayout];
return layoutData.type == ResourceAccess::Write;
}
void ImageHelper::changeLayoutAndQueue(VkImageAspectFlags aspectMask,
ImageLayout newLayout,
uint32_t newQueueFamilyIndex,
CommandBuffer *commandBuffer)
{
ASSERT(isQueueChangeNeccesary(newQueueFamilyIndex));
barrierImpl(aspectMask, newLayout, newQueueFamilyIndex, commandBuffer);
}
void ImageHelper::acquireFromExternal(ContextVk *contextVk,
uint32_t externalQueueFamilyIndex,
uint32_t rendererQueueFamilyIndex,
ImageLayout currentLayout,
CommandBuffer *commandBuffer)
{
// The image must be newly allocated or have been released to the external
// queue. If this is not the case, it's an application bug, so ASSERT might
// eventually need to change to a warning.
ASSERT(mCurrentLayout == ImageLayout::Undefined ||
mCurrentQueueFamilyIndex == externalQueueFamilyIndex);
mCurrentLayout = currentLayout;
mCurrentQueueFamilyIndex = externalQueueFamilyIndex;
changeLayoutAndQueue(getAspectFlags(), mCurrentLayout, rendererQueueFamilyIndex, commandBuffer);
}
void ImageHelper::releaseToExternal(ContextVk *contextVk,
uint32_t rendererQueueFamilyIndex,
uint32_t externalQueueFamilyIndex,
ImageLayout desiredLayout,
CommandBuffer *commandBuffer)
{
ASSERT(mCurrentQueueFamilyIndex == rendererQueueFamilyIndex);
changeLayoutAndQueue(getAspectFlags(), desiredLayout, externalQueueFamilyIndex, commandBuffer);
}
bool ImageHelper::isReleasedToExternal() const
{
#if !defined(ANGLE_PLATFORM_MACOS) && !defined(ANGLE_PLATFORM_ANDROID)
return IsExternalQueueFamily(mCurrentQueueFamilyIndex);
#else
// TODO(anglebug.com/4635): Implement external memory barriers on Mac/Android.
return false;
#endif
}
void ImageHelper::setBaseAndMaxLevels(gl::LevelIndex baseLevel, gl::LevelIndex maxLevel)
{
mBaseLevel = baseLevel;
mMaxLevel = maxLevel;
}
LevelIndex ImageHelper::toVkLevel(gl::LevelIndex levelIndexGL) const
{
return gl_vk::GetLevelIndex(levelIndexGL, mBaseLevel);
}
gl::LevelIndex ImageHelper::toGLLevel(LevelIndex levelIndexVk) const
{
return vk_gl::GetLevelIndex(levelIndexVk, mBaseLevel);
}
ANGLE_INLINE void ImageHelper::initImageMemoryBarrierStruct(
VkImageAspectFlags aspectMask,
ImageLayout newLayout,
uint32_t newQueueFamilyIndex,
VkImageMemoryBarrier *imageMemoryBarrier) const
{
const ImageMemoryBarrierData &transitionFrom = kImageMemoryBarrierData[mCurrentLayout];
const ImageMemoryBarrierData &transitionTo = kImageMemoryBarrierData[newLayout];
imageMemoryBarrier->sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
imageMemoryBarrier->srcAccessMask = transitionFrom.srcAccessMask;
imageMemoryBarrier->dstAccessMask = transitionTo.dstAccessMask;
imageMemoryBarrier->oldLayout = transitionFrom.layout;
imageMemoryBarrier->newLayout = transitionTo.layout;
imageMemoryBarrier->srcQueueFamilyIndex = mCurrentQueueFamilyIndex;
imageMemoryBarrier->dstQueueFamilyIndex = newQueueFamilyIndex;
imageMemoryBarrier->image = mImage.getHandle();
// Transition the whole resource.
imageMemoryBarrier->subresourceRange.aspectMask = aspectMask;
imageMemoryBarrier->subresourceRange.baseMipLevel = 0;
imageMemoryBarrier->subresourceRange.levelCount = mLevelCount;
imageMemoryBarrier->subresourceRange.baseArrayLayer = 0;
imageMemoryBarrier->subresourceRange.layerCount = mLayerCount;
}
// Generalized to accept both "primary" and "secondary" command buffers.
template <typename CommandBufferT>
void ImageHelper::barrierImpl(VkImageAspectFlags aspectMask,
ImageLayout newLayout,
uint32_t newQueueFamilyIndex,
CommandBufferT *commandBuffer)
{
const ImageMemoryBarrierData &transitionFrom = kImageMemoryBarrierData[mCurrentLayout];
const ImageMemoryBarrierData &transitionTo = kImageMemoryBarrierData[newLayout];
VkImageMemoryBarrier imageMemoryBarrier = {};
initImageMemoryBarrierStruct(aspectMask, newLayout, newQueueFamilyIndex, &imageMemoryBarrier);
// There might be other shaderRead operations there other than the current layout.
VkPipelineStageFlags srcStageMask = transitionFrom.srcStageMask;
if (mCurrentShaderReadStageMask)
{
srcStageMask |= mCurrentShaderReadStageMask;
mCurrentShaderReadStageMask = 0;
mLastNonShaderReadOnlyLayout = ImageLayout::Undefined;
}
commandBuffer->imageBarrier(srcStageMask, transitionTo.dstStageMask, imageMemoryBarrier);
mCurrentLayout = newLayout;
mCurrentQueueFamilyIndex = newQueueFamilyIndex;
}
bool ImageHelper::updateLayoutAndBarrier(VkImageAspectFlags aspectMask,
ImageLayout newLayout,
PipelineBarrier *barrier)
{
bool barrierModified = false;
if (newLayout == mCurrentLayout)
{
const ImageMemoryBarrierData &layoutData = kImageMemoryBarrierData[mCurrentLayout];
// RAR is not a hazard and doesn't require a barrier, especially as the image layout hasn't
// changed. The following asserts that such a barrier is not attempted.
ASSERT(layoutData.type == ResourceAccess::Write);
// No layout change, only memory barrier is required
barrier->mergeMemoryBarrier(layoutData.srcStageMask, layoutData.dstStageMask,
layoutData.srcAccessMask, layoutData.dstAccessMask);
barrierModified = true;
}
else
{
const ImageMemoryBarrierData &transitionFrom = kImageMemoryBarrierData[mCurrentLayout];
const ImageMemoryBarrierData &transitionTo = kImageMemoryBarrierData[newLayout];
VkPipelineStageFlags srcStageMask = transitionFrom.srcStageMask;
VkPipelineStageFlags dstStageMask = transitionTo.dstStageMask;
if (IsShaderReadOnlyLayout(transitionTo) && IsShaderReadOnlyLayout(transitionFrom))
{
// If we are switching between different shader stage reads, then there is no actual
// layout change or access type change. We only need a barrier if we are making a read
// that is from a new stage. Also note that we barrier against previous non-shaderRead
// layout. We do not barrier between one shaderRead and another shaderRead.
bool isNewReadStage = (mCurrentShaderReadStageMask & dstStageMask) != dstStageMask;
if (isNewReadStage)
{
const ImageMemoryBarrierData &layoutData =
kImageMemoryBarrierData[mLastNonShaderReadOnlyLayout];
barrier->mergeMemoryBarrier(layoutData.srcStageMask, dstStageMask,
layoutData.srcAccessMask, transitionTo.dstAccessMask);
barrierModified = true;
// Accumulate new read stage.
mCurrentShaderReadStageMask |= dstStageMask;
}
}
else
{
VkImageMemoryBarrier imageMemoryBarrier = {};
initImageMemoryBarrierStruct(aspectMask, newLayout, mCurrentQueueFamilyIndex,
&imageMemoryBarrier);
// if we transition from shaderReadOnly, we must add in stashed shader stage masks since
// there might be outstanding shader reads from stages other than current layout. We do
// not insert barrier between one shaderRead to another shaderRead
if (mCurrentShaderReadStageMask)
{
srcStageMask |= mCurrentShaderReadStageMask;
mCurrentShaderReadStageMask = 0;
mLastNonShaderReadOnlyLayout = ImageLayout::Undefined;
}
barrier->mergeImageBarrier(srcStageMask, dstStageMask, imageMemoryBarrier);
barrierModified = true;
// If we are transition into shaderRead layout, remember the last
// non-shaderRead layout here.
if (IsShaderReadOnlyLayout(transitionTo))
{
ASSERT(!IsShaderReadOnlyLayout(transitionFrom));
mLastNonShaderReadOnlyLayout = mCurrentLayout;
mCurrentShaderReadStageMask = dstStageMask;
}
}
mCurrentLayout = newLayout;
}
return barrierModified;
}
void ImageHelper::clearColor(const VkClearColorValue &color,
LevelIndex baseMipLevelVk,
uint32_t levelCount,
uint32_t baseArrayLayer,
uint32_t layerCount,
CommandBuffer *commandBuffer)
{
ASSERT(valid());
ASSERT(mCurrentLayout == ImageLayout::TransferDst);
VkImageSubresourceRange range = {};
range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
range.baseMipLevel = baseMipLevelVk.get();
range.levelCount = levelCount;
range.baseArrayLayer = baseArrayLayer;
range.layerCount = layerCount;
commandBuffer->clearColorImage(mImage, getCurrentLayout(), color, 1, &range);
}
void ImageHelper::clearDepthStencil(VkImageAspectFlags clearAspectFlags,
const VkClearDepthStencilValue &depthStencil,
LevelIndex baseMipLevelVk,
uint32_t levelCount,
uint32_t baseArrayLayer,
uint32_t layerCount,
CommandBuffer *commandBuffer)
{
ASSERT(valid());
ASSERT(mCurrentLayout == ImageLayout::TransferDst);
VkImageSubresourceRange clearRange = {
/*aspectMask*/ clearAspectFlags,
/*baseMipLevel*/ baseMipLevelVk.get(),
/*levelCount*/ levelCount,
/*baseArrayLayer*/ baseArrayLayer,
/*layerCount*/ layerCount,
};
commandBuffer->clearDepthStencilImage(mImage, getCurrentLayout(), depthStencil, 1, &clearRange);
}
void ImageHelper::clear(VkImageAspectFlags aspectFlags,
const VkClearValue &value,
LevelIndex mipLevel,
uint32_t baseArrayLayer,
uint32_t layerCount,
CommandBuffer *commandBuffer)
{
const angle::Format &angleFormat = mFormat->actualImageFormat();
bool isDepthStencil = angleFormat.depthBits > 0 || angleFormat.stencilBits > 0;
if (isDepthStencil)
{
clearDepthStencil(aspectFlags, value.depthStencil, mipLevel, 1, baseArrayLayer, layerCount,
commandBuffer);
}
else
{
ASSERT(!angleFormat.isBlock);
clearColor(value.color, mipLevel, 1, baseArrayLayer, layerCount, commandBuffer);
}
}
// static
void ImageHelper::Copy(ImageHelper *srcImage,
ImageHelper *dstImage,
const gl::Offset &srcOffset,
const gl::Offset &dstOffset,
const gl::Extents ©Size,
const VkImageSubresourceLayers &srcSubresource,
const VkImageSubresourceLayers &dstSubresource,
CommandBuffer *commandBuffer)
{
ASSERT(commandBuffer->valid() && srcImage->valid() && dstImage->valid());
ASSERT(srcImage->getCurrentLayout() == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
ASSERT(dstImage->getCurrentLayout() == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
VkImageCopy region = {};
region.srcSubresource = srcSubresource;
region.srcOffset.x = srcOffset.x;
region.srcOffset.y = srcOffset.y;
region.srcOffset.z = srcOffset.z;
region.dstSubresource = dstSubresource;
region.dstOffset.x = dstOffset.x;
region.dstOffset.y = dstOffset.y;
region.dstOffset.z = dstOffset.z;
region.extent.width = copySize.width;
region.extent.height = copySize.height;
region.extent.depth = copySize.depth;
commandBuffer->copyImage(srcImage->getImage(), srcImage->getCurrentLayout(),
dstImage->getImage(), dstImage->getCurrentLayout(), 1, ®ion);
}
angle::Result ImageHelper::generateMipmapsWithBlit(ContextVk *contextVk, LevelIndex maxLevel)
{
ANGLE_TRY(contextVk->onImageTransferWrite(VK_IMAGE_ASPECT_COLOR_BIT, this));
CommandBuffer &commandBuffer = contextVk->getOutsideRenderPassCommandBuffer();
// We are able to use blitImage since the image format we are using supports it.
int32_t mipWidth = mExtents.width;
int32_t mipHeight = mExtents.height;
int32_t mipDepth = mExtents.depth;
// Manually manage the image memory barrier because it uses a lot more parameters than our
// usual one.
VkImageMemoryBarrier barrier = {};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.image = mImage.getHandle();
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = mLayerCount;
barrier.subresourceRange.levelCount = 1;
const VkFilter filter = gl_vk::GetFilter(CalculateGenerateMipmapFilter(contextVk, getFormat()));
for (uint32_t mipLevel = 1; mipLevel <= maxLevel.get(); mipLevel++)
{
int32_t nextMipWidth = std::max<int32_t>(1, mipWidth >> 1);
int32_t nextMipHeight = std::max<int32_t>(1, mipHeight >> 1);
int32_t nextMipDepth = std::max<int32_t>(1, mipDepth >> 1);
barrier.subresourceRange.baseMipLevel = mipLevel - 1;
barrier.oldLayout = getCurrentLayout();
barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
// We can do it for all layers at once.
commandBuffer.imageBarrier(VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
barrier);
VkImageBlit blit = {};
blit.srcOffsets[0] = {0, 0, 0};
blit.srcOffsets[1] = {mipWidth, mipHeight, mipDepth};
blit.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
blit.srcSubresource.mipLevel = mipLevel - 1;
blit.srcSubresource.baseArrayLayer = 0;
blit.srcSubresource.layerCount = mLayerCount;
blit.dstOffsets[0] = {0, 0, 0};
blit.dstOffsets[1] = {nextMipWidth, nextMipHeight, nextMipDepth};
blit.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
blit.dstSubresource.mipLevel = mipLevel;
blit.dstSubresource.baseArrayLayer = 0;
blit.dstSubresource.layerCount = mLayerCount;
mipWidth = nextMipWidth;
mipHeight = nextMipHeight;
mipDepth = nextMipDepth;
commandBuffer.blitImage(mImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, mImage,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, filter);
}
// Transition the last mip level to the same layout as all the other ones, so we can declare
// our whole image layout to be SRC_OPTIMAL.
barrier.subresourceRange.baseMipLevel = maxLevel.get();
barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
// We can do it for all layers at once.
commandBuffer.imageBarrier(VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
barrier);
// This is just changing the internal state of the image helper so that the next call
// to changeLayout will use this layout as the "oldLayout" argument.
mCurrentLayout = ImageLayout::TransferSrc;
return angle::Result::Continue;
}
void ImageHelper::resolve(ImageHelper *dest,
const VkImageResolve ®ion,
CommandBuffer *commandBuffer)
{
ASSERT(mCurrentLayout == ImageLayout::TransferSrc);
commandBuffer->resolveImage(getImage(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dest->getImage(),
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion);
}
void ImageHelper::removeSingleSubresourceStagedUpdates(ContextVk *contextVk,
gl::LevelIndex levelIndexGL,
uint32_t layerIndex)
{
// Find any staged updates for this index and removes them from the pending list.
for (size_t index = 0; index < mSubresourceUpdates.size();)
{
auto update = mSubresourceUpdates.begin() + index;
if (update->isUpdateToLayerLevel(layerIndex, levelIndexGL))
{
update->release(contextVk->getRenderer());
mSubresourceUpdates.erase(update);
}
else
{
index++;
}
}
mCurrentSingleClearValue.reset();
}
void ImageHelper::removeStagedUpdates(Context *context,
gl::LevelIndex levelGLStart,
gl::LevelIndex levelGLEnd)
{
// Remove all updates to levels [start, end].
for (size_t index = 0; index < mSubresourceUpdates.size();)
{
auto update = mSubresourceUpdates.begin() + index;
gl::LevelIndex updateMipLevelGL;
uint32_t updateBaseLayer, updateLayerCount;
update->getDestSubresource(mLayerCount, &updateMipLevelGL, &updateBaseLayer,
&updateLayerCount);
if (updateMipLevelGL >= levelGLStart && updateMipLevelGL <= levelGLEnd)
{
update->release(context->getRenderer());
mSubresourceUpdates.erase(update);
}
else
{
index++;
}
}
}
angle::Result ImageHelper::stageSubresourceUpdateImpl(ContextVk *contextVk,
const gl::ImageIndex &index,
const gl::Extents &glExtents,
const gl::Offset &offset,
const gl::InternalFormat &formatInfo,
const gl::PixelUnpackState &unpack,
DynamicBuffer *stagingBufferOverride,
GLenum type,
const uint8_t *pixels,
const Format &vkFormat,
const GLuint inputRowPitch,
const GLuint inputDepthPitch,
const GLuint inputSkipBytes)
{
const angle::Format &storageFormat = vkFormat.actualImageFormat();
size_t outputRowPitch;
size_t outputDepthPitch;
size_t stencilAllocationSize = 0;
uint32_t bufferRowLength;
uint32_t bufferImageHeight;
size_t allocationSize;
LoadImageFunctionInfo loadFunctionInfo = vkFormat.textureLoadFunctions(type);
LoadImageFunction stencilLoadFunction = nullptr;
if (storageFormat.isBlock)
{
const gl::InternalFormat &storageFormatInfo = vkFormat.getInternalFormatInfo(type);
GLuint rowPitch;
GLuint depthPitch;
GLuint totalSize;
ANGLE_VK_CHECK_MATH(contextVk, storageFormatInfo.computeCompressedImageSize(
gl::Extents(glExtents.width, 1, 1), &rowPitch));
ANGLE_VK_CHECK_MATH(contextVk,
storageFormatInfo.computeCompressedImageSize(
gl::Extents(glExtents.width, glExtents.height, 1), &depthPitch));
ANGLE_VK_CHECK_MATH(contextVk,
storageFormatInfo.computeCompressedImageSize(glExtents, &totalSize));
outputRowPitch = rowPitch;
outputDepthPitch = depthPitch;
allocationSize = totalSize;
ANGLE_VK_CHECK_MATH(
contextVk, storageFormatInfo.computeBufferRowLength(glExtents.width, &bufferRowLength));
ANGLE_VK_CHECK_MATH(contextVk, storageFormatInfo.computeBufferImageHeight(
glExtents.height, &bufferImageHeight));
}
else
{
ASSERT(storageFormat.pixelBytes != 0);
if (storageFormat.id == angle::FormatID::D24_UNORM_S8_UINT)
{
stencilLoadFunction = angle::LoadX24S8ToS8;
}
if (storageFormat.id == angle::FormatID::D32_FLOAT_S8X24_UINT)
{
// If depth is D32FLOAT_S8, we must pack D32F tightly (no stencil) for CopyBufferToImage
outputRowPitch = sizeof(float) * glExtents.width;
// The generic load functions don't handle tightly packing D32FS8 to D32F & S8 so call
// special case load functions.
switch (type)
{
case GL_UNSIGNED_INT:
loadFunctionInfo.loadFunction = angle::LoadD32ToD32F;
stencilLoadFunction = nullptr;
break;
case GL_DEPTH32F_STENCIL8:
case GL_FLOAT_32_UNSIGNED_INT_24_8_REV:
loadFunctionInfo.loadFunction = angle::LoadD32FS8X24ToD32F;
stencilLoadFunction = angle::LoadX32S8ToS8;
break;
case GL_UNSIGNED_INT_24_8_OES:
loadFunctionInfo.loadFunction = angle::LoadD24S8ToD32F;
stencilLoadFunction = angle::LoadX24S8ToS8;
break;
default:
UNREACHABLE();
}
}
else
{
outputRowPitch = storageFormat.pixelBytes * glExtents.width;
}
outputDepthPitch = outputRowPitch * glExtents.height;
bufferRowLength = glExtents.width;
bufferImageHeight = glExtents.height;
allocationSize = outputDepthPitch * glExtents.depth;
// Note: because the LoadImageFunctionInfo functions are limited to copying a single
// component, we have to special case packed depth/stencil use and send the stencil as a
// separate chunk.
if (storageFormat.depthBits > 0 && storageFormat.stencilBits > 0 &&
formatInfo.depthBits > 0 && formatInfo.stencilBits > 0)
{
// Note: Stencil is always one byte
stencilAllocationSize = glExtents.width * glExtents.height * glExtents.depth;
allocationSize += stencilAllocationSize;
}
}
VkBuffer bufferHandle = VK_NULL_HANDLE;
uint8_t *stagingPointer = nullptr;
VkDeviceSize stagingOffset = 0;
// If caller has provided a staging buffer, use it.
DynamicBuffer *stagingBuffer = stagingBufferOverride ? stagingBufferOverride : &mStagingBuffer;
size_t alignment = mStagingBuffer.getAlignment();
ANGLE_TRY(stagingBuffer->allocateWithAlignment(contextVk, allocationSize, alignment,
&stagingPointer, &bufferHandle, &stagingOffset,
nullptr));
BufferHelper *currentBuffer = stagingBuffer->getCurrentBuffer();
const uint8_t *source = pixels + static_cast<ptrdiff_t>(inputSkipBytes);
loadFunctionInfo.loadFunction(glExtents.width, glExtents.height, glExtents.depth, source,
inputRowPitch, inputDepthPitch, stagingPointer, outputRowPitch,
outputDepthPitch);
VkBufferImageCopy copy = {};
VkImageAspectFlags aspectFlags = GetFormatAspectFlags(vkFormat.actualImageFormat());
copy.bufferOffset = stagingOffset;
copy.bufferRowLength = bufferRowLength;
copy.bufferImageHeight = bufferImageHeight;
copy.imageSubresource.mipLevel = index.getLevelIndex();
copy.imageSubresource.layerCount = index.getLayerCount();
gl_vk::GetOffset(offset, ©.imageOffset);
gl_vk::GetExtent(glExtents, ©.imageExtent);
if (gl::IsArrayTextureType(index.getType()))
{
copy.imageSubresource.baseArrayLayer = offset.z;
copy.imageOffset.z = 0;
copy.imageExtent.depth = 1;
}
else
{
copy.imageSubresource.baseArrayLayer = index.hasLayer() ? index.getLayerIndex() : 0;
}
if (stencilAllocationSize > 0)
{
// Note: Stencil is always one byte
ASSERT((aspectFlags & VK_IMAGE_ASPECT_STENCIL_BIT) != 0);
// Skip over depth data.
stagingPointer += outputDepthPitch * glExtents.depth;
stagingOffset += outputDepthPitch * glExtents.depth;
// recompute pitch for stencil data
outputRowPitch = glExtents.width;
outputDepthPitch = outputRowPitch * glExtents.height;
ASSERT(stencilLoadFunction != nullptr);
stencilLoadFunction(glExtents.width, glExtents.height, glExtents.depth, source,
inputRowPitch, inputDepthPitch, stagingPointer, outputRowPitch,
outputDepthPitch);
VkBufferImageCopy stencilCopy = {};
stencilCopy.bufferOffset = stagingOffset;
stencilCopy.bufferRowLength = bufferRowLength;
stencilCopy.bufferImageHeight = bufferImageHeight;
stencilCopy.imageSubresource.mipLevel = copy.imageSubresource.mipLevel;
stencilCopy.imageSubresource.baseArrayLayer = copy.imageSubresource.baseArrayLayer;
stencilCopy.imageSubresource.layerCount = copy.imageSubresource.layerCount;
stencilCopy.imageOffset = copy.imageOffset;
stencilCopy.imageExtent = copy.imageExtent;
stencilCopy.imageSubresource.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
appendSubresourceUpdate(SubresourceUpdate(currentBuffer, stencilCopy));
aspectFlags &= ~VK_IMAGE_ASPECT_STENCIL_BIT;
}
if (IsMaskFlagSet(aspectFlags, static_cast<VkImageAspectFlags>(VK_IMAGE_ASPECT_STENCIL_BIT |
VK_IMAGE_ASPECT_DEPTH_BIT)))
{
// We still have both depth and stencil aspect bits set. That means we have a destination
// buffer that is packed depth stencil and that the application is only loading one aspect.
// Figure out which aspect the user is touching and remove the unused aspect bit.
if (formatInfo.stencilBits > 0)
{
aspectFlags &= ~VK_IMAGE_ASPECT_DEPTH_BIT;
}
else
{
aspectFlags &= ~VK_IMAGE_ASPECT_STENCIL_BIT;
}
}
if (aspectFlags)
{
copy.imageSubresource.aspectMask = aspectFlags;
appendSubresourceUpdate(SubresourceUpdate(currentBuffer, copy));
}
return angle::Result::Continue;
}
angle::Result ImageHelper::CalculateBufferInfo(ContextVk *contextVk,
const gl::Extents &glExtents,
const gl::InternalFormat &formatInfo,
const gl::PixelUnpackState &unpack,
GLenum type,
bool is3D,
GLuint *inputRowPitch,
GLuint *inputDepthPitch,
GLuint *inputSkipBytes)
{
ANGLE_VK_CHECK_MATH(contextVk,
formatInfo.computeRowPitch(type, glExtents.width, unpack.alignment,
unpack.rowLength, inputRowPitch));
ANGLE_VK_CHECK_MATH(contextVk,
formatInfo.computeDepthPitch(glExtents.height, unpack.imageHeight,
*inputRowPitch, inputDepthPitch));
ANGLE_VK_CHECK_MATH(
contextVk, formatInfo.computeSkipBytes(type, *inputRowPitch, *inputDepthPitch, unpack, is3D,
inputSkipBytes));
return angle::Result::Continue;
}
angle::Result ImageHelper::stageSubresourceUpdate(ContextVk *contextVk,
const gl::ImageIndex &index,
const gl::Extents &glExtents,
const gl::Offset &offset,
const gl::InternalFormat &formatInfo,
const gl::PixelUnpackState &unpack,
DynamicBuffer *stagingBufferOverride,
GLenum type,
const uint8_t *pixels,
const Format &vkFormat)
{
GLuint inputRowPitch = 0;
GLuint inputDepthPitch = 0;
GLuint inputSkipBytes = 0;
ANGLE_TRY(CalculateBufferInfo(contextVk, glExtents, formatInfo, unpack, type, index.usesTex3D(),
&inputRowPitch, &inputDepthPitch, &inputSkipBytes));
ANGLE_TRY(stageSubresourceUpdateImpl(contextVk, index, glExtents, offset, formatInfo, unpack,
stagingBufferOverride, type, pixels, vkFormat,
inputRowPitch, inputDepthPitch, inputSkipBytes));
return angle::Result::Continue;
}
angle::Result ImageHelper::stageSubresourceUpdateAndGetData(ContextVk *contextVk,
size_t allocationSize,
const gl::ImageIndex &imageIndex,
const gl::Extents &glExtents,
const gl::Offset &offset,
uint8_t **destData,
DynamicBuffer *stagingBufferOverride)
{
VkBuffer bufferHandle;
VkDeviceSize stagingOffset = 0;
DynamicBuffer *stagingBuffer = stagingBufferOverride ? stagingBufferOverride : &mStagingBuffer;
size_t alignment = mStagingBuffer.getAlignment();
ANGLE_TRY(stagingBuffer->allocateWithAlignment(contextVk, allocationSize, alignment, destData,
&bufferHandle, &stagingOffset, nullptr));
VkBufferImageCopy copy = {};
copy.bufferOffset = stagingOffset;
copy.bufferRowLength = glExtents.width;
copy.bufferImageHeight = glExtents.height;
copy.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
copy.imageSubresource.mipLevel = imageIndex.getLevelIndex();
copy.imageSubresource.baseArrayLayer = imageIndex.hasLayer() ? imageIndex.getLayerIndex() : 0;
copy.imageSubresource.layerCount = imageIndex.getLayerCount();
// Note: Only support color now
ASSERT((mFormat == nullptr) || (getAspectFlags() == VK_IMAGE_ASPECT_COLOR_BIT));
gl_vk::GetOffset(offset, ©.imageOffset);
gl_vk::GetExtent(glExtents, ©.imageExtent);
appendSubresourceUpdate(SubresourceUpdate(stagingBuffer->getCurrentBuffer(), copy));
return angle::Result::Continue;
}
angle::Result ImageHelper::stageSubresourceUpdateFromBuffer(ContextVk *contextVk,
size_t allocationSize,
gl::LevelIndex mipLevelGL,
uint32_t baseArrayLayer,
uint32_t layerCount,
uint32_t bufferRowLength,
uint32_t bufferImageHeight,
const VkExtent3D &extent,
const VkOffset3D &offset,
BufferHelper *bufferHelper,
StagingBufferOffsetArray stagingOffsets)
{
// This function stages an update from explicitly provided handle and offset
// It is used when the texture base level has changed, and we need to propagate data
//
// Note that staged updates have the GL mip level so that changing base level doesn't require
// modifying all staged updates.
VkBufferImageCopy copy[2] = {};
copy[0].bufferOffset = stagingOffsets[0];
copy[0].bufferRowLength = bufferRowLength;
copy[0].bufferImageHeight = bufferImageHeight;
copy[0].imageSubresource.aspectMask = getAspectFlags();
copy[0].imageSubresource.mipLevel = mipLevelGL.get();
copy[0].imageSubresource.baseArrayLayer = baseArrayLayer;
copy[0].imageSubresource.layerCount = layerCount;
copy[0].imageOffset = offset;
copy[0].imageExtent = extent;
if (isCombinedDepthStencilFormat())
{
// Force aspect to depth for first copy
copy[0].imageSubresource.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
// Copy stencil aspect separately
copy[1] = copy[0];
copy[1].bufferOffset = stagingOffsets[1];
copy[1].imageSubresource.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
appendSubresourceUpdate(SubresourceUpdate(bufferHelper, copy[1]));
}
appendSubresourceUpdate(SubresourceUpdate(bufferHelper, copy[0]));
return angle::Result::Continue;
}
angle::Result ImageHelper::stageSubresourceUpdateFromFramebuffer(
const gl::Context *context,
const gl::ImageIndex &index,
const gl::Rectangle &sourceArea,
const gl::Offset &dstOffset,
const gl::Extents &dstExtent,
const gl::InternalFormat &formatInfo,
FramebufferVk *framebufferVk,
DynamicBuffer *stagingBufferOverride)
{
ContextVk *contextVk = GetImpl(context);
// If the extents and offset is outside the source image, we need to clip.
gl::Rectangle clippedRectangle;
const gl::Extents readExtents = framebufferVk->getReadImageExtents();
if (!ClipRectangle(sourceArea, gl::Rectangle(0, 0, readExtents.width, readExtents.height),
&clippedRectangle))
{
// Empty source area, nothing to do.
return angle::Result::Continue;
}
bool isViewportFlipEnabled = contextVk->isViewportFlipEnabledForDrawFBO();
if (isViewportFlipEnabled)
{
clippedRectangle.y = readExtents.height - clippedRectangle.y - clippedRectangle.height;
}
// 1- obtain a buffer handle to copy to
RendererVk *renderer = contextVk->getRenderer();
const Format &vkFormat = renderer->getFormat(formatInfo.sizedInternalFormat);
const angle::Format &storageFormat = vkFormat.actualImageFormat();
LoadImageFunctionInfo loadFunction = vkFormat.textureLoadFunctions(formatInfo.type);
size_t outputRowPitch = storageFormat.pixelBytes * clippedRectangle.width;
size_t outputDepthPitch = outputRowPitch * clippedRectangle.height;
VkBuffer bufferHandle = VK_NULL_HANDLE;
uint8_t *stagingPointer = nullptr;
VkDeviceSize stagingOffset = 0;
// The destination is only one layer deep.
size_t allocationSize = outputDepthPitch;
DynamicBuffer *stagingBuffer = stagingBufferOverride ? stagingBufferOverride : &mStagingBuffer;
size_t alignment = mStagingBuffer.getAlignment();
ANGLE_TRY(stagingBuffer->allocateWithAlignment(contextVk, allocationSize, alignment,
&stagingPointer, &bufferHandle, &stagingOffset,
nullptr));
BufferHelper *currentBuffer = stagingBuffer->getCurrentBuffer();
const angle::Format ©Format =
GetFormatFromFormatType(formatInfo.internalFormat, formatInfo.type);
PackPixelsParams params(clippedRectangle, copyFormat, static_cast<GLuint>(outputRowPitch),
isViewportFlipEnabled, nullptr, 0);
RenderTargetVk *readRenderTarget = framebufferVk->getColorReadRenderTarget();
// 2- copy the source image region to the pixel buffer using a cpu readback
if (loadFunction.requiresConversion)
{
// When a conversion is required, we need to use the loadFunction to read from a temporary
// buffer instead so its an even slower path.
size_t bufferSize =
storageFormat.pixelBytes * clippedRectangle.width * clippedRectangle.height;
angle::MemoryBuffer *memoryBuffer = nullptr;
ANGLE_VK_CHECK_ALLOC(contextVk, context->getScratchBuffer(bufferSize, &memoryBuffer));
// Read into the scratch buffer
ANGLE_TRY(framebufferVk->readPixelsImpl(contextVk, clippedRectangle, params,
VK_IMAGE_ASPECT_COLOR_BIT, readRenderTarget,
memoryBuffer->data()));
// Load from scratch buffer to our pixel buffer
loadFunction.loadFunction(clippedRectangle.width, clippedRectangle.height, 1,
memoryBuffer->data(), outputRowPitch, 0, stagingPointer,
outputRowPitch, 0);
}
else
{
// We read directly from the framebuffer into our pixel buffer.
ANGLE_TRY(framebufferVk->readPixelsImpl(contextVk, clippedRectangle, params,
VK_IMAGE_ASPECT_COLOR_BIT, readRenderTarget,
stagingPointer));
}
// 3- enqueue the destination image subresource update
VkBufferImageCopy copyToImage = {};
copyToImage.bufferOffset = static_cast<VkDeviceSize>(stagingOffset);
copyToImage.bufferRowLength = 0; // Tightly packed data can be specified as 0.
copyToImage.bufferImageHeight = clippedRectangle.height;
copyToImage.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
copyToImage.imageSubresource.mipLevel = index.getLevelIndex();
copyToImage.imageSubresource.baseArrayLayer = index.hasLayer() ? index.getLayerIndex() : 0;
copyToImage.imageSubresource.layerCount = index.getLayerCount();
gl_vk::GetOffset(dstOffset, ©ToImage.imageOffset);
gl_vk::GetExtent(dstExtent, ©ToImage.imageExtent);
// 3- enqueue the destination image subresource update
appendSubresourceUpdate(SubresourceUpdate(currentBuffer, copyToImage));
return angle::Result::Continue;
}
void ImageHelper::stageSubresourceUpdateFromImage(ImageHelper *image,
const gl::ImageIndex &index,
const gl::Offset &destOffset,
const gl::Extents &glExtents,
const VkImageType imageType)
{
VkImageCopy copyToImage = {};
copyToImage.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
copyToImage.srcSubresource.layerCount = index.getLayerCount();
copyToImage.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
copyToImage.dstSubresource.mipLevel = index.getLevelIndex();
if (imageType == VK_IMAGE_TYPE_3D)
{
// These values must be set explicitly to follow the Vulkan spec:
// https://www.khronos.org/registry/vulkan/specs/1.1-extensions/man/html/VkImageCopy.html
// If either of the calling command's srcImage or dstImage parameters are of VkImageType
// VK_IMAGE_TYPE_3D, the baseArrayLayer and layerCount members of the corresponding
// subresource must be 0 and 1, respectively
copyToImage.dstSubresource.baseArrayLayer = 0;
copyToImage.dstSubresource.layerCount = 1;
// Preserve the assumption that destOffset.z == "dstSubresource.baseArrayLayer"
ASSERT(destOffset.z == (index.hasLayer() ? index.getLayerIndex() : 0));
}
else
{
copyToImage.dstSubresource.baseArrayLayer = index.hasLayer() ? index.getLayerIndex() : 0;
copyToImage.dstSubresource.layerCount = index.getLayerCount();
}
gl_vk::GetOffset(destOffset, ©ToImage.dstOffset);
gl_vk::GetExtent(glExtents, ©ToImage.extent);
appendSubresourceUpdate(SubresourceUpdate(image, copyToImage));
}
void ImageHelper::stageClear(const gl::ImageIndex &index,
VkImageAspectFlags aspectFlags,
const VkClearValue &clearValue)
{
appendSubresourceUpdate(SubresourceUpdate(aspectFlags, clearValue, index));
}
void ImageHelper::stageRobustResourceClear(const gl::ImageIndex &index)
{
const VkImageAspectFlags aspectFlags = getAspectFlags();
ASSERT(mFormat);
VkClearValue clearValue = GetRobustResourceClearValue(*mFormat);
appendSubresourceUpdate(SubresourceUpdate(aspectFlags, clearValue, index));
}
angle::Result ImageHelper::stageRobustResourceClearWithFormat(ContextVk *contextVk,
const gl::ImageIndex &index,
const gl::Extents &glExtents,
const Format &format)
{
const angle::Format &imageFormat = format.actualImageFormat();
const VkImageAspectFlags aspectFlags = GetFormatAspectFlags(imageFormat);
// Robust clears must only be staged if we do not have any prior data for this subresource.
ASSERT(!isUpdateStaged(gl::LevelIndex(index.getLevelIndex()), index.getLayerIndex()));
VkClearValue clearValue = GetRobustResourceClearValue(format);
if (imageFormat.isBlock)
{
// This only supports doing an initial clear to 0, not clearing to a specific encoded RGBA
// value
ASSERT((clearValue.color.int32[0] == 0) && (clearValue.color.int32[1] == 0) &&
(clearValue.color.int32[2] == 0) && (clearValue.color.int32[3] == 0));
const gl::InternalFormat &formatInfo =
gl::GetSizedInternalFormatInfo(imageFormat.glInternalFormat);
GLuint totalSize;
ANGLE_VK_CHECK_MATH(contextVk,
formatInfo.computeCompressedImageSize(glExtents, &totalSize));
VkBuffer bufferHandle = VK_NULL_HANDLE;
uint8_t *stagingPointer = nullptr;
VkDeviceSize stagingOffset = 0;
ANGLE_TRY(mStagingBuffer.allocate(contextVk, totalSize, &stagingPointer, &bufferHandle,
&stagingOffset, nullptr));
memset(stagingPointer, 0, totalSize);
VkBufferImageCopy copyRegion = {};
copyRegion.imageExtent.width = glExtents.width;
copyRegion.imageExtent.height = glExtents.height;
copyRegion.imageExtent.depth = glExtents.depth;
copyRegion.imageSubresource.mipLevel = index.getLevelIndex();
copyRegion.imageSubresource.aspectMask = aspectFlags;
copyRegion.imageSubresource.baseArrayLayer = index.hasLayer() ? index.getLayerIndex() : 0;
copyRegion.imageSubresource.layerCount = index.getLayerCount();
appendSubresourceUpdate(SubresourceUpdate(mStagingBuffer.getCurrentBuffer(), copyRegion));
}
else
{
appendSubresourceUpdate(SubresourceUpdate(aspectFlags, clearValue, index));
}
return angle::Result::Continue;
}
void ImageHelper::stageClearIfEmulatedFormat(Context *context)
{
// Skip staging extra clears if robust resource init is enabled.
if (!mFormat->hasEmulatedImageChannels() || context->isRobustResourceInitEnabled())
return;
VkClearValue clearValue;
if (mFormat->intendedFormat().hasDepthOrStencilBits())
{
clearValue.depthStencil = kRobustInitDepthStencilValue;
}
else
{
clearValue.color = kEmulatedInitColorValue;
}
const VkImageAspectFlags aspectFlags = getAspectFlags();
// If the image has an emulated channel and robust resource init is not enabled, always clear
// it. These channels will be masked out in future writes, and shouldn't contain uninitialized
// values.
for (LevelIndex level(0); level < LevelIndex(mLevelCount); ++level)
{
gl::ImageIndex index =
gl::ImageIndex::Make2DArrayRange(toGLLevel(level).get(), 0, mLayerCount);
prependSubresourceUpdate(SubresourceUpdate(aspectFlags, clearValue, index));
}
}
void ImageHelper::stageSelfForBaseLevel()
{
std::unique_ptr<ImageHelper> prevImage = std::make_unique<ImageHelper>();
// Move the necessary information for staged update to work, and keep the rest as part of this
// object.
// Vulkan objects
prevImage->mImage = std::move(mImage);
prevImage->mDeviceMemory = std::move(mDeviceMemory);
// Barrier information. Note: mLevelCount is set to 1 so that only the base level is
// transitioned when flushing the update.
prevImage->mFormat = mFormat;
prevImage->mCurrentLayout = mCurrentLayout;
prevImage->mCurrentQueueFamilyIndex = mCurrentQueueFamilyIndex;
prevImage->mLastNonShaderReadOnlyLayout = mLastNonShaderReadOnlyLayout;
prevImage->mCurrentShaderReadStageMask = mCurrentShaderReadStageMask;
prevImage->mLevelCount = 1;
prevImage->mLayerCount = mLayerCount;
prevImage->mImageSerial = mImageSerial;
// Reset information for current (invalid) image.
mCurrentLayout = ImageLayout::Undefined;
mCurrentQueueFamilyIndex = std::numeric_limits<uint32_t>::max();
mLastNonShaderReadOnlyLayout = ImageLayout::Undefined;
mCurrentShaderReadStageMask = 0;
mImageSerial = kInvalidImageSerial;
// Stage an update from the previous image.
const gl::ImageIndex baseLevelIndex =
gl::ImageIndex::Make2DArrayRange(mBaseLevel.get(), 0, mLayerCount);
stageSubresourceUpdateFromImage(prevImage.release(), baseLevelIndex, gl::kOffsetZero,
getLevelExtents(vk::LevelIndex(0)), mImageType);
}
angle::Result ImageHelper::flushSingleSubresourceStagedUpdates(ContextVk *contextVk,
gl::LevelIndex levelGL,
uint32_t layer,
ClearValuesArray *deferredClears,
uint32_t deferredClearIndex)
{
// Handle deferred clears. Search the updates list for a matching clear index.
if (deferredClears)
{
Optional<size_t> foundClear;
for (size_t updateIndex = 0; updateIndex < mSubresourceUpdates.size(); ++updateIndex)
{
SubresourceUpdate &update = mSubresourceUpdates[updateIndex];
if (update.isUpdateToLayerLevel(layer, levelGL))
{
// On any data update, exit out. We'll need to do a full upload.
if (update.updateSource != UpdateSource::Clear ||
(update.clear.layerCount != 1 &&
!(update.clear.layerCount == VK_REMAINING_ARRAY_LAYERS && mLayerCount == 1)))
{
foundClear.reset();
break;
}
// Otherwise track the latest clear update index.
foundClear = updateIndex;
}
}
// If we have a valid index we defer the clear using the clear reference.
if (foundClear.valid())
{
size_t foundIndex = foundClear.value();
const ClearUpdate &update = mSubresourceUpdates[foundIndex].clear;
// Note that this set command handles combined or separate depth/stencil clears.
deferredClears->store(deferredClearIndex, update.aspectFlags, update.value);
// We process the updates again to erase any clears for this level.
removeSingleSubresourceStagedUpdates(contextVk, levelGL, layer);
return angle::Result::Continue;
}
// Otherwise we proceed with a normal update.
}
LevelIndex levelVk = toVkLevel(levelGL);
return flushStagedUpdates(contextVk, levelVk, levelVk + 1, layer, layer + 1, {});
}
angle::Result ImageHelper::flushStagedUpdates(ContextVk *contextVk,
LevelIndex levelVkStart,
LevelIndex levelVkEnd,
uint32_t layerStart,
uint32_t layerEnd,
gl::TexLevelMask skipLevelsMask)
{
if (mSubresourceUpdates.empty())
{
return angle::Result::Continue;
}
removeSupersededUpdates(skipLevelsMask);
// If a clear is requested and we know it has just been cleared with the same value, we drop the
// clear.
if (mSubresourceUpdates.size() == 1)
{
SubresourceUpdate &update = mSubresourceUpdates[0];
if (update.updateSource == UpdateSource::Clear && mCurrentSingleClearValue.valid() &&
mCurrentSingleClearValue.value() == update.clear)
{
ANGLE_PERF_WARNING(contextVk->getDebug(), GL_DEBUG_SEVERITY_LOW,
"Repeated Clear on framebuffer attachment dropped");
update.release(contextVk->getRenderer());
mSubresourceUpdates.clear();
return angle::Result::Continue;
}
}
const gl::LevelIndex levelGLStart = toGLLevel(levelVkStart);
const gl::LevelIndex levelGLEnd = toGLLevel(levelVkEnd);
ANGLE_TRY(mStagingBuffer.flush(contextVk));
std::vector<SubresourceUpdate> updatesToKeep;
const VkImageAspectFlags aspectFlags = GetFormatAspectFlags(mFormat->actualImageFormat());
// Upload levels and layers that don't conflict in parallel. The (level, layer) pair is hashed
// to `(level * mLayerCount + layer) % 64` and used to track whether that subresource is
// currently in transfer. If so, a barrier is inserted. If mLayerCount * mLevelCount > 64,
// there will be a few unnecessary barriers.
constexpr uint32_t kMaxParallelSubresourceUpload = 64;
uint64_t subresourceUploadsInProgress = 0;
// Start in TransferDst.
ANGLE_TRY(contextVk->onImageTransferWrite(aspectFlags, this));
CommandBuffer *commandBuffer = &contextVk->getOutsideRenderPassCommandBuffer();
for (SubresourceUpdate &update : mSubresourceUpdates)
{
ASSERT(update.updateSource == UpdateSource::Clear ||
(update.updateSource == UpdateSource::Buffer &&
update.buffer.bufferHelper != nullptr) ||
(update.updateSource == UpdateSource::Image && update.image.image != nullptr &&
update.image.image->valid()));
gl::LevelIndex updateMipLevelGL;
uint32_t updateBaseLayer, updateLayerCount;
update.getDestSubresource(mLayerCount, &updateMipLevelGL, &updateBaseLayer,
&updateLayerCount);
// If the update level is not within the requested range, skip the update.
const bool isUpdateLevelOutsideRange = updateMipLevelGL < levelGLStart ||
updateMipLevelGL >= levelGLEnd ||
updateMipLevelGL > mMaxLevel;
// If the update layers don't intersect the requested layers, skip the update.
const bool areUpdateLayersOutsideRange =
updateBaseLayer + updateLayerCount <= layerStart || updateBaseLayer >= layerEnd;
LevelIndex updateMipLevelVk =
isUpdateLevelOutsideRange ? LevelIndex(0) : toVkLevel(updateMipLevelGL);
// Additionally, if updates to this level are specifically asked to be skipped, skip them.
// This can happen when recreating an image that has been partially incompatibly redefined,
// in which case only updates to the levels that haven't been redefined should be flushed.
if (isUpdateLevelOutsideRange || areUpdateLayersOutsideRange ||
skipLevelsMask.test(updateMipLevelVk.get()))
{
updatesToKeep.emplace_back(update);
continue;
}
// The updates were holding gl::LevelIndex values so that they would not need modification
// when the base level of the texture changes. Now that the update is about to take effect,
// we need to change miplevel to vk::LevelIndex.
if (update.updateSource == UpdateSource::Clear)
{
update.clear.levelIndex = updateMipLevelVk.get();
}
else if (update.updateSource == UpdateSource::Buffer)
{
update.buffer.copyRegion.imageSubresource.mipLevel = updateMipLevelVk.get();
}
else if (update.updateSource == UpdateSource::Image)
{
update.image.copyRegion.dstSubresource.mipLevel = updateMipLevelVk.get();
}
if (updateLayerCount >= kMaxParallelSubresourceUpload)
{
// If there are more subresources than bits we can track, always insert a barrier.
recordWriteBarrier(aspectFlags, ImageLayout::TransferDst, commandBuffer);
subresourceUploadsInProgress = std::numeric_limits<uint64_t>::max();
}
else
{
const uint64_t subresourceHashRange = angle::Bit<uint64_t>(updateLayerCount) - 1;
const uint32_t subresourceHashOffset =
(updateMipLevelVk.get() * mLayerCount + updateBaseLayer) %
kMaxParallelSubresourceUpload;
const uint64_t subresourceHash =
ANGLE_ROTL64(subresourceHashRange, subresourceHashOffset);
if ((subresourceUploadsInProgress & subresourceHash) != 0)
{
// If there's overlap in subresource upload, issue a barrier.
recordWriteBarrier(aspectFlags, ImageLayout::TransferDst, commandBuffer);
subresourceUploadsInProgress = 0;
}
subresourceUploadsInProgress |= subresourceHash;
}
if (update.updateSource == UpdateSource::Clear)
{
clear(update.clear.aspectFlags, update.clear.value, updateMipLevelVk, updateBaseLayer,
updateLayerCount, commandBuffer);
// Remember the latest operation is a clear call
mCurrentSingleClearValue = update.clear;
}
else if (update.updateSource == UpdateSource::Buffer)
{
BufferUpdate &bufferUpdate = update.buffer;
BufferHelper *currentBuffer = bufferUpdate.bufferHelper;
ASSERT(currentBuffer && currentBuffer->valid());
ANGLE_TRY(contextVk->onBufferTransferRead(currentBuffer));
commandBuffer = &contextVk->getOutsideRenderPassCommandBuffer();
commandBuffer->copyBufferToImage(currentBuffer->getBuffer().getHandle(), mImage,
getCurrentLayout(), 1, &update.buffer.copyRegion);
onWrite();
}
else
{
ANGLE_TRY(contextVk->onImageTransferRead(aspectFlags, update.image.image));
commandBuffer = &contextVk->getOutsideRenderPassCommandBuffer();
commandBuffer->copyImage(update.image.image->getImage(),
update.image.image->getCurrentLayout(), mImage,
getCurrentLayout(), 1, &update.image.copyRegion);
onWrite();
}
update.release(contextVk->getRenderer());
}
// Only remove the updates that were actually applied to the image.
mSubresourceUpdates = std::move(updatesToKeep);
if (mSubresourceUpdates.empty())
{
mStagingBuffer.releaseInFlightBuffers(contextVk);
mStagingBuffer.release(contextVk->getRenderer());
}
return angle::Result::Continue;
}
angle::Result ImageHelper::flushAllStagedUpdates(ContextVk *contextVk)
{
// Clear the image.
return flushStagedUpdates(contextVk, LevelIndex(0), LevelIndex(mLevelCount), 0, mLayerCount,
{});
}
bool ImageHelper::isUpdateStaged(gl::LevelIndex levelGL, uint32_t layer)
{
// Check to see if any updates are staged for the given level and layer
if (mSubresourceUpdates.empty())
{
return false;
}
for (SubresourceUpdate &update : mSubresourceUpdates)
{
gl::LevelIndex updateMipLevelGL;
uint32_t updateBaseLayer, updateLayerCount;
update.getDestSubresource(mLayerCount, &updateMipLevelGL, &updateBaseLayer,
&updateLayerCount);
if (updateMipLevelGL == levelGL)
{
if (layer >= updateBaseLayer && layer < (updateBaseLayer + updateLayerCount))
{
// The level matches, and the layer is within the range
return true;
}
}
}
return false;
}
void ImageHelper::removeSupersededUpdates(gl::TexLevelMask skipLevelsMask)
{
if (mLayerCount > 64)
{
// Not implemented for images with more than 64 layers. A 64-bit mask is used for
// efficiency, hence the limit.
return;
}
// Cache extents for each mip level.
gl::TexLevelArray<gl::Extents> levelExtents;
for (LevelIndex level(0); level < LevelIndex(mLevelCount); ++level)
{
levelExtents[level.get()] = getLevelExtents(level);
}
// Go over updates in reverse order, and mark the layers they completely overwrite. If an
// update is encountered whose layers are all already marked, that update is superseded by
// future updates, so it can be dropped. This tracking is done per level. If the aspect being
// written to is color/depth or stencil, index 0 or 1 is used respectively. This is so
// that if a depth write for example covers the whole subresource, a stencil write to that same
// subresource is not dropped.
constexpr size_t kIndexColorOrDepth = 0;
constexpr size_t kIndexStencil = 1;
gl::TexLevelArray<uint64_t> levelSupersededLayers[2] = {};
auto markLayersAndDropSuperseded = [&, skipLevelsMask](const SubresourceUpdate &update) {
gl::LevelIndex updateMipLevelGL;
uint32_t updateBaseLayer, updateLayerCount;
update.getDestSubresource(mLayerCount, &updateMipLevelGL, &updateBaseLayer,
&updateLayerCount);
// If the update level is not within the image range, keep the update.
if (updateMipLevelGL < mBaseLevel || updateMipLevelGL > mMaxLevel)
{
return false;
}
// If level is skipped (because incompatibly redefined), don't remove any of its updates.
const LevelIndex updateMipLevelVk = toVkLevel(updateMipLevelGL);
if (skipLevelsMask.test(updateMipLevelVk.get()))
{
return false;
}
const VkImageAspectFlags aspectMask = update.getDestAspectFlags();
const bool hasColorOrDepth =
(aspectMask & (VK_IMAGE_ASPECT_COLOR_BIT | VK_IMAGE_ASPECT_DEPTH_BIT)) != 0;
const bool hasStencil = (aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT) != 0;
// Test if the update is to layers that are all superseded. In that case, drop the update.
ASSERT(updateLayerCount <= 64);
uint64_t updateLayersMask = updateLayerCount >= 64
? ~static_cast<uint64_t>(0)
: angle::Bit<uint64_t>(updateLayerCount) - 1;
updateLayersMask <<= updateBaseLayer;
const bool isColorOrDepthSuperseded =
!hasColorOrDepth || (levelSupersededLayers[kIndexColorOrDepth][updateMipLevelVk.get()] &
updateLayersMask) == updateLayersMask;
const bool isStencilSuperseded =
!hasStencil || (levelSupersededLayers[kIndexStencil][updateMipLevelVk.get()] &
updateLayersMask) == updateLayersMask;
if (isColorOrDepthSuperseded && isStencilSuperseded)
{
return true;
}
// Get the area this update affects. Note that clear updates always clear the whole
// subresource.
const gl::Extents &levelExtent = levelExtents[updateMipLevelVk.get()];
gl::Box updateBox(gl::kOffsetZero, levelExtent);
if (update.updateSource == UpdateSource::Buffer)
{
updateBox =
gl::Box(update.buffer.copyRegion.imageOffset, update.buffer.copyRegion.imageExtent);
}
else if (update.updateSource == UpdateSource::Image)
{
updateBox = gl::Box(update.image.copyRegion.dstOffset, update.image.copyRegion.extent);
}
// Only if the update is to the whole subresource, mark its layers.
if (updateBox.coversSameExtent(levelExtent))
{
if (hasColorOrDepth)
{
levelSupersededLayers[kIndexColorOrDepth][updateMipLevelVk.get()] |=
updateLayersMask;
}
if (hasStencil)
{
levelSupersededLayers[kIndexStencil][updateMipLevelVk.get()] |= updateLayersMask;
}
}
return false;
};
mSubresourceUpdates.erase(
mSubresourceUpdates.rend().base(),
std::remove_if(mSubresourceUpdates.rbegin(), mSubresourceUpdates.rend(),
markLayersAndDropSuperseded)
.base());
}
angle::Result ImageHelper::copyImageDataToBuffer(ContextVk *contextVk,
gl::LevelIndex sourceLevelGL,
uint32_t layerCount,
uint32_t baseLayer,
const gl::Box &sourceArea,
BufferHelper **bufferOut,
size_t *bufferSize,
StagingBufferOffsetArray *bufferOffsetsOut,
uint8_t **outDataPtr)
{
ANGLE_TRACE_EVENT0("gpu.angle", "ImageHelper::copyImageDataToBuffer");
const angle::Format &imageFormat = mFormat->actualImageFormat();
// Two VK formats (one depth-only, one combined depth/stencil) use an extra byte for depth.
// From https://www.khronos.org/registry/vulkan/specs/1.1/html/vkspec.html#VkBufferImageCopy:
// data copied to or from the depth aspect of a VK_FORMAT_X8_D24_UNORM_PACK32 or
// VK_FORMAT_D24_UNORM_S8_UINT format is packed with one 32-bit word per texel...
// So make sure if we hit the depth/stencil format that we have 5 bytes per pixel (4 for depth
// data, 1 for stencil). NOTE that depth-only VK_FORMAT_X8_D24_UNORM_PACK32 already has 4 bytes
// per pixel which is sufficient to contain its depth aspect (no stencil aspect).
uint32_t pixelBytes = imageFormat.pixelBytes;
uint32_t depthBytesPerPixel = imageFormat.depthBits >> 3;
if (mFormat->vkImageFormat == VK_FORMAT_D24_UNORM_S8_UINT)
{
pixelBytes = 5;
depthBytesPerPixel = 4;
}
*bufferSize = sourceArea.width * sourceArea.height * sourceArea.depth * pixelBytes * layerCount;
const VkImageAspectFlags aspectFlags = getAspectFlags();
// Allocate staging buffer data from context
VkBuffer bufferHandle;
size_t alignment = mStagingBuffer.getAlignment();
ANGLE_TRY(mStagingBuffer.allocateWithAlignment(contextVk, *bufferSize, alignment, outDataPtr,
&bufferHandle, &(*bufferOffsetsOut)[0],
nullptr));
*bufferOut = mStagingBuffer.getCurrentBuffer();
LevelIndex sourceLevelVk = toVkLevel(sourceLevelGL);
VkBufferImageCopy regions[2] = {};
// Default to non-combined DS case
regions[0].bufferOffset = (*bufferOffsetsOut)[0];
regions[0].bufferRowLength = 0;
regions[0].bufferImageHeight = 0;
regions[0].imageExtent.width = sourceArea.width;
regions[0].imageExtent.height = sourceArea.height;
regions[0].imageExtent.depth = sourceArea.depth;
regions[0].imageOffset.x = sourceArea.x;
regions[0].imageOffset.y = sourceArea.y;
regions[0].imageOffset.z = sourceArea.z;
regions[0].imageSubresource.aspectMask = aspectFlags;
regions[0].imageSubresource.baseArrayLayer = baseLayer;
regions[0].imageSubresource.layerCount = layerCount;
regions[0].imageSubresource.mipLevel = sourceLevelVk.get();
if (isCombinedDepthStencilFormat())
{
// For combined DS image we'll copy depth and stencil aspects separately
// Depth aspect comes first in buffer and can use most settings from above
regions[0].imageSubresource.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
// Get depth data size since stencil data immediately follows depth data in buffer
const VkDeviceSize depthSize = depthBytesPerPixel * sourceArea.width * sourceArea.height *
sourceArea.depth * layerCount;
// Double-check that we allocated enough buffer space (always 1 byte per stencil)
ASSERT(*bufferSize >= (depthSize + (sourceArea.width * sourceArea.height *
sourceArea.depth * layerCount)));
// Copy stencil data into buffer immediately following the depth data
const VkDeviceSize stencilOffset = (*bufferOffsetsOut)[0] + depthSize;
(*bufferOffsetsOut)[1] = stencilOffset;
regions[1] = regions[0];
regions[1].bufferOffset = stencilOffset;
regions[1].imageSubresource.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
}
ANGLE_TRY(contextVk->onBufferTransferWrite(*bufferOut));
ANGLE_TRY(contextVk->onImageTransferRead(aspectFlags, this));
CommandBuffer &commandBuffer = contextVk->getOutsideRenderPassCommandBuffer();
commandBuffer.copyImageToBuffer(mImage, getCurrentLayout(), bufferHandle, 1, regions);
return angle::Result::Continue;
}
// static
angle::Result ImageHelper::GetReadPixelsParams(ContextVk *contextVk,
const gl::PixelPackState &packState,
gl::Buffer *packBuffer,
GLenum format,
GLenum type,
const gl::Rectangle &area,
const gl::Rectangle &clippedArea,
PackPixelsParams *paramsOut,
GLuint *skipBytesOut)
{
const gl::InternalFormat &sizedFormatInfo = gl::GetInternalFormatInfo(format, type);
GLuint outputPitch = 0;
ANGLE_VK_CHECK_MATH(contextVk,
sizedFormatInfo.computeRowPitch(type, area.width, packState.alignment,
packState.rowLength, &outputPitch));
ANGLE_VK_CHECK_MATH(contextVk, sizedFormatInfo.computeSkipBytes(type, outputPitch, 0, packState,
false, skipBytesOut));
*skipBytesOut += (clippedArea.x - area.x) * sizedFormatInfo.pixelBytes +
(clippedArea.y - area.y) * outputPitch;
const angle::Format &angleFormat = GetFormatFromFormatType(format, type);
*paramsOut = PackPixelsParams(clippedArea, angleFormat, outputPitch, packState.reverseRowOrder,
packBuffer, 0);
return angle::Result::Continue;
}
angle::Result ImageHelper::readPixelsForGetImage(ContextVk *contextVk,
const gl::PixelPackState &packState,
gl::Buffer *packBuffer,
gl::LevelIndex levelGL,
uint32_t layer,
GLenum format,
GLenum type,
void *pixels)
{
const angle::Format &angleFormat = GetFormatFromFormatType(format, type);
VkImageAspectFlagBits aspectFlags = {};
if (angleFormat.redBits > 0 || angleFormat.blueBits > 0 || angleFormat.greenBits > 0 ||
angleFormat.alphaBits > 0 || angleFormat.luminanceBits > 0)
{
aspectFlags = VK_IMAGE_ASPECT_COLOR_BIT;
}
else
{
if (angleFormat.depthBits > 0)
{
if (angleFormat.stencilBits != 0)
{
// TODO (anglebug.com/4688) Support combined depth stencil for GetTexImage
WARN() << "Unable to pull combined depth/stencil for GetTexImage";
return angle::Result::Continue;
}
aspectFlags = VK_IMAGE_ASPECT_DEPTH_BIT;
}
if (angleFormat.stencilBits > 0)
{
aspectFlags = VK_IMAGE_ASPECT_STENCIL_BIT;
}
}
ASSERT(aspectFlags != 0);
PackPixelsParams params;
GLuint outputSkipBytes = 0;
const LevelIndex levelVk = toVkLevel(levelGL);
const gl::Extents mipExtents = getLevelExtents(levelVk);
gl::Rectangle area(0, 0, mipExtents.width, mipExtents.height);
ANGLE_TRY(GetReadPixelsParams(contextVk, packState, packBuffer, format, type, area, area,
¶ms, &outputSkipBytes));
// Use a temporary staging buffer. Could be optimized.
RendererScoped<DynamicBuffer> stagingBuffer(contextVk->getRenderer());
stagingBuffer.get().init(contextVk->getRenderer(), VK_BUFFER_USAGE_TRANSFER_DST_BIT, 1,
kStagingBufferSize, true);
if (mExtents.depth > 1)
{
// Depth > 1 means this is a 3D texture and we need to copy all layers
for (layer = 0; layer < static_cast<uint32_t>(mipExtents.depth); layer++)
{
ANGLE_TRY(readPixels(contextVk, area, params, aspectFlags, levelGL, layer,
static_cast<uint8_t *>(pixels) + outputSkipBytes,
&stagingBuffer.get()));
outputSkipBytes += mipExtents.width * mipExtents.height *
gl::GetInternalFormatInfo(format, type).pixelBytes;
}
}
else
{
ANGLE_TRY(readPixels(contextVk, area, params, aspectFlags, levelGL, layer,
static_cast<uint8_t *>(pixels) + outputSkipBytes,
&stagingBuffer.get()));
}
return angle::Result::Continue;
}
angle::Result ImageHelper::readPixels(ContextVk *contextVk,
const gl::Rectangle &area,
const PackPixelsParams &packPixelsParams,
VkImageAspectFlagBits copyAspectFlags,
gl::LevelIndex levelGL,
uint32_t layer,
void *pixels,
DynamicBuffer *stagingBuffer)
{
ANGLE_TRACE_EVENT0("gpu.angle", "ImageHelper::readPixels");
RendererVk *renderer = contextVk->getRenderer();
// If the source image is multisampled, we need to resolve it into a temporary image before
// performing a readback.
bool isMultisampled = mSamples > 1;
RendererScoped<ImageHelper> resolvedImage(contextVk->getRenderer());
ImageHelper *src = this;
ASSERT(!isUpdateStaged(levelGL, layer));
if (isMultisampled)
{
ANGLE_TRY(resolvedImage.get().init2DStaging(
contextVk, renderer->getMemoryProperties(), gl::Extents(area.width, area.height, 1),
*mFormat, VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, 1));
resolvedImage.get().retain(&contextVk->getResourceUseList());
}
VkImageAspectFlags layoutChangeAspectFlags = src->getAspectFlags();
// Note that although we're reading from the image, we need to update the layout below.
if (isMultisampled)
{
ANGLE_TRY(contextVk->onImageTransferWrite(layoutChangeAspectFlags, &resolvedImage.get()));
}
ANGLE_TRY(contextVk->onImageTransferRead(layoutChangeAspectFlags, this));
CommandBuffer &commandBuffer = contextVk->getOutsideRenderPassCommandBuffer();
const angle::Format *readFormat = &mFormat->actualImageFormat();
if (copyAspectFlags != VK_IMAGE_ASPECT_COLOR_BIT)
{
readFormat = &GetDepthStencilImageToBufferFormat(*readFormat, copyAspectFlags);
}
VkOffset3D srcOffset = {area.x, area.y, 0};
VkImageSubresourceLayers srcSubresource = {};
srcSubresource.aspectMask = copyAspectFlags;
srcSubresource.mipLevel = toVkLevel(levelGL).get();
srcSubresource.baseArrayLayer = layer;
srcSubresource.layerCount = 1;
VkExtent3D srcExtent = {static_cast<uint32_t>(area.width), static_cast<uint32_t>(area.height),
1};
if (mExtents.depth > 1)
{
// Depth > 1 means this is a 3D texture and we need special handling
srcOffset.z = layer;
srcSubresource.baseArrayLayer = 0;
}
if (isMultisampled)
{
// Note: resolve only works on color images (not depth/stencil).
ASSERT(copyAspectFlags == VK_IMAGE_ASPECT_COLOR_BIT);
VkImageResolve resolveRegion = {};
resolveRegion.srcSubresource = srcSubresource;
resolveRegion.srcOffset = srcOffset;
resolveRegion.dstSubresource.aspectMask = copyAspectFlags;
resolveRegion.dstSubresource.mipLevel = 0;
resolveRegion.dstSubresource.baseArrayLayer = 0;
resolveRegion.dstSubresource.layerCount = 1;
resolveRegion.dstOffset = {};
resolveRegion.extent = srcExtent;
resolve(&resolvedImage.get(), resolveRegion, &commandBuffer);
ANGLE_TRY(contextVk->onImageTransferRead(layoutChangeAspectFlags, &resolvedImage.get()));
// Make the resolved image the target of buffer copy.
src = &resolvedImage.get();
srcOffset = {0, 0, 0};
srcSubresource.baseArrayLayer = 0;
srcSubresource.layerCount = 1;
srcSubresource.mipLevel = 0;
}
VkBuffer bufferHandle = VK_NULL_HANDLE;
uint8_t *readPixelBuffer = nullptr;
VkDeviceSize stagingOffset = 0;
size_t allocationSize = readFormat->pixelBytes * area.width * area.height;
ANGLE_TRY(stagingBuffer->allocate(contextVk, allocationSize, &readPixelBuffer, &bufferHandle,
&stagingOffset, nullptr));
VkBufferImageCopy region = {};
region.bufferImageHeight = srcExtent.height;
region.bufferOffset = stagingOffset;
region.bufferRowLength = srcExtent.width;
region.imageExtent = srcExtent;
region.imageOffset = srcOffset;
region.imageSubresource = srcSubresource;
commandBuffer.copyImageToBuffer(src->getImage(), src->getCurrentLayout(), bufferHandle, 1,
®ion);
ANGLE_PERF_WARNING(contextVk->getDebug(), GL_DEBUG_SEVERITY_HIGH,
"GPU stall due to ReadPixels");
// Triggers a full finish.
// TODO(jmadill): Don't block on asynchronous readback.
ANGLE_TRY(contextVk->finishImpl());
// The buffer we copied to needs to be invalidated before we read from it because its not been
// created with the host coherent bit.
ANGLE_TRY(stagingBuffer->invalidate(contextVk));
if (packPixelsParams.packBuffer)
{
// Must map the PBO in order to read its contents (and then unmap it later)
BufferVk *packBufferVk = GetImpl(packPixelsParams.packBuffer);
void *mapPtr = nullptr;
ANGLE_TRY(packBufferVk->mapImpl(contextVk, &mapPtr));
uint8_t *dest = static_cast<uint8_t *>(mapPtr) + reinterpret_cast<ptrdiff_t>(pixels);
PackPixels(packPixelsParams, *readFormat, area.width * readFormat->pixelBytes,
readPixelBuffer, static_cast<uint8_t *>(dest));
ANGLE_TRY(packBufferVk->unmapImpl(contextVk));
}
else
{
PackPixels(packPixelsParams, *readFormat, area.width * readFormat->pixelBytes,
readPixelBuffer, static_cast<uint8_t *>(pixels));
}
return angle::Result::Continue;
}
// ImageHelper::SubresourceUpdate implementation
ImageHelper::SubresourceUpdate::SubresourceUpdate() : updateSource(UpdateSource::Buffer), buffer{}
{}
ImageHelper::SubresourceUpdate::SubresourceUpdate(BufferHelper *bufferHelperIn,
const VkBufferImageCopy ©RegionIn)
: updateSource(UpdateSource::Buffer), buffer{bufferHelperIn, copyRegionIn}
{}
ImageHelper::SubresourceUpdate::SubresourceUpdate(ImageHelper *imageIn,
const VkImageCopy ©RegionIn)
: updateSource(UpdateSource::Image), image{imageIn, copyRegionIn}
{}
ImageHelper::SubresourceUpdate::SubresourceUpdate(VkImageAspectFlags aspectFlags,
const VkClearValue &clearValue,
const gl::ImageIndex &imageIndex)
: updateSource(UpdateSource::Clear)
{
clear.aspectFlags = aspectFlags;
clear.value = clearValue;
clear.levelIndex = imageIndex.getLevelIndex();
clear.layerIndex = imageIndex.hasLayer() ? imageIndex.getLayerIndex() : 0;
clear.layerCount =
imageIndex.hasLayer() ? imageIndex.getLayerCount() : VK_REMAINING_ARRAY_LAYERS;
}
ImageHelper::SubresourceUpdate::SubresourceUpdate(const SubresourceUpdate &other)
: updateSource(other.updateSource)
{
if (updateSource == UpdateSource::Clear)
{
clear = other.clear;
}
else if (updateSource == UpdateSource::Buffer)
{
buffer = other.buffer;
}
else
{
image = other.image;
}
}
ImageHelper::SubresourceUpdate &ImageHelper::SubresourceUpdate::operator=(
const SubresourceUpdate &other)
{
updateSource = other.updateSource;
if (updateSource == UpdateSource::Clear)
{
clear = other.clear;
}
else if (updateSource == UpdateSource::Buffer)
{
buffer = other.buffer;
}
else
{
image = other.image;
}
return *this;
}
void ImageHelper::SubresourceUpdate::release(RendererVk *renderer)
{
if (updateSource == UpdateSource::Image)
{
image.image->releaseImage(renderer);
image.image->releaseStagingBuffer(renderer);
SafeDelete(image.image);
}
}
bool ImageHelper::SubresourceUpdate::isUpdateToLayerLevel(uint32_t layerIndex,
gl::LevelIndex levelIndexGL) const
{
gl::LevelIndex updateMipLevelGL;
uint32_t updateBaseLayer, updateLayerCount;
getDestSubresource(gl::ImageIndex::kEntireLevel, &updateMipLevelGL, &updateBaseLayer,
&updateLayerCount);
return updateMipLevelGL == levelIndexGL && updateBaseLayer == layerIndex;
}
void ImageHelper::SubresourceUpdate::getDestSubresource(uint32_t imageLayerCount,
gl::LevelIndex *levelIndexGLOut,
uint32_t *baseLayerOut,
uint32_t *layerCountOut) const
{
if (updateSource == UpdateSource::Clear)
{
*levelIndexGLOut = gl::LevelIndex(clear.levelIndex);
*baseLayerOut = clear.layerIndex;
*layerCountOut = clear.layerCount;
if (*layerCountOut == static_cast<uint32_t>(gl::ImageIndex::kEntireLevel))
{
*layerCountOut = imageLayerCount;
}
}
else
{
const VkImageSubresourceLayers &dstSubresource = updateSource == UpdateSource::Buffer
? buffer.copyRegion.imageSubresource
: image.copyRegion.dstSubresource;
// Note that the updates store a gl::LevelIndex until they are flushed.
*levelIndexGLOut = gl::LevelIndex(dstSubresource.mipLevel);
*baseLayerOut = dstSubresource.baseArrayLayer;
*layerCountOut = dstSubresource.layerCount;
ASSERT(*layerCountOut != static_cast<uint32_t>(gl::ImageIndex::kEntireLevel));
}
}
VkImageAspectFlags ImageHelper::SubresourceUpdate::getDestAspectFlags() const
{
if (updateSource == UpdateSource::Clear)
{
return clear.aspectFlags;
}
else if (updateSource == UpdateSource::Buffer)
{
return buffer.copyRegion.imageSubresource.aspectMask;
}
else
{
ASSERT(updateSource == UpdateSource::Image);
return image.copyRegion.dstSubresource.aspectMask;
}
}
void ImageHelper::appendSubresourceUpdate(SubresourceUpdate &&update)
{
mSubresourceUpdates.emplace_back(std::move(update));
onStateChange(angle::SubjectMessage::SubjectChanged);
}
void ImageHelper::prependSubresourceUpdate(SubresourceUpdate &&update)
{
mSubresourceUpdates.insert(mSubresourceUpdates.begin(), std::move(update));
onStateChange(angle::SubjectMessage::SubjectChanged);
}
// FramebufferHelper implementation.
FramebufferHelper::FramebufferHelper() = default;
FramebufferHelper::~FramebufferHelper() = default;
FramebufferHelper::FramebufferHelper(FramebufferHelper &&other)
{
mFramebuffer = std::move(other.mFramebuffer);
}
FramebufferHelper &FramebufferHelper::operator=(FramebufferHelper &&other)
{
std::swap(mFramebuffer, other.mFramebuffer);
return *this;
}
angle::Result FramebufferHelper::init(ContextVk *contextVk,
const VkFramebufferCreateInfo &createInfo)
{
ANGLE_VK_TRY(contextVk, mFramebuffer.init(contextVk->getDevice(), createInfo));
return angle::Result::Continue;
}
void FramebufferHelper::release(ContextVk *contextVk)
{
contextVk->addGarbage(&mFramebuffer);
}
// ImageViewHelper implementation.
ImageViewHelper::ImageViewHelper() : mCurrentMaxLevel(0), mLinearColorspace(true)
{
mUse.init();
}
ImageViewHelper::ImageViewHelper(ImageViewHelper &&other)
{
std::swap(mCurrentMaxLevel, other.mCurrentMaxLevel);
std::swap(mPerLevelLinearReadImageViews, other.mPerLevelLinearReadImageViews);
std::swap(mPerLevelNonLinearReadImageViews, other.mPerLevelNonLinearReadImageViews);
std::swap(mPerLevelLinearFetchImageViews, other.mPerLevelLinearFetchImageViews);
std::swap(mPerLevelNonLinearFetchImageViews, other.mPerLevelNonLinearFetchImageViews);
std::swap(mPerLevelLinearCopyImageViews, other.mPerLevelLinearCopyImageViews);
std::swap(mPerLevelNonLinearCopyImageViews, other.mPerLevelNonLinearCopyImageViews);
std::swap(mLinearColorspace, other.mLinearColorspace);
std::swap(mPerLevelStencilReadImageViews, other.mPerLevelStencilReadImageViews);
std::swap(mLevelDrawImageViews, other.mLevelDrawImageViews);
std::swap(mLayerLevelDrawImageViews, other.mLayerLevelDrawImageViews);
std::swap(mImageViewSerial, other.mImageViewSerial);
}
ImageViewHelper::~ImageViewHelper()
{
mUse.release();
}
void ImageViewHelper::init(RendererVk *renderer)
{
if (!mImageViewSerial.valid())
{
mImageViewSerial = renderer->getResourceSerialFactory().generateImageViewSerial();
}
}
void ImageViewHelper::release(RendererVk *renderer)
{
std::vector<GarbageObject> garbage;
mCurrentMaxLevel = LevelIndex(0);
// Release the read views
ReleaseImageViews(&mPerLevelLinearReadImageViews, &garbage);
ReleaseImageViews(&mPerLevelNonLinearReadImageViews, &garbage);
ReleaseImageViews(&mPerLevelLinearFetchImageViews, &garbage);
ReleaseImageViews(&mPerLevelNonLinearFetchImageViews, &garbage);
ReleaseImageViews(&mPerLevelLinearCopyImageViews, &garbage);
ReleaseImageViews(&mPerLevelNonLinearCopyImageViews, &garbage);
ReleaseImageViews(&mPerLevelStencilReadImageViews, &garbage);
// Release the draw views
ReleaseImageViews(&mLevelDrawImageViews, &garbage);
for (ImageViewVector &layerViews : mLayerLevelDrawImageViews)
{
for (ImageView &imageView : layerViews)
{
if (imageView.valid())
{
garbage.emplace_back(GetGarbage(&imageView));
}
}
}
mLayerLevelDrawImageViews.clear();
if (!garbage.empty())
{
renderer->collectGarbage(std::move(mUse), std::move(garbage));
// Ensure the resource use is always valid.
mUse.init();
}
// Update image view serial.
mImageViewSerial = renderer->getResourceSerialFactory().generateImageViewSerial();
}
void ImageViewHelper::destroy(VkDevice device)
{
mCurrentMaxLevel = LevelIndex(0);
// Release the read views
DestroyImageViews(&mPerLevelLinearReadImageViews, device);
DestroyImageViews(&mPerLevelNonLinearReadImageViews, device);
DestroyImageViews(&mPerLevelLinearFetchImageViews, device);
DestroyImageViews(&mPerLevelNonLinearFetchImageViews, device);
DestroyImageViews(&mPerLevelLinearCopyImageViews, device);
DestroyImageViews(&mPerLevelNonLinearCopyImageViews, device);
DestroyImageViews(&mPerLevelStencilReadImageViews, device);
// Release the draw views
DestroyImageViews(&mLevelDrawImageViews, device);
for (ImageViewVector &layerViews : mLayerLevelDrawImageViews)
{
for (ImageView &imageView : layerViews)
{
imageView.destroy(device);
}
}
mLayerLevelDrawImageViews.clear();
mImageViewSerial = kInvalidImageViewSerial;
}
angle::Result ImageViewHelper::initReadViews(ContextVk *contextVk,
gl::TextureType viewType,
const ImageHelper &image,
const Format &format,
const gl::SwizzleState &formatSwizzle,
const gl::SwizzleState &readSwizzle,
LevelIndex baseLevel,
uint32_t levelCount,
uint32_t baseLayer,
uint32_t layerCount,
bool requiresSRGBViews,
VkImageUsageFlags imageUsageFlags)
{
ASSERT(levelCount > 0);
if (levelCount > mPerLevelLinearReadImageViews.size())
{
mPerLevelLinearReadImageViews.resize(levelCount);
mPerLevelNonLinearReadImageViews.resize(levelCount);
mPerLevelLinearFetchImageViews.resize(levelCount);
mPerLevelNonLinearFetchImageViews.resize(levelCount);
mPerLevelLinearCopyImageViews.resize(levelCount);
mPerLevelNonLinearCopyImageViews.resize(levelCount);
mPerLevelStencilReadImageViews.resize(levelCount);
}
mCurrentMaxLevel = LevelIndex(levelCount - 1);
// Determine if we already have ImageViews for the new max level
if (getReadImageView().valid())
{
return angle::Result::Continue;
}
// Since we don't have a readImageView, we must create ImageViews for the new max level
ANGLE_TRY(initReadViewsImpl(contextVk, viewType, image, format, formatSwizzle, readSwizzle,
baseLevel, levelCount, baseLayer, layerCount));
if (requiresSRGBViews)
{
ANGLE_TRY(initSRGBReadViewsImpl(contextVk, viewType, image, format, formatSwizzle,
readSwizzle, baseLevel, levelCount, baseLayer, layerCount,
imageUsageFlags));
}
return angle::Result::Continue;
}
angle::Result ImageViewHelper::initReadViewsImpl(ContextVk *contextVk,
gl::TextureType viewType,
const ImageHelper &image,
const Format &format,
const gl::SwizzleState &formatSwizzle,
const gl::SwizzleState &readSwizzle,
LevelIndex baseLevel,
uint32_t levelCount,
uint32_t baseLayer,
uint32_t layerCount)
{
ASSERT(mImageViewSerial.valid());
const VkImageAspectFlags aspectFlags = GetFormatAspectFlags(format.intendedFormat());
mLinearColorspace = IsLinearFormat(format.vkImageFormat);
if (HasBothDepthAndStencilAspects(aspectFlags))
{
ANGLE_TRY(image.initLayerImageView(contextVk, viewType, VK_IMAGE_ASPECT_DEPTH_BIT,
readSwizzle, &getReadImageView(), baseLevel, levelCount,
baseLayer, layerCount));
ANGLE_TRY(image.initLayerImageView(contextVk, viewType, VK_IMAGE_ASPECT_STENCIL_BIT,
readSwizzle,
&mPerLevelStencilReadImageViews[mCurrentMaxLevel.get()],
baseLevel, levelCount, baseLayer, layerCount));
}
else
{
ANGLE_TRY(image.initLayerImageView(contextVk, viewType, aspectFlags, readSwizzle,
&getReadImageView(), baseLevel, levelCount, baseLayer,
layerCount));
}
gl::TextureType fetchType = viewType;
if (viewType == gl::TextureType::CubeMap || viewType == gl::TextureType::_2DArray ||
viewType == gl::TextureType::_2DMultisampleArray)
{
fetchType = Get2DTextureType(layerCount, image.getSamples());
ANGLE_TRY(image.initLayerImageView(contextVk, fetchType, aspectFlags, readSwizzle,
&getFetchImageView(), baseLevel, levelCount, baseLayer,
layerCount));
}
ANGLE_TRY(image.initLayerImageView(contextVk, fetchType, aspectFlags, formatSwizzle,
&getCopyImageView(), baseLevel, levelCount, baseLayer,
layerCount));
return angle::Result::Continue;
}
angle::Result ImageViewHelper::initSRGBReadViewsImpl(ContextVk *contextVk,
gl::TextureType viewType,
const ImageHelper &image,
const Format &format,
const gl::SwizzleState &formatSwizzle,
const gl::SwizzleState &readSwizzle,
LevelIndex baseLevel,
uint32_t levelCount,
uint32_t baseLayer,
uint32_t layerCount,
VkImageUsageFlags imageUsageFlags)
{
VkFormat nonLinearOverrideFormat = ConvertToNonLinear(image.getFormat().vkImageFormat);
VkFormat linearOverrideFormat = ConvertToLinear(image.getFormat().vkImageFormat);
VkFormat linearFormat =
(linearOverrideFormat != VK_FORMAT_UNDEFINED) ? linearOverrideFormat : format.vkImageFormat;
ASSERT(linearFormat != VK_FORMAT_UNDEFINED);
const VkImageAspectFlags aspectFlags = GetFormatAspectFlags(format.intendedFormat());
if (!mPerLevelLinearReadImageViews[mCurrentMaxLevel.get()].valid())
{
ANGLE_TRY(image.initAliasedLayerImageView(
contextVk, viewType, aspectFlags, readSwizzle,
&mPerLevelLinearReadImageViews[mCurrentMaxLevel.get()], baseLevel, levelCount,
baseLayer, layerCount, imageUsageFlags, linearFormat));
}
if (nonLinearOverrideFormat != VK_FORMAT_UNDEFINED &&
!mPerLevelNonLinearReadImageViews[mCurrentMaxLevel.get()].valid())
{
ANGLE_TRY(image.initAliasedLayerImageView(
contextVk, viewType, aspectFlags, readSwizzle,
&mPerLevelNonLinearReadImageViews[mCurrentMaxLevel.get()], baseLevel, levelCount,
baseLayer, layerCount, imageUsageFlags, nonLinearOverrideFormat));
}
gl::TextureType fetchType = viewType;
if (viewType == gl::TextureType::CubeMap || viewType == gl::TextureType::_2DArray ||
viewType == gl::TextureType::_2DMultisampleArray)
{
fetchType = Get2DTextureType(layerCount, image.getSamples());
if (!mPerLevelLinearFetchImageViews[mCurrentMaxLevel.get()].valid())
{
ANGLE_TRY(image.initAliasedLayerImageView(
contextVk, fetchType, aspectFlags, readSwizzle,
&mPerLevelLinearFetchImageViews[mCurrentMaxLevel.get()], baseLevel, levelCount,
baseLayer, layerCount, imageUsageFlags, linearFormat));
}
if (nonLinearOverrideFormat != VK_FORMAT_UNDEFINED &&
!mPerLevelNonLinearFetchImageViews[mCurrentMaxLevel.get()].valid())
{
ANGLE_TRY(image.initAliasedLayerImageView(
contextVk, fetchType, aspectFlags, readSwizzle,
&mPerLevelNonLinearFetchImageViews[mCurrentMaxLevel.get()], baseLevel, levelCount,
baseLayer, layerCount, imageUsageFlags, nonLinearOverrideFormat));
}
}
if (!mPerLevelLinearCopyImageViews[mCurrentMaxLevel.get()].valid())
{
ANGLE_TRY(image.initAliasedLayerImageView(
contextVk, fetchType, aspectFlags, formatSwizzle,
&mPerLevelLinearCopyImageViews[mCurrentMaxLevel.get()], baseLevel, levelCount,
baseLayer, layerCount, imageUsageFlags, linearFormat));
}
if (nonLinearOverrideFormat != VK_FORMAT_UNDEFINED &&
!mPerLevelNonLinearCopyImageViews[mCurrentMaxLevel.get()].valid())
{
ANGLE_TRY(image.initAliasedLayerImageView(
contextVk, fetchType, aspectFlags, formatSwizzle,
&mPerLevelNonLinearCopyImageViews[mCurrentMaxLevel.get()], baseLevel, levelCount,
baseLayer, layerCount, imageUsageFlags, nonLinearOverrideFormat));
}
return angle::Result::Continue;
}
angle::Result ImageViewHelper::getLevelDrawImageView(ContextVk *contextVk,
gl::TextureType viewType,
const ImageHelper &image,
LevelIndex levelVk,
uint32_t layer,
VkImageUsageFlags imageUsageFlags,
VkFormat vkImageFormat,
const ImageView **imageViewOut)
{
ASSERT(mImageViewSerial.valid());
retain(&contextVk->getResourceUseList());
ImageView *imageView = GetLevelImageView(&mLevelDrawImageViews, levelVk, image.getLevelCount());
*imageViewOut = imageView;
if (imageView->valid())
{
return angle::Result::Continue;
}
// Create the view. Note that storage images are not affected by swizzle parameters.
return image.initAliasedLayerImageView(contextVk, viewType, image.getAspectFlags(),
gl::SwizzleState(), imageView, levelVk, 1, layer,
image.getLayerCount(), imageUsageFlags, vkImageFormat);
}
angle::Result ImageViewHelper::getLevelLayerDrawImageView(ContextVk *contextVk,
const ImageHelper &image,
LevelIndex levelVk,
uint32_t layer,
const ImageView **imageViewOut)
{
ASSERT(image.valid());
ASSERT(mImageViewSerial.valid());
ASSERT(!image.getFormat().actualImageFormat().isBlock);
retain(&contextVk->getResourceUseList());
uint32_t layerCount = GetImageLayerCountForView(image);
// Lazily allocate the storage for image views
if (mLayerLevelDrawImageViews.empty())
{
mLayerLevelDrawImageViews.resize(layerCount);
}
ASSERT(mLayerLevelDrawImageViews.size() > layer);
ImageView *imageView =
GetLevelImageView(&mLayerLevelDrawImageViews[layer], levelVk, image.getLevelCount());
*imageViewOut = imageView;
if (imageView->valid())
{
return angle::Result::Continue;
}
// Lazily allocate the image view itself.
// Note that these views are specifically made to be used as color attachments, and therefore
// don't have swizzle.
gl::TextureType viewType = Get2DTextureType(1, image.getSamples());
return image.initLayerImageView(contextVk, viewType, image.getAspectFlags(), gl::SwizzleState(),
imageView, levelVk, 1, layer, 1);
}
ImageViewSubresourceSerial ImageViewHelper::getSubresourceSerial(gl::LevelIndex levelGL,
uint32_t levelCount,
uint32_t layer,
LayerMode layerMode) const
{
ASSERT(mImageViewSerial.valid());
ImageViewSubresourceSerial serial;
serial.imageViewSerial = mImageViewSerial;
SetBitField(serial.subresource.level, levelGL.get());
SetBitField(serial.subresource.levelCount, levelCount);
SetBitField(serial.subresource.layer, layer);
SetBitField(serial.subresource.singleLayer, layerMode == LayerMode::Single ? 1 : 0);
return serial;
}
// ShaderProgramHelper implementation.
ShaderProgramHelper::ShaderProgramHelper() = default;
ShaderProgramHelper::~ShaderProgramHelper() = default;
bool ShaderProgramHelper::valid(const gl::ShaderType shaderType) const
{
return mShaders[shaderType].valid();
}
void ShaderProgramHelper::destroy(VkDevice device)
{
mGraphicsPipelines.destroy(device);
mComputePipeline.destroy(device);
for (BindingPointer<ShaderAndSerial> &shader : mShaders)
{
shader.reset();
}
}
void ShaderProgramHelper::release(ContextVk *contextVk)
{
mGraphicsPipelines.release(contextVk);
contextVk->addGarbage(&mComputePipeline.get());
for (BindingPointer<ShaderAndSerial> &shader : mShaders)
{
shader.reset();
}
}
void ShaderProgramHelper::setShader(gl::ShaderType shaderType, RefCounted<ShaderAndSerial> *shader)
{
mShaders[shaderType].set(shader);
}
void ShaderProgramHelper::enableSpecializationConstant(sh::vk::SpecializationConstantId id)
{
ASSERT(id < sh::vk::SpecializationConstantId::EnumCount);
mSpecializationConstants.set(id);
}
angle::Result ShaderProgramHelper::getComputePipeline(Context *context,
const PipelineLayout &pipelineLayout,
PipelineAndSerial **pipelineOut)
{
if (mComputePipeline.valid())
{
*pipelineOut = &mComputePipeline;
return angle::Result::Continue;
}
RendererVk *renderer = context->getRenderer();
VkPipelineShaderStageCreateInfo shaderStage = {};
VkComputePipelineCreateInfo createInfo = {};
shaderStage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
shaderStage.flags = 0;
shaderStage.stage = VK_SHADER_STAGE_COMPUTE_BIT;
shaderStage.module = mShaders[gl::ShaderType::Compute].get().get().getHandle();
shaderStage.pName = "main";
shaderStage.pSpecializationInfo = nullptr;
createInfo.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO;
createInfo.flags = 0;
createInfo.stage = shaderStage;
createInfo.layout = pipelineLayout.getHandle();
createInfo.basePipelineHandle = VK_NULL_HANDLE;
createInfo.basePipelineIndex = 0;
PipelineCache *pipelineCache = nullptr;
ANGLE_TRY(renderer->getPipelineCache(&pipelineCache));
ANGLE_VK_TRY(context, mComputePipeline.get().initCompute(context->getDevice(), createInfo,
*pipelineCache));
*pipelineOut = &mComputePipeline;
return angle::Result::Continue;
}
// ActiveHandleCounter implementation.
ActiveHandleCounter::ActiveHandleCounter() : mActiveCounts{}, mAllocatedCounts{} {}
ActiveHandleCounter::~ActiveHandleCounter() = default;
} // namespace vk
} // namespace rx