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 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448 10449 10450 10451 10452 10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466 10467 10468 10469 10470 10471 10472 10473 10474 10475 10476 10477 10478 10479 10480 10481 10482 10483 10484 10485 10486 10487 10488 10489 10490 10491 10492 10493 10494 10495 10496 10497 10498 10499 10500 10501 10502 10503 10504 10505 10506 10507 10508 10509 10510 10511 10512 10513 10514 10515 10516 10517 10518 10519 10520 10521 10522 10523 10524 10525 10526 10527 10528 10529 10530 10531 10532 10533 10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544 10545 10546 10547 10548 10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573 10574 10575 10576 10577 10578 10579 10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593 10594 10595 10596 10597 10598 10599 10600 10601 10602 10603 10604 10605 10606 10607 10608 10609 10610 10611 10612 10613 10614 10615 10616 10617 10618 10619 10620 10621 10622 10623 10624 10625 10626 10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638 10639 10640 10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661 10662 10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675 10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691 10692 10693 10694 10695 10696 10697 10698 10699 10700 10701 10702 10703 10704 10705 10706 10707 10708 10709 10710 10711 10712 10713 10714 10715 10716 10717 10718 10719 10720 10721 10722 10723 10724 10725 10726 10727 10728 10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747 10748 10749 10750 10751 10752 10753 10754 10755 10756 10757 10758 10759 10760 10761 10762 10763 10764 10765 10766 10767 10768 10769 10770 10771 10772 10773 10774 10775 10776 10777 10778 10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797 10798 10799 10800 10801 10802 10803 10804 10805 10806 10807 10808 10809 10810 10811 10812 10813 10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849 10850 10851 10852 10853 10854 10855 10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869 10870 10871 10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910 10911 10912 10913 10914 10915 10916 10917 10918 10919 10920 10921 10922 10923 10924 10925 10926 10927 10928 10929 10930 10931 10932 10933 10934 10935 10936 10937 10938 10939 10940 10941 10942 10943 10944 10945 10946 10947 10948 10949 10950 10951 10952 10953 10954 10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972 10973 10974 10975 10976 10977 10978 10979 10980 10981 10982 10983 10984 10985 10986 10987 10988 10989 10990 10991 10992 10993 10994 10995 10996 10997 10998 10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013 11014 11015 11016 11017 11018 11019 11020 11021 11022 11023 11024 11025 11026 11027 11028 11029 11030 11031 11032 11033 11034 11035 11036 11037 11038 11039 11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050 11051 11052 11053 11054 11055 11056 11057 11058 11059 11060 11061 11062 11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076 11077 11078 11079 11080 11081 11082 11083 11084 11085 11086 11087 11088 11089 11090 11091 11092 11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109 11110 11111 11112 11113 11114 11115 11116 11117 11118 11119 11120 11121 11122 11123 11124 11125 11126 11127 11128 11129 11130 11131 11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181 11182 11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196 11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238 11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311 11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347 11348 11349 11350 11351 11352 11353 11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478 11479 11480 11481 11482 11483 11484 11485 11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500 11501 11502 11503 11504 11505 11506 11507 11508 11509 11510 11511 11512 11513 11514 11515 11516 11517 11518 11519 11520 11521 11522 11523 11524 11525 11526 11527 11528 11529 11530 11531 11532 11533 11534 11535 11536 11537 11538 11539 11540 11541 11542 11543 11544 11545 11546 11547 11548 11549 11550 11551 11552 11553 11554 11555 11556 11557 11558 11559 11560 11561 11562 11563 11564 11565 11566 11567 11568 11569 11570 11571 11572 11573 11574 11575 11576 11577 11578 11579 11580 11581 11582 11583 11584 11585 11586 11587 11588 11589 11590 11591 11592 11593 11594 11595 11596 11597 11598 11599 11600 11601 11602 11603 11604 11605 11606 11607 11608 11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627 11628 11629 11630 11631 11632 11633 11634 11635 11636 11637 11638 11639 11640 11641 11642 11643 11644 11645 11646 11647 11648 11649 11650 11651 11652 11653 11654 11655 11656 11657 11658 11659 11660 11661 11662 11663 11664 11665 11666 11667 11668 11669 11670 11671 11672 11673 11674 11675 11676 11677 11678 11679 11680 11681 11682 11683 11684 11685 11686 11687 11688 11689 11690 11691 11692 11693 11694 11695 11696 11697 11698 11699 11700 11701 11702 11703 11704 11705 11706 11707 11708 11709 11710 11711 11712 11713 11714 11715 11716 11717 11718 11719 11720 11721 11722 11723 11724 11725 11726 11727 11728 11729 11730 11731 11732 11733 11734 11735 11736 11737 11738 11739 11740 11741 11742 11743 11744 11745 11746 11747 11748 11749 11750 11751 11752 11753 11754 11755 11756 11757 11758 11759 11760 11761 11762 11763 11764 11765 11766 11767 11768 11769 11770 11771 11772 11773 11774 11775 11776 11777 11778 11779 11780 11781 11782 11783 11784 11785 11786 11787 11788 11789 11790 11791 11792 11793 11794 11795 11796 11797 11798 11799 11800 11801 11802 11803 11804 11805 11806 11807 11808 11809 11810 11811 11812 11813 11814 11815 11816 11817 11818 11819 11820 11821 11822 11823 11824 11825 11826 11827 11828 11829 11830 11831 11832 11833 11834 11835 11836 11837 11838 11839 11840 11841 11842 11843 11844 11845 11846 11847 11848 11849 11850 11851 11852 11853 11854 11855 11856 11857 11858 11859 11860 11861 11862 11863 11864 11865 11866 11867 11868 11869 11870 11871 11872 11873 11874 11875 11876 11877 11878 11879 11880 11881 11882 11883 11884 11885 11886 11887 11888 11889 11890 11891 11892 11893 11894 11895 11896 11897 11898 11899 11900 11901 11902 11903 11904 11905 11906 11907 11908 11909 11910 11911 11912 11913 11914 11915 11916 11917 11918 11919 11920 11921 11922 11923 11924 11925 11926 11927 11928 11929 11930 11931 11932 11933 11934 11935 11936 11937 11938 11939 11940 11941 11942 11943 11944 11945 11946 11947 11948 11949 11950 11951 11952 11953 11954 11955 11956 11957 11958 11959 11960 11961 11962 11963 11964 11965 11966 11967 11968 11969 11970 11971 11972 11973 11974 11975 11976 11977 11978 11979 11980 11981 11982 11983 11984 11985 11986 11987 11988 11989 11990 11991 11992 11993 11994 11995 11996 11997 11998 11999 12000 12001 12002 12003 12004 12005 12006 12007 12008 12009 12010 12011 12012 12013 12014 12015 12016 12017 12018 12019 12020 12021 12022 12023 12024 12025 12026 12027 12028 12029 12030 12031 12032 12033 12034 12035 12036 12037 12038 12039 12040 12041 12042 12043 12044 12045 12046 12047 12048 12049 12050 12051 12052 12053 12054 12055 12056 12057 12058 12059 12060 12061 12062 12063 12064 12065 12066 12067 12068 12069 12070 12071 12072 12073 12074 12075 12076 12077 12078 12079 12080 12081 12082 12083 12084 12085 12086 12087 12088 12089 12090 12091 12092 12093 12094 12095 12096 12097 12098 12099 12100 12101 12102 12103 12104 12105 12106 12107 12108 12109 12110 12111 12112 12113 12114 12115 12116 12117 12118 12119 12120 12121 12122 12123 12124 12125 12126 12127 12128 12129 12130 12131 12132 12133 12134 12135 12136 12137 12138 12139 12140 12141 12142 12143 12144 12145 12146 12147 12148 12149 12150 12151 12152 12153 12154 12155 12156 12157 12158 12159 12160 12161 12162 12163 12164 12165 12166 12167 12168 12169 12170 12171 12172 12173 12174 12175 12176 12177 12178 12179 12180 12181 12182 12183 12184 12185 12186 12187 12188 12189 12190 12191 12192 12193 12194 12195 12196 12197 12198 12199 12200 12201 12202 12203 12204 12205 12206 12207 12208 12209 12210 12211 12212 12213 12214 12215 12216 12217 12218 12219 12220 12221 12222 12223 12224 12225 12226 12227 12228 12229 12230 12231 12232 12233 12234 12235 12236 12237 12238 12239 12240 12241 12242 12243 12244 12245 12246 12247 12248 12249 12250 12251 12252 12253 12254 12255 12256 12257 12258 12259 12260 12261 12262 12263 12264 12265 12266 12267 12268 12269 12270 12271 12272 12273 12274 12275 12276 12277 12278 12279 12280 12281 12282 12283 12284 12285 12286 12287 12288 12289 12290 12291 12292 12293 12294 12295 12296 12297 12298 12299 12300 12301 12302 12303 12304 12305 12306 12307 12308 12309 12310 12311 12312 12313 12314 12315 12316 12317 12318 12319 12320 12321 12322 12323 12324 12325 12326 12327 12328 12329 12330 12331 12332 12333 12334 12335 12336 12337 12338 12339 12340 12341 12342 12343 12344 12345 12346 12347 12348 12349 12350 12351 12352 12353 12354 12355 12356 12357 12358 12359 12360 12361 12362 12363 12364 12365 12366 12367 12368 12369 12370 12371 12372 12373 12374 12375 12376 12377 12378 12379 12380 12381 12382 12383 12384 12385 12386 12387 12388 12389 12390 12391 12392 12393 12394 12395 12396 12397 12398 12399 12400 12401 12402 12403 12404 12405 12406 12407 12408 12409 12410 12411 12412 12413 12414 12415 12416 12417 12418 12419 12420 12421 12422 12423 12424 12425 12426 12427 12428 12429 12430 12431 12432 12433 12434 12435 12436 12437 12438 12439 12440 12441 12442 12443 12444 12445 12446 12447 12448 12449 12450 12451 12452 12453 12454 12455 12456 12457 12458 12459 12460 12461 12462 12463 12464 12465 12466 12467 12468 12469 12470 12471 12472 12473 12474 12475 12476 12477 12478 12479 12480 12481 12482 12483 12484 12485 12486 12487 12488 12489 12490 12491 12492 12493 12494 12495 12496 12497 12498 12499 12500 12501 12502 12503 12504 12505 12506 12507 12508 12509 12510 12511 12512 12513 12514 12515 12516 12517 12518 12519 12520 12521 12522 12523 12524 12525 12526 12527 12528 12529 12530 12531 12532 12533 12534 12535 12536 12537 12538 12539 12540 12541 12542 12543 12544 12545 12546 12547 12548 12549 12550 12551 12552 12553 12554 12555 12556 12557 12558 12559 12560 12561 12562 12563 12564 12565 12566 12567 12568 12569 12570 12571 12572 12573 12574 12575 12576 12577 12578 12579 12580 12581 12582 12583 12584 12585 12586 12587 12588 12589 12590 12591 12592 12593 12594 12595 12596 12597 12598 12599 12600 12601 12602 12603 12604 12605 12606 12607 12608 12609 12610 12611 12612 12613 12614 12615 12616 12617 12618 12619 12620 12621 12622 12623 12624 12625 12626 12627 12628 12629 12630 12631 12632 12633 12634 12635 12636 12637 12638 12639 12640 12641 12642 12643 12644 12645 12646 12647 12648 12649 12650 12651 12652 12653 12654 12655 12656 12657 12658 12659 12660 12661 12662 12663 12664 12665 12666 12667 12668 12669 12670 12671 12672 12673 12674 12675 12676 12677 12678 12679 12680 12681 12682 12683 12684 12685 12686 12687 12688 12689 12690 12691 12692 12693 12694 12695 12696 12697 12698 12699 12700 12701 12702 12703 12704 12705 12706 12707 12708 12709 12710 12711 12712 12713 12714 12715 12716 12717 12718 12719 12720 12721 12722 12723 12724 12725 12726 12727 12728 12729 12730 12731 12732 12733 12734 12735 12736 12737 12738 12739 12740 12741 12742 12743 12744 12745 12746 12747 12748 12749 12750 12751 12752 12753 12754 12755 12756 12757 12758 12759 12760 12761 12762 12763 12764 12765 12766 12767 12768 12769 12770 12771 12772 12773 12774 12775 12776 12777 12778 12779 12780 12781 12782 12783 12784 12785 12786 12787 12788 12789 12790 12791 12792 12793 12794 12795 12796 12797 12798 12799 12800 12801 12802 12803 12804 12805 12806 12807 12808 12809 12810 12811 12812 12813 12814 12815 12816 12817 12818 12819 12820 12821 12822 12823 12824 12825 12826 12827 12828 12829 12830 12831 12832 12833 12834 12835 12836 12837 12838 12839 12840 12841 12842 12843 12844 12845 12846 12847 12848 12849 12850 12851 12852 12853 12854 12855 12856 12857 12858 12859 12860 12861 12862 12863 12864 12865 12866 12867 12868 12869 12870 12871 12872 12873 12874 12875 12876 12877 12878 12879 12880 12881 12882 12883 12884 12885 12886 12887 12888 12889 12890 12891 12892 12893 12894 12895 12896 12897 12898 12899 12900 12901 12902 12903 12904 12905 12906 12907 12908 12909 12910 12911 12912 12913 12914 12915 12916 12917 12918 12919 12920 12921 12922 12923 12924 12925 12926 12927 12928 12929 12930 12931 12932 12933 12934 12935 12936 12937 12938 12939 12940 12941 12942 12943 12944 12945 12946 12947 12948 12949 12950 12951 12952 12953 12954 12955 12956 12957 12958 12959 12960 12961 12962 12963 12964 12965 12966 12967 12968 12969 12970 12971 12972 12973 12974 12975 12976 12977 12978 12979 12980 12981 12982 12983 12984 12985 12986 12987 12988 12989 12990 12991 12992 12993 12994 12995 12996 12997 12998 12999 13000 13001 13002 13003 13004 13005 13006 13007 13008 13009 13010 13011 13012 13013 13014 13015 13016 13017 13018 13019 13020 13021 13022 13023 13024 13025 13026 13027 13028 13029 13030 13031 13032 13033 13034 13035 13036 13037 13038 13039 13040 13041 13042 13043 13044 13045 13046 13047 13048 13049 13050 13051 13052 13053 13054 13055 13056 13057 13058 13059 13060 13061 13062 13063 13064 13065 13066 13067 13068 13069 13070 13071 13072 13073 13074 13075 13076 13077 13078 13079 13080 13081 13082 13083 13084 13085 13086 13087 13088 13089 13090 13091 13092 13093 13094 13095 13096 13097 13098 13099 13100 13101 13102 13103 13104 13105 13106 13107 13108 13109 13110 13111 13112 13113 13114 13115 13116 13117 13118 13119 13120 13121 13122 13123 13124 13125 13126 13127 13128 13129 13130 13131 13132 13133 13134 13135 13136 13137 13138 13139 13140 13141 13142 13143 13144 13145 13146 13147 13148 13149 13150 13151 13152 13153 13154 13155 13156 13157 13158 13159 13160 13161 13162 13163 13164 13165 13166 13167 13168 13169 13170 13171 13172 13173 13174 13175 13176 13177 13178 13179 13180 13181 13182 13183 13184 13185 13186 13187 13188 13189 13190 13191 13192 13193 13194 13195 13196 13197 13198 13199 13200 13201 13202 13203 13204 13205 13206 13207 13208 13209 13210 13211 13212 13213 13214 13215 13216 13217 13218 13219 13220 13221 13222 13223 13224 13225 13226 13227 13228 13229 13230 13231 13232 13233 13234 13235 13236 13237 13238 13239 13240 13241 13242 13243 13244 13245 13246 13247 13248 13249 13250 13251 13252 13253 13254 13255 13256 13257 13258 13259 13260 13261 13262 13263 13264 13265 13266 13267 13268 13269 13270 13271 13272 13273 13274 13275 13276 13277 13278 13279 13280 13281 13282 13283 13284 13285 13286 13287 13288 13289 13290 13291 13292 13293 13294 13295 13296 13297 13298 13299 13300 13301 13302 13303 13304 13305 13306 13307 13308 13309 13310 13311 13312 13313 13314 13315 13316 13317 13318 13319 13320 13321 13322 13323 13324 13325 13326 13327 13328 13329 13330 13331 13332 13333 13334 13335 13336 13337 13338 13339 13340 13341 13342 13343 13344 13345 13346 13347 13348 13349 13350 13351 13352 13353 13354 13355 13356 13357 13358 13359 13360 13361 13362 13363 13364 13365 13366 13367 13368 13369 13370 13371 13372 13373 13374 13375 13376 13377 13378 13379 13380 13381 13382 13383 13384 13385 13386 13387 13388 13389 13390 13391 13392 13393 13394 13395 13396 13397 13398 13399 13400 13401 13402 13403 13404 13405 13406 13407 13408 13409 13410 13411 13412 13413 13414 13415 13416 13417 13418 13419 13420 13421 13422 13423 13424 13425 13426 13427 13428 13429 13430 13431 13432 13433 13434 13435 13436 13437 13438 13439 13440 13441 13442 13443 13444 13445 13446 13447 13448 13449 13450 13451 13452 13453 13454 13455 13456 13457 13458 13459 13460 13461 13462 13463 13464 13465 13466 13467 13468 13469 13470
|
//
// Copyright (c) 2017-2018 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#ifndef AMD_VULKAN_MEMORY_ALLOCATOR_H
#define AMD_VULKAN_MEMORY_ALLOCATOR_H
#ifdef __cplusplus
extern "C" {
#endif
/** \mainpage Vulkan Memory Allocator
<b>Version 2.1.0</b> (2018-09-10)
Copyright (c) 2017-2018 Advanced Micro Devices, Inc. All rights reserved. \n
License: MIT
Documentation of all members: vk_mem_alloc.h
\section main_table_of_contents Table of contents
- <b>User guide</b>
- \subpage quick_start
- [Project setup](@ref quick_start_project_setup)
- [Initialization](@ref quick_start_initialization)
- [Resource allocation](@ref quick_start_resource_allocation)
- \subpage choosing_memory_type
- [Usage](@ref choosing_memory_type_usage)
- [Required and preferred flags](@ref choosing_memory_type_required_preferred_flags)
- [Explicit memory types](@ref choosing_memory_type_explicit_memory_types)
- [Custom memory pools](@ref choosing_memory_type_custom_memory_pools)
- \subpage memory_mapping
- [Mapping functions](@ref memory_mapping_mapping_functions)
- [Persistently mapped memory](@ref memory_mapping_persistently_mapped_memory)
- [Cache control](@ref memory_mapping_cache_control)
- [Finding out if memory is mappable](@ref memory_mapping_finding_if_memory_mappable)
- \subpage custom_memory_pools
- [Choosing memory type index](@ref custom_memory_pools_MemTypeIndex)
- [Linear allocation algorithm](@ref linear_algorithm)
- [Free-at-once](@ref linear_algorithm_free_at_once)
- [Stack](@ref linear_algorithm_stack)
- [Double stack](@ref linear_algorithm_double_stack)
- [Ring buffer](@ref linear_algorithm_ring_buffer)
- \subpage defragmentation
- \subpage lost_allocations
- \subpage statistics
- [Numeric statistics](@ref statistics_numeric_statistics)
- [JSON dump](@ref statistics_json_dump)
- \subpage allocation_annotation
- [Allocation user data](@ref allocation_user_data)
- [Allocation names](@ref allocation_names)
- \subpage debugging_memory_usage
- [Memory initialization](@ref debugging_memory_usage_initialization)
- [Margins](@ref debugging_memory_usage_margins)
- [Corruption detection](@ref debugging_memory_usage_corruption_detection)
- \subpage record_and_replay
- \subpage usage_patterns
- [Simple patterns](@ref usage_patterns_simple)
- [Advanced patterns](@ref usage_patterns_advanced)
- \subpage configuration
- [Pointers to Vulkan functions](@ref config_Vulkan_functions)
- [Custom host memory allocator](@ref custom_memory_allocator)
- [Device memory allocation callbacks](@ref allocation_callbacks)
- [Device heap memory limit](@ref heap_memory_limit)
- \subpage vk_khr_dedicated_allocation
- \subpage general_considerations
- [Thread safety](@ref general_considerations_thread_safety)
- [Validation layer warnings](@ref general_considerations_validation_layer_warnings)
- [Allocation algorithm](@ref general_considerations_allocation_algorithm)
- [Features not supported](@ref general_considerations_features_not_supported)
\section main_see_also See also
- [Product page on GPUOpen](https://gpuopen.com/gaming-product/vulkan-memory-allocator/)
- [Source repository on GitHub](https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator)
\page quick_start Quick start
\section quick_start_project_setup Project setup
Vulkan Memory Allocator comes in form of a single header file.
You don't need to build it as a separate library project.
You can add this file directly to your project and submit it to code repository next to your other source files.
"Single header" doesn't mean that everything is contained in C/C++ declarations,
like it tends to be in case of inline functions or C++ templates.
It means that implementation is bundled with interface in a single file and needs to be extracted using preprocessor macro.
If you don't do it properly, you will get linker errors.
To do it properly:
-# Include "vk_mem_alloc.h" file in each CPP file where you want to use the library.
This includes declarations of all members of the library.
-# In exacly one CPP file define following macro before this include.
It enables also internal definitions.
\code
#define VMA_IMPLEMENTATION
#include "vk_mem_alloc.h"
\endcode
It may be a good idea to create dedicated CPP file just for this purpose.
Please note that this library includes header `<vulkan/vulkan.h>`, which in turn
includes `<windows.h>` on Windows. If you need some specific macros defined
before including these headers (like `WIN32_LEAN_AND_MEAN` or
`WINVER` for Windows, `VK_USE_PLATFORM_WIN32_KHR` for Vulkan), you must define
them before every `#include` of this library.
\section quick_start_initialization Initialization
At program startup:
-# Initialize Vulkan to have `VkPhysicalDevice` and `VkDevice` object.
-# Fill VmaAllocatorCreateInfo structure and create #VmaAllocator object by
calling vmaCreateAllocator().
\code
VmaAllocatorCreateInfo allocatorInfo = {};
allocatorInfo.physicalDevice = physicalDevice;
allocatorInfo.device = device;
VmaAllocator allocator;
vmaCreateAllocator(&allocatorInfo, &allocator);
\endcode
\section quick_start_resource_allocation Resource allocation
When you want to create a buffer or image:
-# Fill `VkBufferCreateInfo` / `VkImageCreateInfo` structure.
-# Fill VmaAllocationCreateInfo structure.
-# Call vmaCreateBuffer() / vmaCreateImage() to get `VkBuffer`/`VkImage` with memory
already allocated and bound to it.
\code
VkBufferCreateInfo bufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
bufferInfo.size = 65536;
bufferInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
VmaAllocationCreateInfo allocInfo = {};
allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
VkBuffer buffer;
VmaAllocation allocation;
vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr);
\endcode
Don't forget to destroy your objects when no longer needed:
\code
vmaDestroyBuffer(allocator, buffer, allocation);
vmaDestroyAllocator(allocator);
\endcode
\page choosing_memory_type Choosing memory type
Physical devices in Vulkan support various combinations of memory heaps and
types. Help with choosing correct and optimal memory type for your specific
resource is one of the key features of this library. You can use it by filling
appropriate members of VmaAllocationCreateInfo structure, as described below.
You can also combine multiple methods.
-# If you just want to find memory type index that meets your requirements, you
can use function vmaFindMemoryTypeIndex().
-# If you want to allocate a region of device memory without association with any
specific image or buffer, you can use function vmaAllocateMemory(). Usage of
this function is not recommended and usually not needed.
-# If you already have a buffer or an image created, you want to allocate memory
for it and then you will bind it yourself, you can use function
vmaAllocateMemoryForBuffer(), vmaAllocateMemoryForImage().
For binding you should use functions: vmaBindBufferMemory(), vmaBindImageMemory().
-# If you want to create a buffer or an image, allocate memory for it and bind
them together, all in one call, you can use function vmaCreateBuffer(),
vmaCreateImage(). This is the recommended way to use this library.
When using 3. or 4., the library internally queries Vulkan for memory types
supported for that buffer or image (function `vkGetBufferMemoryRequirements()`)
and uses only one of these types.
If no memory type can be found that meets all the requirements, these functions
return `VK_ERROR_FEATURE_NOT_PRESENT`.
You can leave VmaAllocationCreateInfo structure completely filled with zeros.
It means no requirements are specified for memory type.
It is valid, although not very useful.
\section choosing_memory_type_usage Usage
The easiest way to specify memory requirements is to fill member
VmaAllocationCreateInfo::usage using one of the values of enum #VmaMemoryUsage.
It defines high level, common usage types.
For more details, see description of this enum.
For example, if you want to create a uniform buffer that will be filled using
transfer only once or infrequently and used for rendering every frame, you can
do it using following code:
\code
VkBufferCreateInfo bufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
bufferInfo.size = 65536;
bufferInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
VmaAllocationCreateInfo allocInfo = {};
allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
VkBuffer buffer;
VmaAllocation allocation;
vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr);
\endcode
\section choosing_memory_type_required_preferred_flags Required and preferred flags
You can specify more detailed requirements by filling members
VmaAllocationCreateInfo::requiredFlags and VmaAllocationCreateInfo::preferredFlags
with a combination of bits from enum `VkMemoryPropertyFlags`. For example,
if you want to create a buffer that will be persistently mapped on host (so it
must be `HOST_VISIBLE`) and preferably will also be `HOST_COHERENT` and `HOST_CACHED`,
use following code:
\code
VmaAllocationCreateInfo allocInfo = {};
allocInfo.requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
allocInfo.preferredFlags = VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
allocInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
VkBuffer buffer;
VmaAllocation allocation;
vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr);
\endcode
A memory type is chosen that has all the required flags and as many preferred
flags set as possible.
If you use VmaAllocationCreateInfo::usage, it is just internally converted to
a set of required and preferred flags.
\section choosing_memory_type_explicit_memory_types Explicit memory types
If you inspected memory types available on the physical device and you have
a preference for memory types that you want to use, you can fill member
VmaAllocationCreateInfo::memoryTypeBits. It is a bit mask, where each bit set
means that a memory type with that index is allowed to be used for the
allocation. Special value 0, just like `UINT32_MAX`, means there are no
restrictions to memory type index.
Please note that this member is NOT just a memory type index.
Still you can use it to choose just one, specific memory type.
For example, if you already determined that your buffer should be created in
memory type 2, use following code:
\code
uint32_t memoryTypeIndex = 2;
VmaAllocationCreateInfo allocInfo = {};
allocInfo.memoryTypeBits = 1u << memoryTypeIndex;
VkBuffer buffer;
VmaAllocation allocation;
vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr);
\endcode
\section choosing_memory_type_custom_memory_pools Custom memory pools
If you allocate from custom memory pool, all the ways of specifying memory
requirements described above are not applicable and the aforementioned members
of VmaAllocationCreateInfo structure are ignored. Memory type is selected
explicitly when creating the pool and then used to make all the allocations from
that pool. For further details, see \ref custom_memory_pools.
\page memory_mapping Memory mapping
To "map memory" in Vulkan means to obtain a CPU pointer to `VkDeviceMemory`,
to be able to read from it or write to it in CPU code.
Mapping is possible only of memory allocated from a memory type that has
`VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT` flag.
Functions `vkMapMemory()`, `vkUnmapMemory()` are designed for this purpose.
You can use them directly with memory allocated by this library,
but it is not recommended because of following issue:
Mapping the same `VkDeviceMemory` block multiple times is illegal - only one mapping at a time is allowed.
This includes mapping disjoint regions. Mapping is not reference-counted internally by Vulkan.
Because of this, Vulkan Memory Allocator provides following facilities:
\section memory_mapping_mapping_functions Mapping functions
The library provides following functions for mapping of a specific #VmaAllocation: vmaMapMemory(), vmaUnmapMemory().
They are safer and more convenient to use than standard Vulkan functions.
You can map an allocation multiple times simultaneously - mapping is reference-counted internally.
You can also map different allocations simultaneously regardless of whether they use the same `VkDeviceMemory` block.
The way it's implemented is that the library always maps entire memory block, not just region of the allocation.
For further details, see description of vmaMapMemory() function.
Example:
\code
// Having these objects initialized:
struct ConstantBuffer
{
...
};
ConstantBuffer constantBufferData;
VmaAllocator allocator;
VkBuffer constantBuffer;
VmaAllocation constantBufferAllocation;
// You can map and fill your buffer using following code:
void* mappedData;
vmaMapMemory(allocator, constantBufferAllocation, &mappedData);
memcpy(mappedData, &constantBufferData, sizeof(constantBufferData));
vmaUnmapMemory(allocator, constantBufferAllocation);
\endcode
When mapping, you may see a warning from Vulkan validation layer similar to this one:
<i>Mapping an image with layout VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL can result in undefined behavior if this memory is used by the device. Only GENERAL or PREINITIALIZED should be used.</i>
It happens because the library maps entire `VkDeviceMemory` block, where different
types of images and buffers may end up together, especially on GPUs with unified memory like Intel.
You can safely ignore it if you are sure you access only memory of the intended
object that you wanted to map.
\section memory_mapping_persistently_mapped_memory Persistently mapped memory
Kepping your memory persistently mapped is generally OK in Vulkan.
You don't need to unmap it before using its data on the GPU.
The library provides a special feature designed for that:
Allocations made with #VMA_ALLOCATION_CREATE_MAPPED_BIT flag set in
VmaAllocationCreateInfo::flags stay mapped all the time,
so you can just access CPU pointer to it any time
without a need to call any "map" or "unmap" function.
Example:
\code
VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
bufCreateInfo.size = sizeof(ConstantBuffer);
bufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
VmaAllocationCreateInfo allocCreateInfo = {};
allocCreateInfo.usage = VMA_MEMORY_USAGE_CPU_ONLY;
allocCreateInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
VkBuffer buf;
VmaAllocation alloc;
VmaAllocationInfo allocInfo;
vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo);
// Buffer is already mapped. You can access its memory.
memcpy(allocInfo.pMappedData, &constantBufferData, sizeof(constantBufferData));
\endcode
There are some exceptions though, when you should consider mapping memory only for a short period of time:
- When operating system is Windows 7 or 8.x (Windows 10 is not affected because it uses WDDM2),
device is discrete AMD GPU,
and memory type is the special 256 MiB pool of `DEVICE_LOCAL + HOST_VISIBLE` memory
(selected when you use #VMA_MEMORY_USAGE_CPU_TO_GPU),
then whenever a memory block allocated from this memory type stays mapped
for the time of any call to `vkQueueSubmit()` or `vkQueuePresentKHR()`, this
block is migrated by WDDM to system RAM, which degrades performance. It doesn't
matter if that particular memory block is actually used by the command buffer
being submitted.
- Keeping many large memory blocks mapped may impact performance or stability of some debugging tools.
\section memory_mapping_cache_control Cache control
Memory in Vulkan doesn't need to be unmapped before using it on GPU,
but unless a memory types has `VK_MEMORY_PROPERTY_HOST_COHERENT_BIT` flag set,
you need to manually invalidate cache before reading of mapped pointer
and flush cache after writing to mapped pointer.
Vulkan provides following functions for this purpose `vkFlushMappedMemoryRanges()`,
`vkInvalidateMappedMemoryRanges()`, but this library provides more convenient
functions that refer to given allocation object: vmaFlushAllocation(),
vmaInvalidateAllocation().
Regions of memory specified for flush/invalidate must be aligned to
`VkPhysicalDeviceLimits::nonCoherentAtomSize`. This is automatically ensured by the library.
In any memory type that is `HOST_VISIBLE` but not `HOST_COHERENT`, all allocations
within blocks are aligned to this value, so their offsets are always multiply of
`nonCoherentAtomSize` and two different allocations never share same "line" of this size.
Please note that memory allocated with #VMA_MEMORY_USAGE_CPU_ONLY is guaranteed to be `HOST_COHERENT`.
Also, Windows drivers from all 3 PC GPU vendors (AMD, Intel, NVIDIA)
currently provide `HOST_COHERENT` flag on all memory types that are
`HOST_VISIBLE`, so on this platform you may not need to bother.
\section memory_mapping_finding_if_memory_mappable Finding out if memory is mappable
It may happen that your allocation ends up in memory that is `HOST_VISIBLE` (available for mapping)
despite it wasn't explicitly requested.
For example, application may work on integrated graphics with unified memory (like Intel) or
allocation from video memory might have failed, so the library chose system memory as fallback.
You can detect this case and map such allocation to access its memory on CPU directly,
instead of launching a transfer operation.
In order to do that: inspect `allocInfo.memoryType`, call vmaGetMemoryTypeProperties(),
and look for `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT` flag in properties of that memory type.
\code
VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
bufCreateInfo.size = sizeof(ConstantBuffer);
bufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
VmaAllocationCreateInfo allocCreateInfo = {};
allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
allocCreateInfo.preferredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
VkBuffer buf;
VmaAllocation alloc;
VmaAllocationInfo allocInfo;
vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo);
VkMemoryPropertyFlags memFlags;
vmaGetMemoryTypeProperties(allocator, allocInfo.memoryType, &memFlags);
if((memFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0)
{
// Allocation ended up in mappable memory. You can map it and access it directly.
void* mappedData;
vmaMapMemory(allocator, alloc, &mappedData);
memcpy(mappedData, &constantBufferData, sizeof(constantBufferData));
vmaUnmapMemory(allocator, alloc);
}
else
{
// Allocation ended up in non-mappable memory.
// You need to create CPU-side buffer in VMA_MEMORY_USAGE_CPU_ONLY and make a transfer.
}
\endcode
You can even use #VMA_ALLOCATION_CREATE_MAPPED_BIT flag while creating allocations
that are not necessarily `HOST_VISIBLE` (e.g. using #VMA_MEMORY_USAGE_GPU_ONLY).
If the allocation ends up in memory type that is `HOST_VISIBLE`, it will be persistently mapped and you can use it directly.
If not, the flag is just ignored.
Example:
\code
VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
bufCreateInfo.size = sizeof(ConstantBuffer);
bufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
VmaAllocationCreateInfo allocCreateInfo = {};
allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
allocCreateInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT;
VkBuffer buf;
VmaAllocation alloc;
VmaAllocationInfo allocInfo;
vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo);
if(allocInfo.pUserData != nullptr)
{
// Allocation ended up in mappable memory.
// It's persistently mapped. You can access it directly.
memcpy(allocInfo.pMappedData, &constantBufferData, sizeof(constantBufferData));
}
else
{
// Allocation ended up in non-mappable memory.
// You need to create CPU-side buffer in VMA_MEMORY_USAGE_CPU_ONLY and make a transfer.
}
\endcode
\page custom_memory_pools Custom memory pools
A memory pool contains a number of `VkDeviceMemory` blocks.
The library automatically creates and manages default pool for each memory type available on the device.
Default memory pool automatically grows in size.
Size of allocated blocks is also variable and managed automatically.
You can create custom pool and allocate memory out of it.
It can be useful if you want to:
- Keep certain kind of allocations separate from others.
- Enforce particular, fixed size of Vulkan memory blocks.
- Limit maximum amount of Vulkan memory allocated for that pool.
- Reserve minimum or fixed amount of Vulkan memory always preallocated for that pool.
To use custom memory pools:
-# Fill VmaPoolCreateInfo structure.
-# Call vmaCreatePool() to obtain #VmaPool handle.
-# When making an allocation, set VmaAllocationCreateInfo::pool to this handle.
You don't need to specify any other parameters of this structure, like `usage`.
Example:
\code
// Create a pool that can have at most 2 blocks, 128 MiB each.
VmaPoolCreateInfo poolCreateInfo = {};
poolCreateInfo.memoryTypeIndex = ...
poolCreateInfo.blockSize = 128ull * 1024 * 1024;
poolCreateInfo.maxBlockCount = 2;
VmaPool pool;
vmaCreatePool(allocator, &poolCreateInfo, &pool);
// Allocate a buffer out of it.
VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
bufCreateInfo.size = 1024;
bufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
VmaAllocationCreateInfo allocCreateInfo = {};
allocCreateInfo.pool = pool;
VkBuffer buf;
VmaAllocation alloc;
VmaAllocationInfo allocInfo;
vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo);
\endcode
You have to free all allocations made from this pool before destroying it.
\code
vmaDestroyBuffer(allocator, buf, alloc);
vmaDestroyPool(allocator, pool);
\endcode
\section custom_memory_pools_MemTypeIndex Choosing memory type index
When creating a pool, you must explicitly specify memory type index.
To find the one suitable for your buffers or images, you can use helper functions
vmaFindMemoryTypeIndexForBufferInfo(), vmaFindMemoryTypeIndexForImageInfo().
You need to provide structures with example parameters of buffers or images
that you are going to create in that pool.
\code
VkBufferCreateInfo exampleBufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
exampleBufCreateInfo.size = 1024; // Whatever.
exampleBufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; // Change if needed.
VmaAllocationCreateInfo allocCreateInfo = {};
allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; // Change if needed.
uint32_t memTypeIndex;
vmaFindMemoryTypeIndexForBufferInfo(allocator, &exampleBufCreateInfo, &allocCreateInfo, &memTypeIndex);
VmaPoolCreateInfo poolCreateInfo = {};
poolCreateInfo.memoryTypeIndex = memTypeIndex;
// ...
\endcode
When creating buffers/images allocated in that pool, provide following parameters:
- `VkBufferCreateInfo`: Prefer to pass same parameters as above.
Otherwise you risk creating resources in a memory type that is not suitable for them, which may result in undefined behavior.
Using different `VK_BUFFER_USAGE_` flags may work, but you shouldn't create images in a pool intended for buffers
or the other way around.
- VmaAllocationCreateInfo: You don't need to pass same parameters. Fill only `pool` member.
Other members are ignored anyway.
\section linear_algorithm Linear allocation algorithm
Each Vulkan memory block managed by this library has accompanying metadata that
keeps track of used and unused regions. By default, the metadata structure and
algorithm tries to find best place for new allocations among free regions to
optimize memory usage. This way you can allocate and free objects in any order.

Sometimes there is a need to use simpler, linear allocation algorithm. You can
create custom pool that uses such algorithm by adding flag
#VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT to VmaPoolCreateInfo::flags while creating
#VmaPool object. Then an alternative metadata management is used. It always
creates new allocations after last one and doesn't reuse free regions after
allocations freed in the middle. It results in better allocation performance and
less memory consumed by metadata.

With this one flag, you can create a custom pool that can be used in many ways:
free-at-once, stack, double stack, and ring buffer. See below for details.
\subsection linear_algorithm_free_at_once Free-at-once
In a pool that uses linear algorithm, you still need to free all the allocations
individually, e.g. by using vmaFreeMemory() or vmaDestroyBuffer(). You can free
them in any order. New allocations are always made after last one - free space
in the middle is not reused. However, when you release all the allocation and
the pool becomes empty, allocation starts from the beginning again. This way you
can use linear algorithm to speed up creation of allocations that you are going
to release all at once.

This mode is also available for pools created with VmaPoolCreateInfo::maxBlockCount
value that allows multiple memory blocks.
\subsection linear_algorithm_stack Stack
When you free an allocation that was created last, its space can be reused.
Thanks to this, if you always release allocations in the order opposite to their
creation (LIFO - Last In First Out), you can achieve behavior of a stack.

This mode is also available for pools created with VmaPoolCreateInfo::maxBlockCount
value that allows multiple memory blocks.
\subsection linear_algorithm_double_stack Double stack
The space reserved by a custom pool with linear algorithm may be used by two
stacks:
- First, default one, growing up from offset 0.
- Second, "upper" one, growing down from the end towards lower offsets.
To make allocation from upper stack, add flag #VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT
to VmaAllocationCreateInfo::flags.

Double stack is available only in pools with one memory block -
VmaPoolCreateInfo::maxBlockCount must be 1. Otherwise behavior is undefined.
When the two stacks' ends meet so there is not enough space between them for a
new allocation, such allocation fails with usual
`VK_ERROR_OUT_OF_DEVICE_MEMORY` error.
\subsection linear_algorithm_ring_buffer Ring buffer
When you free some allocations from the beginning and there is not enough free space
for a new one at the end of a pool, allocator's "cursor" wraps around to the
beginning and starts allocation there. Thanks to this, if you always release
allocations in the same order as you created them (FIFO - First In First Out),
you can achieve behavior of a ring buffer / queue.

Pools with linear algorithm support [lost allocations](@ref lost_allocations) when used as ring buffer.
If there is not enough free space for a new allocation, but existing allocations
from the front of the queue can become lost, they become lost and the allocation
succeeds.

Ring buffer is available only in pools with one memory block -
VmaPoolCreateInfo::maxBlockCount must be 1. Otherwise behavior is undefined.
\page defragmentation Defragmentation
Interleaved allocations and deallocations of many objects of varying size can
cause fragmentation, which can lead to a situation where the library is unable
to find a continuous range of free memory for a new allocation despite there is
enough free space, just scattered across many small free ranges between existing
allocations.
To mitigate this problem, you can use vmaDefragment(). Given set of allocations,
this function can move them to compact used memory, ensure more continuous free
space and possibly also free some `VkDeviceMemory`. It can work only on
allocations made from memory type that is `HOST_VISIBLE`. Allocations are
modified to point to the new `VkDeviceMemory` and offset. Data in this memory is
also `memmove`-ed to the new place. However, if you have images or buffers bound
to these allocations (and you certainly do), you need to destroy, recreate, and
bind them to the new place in memory.
For further details and example code, see documentation of function
vmaDefragment().
\page lost_allocations Lost allocations
If your game oversubscribes video memory, if may work OK in previous-generation
graphics APIs (DirectX 9, 10, 11, OpenGL) because resources are automatically
paged to system RAM. In Vulkan you can't do it because when you run out of
memory, an allocation just fails. If you have more data (e.g. textures) that can
fit into VRAM and you don't need it all at once, you may want to upload them to
GPU on demand and "push out" ones that are not used for a long time to make room
for the new ones, effectively using VRAM (or a cartain memory pool) as a form of
cache. Vulkan Memory Allocator can help you with that by supporting a concept of
"lost allocations".
To create an allocation that can become lost, include #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT
flag in VmaAllocationCreateInfo::flags. Before using a buffer or image bound to
such allocation in every new frame, you need to query it if it's not lost.
To check it, call vmaTouchAllocation().
If the allocation is lost, you should not use it or buffer/image bound to it.
You mustn't forget to destroy this allocation and this buffer/image.
vmaGetAllocationInfo() can also be used for checking status of the allocation.
Allocation is lost when returned VmaAllocationInfo::deviceMemory == `VK_NULL_HANDLE`.
To create an allocation that can make some other allocations lost to make room
for it, use #VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT flag. You will
usually use both flags #VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT and
#VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT at the same time.
Warning! Current implementation uses quite naive, brute force algorithm,
which can make allocation calls that use #VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT
flag quite slow. A new, more optimal algorithm and data structure to speed this
up is planned for the future.
<b>Q: When interleaving creation of new allocations with usage of existing ones,
how do you make sure that an allocation won't become lost while it's used in the
current frame?</b>
It is ensured because vmaTouchAllocation() / vmaGetAllocationInfo() not only returns allocation
status/parameters and checks whether it's not lost, but when it's not, it also
atomically marks it as used in the current frame, which makes it impossible to
become lost in that frame. It uses lockless algorithm, so it works fast and
doesn't involve locking any internal mutex.
<b>Q: What if my allocation may still be in use by the GPU when it's rendering a
previous frame while I already submit new frame on the CPU?</b>
You can make sure that allocations "touched" by vmaTouchAllocation() / vmaGetAllocationInfo() will not
become lost for a number of additional frames back from the current one by
specifying this number as VmaAllocatorCreateInfo::frameInUseCount (for default
memory pool) and VmaPoolCreateInfo::frameInUseCount (for custom pool).
<b>Q: How do you inform the library when new frame starts?</b>
You need to call function vmaSetCurrentFrameIndex().
Example code:
\code
struct MyBuffer
{
VkBuffer m_Buf = nullptr;
VmaAllocation m_Alloc = nullptr;
// Called when the buffer is really needed in the current frame.
void EnsureBuffer();
};
void MyBuffer::EnsureBuffer()
{
// Buffer has been created.
if(m_Buf != VK_NULL_HANDLE)
{
// Check if its allocation is not lost + mark it as used in current frame.
if(vmaTouchAllocation(allocator, m_Alloc))
{
// It's all OK - safe to use m_Buf.
return;
}
}
// Buffer not yet exists or lost - destroy and recreate it.
vmaDestroyBuffer(allocator, m_Buf, m_Alloc);
VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
bufCreateInfo.size = 1024;
bufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
VmaAllocationCreateInfo allocCreateInfo = {};
allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
allocCreateInfo.flags = VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT |
VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT;
vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &m_Buf, &m_Alloc, nullptr);
}
\endcode
When using lost allocations, you may see some Vulkan validation layer warnings
about overlapping regions of memory bound to different kinds of buffers and
images. This is still valid as long as you implement proper handling of lost
allocations (like in the example above) and don't use them.
You can create an allocation that is already in lost state from the beginning using function
vmaCreateLostAllocation(). It may be useful if you need a "dummy" allocation that is not null.
You can call function vmaMakePoolAllocationsLost() to set all eligible allocations
in a specified custom pool to lost state.
Allocations that have been "touched" in current frame or VmaPoolCreateInfo::frameInUseCount frames back
cannot become lost.
<b>Q: Can I touch allocation that cannot become lost?</b>
Yes, although it has no visible effect.
Calls to vmaGetAllocationInfo() and vmaTouchAllocation() update last use frame index
also for allocations that cannot become lost, but the only way to observe it is to dump
internal allocator state using vmaBuildStatsString().
You can use this feature for debugging purposes to explicitly mark allocations that you use
in current frame and then analyze JSON dump to see for how long each allocation stays unused.
\page statistics Statistics
This library contains functions that return information about its internal state,
especially the amount of memory allocated from Vulkan.
Please keep in mind that these functions need to traverse all internal data structures
to gather these information, so they may be quite time-consuming.
Don't call them too often.
\section statistics_numeric_statistics Numeric statistics
You can query for overall statistics of the allocator using function vmaCalculateStats().
Information are returned using structure #VmaStats.
It contains #VmaStatInfo - number of allocated blocks, number of allocations
(occupied ranges in these blocks), number of unused (free) ranges in these blocks,
number of bytes used and unused (but still allocated from Vulkan) and other information.
They are summed across memory heaps, memory types and total for whole allocator.
You can query for statistics of a custom pool using function vmaGetPoolStats().
Information are returned using structure #VmaPoolStats.
You can query for information about specific allocation using function vmaGetAllocationInfo().
It fill structure #VmaAllocationInfo.
\section statistics_json_dump JSON dump
You can dump internal state of the allocator to a string in JSON format using function vmaBuildStatsString().
The result is guaranteed to be correct JSON.
It uses ANSI encoding.
Any strings provided by user (see [Allocation names](@ref allocation_names))
are copied as-is and properly escaped for JSON, so if they use UTF-8, ISO-8859-2 or any other encoding,
this JSON string can be treated as using this encoding.
It must be freed using function vmaFreeStatsString().
The format of this JSON string is not part of official documentation of the library,
but it will not change in backward-incompatible way without increasing library major version number
and appropriate mention in changelog.
The JSON string contains all the data that can be obtained using vmaCalculateStats().
It can also contain detailed map of allocated memory blocks and their regions -
free and occupied by allocations.
This allows e.g. to visualize the memory or assess fragmentation.
\page allocation_annotation Allocation names and user data
\section allocation_user_data Allocation user data
You can annotate allocations with your own information, e.g. for debugging purposes.
To do that, fill VmaAllocationCreateInfo::pUserData field when creating
an allocation. It's an opaque `void*` pointer. You can use it e.g. as a pointer,
some handle, index, key, ordinal number or any other value that would associate
the allocation with your custom metadata.
\code
VkBufferCreateInfo bufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
// Fill bufferInfo...
MyBufferMetadata* pMetadata = CreateBufferMetadata();
VmaAllocationCreateInfo allocCreateInfo = {};
allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
allocCreateInfo.pUserData = pMetadata;
VkBuffer buffer;
VmaAllocation allocation;
vmaCreateBuffer(allocator, &bufferInfo, &allocCreateInfo, &buffer, &allocation, nullptr);
\endcode
The pointer may be later retrieved as VmaAllocationInfo::pUserData:
\code
VmaAllocationInfo allocInfo;
vmaGetAllocationInfo(allocator, allocation, &allocInfo);
MyBufferMetadata* pMetadata = (MyBufferMetadata*)allocInfo.pUserData;
\endcode
It can also be changed using function vmaSetAllocationUserData().
Values of (non-zero) allocations' `pUserData` are printed in JSON report created by
vmaBuildStatsString(), in hexadecimal form.
\section allocation_names Allocation names
There is alternative mode available where `pUserData` pointer is used to point to
a null-terminated string, giving a name to the allocation. To use this mode,
set #VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT flag in VmaAllocationCreateInfo::flags.
Then `pUserData` passed as VmaAllocationCreateInfo::pUserData or argument to
vmaSetAllocationUserData() must be either null or pointer to a null-terminated string.
The library creates internal copy of the string, so the pointer you pass doesn't need
to be valid for whole lifetime of the allocation. You can free it after the call.
\code
VkImageCreateInfo imageInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
// Fill imageInfo...
std::string imageName = "Texture: ";
imageName += fileName;
VmaAllocationCreateInfo allocCreateInfo = {};
allocCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY;
allocCreateInfo.flags = VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT;
allocCreateInfo.pUserData = imageName.c_str();
VkImage image;
VmaAllocation allocation;
vmaCreateImage(allocator, &imageInfo, &allocCreateInfo, &image, &allocation, nullptr);
\endcode
The value of `pUserData` pointer of the allocation will be different than the one
you passed when setting allocation's name - pointing to a buffer managed
internally that holds copy of the string.
\code
VmaAllocationInfo allocInfo;
vmaGetAllocationInfo(allocator, allocation, &allocInfo);
const char* imageName = (const char*)allocInfo.pUserData;
printf("Image name: %s\n", imageName);
\endcode
That string is also printed in JSON report created by vmaBuildStatsString().
\page debugging_memory_usage Debugging incorrect memory usage
If you suspect a bug with memory usage, like usage of uninitialized memory or
memory being overwritten out of bounds of an allocation,
you can use debug features of this library to verify this.
\section debugging_memory_usage_initialization Memory initialization
If you experience a bug with incorrect and nondeterministic data in your program and you suspect uninitialized memory to be used,
you can enable automatic memory initialization to verify this.
To do it, define macro `VMA_DEBUG_INITIALIZE_ALLOCATIONS` to 1.
\code
#define VMA_DEBUG_INITIALIZE_ALLOCATIONS 1
#include "vk_mem_alloc.h"
\endcode
It makes memory of all new allocations initialized to bit pattern `0xDCDCDCDC`.
Before an allocation is destroyed, its memory is filled with bit pattern `0xEFEFEFEF`.
Memory is automatically mapped and unmapped if necessary.
If you find these values while debugging your program, good chances are that you incorrectly
read Vulkan memory that is allocated but not initialized, or already freed, respectively.
Memory initialization works only with memory types that are `HOST_VISIBLE`.
It works also with dedicated allocations.
It doesn't work with allocations created with #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT flag,
as they cannot be mapped.
\section debugging_memory_usage_margins Margins
By default, allocations are laid out in memory blocks next to each other if possible
(considering required alignment, `bufferImageGranularity`, and `nonCoherentAtomSize`).

Define macro `VMA_DEBUG_MARGIN` to some non-zero value (e.g. 16) to enforce specified
number of bytes as a margin before and after every allocation.
\code
#define VMA_DEBUG_MARGIN 16
#include "vk_mem_alloc.h"
\endcode

If your bug goes away after enabling margins, it means it may be caused by memory
being overwritten outside of allocation boundaries. It is not 100% certain though.
Change in application behavior may also be caused by different order and distribution
of allocations across memory blocks after margins are applied.
The margin is applied also before first and after last allocation in a block.
It may occur only once between two adjacent allocations.
Margins work with all types of memory.
Margin is applied only to allocations made out of memory blocks and not to dedicated
allocations, which have their own memory block of specific size.
It is thus not applied to allocations made using #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT flag
or those automatically decided to put into dedicated allocations, e.g. due to its
large size or recommended by VK_KHR_dedicated_allocation extension.
Margins appear in [JSON dump](@ref statistics_json_dump) as part of free space.
Note that enabling margins increases memory usage and fragmentation.
\section debugging_memory_usage_corruption_detection Corruption detection
You can additionally define macro `VMA_DEBUG_DETECT_CORRUPTION` to 1 to enable validation
of contents of the margins.
\code
#define VMA_DEBUG_MARGIN 16
#define VMA_DEBUG_DETECT_CORRUPTION 1
#include "vk_mem_alloc.h"
\endcode
When this feature is enabled, number of bytes specified as `VMA_DEBUG_MARGIN`
(it must be multiply of 4) before and after every allocation is filled with a magic number.
This idea is also know as "canary".
Memory is automatically mapped and unmapped if necessary.
This number is validated automatically when the allocation is destroyed.
If it's not equal to the expected value, `VMA_ASSERT()` is executed.
It clearly means that either CPU or GPU overwritten the memory outside of boundaries of the allocation,
which indicates a serious bug.
You can also explicitly request checking margins of all allocations in all memory blocks
that belong to specified memory types by using function vmaCheckCorruption(),
or in memory blocks that belong to specified custom pool, by using function
vmaCheckPoolCorruption().
Margin validation (corruption detection) works only for memory types that are
`HOST_VISIBLE` and `HOST_COHERENT`.
\page record_and_replay Record and replay
\section record_and_replay_introduction Introduction
While using the library, sequence of calls to its functions together with their
parameters can be recorded to a file and later replayed using standalone player
application. It can be useful to:
- Test correctness - check if same sequence of calls will not cause crash or
failures on a target platform.
- Gather statistics - see number of allocations, peak memory usage, number of
calls etc.
- Benchmark performance - see how much time it takes to replay the whole
sequence.
\section record_and_replay_usage Usage
<b>To record sequence of calls to a file:</b> Fill in
VmaAllocatorCreateInfo::pRecordSettings member while creating #VmaAllocator
object. File is opened and written during whole lifetime of the allocator.
<b>To replay file:</b> Use VmaReplay - standalone command-line program.
Precompiled binary can be found in "bin" directory.
Its source can be found in "src/VmaReplay" directory.
Its project is generated by Premake.
Command line syntax is printed when the program is launched without parameters.
Basic usage:
VmaReplay.exe MyRecording.csv
<b>Documentation of file format</b> can be found in file: "docs/Recording file format.md".
It's a human-readable, text file in CSV format (Comma Separated Values).
\section record_and_replay_additional_considerations Additional considerations
- Replaying file that was recorded on a different GPU (with different parameters
like `bufferImageGranularity`, `nonCoherentAtomSize`, and especially different
set of memory heaps and types) may give different performance and memory usage
results, as well as issue some warnings and errors.
- Current implementation of recording in VMA, as well as VmaReplay application, is
coded and tested only on Windows. Inclusion of recording code is driven by
`VMA_RECORDING_ENABLED` macro. Support for other platforms should be easy to
add. Contributions are welcomed.
- Currently calls to vmaDefragment() function are not recorded.
\page usage_patterns Recommended usage patterns
See also slides from talk:
[Sawicki, Adam. Advanced Graphics Techniques Tutorial: Memory management in Vulkan and DX12. Game Developers Conference, 2018](https://www.gdcvault.com/play/1025458/Advanced-Graphics-Techniques-Tutorial-New)
\section usage_patterns_simple Simple patterns
\subsection usage_patterns_simple_render_targets Render targets
<b>When:</b>
Any resources that you frequently write and read on GPU,
e.g. images used as color attachments (aka "render targets"), depth-stencil attachments,
images/buffers used as storage image/buffer (aka "Unordered Access View (UAV)").
<b>What to do:</b>
Create them in video memory that is fastest to access from GPU using
#VMA_MEMORY_USAGE_GPU_ONLY.
Consider using [VK_KHR_dedicated_allocation](@ref vk_khr_dedicated_allocation) extension
and/or manually creating them as dedicated allocations using #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT,
especially if they are large or if you plan to destroy and recreate them e.g. when
display resolution changes.
Prefer to create such resources first and all other GPU resources (like textures and vertex buffers) later.
\subsection usage_patterns_simple_immutable_resources Immutable resources
<b>When:</b>
Any resources that you fill on CPU only once (aka "immutable") or infrequently
and then read frequently on GPU,
e.g. textures, vertex and index buffers, constant buffers that don't change often.
<b>What to do:</b>
Create them in video memory that is fastest to access from GPU using
#VMA_MEMORY_USAGE_GPU_ONLY.
To initialize content of such resource, create a CPU-side (aka "staging") copy of it
in system memory - #VMA_MEMORY_USAGE_CPU_ONLY, map it, fill it,
and submit a transfer from it to the GPU resource.
You can keep the staging copy if you need it for another upload transfer in the future.
If you don't, you can destroy it or reuse this buffer for uploading different resource
after the transfer finishes.
Prefer to create just buffers in system memory rather than images, even for uploading textures.
Use `vkCmdCopyBufferToImage()`.
Dont use images with `VK_IMAGE_TILING_LINEAR`.
\subsection usage_patterns_dynamic_resources Dynamic resources
<b>When:</b>
Any resources that change frequently (aka "dynamic"), e.g. every frame or every draw call,
written on CPU, read on GPU.
<b>What to do:</b>
Create them using #VMA_MEMORY_USAGE_CPU_TO_GPU.
You can map it and write to it directly on CPU, as well as read from it on GPU.
This is a more complex situation. Different solutions are possible,
and the best one depends on specific GPU type, but you can use this simple approach for the start.
Prefer to write to such resource sequentially (e.g. using `memcpy`).
Don't perform random access or any reads from it on CPU, as it may be very slow.
\subsection usage_patterns_readback Readback
<b>When:</b>
Resources that contain data written by GPU that you want to read back on CPU,
e.g. results of some computations.
<b>What to do:</b>
Create them using #VMA_MEMORY_USAGE_GPU_TO_CPU.
You can write to them directly on GPU, as well as map and read them on CPU.
\section usage_patterns_advanced Advanced patterns
\subsection usage_patterns_integrated_graphics Detecting integrated graphics
You can support integrated graphics (like Intel HD Graphics, AMD APU) better
by detecting it in Vulkan.
To do it, call `vkGetPhysicalDeviceProperties()`, inspect
`VkPhysicalDeviceProperties::deviceType` and look for `VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU`.
When you find it, you can assume that memory is unified and all memory types are comparably fast
to access from GPU, regardless of `VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT`.
You can then sum up sizes of all available memory heaps and treat them as useful for
your GPU resources, instead of only `DEVICE_LOCAL` ones.
You can also prefer to create your resources in memory types that are `HOST_VISIBLE` to map them
directly instead of submitting explicit transfer (see below).
\subsection usage_patterns_direct_vs_transfer Direct access versus transfer
For resources that you frequently write on CPU and read on GPU, many solutions are possible:
-# Create one copy in video memory using #VMA_MEMORY_USAGE_GPU_ONLY,
second copy in system memory using #VMA_MEMORY_USAGE_CPU_ONLY and submit explicit tranfer each time.
-# Create just single copy using #VMA_MEMORY_USAGE_CPU_TO_GPU, map it and fill it on CPU,
read it directly on GPU.
-# Create just single copy using #VMA_MEMORY_USAGE_CPU_ONLY, map it and fill it on CPU,
read it directly on GPU.
Which solution is the most efficient depends on your resource and especially on the GPU.
It is best to measure it and then make the decision.
Some general recommendations:
- On integrated graphics use (2) or (3) to avoid unnecesary time and memory overhead
related to using a second copy and making transfer.
- For small resources (e.g. constant buffers) use (2).
Discrete AMD cards have special 256 MiB pool of video memory that is directly mappable.
Even if the resource ends up in system memory, its data may be cached on GPU after first
fetch over PCIe bus.
- For larger resources (e.g. textures), decide between (1) and (2).
You may want to differentiate NVIDIA and AMD, e.g. by looking for memory type that is
both `DEVICE_LOCAL` and `HOST_VISIBLE`. When you find it, use (2), otherwise use (1).
Similarly, for resources that you frequently write on GPU and read on CPU, multiple
solutions are possible:
-# Create one copy in video memory using #VMA_MEMORY_USAGE_GPU_ONLY,
second copy in system memory using #VMA_MEMORY_USAGE_GPU_TO_CPU and submit explicit tranfer each time.
-# Create just single copy using #VMA_MEMORY_USAGE_GPU_TO_CPU, write to it directly on GPU,
map it and read it on CPU.
You should take some measurements to decide which option is faster in case of your specific
resource.
If you don't want to specialize your code for specific types of GPUs, you can still make
an simple optimization for cases when your resource ends up in mappable memory to use it
directly in this case instead of creating CPU-side staging copy.
For details see [Finding out if memory is mappable](@ref memory_mapping_finding_if_memory_mappable).
\page configuration Configuration
Please check "CONFIGURATION SECTION" in the code to find macros that you can define
before each include of this file or change directly in this file to provide
your own implementation of basic facilities like assert, `min()` and `max()` functions,
mutex, atomic etc.
The library uses its own implementation of containers by default, but you can switch to using
STL containers instead.
\section config_Vulkan_functions Pointers to Vulkan functions
The library uses Vulkan functions straight from the `vulkan.h` header by default.
If you want to provide your own pointers to these functions, e.g. fetched using
`vkGetInstanceProcAddr()` and `vkGetDeviceProcAddr()`:
-# Define `VMA_STATIC_VULKAN_FUNCTIONS 0`.
-# Provide valid pointers through VmaAllocatorCreateInfo::pVulkanFunctions.
\section custom_memory_allocator Custom host memory allocator
If you use custom allocator for CPU memory rather than default operator `new`
and `delete` from C++, you can make this library using your allocator as well
by filling optional member VmaAllocatorCreateInfo::pAllocationCallbacks. These
functions will be passed to Vulkan, as well as used by the library itself to
make any CPU-side allocations.
\section allocation_callbacks Device memory allocation callbacks
The library makes calls to `vkAllocateMemory()` and `vkFreeMemory()` internally.
You can setup callbacks to be informed about these calls, e.g. for the purpose
of gathering some statistics. To do it, fill optional member
VmaAllocatorCreateInfo::pDeviceMemoryCallbacks.
\section heap_memory_limit Device heap memory limit
If you want to test how your program behaves with limited amount of Vulkan device
memory available without switching your graphics card to one that really has
smaller VRAM, you can use a feature of this library intended for this purpose.
To do it, fill optional member VmaAllocatorCreateInfo::pHeapSizeLimit.
\page vk_khr_dedicated_allocation VK_KHR_dedicated_allocation
VK_KHR_dedicated_allocation is a Vulkan extension which can be used to improve
performance on some GPUs. It augments Vulkan API with possibility to query
driver whether it prefers particular buffer or image to have its own, dedicated
allocation (separate `VkDeviceMemory` block) for better efficiency - to be able
to do some internal optimizations.
The extension is supported by this library. It will be used automatically when
enabled. To enable it:
1 . When creating Vulkan device, check if following 2 device extensions are
supported (call `vkEnumerateDeviceExtensionProperties()`).
If yes, enable them (fill `VkDeviceCreateInfo::ppEnabledExtensionNames`).
- VK_KHR_get_memory_requirements2
- VK_KHR_dedicated_allocation
If you enabled these extensions:
2 . Use #VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT flag when creating
your #VmaAllocator`to inform the library that you enabled required extensions
and you want the library to use them.
\code
allocatorInfo.flags |= VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT;
vmaCreateAllocator(&allocatorInfo, &allocator);
\endcode
That's all. The extension will be automatically used whenever you create a
buffer using vmaCreateBuffer() or image using vmaCreateImage().
When using the extension together with Vulkan Validation Layer, you will receive
warnings like this:
vkBindBufferMemory(): Binding memory to buffer 0x33 but vkGetBufferMemoryRequirements() has not been called on that buffer.
It is OK, you should just ignore it. It happens because you use function
`vkGetBufferMemoryRequirements2KHR()` instead of standard
`vkGetBufferMemoryRequirements()`, while the validation layer seems to be
unaware of it.
To learn more about this extension, see:
- [VK_KHR_dedicated_allocation in Vulkan specification](https://www.khronos.org/registry/vulkan/specs/1.0-extensions/html/vkspec.html#VK_KHR_dedicated_allocation)
- [VK_KHR_dedicated_allocation unofficial manual](http://asawicki.info/articles/VK_KHR_dedicated_allocation.php5)
\page general_considerations General considerations
\section general_considerations_thread_safety Thread safety
- The library has no global state, so separate #VmaAllocator objects can be used
independently.
There should be no need to create multiple such objects though - one per `VkDevice` is enough.
- By default, all calls to functions that take #VmaAllocator as first parameter
are safe to call from multiple threads simultaneously because they are
synchronized internally when needed.
- When the allocator is created with #VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT
flag, calls to functions that take such #VmaAllocator object must be
synchronized externally.
- Access to a #VmaAllocation object must be externally synchronized. For example,
you must not call vmaGetAllocationInfo() and vmaMapMemory() from different
threads at the same time if you pass the same #VmaAllocation object to these
functions.
\section general_considerations_validation_layer_warnings Validation layer warnings
When using this library, you can meet following types of warnings issued by
Vulkan validation layer. They don't necessarily indicate a bug, so you may need
to just ignore them.
- *vkBindBufferMemory(): Binding memory to buffer 0xeb8e4 but vkGetBufferMemoryRequirements() has not been called on that buffer.*
- It happens when VK_KHR_dedicated_allocation extension is enabled.
`vkGetBufferMemoryRequirements2KHR` function is used instead, while validation layer seems to be unaware of it.
- *Mapping an image with layout VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL can result in undefined behavior if this memory is used by the device. Only GENERAL or PREINITIALIZED should be used.*
- It happens when you map a buffer or image, because the library maps entire
`VkDeviceMemory` block, where different types of images and buffers may end
up together, especially on GPUs with unified memory like Intel.
- *Non-linear image 0xebc91 is aliased with linear buffer 0xeb8e4 which may indicate a bug.*
- It happens when you use lost allocations, and a new image or buffer is
created in place of an existing object that bacame lost.
\section general_considerations_allocation_algorithm Allocation algorithm
The library uses following algorithm for allocation, in order:
-# Try to find free range of memory in existing blocks.
-# If failed, try to create a new block of `VkDeviceMemory`, with preferred block size.
-# If failed, try to create such block with size/2, size/4, size/8.
-# If failed and #VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT flag was
specified, try to find space in existing blocks, possilby making some other
allocations lost.
-# If failed, try to allocate separate `VkDeviceMemory` for this allocation,
just like when you use #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT.
-# If failed, choose other memory type that meets the requirements specified in
VmaAllocationCreateInfo and go to point 1.
-# If failed, return `VK_ERROR_OUT_OF_DEVICE_MEMORY`.
\section general_considerations_features_not_supported Features not supported
Features deliberately excluded from the scope of this library:
- Sparse resources.
- Data transfer - issuing commands that transfer data between buffers or images, any usage of
`VkCommandList` or `VkQueue` and related synchronization is responsibility of the user.
- Allocations for imported/exported external memory. They tend to require
explicit memory type index and dedicated allocation anyway, so they don't
interact with main features of this library. Such special purpose allocations
should be made manually, using `vkCreateBuffer()` and `vkAllocateMemory()`.
- Support for any programming languages other than C/C++.
Bindings to other languages are welcomed as external projects.
*/
/*
Define this macro to 0/1 to disable/enable support for recording functionality,
available through VmaAllocatorCreateInfo::pRecordSettings.
*/
#ifndef VMA_RECORDING_ENABLED
#ifdef _WIN32
#define VMA_RECORDING_ENABLED 1
#else
#define VMA_RECORDING_ENABLED 0
#endif
#endif
#define NOMINMAX // For Windows.h
#include <vulkan/vulkan.h>
#if VMA_RECORDING_ENABLED
#include <Windows.h>
#endif
#if !defined(VMA_DEDICATED_ALLOCATION)
#if VK_KHR_get_memory_requirements2 && VK_KHR_dedicated_allocation
#define VMA_DEDICATED_ALLOCATION 1
#else
#define VMA_DEDICATED_ALLOCATION 0
#endif
#endif
/** \struct VmaAllocator
\brief Represents main object of this library initialized.
Fill structure VmaAllocatorCreateInfo and call function vmaCreateAllocator() to create it.
Call function vmaDestroyAllocator() to destroy it.
It is recommended to create just one object of this type per `VkDevice` object,
right after Vulkan is initialized and keep it alive until before Vulkan device is destroyed.
*/
VK_DEFINE_HANDLE(VmaAllocator)
/// Callback function called after successful vkAllocateMemory.
typedef void (VKAPI_PTR *PFN_vmaAllocateDeviceMemoryFunction)(
VmaAllocator allocator,
uint32_t memoryType,
VkDeviceMemory memory,
VkDeviceSize size);
/// Callback function called before vkFreeMemory.
typedef void (VKAPI_PTR *PFN_vmaFreeDeviceMemoryFunction)(
VmaAllocator allocator,
uint32_t memoryType,
VkDeviceMemory memory,
VkDeviceSize size);
/** \brief Set of callbacks that the library will call for `vkAllocateMemory` and `vkFreeMemory`.
Provided for informative purpose, e.g. to gather statistics about number of
allocations or total amount of memory allocated in Vulkan.
Used in VmaAllocatorCreateInfo::pDeviceMemoryCallbacks.
*/
typedef struct VmaDeviceMemoryCallbacks {
/// Optional, can be null.
PFN_vmaAllocateDeviceMemoryFunction pfnAllocate;
/// Optional, can be null.
PFN_vmaFreeDeviceMemoryFunction pfnFree;
} VmaDeviceMemoryCallbacks;
/// Flags for created #VmaAllocator.
typedef enum VmaAllocatorCreateFlagBits {
/** \brief Allocator and all objects created from it will not be synchronized internally, so you must guarantee they are used from only one thread at a time or synchronized externally by you.
Using this flag may increase performance because internal mutexes are not used.
*/
VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT = 0x00000001,
/** \brief Enables usage of VK_KHR_dedicated_allocation extension.
Using this extenion will automatically allocate dedicated blocks of memory for
some buffers and images instead of suballocating place for them out of bigger
memory blocks (as if you explicitly used #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT
flag) when it is recommended by the driver. It may improve performance on some
GPUs.
You may set this flag only if you found out that following device extensions are
supported, you enabled them while creating Vulkan device passed as
VmaAllocatorCreateInfo::device, and you want them to be used internally by this
library:
- VK_KHR_get_memory_requirements2
- VK_KHR_dedicated_allocation
When this flag is set, you can experience following warnings reported by Vulkan
validation layer. You can ignore them.
> vkBindBufferMemory(): Binding memory to buffer 0x2d but vkGetBufferMemoryRequirements() has not been called on that buffer.
*/
VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT = 0x00000002,
VMA_ALLOCATOR_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} VmaAllocatorCreateFlagBits;
typedef VkFlags VmaAllocatorCreateFlags;
/** \brief Pointers to some Vulkan functions - a subset used by the library.
Used in VmaAllocatorCreateInfo::pVulkanFunctions.
*/
typedef struct VmaVulkanFunctions {
PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties;
PFN_vkGetPhysicalDeviceMemoryProperties vkGetPhysicalDeviceMemoryProperties;
PFN_vkAllocateMemory vkAllocateMemory;
PFN_vkFreeMemory vkFreeMemory;
PFN_vkMapMemory vkMapMemory;
PFN_vkUnmapMemory vkUnmapMemory;
PFN_vkFlushMappedMemoryRanges vkFlushMappedMemoryRanges;
PFN_vkInvalidateMappedMemoryRanges vkInvalidateMappedMemoryRanges;
PFN_vkBindBufferMemory vkBindBufferMemory;
PFN_vkBindImageMemory vkBindImageMemory;
PFN_vkGetBufferMemoryRequirements vkGetBufferMemoryRequirements;
PFN_vkGetImageMemoryRequirements vkGetImageMemoryRequirements;
PFN_vkCreateBuffer vkCreateBuffer;
PFN_vkDestroyBuffer vkDestroyBuffer;
PFN_vkCreateImage vkCreateImage;
PFN_vkDestroyImage vkDestroyImage;
#if VMA_DEDICATED_ALLOCATION
PFN_vkGetBufferMemoryRequirements2KHR vkGetBufferMemoryRequirements2KHR;
PFN_vkGetImageMemoryRequirements2KHR vkGetImageMemoryRequirements2KHR;
#endif
} VmaVulkanFunctions;
/// Flags to be used in VmaRecordSettings::flags.
typedef enum VmaRecordFlagBits {
/** \brief Enables flush after recording every function call.
Enable it if you expect your application to crash, which may leave recording file truncated.
It may degrade performance though.
*/
VMA_RECORD_FLUSH_AFTER_CALL_BIT = 0x00000001,
VMA_RECORD_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} VmaRecordFlagBits;
typedef VkFlags VmaRecordFlags;
/// Parameters for recording calls to VMA functions. To be used in VmaAllocatorCreateInfo::pRecordSettings.
typedef struct VmaRecordSettings
{
/// Flags for recording. Use #VmaRecordFlagBits enum.
VmaRecordFlags flags;
/** \brief Path to the file that should be written by the recording.
Suggested extension: "csv".
If the file already exists, it will be overwritten.
It will be opened for the whole time #VmaAllocator object is alive.
If opening this file fails, creation of the whole allocator object fails.
*/
const char* pFilePath;
} VmaRecordSettings;
/// Description of a Allocator to be created.
typedef struct VmaAllocatorCreateInfo
{
/// Flags for created allocator. Use #VmaAllocatorCreateFlagBits enum.
VmaAllocatorCreateFlags flags;
/// Vulkan physical device.
/** It must be valid throughout whole lifetime of created allocator. */
VkPhysicalDevice physicalDevice;
/// Vulkan device.
/** It must be valid throughout whole lifetime of created allocator. */
VkDevice device;
/// Preferred size of a single `VkDeviceMemory` block to be allocated from large heaps > 1 GiB. Optional.
/** Set to 0 to use default, which is currently 256 MiB. */
VkDeviceSize preferredLargeHeapBlockSize;
/// Custom CPU memory allocation callbacks. Optional.
/** Optional, can be null. When specified, will also be used for all CPU-side memory allocations. */
const VkAllocationCallbacks* pAllocationCallbacks;
/// Informative callbacks for `vkAllocateMemory`, `vkFreeMemory`. Optional.
/** Optional, can be null. */
const VmaDeviceMemoryCallbacks* pDeviceMemoryCallbacks;
/** \brief Maximum number of additional frames that are in use at the same time as current frame.
This value is used only when you make allocations with
VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT flag. Such allocation cannot become
lost if allocation.lastUseFrameIndex >= allocator.currentFrameIndex - frameInUseCount.
For example, if you double-buffer your command buffers, so resources used for
rendering in previous frame may still be in use by the GPU at the moment you
allocate resources needed for the current frame, set this value to 1.
If you want to allow any allocations other than used in the current frame to
become lost, set this value to 0.
*/
uint32_t frameInUseCount;
/** \brief Either null or a pointer to an array of limits on maximum number of bytes that can be allocated out of particular Vulkan memory heap.
If not NULL, it must be a pointer to an array of
`VkPhysicalDeviceMemoryProperties::memoryHeapCount` elements, defining limit on
maximum number of bytes that can be allocated out of particular Vulkan memory
heap.
Any of the elements may be equal to `VK_WHOLE_SIZE`, which means no limit on that
heap. This is also the default in case of `pHeapSizeLimit` = NULL.
If there is a limit defined for a heap:
- If user tries to allocate more memory from that heap using this allocator,
the allocation fails with `VK_ERROR_OUT_OF_DEVICE_MEMORY`.
- If the limit is smaller than heap size reported in `VkMemoryHeap::size`, the
value of this limit will be reported instead when using vmaGetMemoryProperties().
Warning! Using this feature may not be equivalent to installing a GPU with
smaller amount of memory, because graphics driver doesn't necessary fail new
allocations with `VK_ERROR_OUT_OF_DEVICE_MEMORY` result when memory capacity is
exceeded. It may return success and just silently migrate some device memory
blocks to system RAM.
*/
const VkDeviceSize* pHeapSizeLimit;
/** \brief Pointers to Vulkan functions. Can be null if you leave define `VMA_STATIC_VULKAN_FUNCTIONS 1`.
If you leave define `VMA_STATIC_VULKAN_FUNCTIONS 1` in configuration section,
you can pass null as this member, because the library will fetch pointers to
Vulkan functions internally in a static way, like:
vulkanFunctions.vkAllocateMemory = &vkAllocateMemory;
Fill this member if you want to provide your own pointers to Vulkan functions,
e.g. fetched using `vkGetInstanceProcAddr()` and `vkGetDeviceProcAddr()`.
*/
const VmaVulkanFunctions* pVulkanFunctions;
/** \brief Parameters for recording of VMA calls. Can be null.
If not null, it enables recording of calls to VMA functions to a file.
If support for recording is not enabled using `VMA_RECORDING_ENABLED` macro,
creation of the allocator object fails with `VK_ERROR_FEATURE_NOT_PRESENT`.
*/
const VmaRecordSettings* pRecordSettings;
} VmaAllocatorCreateInfo;
/// Creates Allocator object.
VkResult vmaCreateAllocator(
const VmaAllocatorCreateInfo* pCreateInfo,
VmaAllocator* pAllocator);
/// Destroys allocator object.
void vmaDestroyAllocator(
VmaAllocator allocator);
/**
PhysicalDeviceProperties are fetched from physicalDevice by the allocator.
You can access it here, without fetching it again on your own.
*/
void vmaGetPhysicalDeviceProperties(
VmaAllocator allocator,
const VkPhysicalDeviceProperties** ppPhysicalDeviceProperties);
/**
PhysicalDeviceMemoryProperties are fetched from physicalDevice by the allocator.
You can access it here, without fetching it again on your own.
*/
void vmaGetMemoryProperties(
VmaAllocator allocator,
const VkPhysicalDeviceMemoryProperties** ppPhysicalDeviceMemoryProperties);
/**
\brief Given Memory Type Index, returns Property Flags of this memory type.
This is just a convenience function. Same information can be obtained using
vmaGetMemoryProperties().
*/
void vmaGetMemoryTypeProperties(
VmaAllocator allocator,
uint32_t memoryTypeIndex,
VkMemoryPropertyFlags* pFlags);
/** \brief Sets index of the current frame.
This function must be used if you make allocations with
#VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT and
#VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT flags to inform the allocator
when a new frame begins. Allocations queried using vmaGetAllocationInfo() cannot
become lost in the current frame.
*/
void vmaSetCurrentFrameIndex(
VmaAllocator allocator,
uint32_t frameIndex);
/** \brief Calculated statistics of memory usage in entire allocator.
*/
typedef struct VmaStatInfo
{
/// Number of `VkDeviceMemory` Vulkan memory blocks allocated.
uint32_t blockCount;
/// Number of #VmaAllocation allocation objects allocated.
uint32_t allocationCount;
/// Number of free ranges of memory between allocations.
uint32_t unusedRangeCount;
/// Total number of bytes occupied by all allocations.
VkDeviceSize usedBytes;
/// Total number of bytes occupied by unused ranges.
VkDeviceSize unusedBytes;
VkDeviceSize allocationSizeMin, allocationSizeAvg, allocationSizeMax;
VkDeviceSize unusedRangeSizeMin, unusedRangeSizeAvg, unusedRangeSizeMax;
} VmaStatInfo;
/// General statistics from current state of Allocator.
typedef struct VmaStats
{
VmaStatInfo memoryType[VK_MAX_MEMORY_TYPES];
VmaStatInfo memoryHeap[VK_MAX_MEMORY_HEAPS];
VmaStatInfo total;
} VmaStats;
/// Retrieves statistics from current state of the Allocator.
void vmaCalculateStats(
VmaAllocator allocator,
VmaStats* pStats);
#define VMA_STATS_STRING_ENABLED 1
#if VMA_STATS_STRING_ENABLED
/// Builds and returns statistics as string in JSON format.
/** @param[out] ppStatsString Must be freed using vmaFreeStatsString() function.
*/
void vmaBuildStatsString(
VmaAllocator allocator,
char** ppStatsString,
VkBool32 detailedMap);
void vmaFreeStatsString(
VmaAllocator allocator,
char* pStatsString);
#endif // #if VMA_STATS_STRING_ENABLED
/** \struct VmaPool
\brief Represents custom memory pool
Fill structure VmaPoolCreateInfo and call function vmaCreatePool() to create it.
Call function vmaDestroyPool() to destroy it.
For more information see [Custom memory pools](@ref choosing_memory_type_custom_memory_pools).
*/
VK_DEFINE_HANDLE(VmaPool)
typedef enum VmaMemoryUsage
{
/** No intended memory usage specified.
Use other members of VmaAllocationCreateInfo to specify your requirements.
*/
VMA_MEMORY_USAGE_UNKNOWN = 0,
/** Memory will be used on device only, so fast access from the device is preferred.
It usually means device-local GPU (video) memory.
No need to be mappable on host.
It is roughly equivalent of `D3D12_HEAP_TYPE_DEFAULT`.
Usage:
- Resources written and read by device, e.g. images used as attachments.
- Resources transferred from host once (immutable) or infrequently and read by
device multiple times, e.g. textures to be sampled, vertex buffers, uniform
(constant) buffers, and majority of other types of resources used on GPU.
Allocation may still end up in `HOST_VISIBLE` memory on some implementations.
In such case, you are free to map it.
You can use #VMA_ALLOCATION_CREATE_MAPPED_BIT with this usage type.
*/
VMA_MEMORY_USAGE_GPU_ONLY = 1,
/** Memory will be mappable on host.
It usually means CPU (system) memory.
Guarantees to be `HOST_VISIBLE` and `HOST_COHERENT`.
CPU access is typically uncached. Writes may be write-combined.
Resources created in this pool may still be accessible to the device, but access to them can be slow.
It is roughly equivalent of `D3D12_HEAP_TYPE_UPLOAD`.
Usage: Staging copy of resources used as transfer source.
*/
VMA_MEMORY_USAGE_CPU_ONLY = 2,
/**
Memory that is both mappable on host (guarantees to be `HOST_VISIBLE`) and preferably fast to access by GPU.
CPU access is typically uncached. Writes may be write-combined.
Usage: Resources written frequently by host (dynamic), read by device. E.g. textures, vertex buffers, uniform buffers updated every frame or every draw call.
*/
VMA_MEMORY_USAGE_CPU_TO_GPU = 3,
/** Memory mappable on host (guarantees to be `HOST_VISIBLE`) and cached.
It is roughly equivalent of `D3D12_HEAP_TYPE_READBACK`.
Usage:
- Resources written by device, read by host - results of some computations, e.g. screen capture, average scene luminance for HDR tone mapping.
- Any resources read or accessed randomly on host, e.g. CPU-side copy of vertex buffer used as source of transfer, but also used for collision detection.
*/
VMA_MEMORY_USAGE_GPU_TO_CPU = 4,
VMA_MEMORY_USAGE_MAX_ENUM = 0x7FFFFFFF
} VmaMemoryUsage;
/// Flags to be passed as VmaAllocationCreateInfo::flags.
typedef enum VmaAllocationCreateFlagBits {
/** \brief Set this flag if the allocation should have its own memory block.
Use it for special, big resources, like fullscreen images used as attachments.
This flag must also be used for host visible resources that you want to map
simultaneously because otherwise they might end up as regions of the same
`VkDeviceMemory`, while mapping same `VkDeviceMemory` multiple times
simultaneously is illegal.
You should not use this flag if VmaAllocationCreateInfo::pool is not null.
*/
VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT = 0x00000001,
/** \brief Set this flag to only try to allocate from existing `VkDeviceMemory` blocks and never create new such block.
If new allocation cannot be placed in any of the existing blocks, allocation
fails with `VK_ERROR_OUT_OF_DEVICE_MEMORY` error.
You should not use #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT and
#VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT at the same time. It makes no sense.
If VmaAllocationCreateInfo::pool is not null, this flag is implied and ignored. */
VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT = 0x00000002,
/** \brief Set this flag to use a memory that will be persistently mapped and retrieve pointer to it.
Pointer to mapped memory will be returned through VmaAllocationInfo::pMappedData.
Is it valid to use this flag for allocation made from memory type that is not
`HOST_VISIBLE`. This flag is then ignored and memory is not mapped. This is
useful if you need an allocation that is efficient to use on GPU
(`DEVICE_LOCAL`) and still want to map it directly if possible on platforms that
support it (e.g. Intel GPU).
You should not use this flag together with #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT.
*/
VMA_ALLOCATION_CREATE_MAPPED_BIT = 0x00000004,
/** Allocation created with this flag can become lost as a result of another
allocation with #VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT flag, so you
must check it before use.
To check if allocation is not lost, call vmaGetAllocationInfo() and check if
VmaAllocationInfo::deviceMemory is not `VK_NULL_HANDLE`.
For details about supporting lost allocations, see Lost Allocations
chapter of User Guide on Main Page.
You should not use this flag together with #VMA_ALLOCATION_CREATE_MAPPED_BIT.
*/
VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT = 0x00000008,
/** While creating allocation using this flag, other allocations that were
created with flag #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT can become lost.
For details about supporting lost allocations, see Lost Allocations
chapter of User Guide on Main Page.
*/
VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT = 0x00000010,
/** Set this flag to treat VmaAllocationCreateInfo::pUserData as pointer to a
null-terminated string. Instead of copying pointer value, a local copy of the
string is made and stored in allocation's `pUserData`. The string is automatically
freed together with the allocation. It is also used in vmaBuildStatsString().
*/
VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT = 0x00000020,
/** Allocation will be created from upper stack in a double stack pool.
This flag is only allowed for custom pools created with #VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT flag.
*/
VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT = 0x00000040,
VMA_ALLOCATION_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} VmaAllocationCreateFlagBits;
typedef VkFlags VmaAllocationCreateFlags;
typedef struct VmaAllocationCreateInfo
{
/// Use #VmaAllocationCreateFlagBits enum.
VmaAllocationCreateFlags flags;
/** \brief Intended usage of memory.
You can leave #VMA_MEMORY_USAGE_UNKNOWN if you specify memory requirements in other way. \n
If `pool` is not null, this member is ignored.
*/
VmaMemoryUsage usage;
/** \brief Flags that must be set in a Memory Type chosen for an allocation.
Leave 0 if you specify memory requirements in other way. \n
If `pool` is not null, this member is ignored.*/
VkMemoryPropertyFlags requiredFlags;
/** \brief Flags that preferably should be set in a memory type chosen for an allocation.
Set to 0 if no additional flags are prefered. \n
If `pool` is not null, this member is ignored. */
VkMemoryPropertyFlags preferredFlags;
/** \brief Bitmask containing one bit set for every memory type acceptable for this allocation.
Value 0 is equivalent to `UINT32_MAX` - it means any memory type is accepted if
it meets other requirements specified by this structure, with no further
restrictions on memory type index. \n
If `pool` is not null, this member is ignored.
*/
uint32_t memoryTypeBits;
/** \brief Pool that this allocation should be created in.
Leave `VK_NULL_HANDLE` to allocate from default pool. If not null, members:
`usage`, `requiredFlags`, `preferredFlags`, `memoryTypeBits` are ignored.
*/
VmaPool pool;
/** \brief Custom general-purpose pointer that will be stored in #VmaAllocation, can be read as VmaAllocationInfo::pUserData and changed using vmaSetAllocationUserData().
If #VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT is used, it must be either
null or pointer to a null-terminated string. The string will be then copied to
internal buffer, so it doesn't need to be valid after allocation call.
*/
void* pUserData;
} VmaAllocationCreateInfo;
/**
\brief Helps to find memoryTypeIndex, given memoryTypeBits and VmaAllocationCreateInfo.
This algorithm tries to find a memory type that:
- Is allowed by memoryTypeBits.
- Contains all the flags from pAllocationCreateInfo->requiredFlags.
- Matches intended usage.
- Has as many flags from pAllocationCreateInfo->preferredFlags as possible.
\return Returns VK_ERROR_FEATURE_NOT_PRESENT if not found. Receiving such result
from this function or any other allocating function probably means that your
device doesn't support any memory type with requested features for the specific
type of resource you want to use it for. Please check parameters of your
resource, like image layout (OPTIMAL versus LINEAR) or mip level count.
*/
VkResult vmaFindMemoryTypeIndex(
VmaAllocator allocator,
uint32_t memoryTypeBits,
const VmaAllocationCreateInfo* pAllocationCreateInfo,
uint32_t* pMemoryTypeIndex);
/**
\brief Helps to find memoryTypeIndex, given VkBufferCreateInfo and VmaAllocationCreateInfo.
It can be useful e.g. to determine value to be used as VmaPoolCreateInfo::memoryTypeIndex.
It internally creates a temporary, dummy buffer that never has memory bound.
It is just a convenience function, equivalent to calling:
- `vkCreateBuffer`
- `vkGetBufferMemoryRequirements`
- `vmaFindMemoryTypeIndex`
- `vkDestroyBuffer`
*/
VkResult vmaFindMemoryTypeIndexForBufferInfo(
VmaAllocator allocator,
const VkBufferCreateInfo* pBufferCreateInfo,
const VmaAllocationCreateInfo* pAllocationCreateInfo,
uint32_t* pMemoryTypeIndex);
/**
\brief Helps to find memoryTypeIndex, given VkImageCreateInfo and VmaAllocationCreateInfo.
It can be useful e.g. to determine value to be used as VmaPoolCreateInfo::memoryTypeIndex.
It internally creates a temporary, dummy image that never has memory bound.
It is just a convenience function, equivalent to calling:
- `vkCreateImage`
- `vkGetImageMemoryRequirements`
- `vmaFindMemoryTypeIndex`
- `vkDestroyImage`
*/
VkResult vmaFindMemoryTypeIndexForImageInfo(
VmaAllocator allocator,
const VkImageCreateInfo* pImageCreateInfo,
const VmaAllocationCreateInfo* pAllocationCreateInfo,
uint32_t* pMemoryTypeIndex);
/// Flags to be passed as VmaPoolCreateInfo::flags.
typedef enum VmaPoolCreateFlagBits {
/** \brief Use this flag if you always allocate only buffers and linear images or only optimal images out of this pool and so Buffer-Image Granularity can be ignored.
This is an optional optimization flag.
If you always allocate using vmaCreateBuffer(), vmaCreateImage(),
vmaAllocateMemoryForBuffer(), then you don't need to use it because allocator
knows exact type of your allocations so it can handle Buffer-Image Granularity
in the optimal way.
If you also allocate using vmaAllocateMemoryForImage() or vmaAllocateMemory(),
exact type of such allocations is not known, so allocator must be conservative
in handling Buffer-Image Granularity, which can lead to suboptimal allocation
(wasted memory). In that case, if you can make sure you always allocate only
buffers and linear images or only optimal images out of this pool, use this flag
to make allocator disregard Buffer-Image Granularity and so make allocations
more optimal.
*/
VMA_POOL_CREATE_IGNORE_BUFFER_IMAGE_GRANULARITY_BIT = 0x00000002,
/** \brief Enables alternative, linear allocation algorithm in this pool.
Specify this flag to enable linear allocation algorithm, which always creates
new allocations after last one and doesn't reuse space from allocations freed in
between. It trades memory consumption for simplified algorithm and data
structure, which has better performance and uses less memory for metadata.
By using this flag, you can achieve behavior of free-at-once, stack,
ring buffer, and double stack. For details, see documentation chapter
\ref linear_algorithm.
When using this flag, you must specify VmaPoolCreateInfo::maxBlockCount == 1 (or 0 for default).
*/
VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT = 0x00000004,
VMA_POOL_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} VmaPoolCreateFlagBits;
typedef VkFlags VmaPoolCreateFlags;
/** \brief Describes parameter of created #VmaPool.
*/
typedef struct VmaPoolCreateInfo {
/** \brief Vulkan memory type index to allocate this pool from.
*/
uint32_t memoryTypeIndex;
/** \brief Use combination of #VmaPoolCreateFlagBits.
*/
VmaPoolCreateFlags flags;
/** \brief Size of a single `VkDeviceMemory` block to be allocated as part of this pool, in bytes. Optional.
Specify nonzero to set explicit, constant size of memory blocks used by this
pool.
Leave 0 to use default and let the library manage block sizes automatically.
Sizes of particular blocks may vary.
*/
VkDeviceSize blockSize;
/** \brief Minimum number of blocks to be always allocated in this pool, even if they stay empty.
Set to 0 to have no preallocated blocks and allow the pool be completely empty.
*/
size_t minBlockCount;
/** \brief Maximum number of blocks that can be allocated in this pool. Optional.
Set to 0 to use default, which is `SIZE_MAX`, which means no limit.
Set to same value as VmaPoolCreateInfo::minBlockCount to have fixed amount of memory allocated
throughout whole lifetime of this pool.
*/
size_t maxBlockCount;
/** \brief Maximum number of additional frames that are in use at the same time as current frame.
This value is used only when you make allocations with
#VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT flag. Such allocation cannot become
lost if allocation.lastUseFrameIndex >= allocator.currentFrameIndex - frameInUseCount.
For example, if you double-buffer your command buffers, so resources used for
rendering in previous frame may still be in use by the GPU at the moment you
allocate resources needed for the current frame, set this value to 1.
If you want to allow any allocations other than used in the current frame to
become lost, set this value to 0.
*/
uint32_t frameInUseCount;
} VmaPoolCreateInfo;
/** \brief Describes parameter of existing #VmaPool.
*/
typedef struct VmaPoolStats {
/** \brief Total amount of `VkDeviceMemory` allocated from Vulkan for this pool, in bytes.
*/
VkDeviceSize size;
/** \brief Total number of bytes in the pool not used by any #VmaAllocation.
*/
VkDeviceSize unusedSize;
/** \brief Number of #VmaAllocation objects created from this pool that were not destroyed or lost.
*/
size_t allocationCount;
/** \brief Number of continuous memory ranges in the pool not used by any #VmaAllocation.
*/
size_t unusedRangeCount;
/** \brief Size of the largest continuous free memory region available for new allocation.
Making a new allocation of that size is not guaranteed to succeed because of
possible additional margin required to respect alignment and buffer/image
granularity.
*/
VkDeviceSize unusedRangeSizeMax;
/** \brief Number of `VkDeviceMemory` blocks allocated for this pool.
*/
size_t blockCount;
} VmaPoolStats;
/** \brief Allocates Vulkan device memory and creates #VmaPool object.
@param allocator Allocator object.
@param pCreateInfo Parameters of pool to create.
@param[out] pPool Handle to created pool.
*/
VkResult vmaCreatePool(
VmaAllocator allocator,
const VmaPoolCreateInfo* pCreateInfo,
VmaPool* pPool);
/** \brief Destroys #VmaPool object and frees Vulkan device memory.
*/
void vmaDestroyPool(
VmaAllocator allocator,
VmaPool pool);
/** \brief Retrieves statistics of existing #VmaPool object.
@param allocator Allocator object.
@param pool Pool object.
@param[out] pPoolStats Statistics of specified pool.
*/
void vmaGetPoolStats(
VmaAllocator allocator,
VmaPool pool,
VmaPoolStats* pPoolStats);
/** \brief Marks all allocations in given pool as lost if they are not used in current frame or VmaPoolCreateInfo::frameInUseCount back from now.
@param allocator Allocator object.
@param pool Pool.
@param[out] pLostAllocationCount Number of allocations marked as lost. Optional - pass null if you don't need this information.
*/
void vmaMakePoolAllocationsLost(
VmaAllocator allocator,
VmaPool pool,
size_t* pLostAllocationCount);
/** \brief Checks magic number in margins around all allocations in given memory pool in search for corruptions.
Corruption detection is enabled only when `VMA_DEBUG_DETECT_CORRUPTION` macro is defined to nonzero,
`VMA_DEBUG_MARGIN` is defined to nonzero and the pool is created in memory type that is
`HOST_VISIBLE` and `HOST_COHERENT`. For more information, see [Corruption detection](@ref debugging_memory_usage_corruption_detection).
Possible return values:
- `VK_ERROR_FEATURE_NOT_PRESENT` - corruption detection is not enabled for specified pool.
- `VK_SUCCESS` - corruption detection has been performed and succeeded.
- `VK_ERROR_VALIDATION_FAILED_EXT` - corruption detection has been performed and found memory corruptions around one of the allocations.
`VMA_ASSERT` is also fired in that case.
- Other value: Error returned by Vulkan, e.g. memory mapping failure.
*/
VkResult vmaCheckPoolCorruption(VmaAllocator allocator, VmaPool pool);
/** \struct VmaAllocation
\brief Represents single memory allocation.
It may be either dedicated block of `VkDeviceMemory` or a specific region of a bigger block of this type
plus unique offset.
There are multiple ways to create such object.
You need to fill structure VmaAllocationCreateInfo.
For more information see [Choosing memory type](@ref choosing_memory_type).
Although the library provides convenience functions that create Vulkan buffer or image,
allocate memory for it and bind them together,
binding of the allocation to a buffer or an image is out of scope of the allocation itself.
Allocation object can exist without buffer/image bound,
binding can be done manually by the user, and destruction of it can be done
independently of destruction of the allocation.
The object also remembers its size and some other information.
To retrieve this information, use function vmaGetAllocationInfo() and inspect
returned structure VmaAllocationInfo.
Some kinds allocations can be in lost state.
For more information, see [Lost allocations](@ref lost_allocations).
*/
VK_DEFINE_HANDLE(VmaAllocation)
/** \brief Parameters of #VmaAllocation objects, that can be retrieved using function vmaGetAllocationInfo().
*/
typedef struct VmaAllocationInfo {
/** \brief Memory type index that this allocation was allocated from.
It never changes.
*/
uint32_t memoryType;
/** \brief Handle to Vulkan memory object.
Same memory object can be shared by multiple allocations.
It can change after call to vmaDefragment() if this allocation is passed to the function, or if allocation is lost.
If the allocation is lost, it is equal to `VK_NULL_HANDLE`.
*/
VkDeviceMemory deviceMemory;
/** \brief Offset into deviceMemory object to the beginning of this allocation, in bytes. (deviceMemory, offset) pair is unique to this allocation.
It can change after call to vmaDefragment() if this allocation is passed to the function, or if allocation is lost.
*/
VkDeviceSize offset;
/** \brief Size of this allocation, in bytes.
It never changes, unless allocation is lost.
*/
VkDeviceSize size;
/** \brief Pointer to the beginning of this allocation as mapped data.
If the allocation hasn't been mapped using vmaMapMemory() and hasn't been
created with #VMA_ALLOCATION_CREATE_MAPPED_BIT flag, this value null.
It can change after call to vmaMapMemory(), vmaUnmapMemory().
It can also change after call to vmaDefragment() if this allocation is passed to the function.
*/
void* pMappedData;
/** \brief Custom general-purpose pointer that was passed as VmaAllocationCreateInfo::pUserData or set using vmaSetAllocationUserData().
It can change after call to vmaSetAllocationUserData() for this allocation.
*/
void* pUserData;
} VmaAllocationInfo;
/** \brief General purpose memory allocation.
@param[out] pAllocation Handle to allocated memory.
@param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo().
You should free the memory using vmaFreeMemory().
It is recommended to use vmaAllocateMemoryForBuffer(), vmaAllocateMemoryForImage(),
vmaCreateBuffer(), vmaCreateImage() instead whenever possible.
*/
VkResult vmaAllocateMemory(
VmaAllocator allocator,
const VkMemoryRequirements* pVkMemoryRequirements,
const VmaAllocationCreateInfo* pCreateInfo,
VmaAllocation* pAllocation,
VmaAllocationInfo* pAllocationInfo);
/**
@param[out] pAllocation Handle to allocated memory.
@param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo().
You should free the memory using vmaFreeMemory().
*/
VkResult vmaAllocateMemoryForBuffer(
VmaAllocator allocator,
VkBuffer buffer,
const VmaAllocationCreateInfo* pCreateInfo,
VmaAllocation* pAllocation,
VmaAllocationInfo* pAllocationInfo);
/// Function similar to vmaAllocateMemoryForBuffer().
VkResult vmaAllocateMemoryForImage(
VmaAllocator allocator,
VkImage image,
const VmaAllocationCreateInfo* pCreateInfo,
VmaAllocation* pAllocation,
VmaAllocationInfo* pAllocationInfo);
/// Frees memory previously allocated using vmaAllocateMemory(), vmaAllocateMemoryForBuffer(), or vmaAllocateMemoryForImage().
void vmaFreeMemory(
VmaAllocator allocator,
VmaAllocation allocation);
/** \brief Returns current information about specified allocation and atomically marks it as used in current frame.
Current paramters of given allocation are returned in `pAllocationInfo`.
This function also atomically "touches" allocation - marks it as used in current frame,
just like vmaTouchAllocation().
If the allocation is in lost state, `pAllocationInfo->deviceMemory == VK_NULL_HANDLE`.
Although this function uses atomics and doesn't lock any mutex, so it should be quite efficient,
you can avoid calling it too often.
- You can retrieve same VmaAllocationInfo structure while creating your resource, from function
vmaCreateBuffer(), vmaCreateImage(). You can remember it if you are sure parameters don't change
(e.g. due to defragmentation or allocation becoming lost).
- If you just want to check if allocation is not lost, vmaTouchAllocation() will work faster.
*/
void vmaGetAllocationInfo(
VmaAllocator allocator,
VmaAllocation allocation,
VmaAllocationInfo* pAllocationInfo);
/** \brief Returns `VK_TRUE` if allocation is not lost and atomically marks it as used in current frame.
If the allocation has been created with #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT flag,
this function returns `VK_TRUE` if it's not in lost state, so it can still be used.
It then also atomically "touches" the allocation - marks it as used in current frame,
so that you can be sure it won't become lost in current frame or next `frameInUseCount` frames.
If the allocation is in lost state, the function returns `VK_FALSE`.
Memory of such allocation, as well as buffer or image bound to it, should not be used.
Lost allocation and the buffer/image still need to be destroyed.
If the allocation has been created without #VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT flag,
this function always returns `VK_TRUE`.
*/
VkBool32 vmaTouchAllocation(
VmaAllocator allocator,
VmaAllocation allocation);
/** \brief Sets pUserData in given allocation to new value.
If the allocation was created with VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT,
pUserData must be either null, or pointer to a null-terminated string. The function
makes local copy of the string and sets it as allocation's `pUserData`. String
passed as pUserData doesn't need to be valid for whole lifetime of the allocation -
you can free it after this call. String previously pointed by allocation's
pUserData is freed from memory.
If the flag was not used, the value of pointer `pUserData` is just copied to
allocation's `pUserData`. It is opaque, so you can use it however you want - e.g.
as a pointer, ordinal number or some handle to you own data.
*/
void vmaSetAllocationUserData(
VmaAllocator allocator,
VmaAllocation allocation,
void* pUserData);
/** \brief Creates new allocation that is in lost state from the beginning.
It can be useful if you need a dummy, non-null allocation.
You still need to destroy created object using vmaFreeMemory().
Returned allocation is not tied to any specific memory pool or memory type and
not bound to any image or buffer. It has size = 0. It cannot be turned into
a real, non-empty allocation.
*/
void vmaCreateLostAllocation(
VmaAllocator allocator,
VmaAllocation* pAllocation);
/** \brief Maps memory represented by given allocation and returns pointer to it.
Maps memory represented by given allocation to make it accessible to CPU code.
When succeeded, `*ppData` contains pointer to first byte of this memory.
If the allocation is part of bigger `VkDeviceMemory` block, the pointer is
correctly offseted to the beginning of region assigned to this particular
allocation.
Mapping is internally reference-counted and synchronized, so despite raw Vulkan
function `vkMapMemory()` cannot be used to map same block of `VkDeviceMemory`
multiple times simultaneously, it is safe to call this function on allocations
assigned to the same memory block. Actual Vulkan memory will be mapped on first
mapping and unmapped on last unmapping.
If the function succeeded, you must call vmaUnmapMemory() to unmap the
allocation when mapping is no longer needed or before freeing the allocation, at
the latest.
It also safe to call this function multiple times on the same allocation. You
must call vmaUnmapMemory() same number of times as you called vmaMapMemory().
It is also safe to call this function on allocation created with
#VMA_ALLOCATION_CREATE_MAPPED_BIT flag. Its memory stays mapped all the time.
You must still call vmaUnmapMemory() same number of times as you called
vmaMapMemory(). You must not call vmaUnmapMemory() additional time to free the
"0-th" mapping made automatically due to #VMA_ALLOCATION_CREATE_MAPPED_BIT flag.
This function fails when used on allocation made in memory type that is not
`HOST_VISIBLE`.
This function always fails when called for allocation that was created with
#VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT flag. Such allocations cannot be
mapped.
*/
VkResult vmaMapMemory(
VmaAllocator allocator,
VmaAllocation allocation,
void** ppData);
/** \brief Unmaps memory represented by given allocation, mapped previously using vmaMapMemory().
For details, see description of vmaMapMemory().
*/
void vmaUnmapMemory(
VmaAllocator allocator,
VmaAllocation allocation);
/** \brief Flushes memory of given allocation.
Calls `vkFlushMappedMemoryRanges()` for memory associated with given range of given allocation.
- `offset` must be relative to the beginning of allocation.
- `size` can be `VK_WHOLE_SIZE`. It means all memory from `offset` the the end of given allocation.
- `offset` and `size` don't have to be aligned.
They are internally rounded down/up to multiply of `nonCoherentAtomSize`.
- If `size` is 0, this call is ignored.
- If memory type that the `allocation` belongs to is not `HOST_VISIBLE` or it is `HOST_COHERENT`,
this call is ignored.
*/
void vmaFlushAllocation(VmaAllocator allocator, VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size);
/** \brief Invalidates memory of given allocation.
Calls `vkInvalidateMappedMemoryRanges()` for memory associated with given range of given allocation.
- `offset` must be relative to the beginning of allocation.
- `size` can be `VK_WHOLE_SIZE`. It means all memory from `offset` the the end of given allocation.
- `offset` and `size` don't have to be aligned.
They are internally rounded down/up to multiply of `nonCoherentAtomSize`.
- If `size` is 0, this call is ignored.
- If memory type that the `allocation` belongs to is not `HOST_VISIBLE` or it is `HOST_COHERENT`,
this call is ignored.
*/
void vmaInvalidateAllocation(VmaAllocator allocator, VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size);
/** \brief Checks magic number in margins around all allocations in given memory types (in both default and custom pools) in search for corruptions.
@param memoryTypeBits Bit mask, where each bit set means that a memory type with that index should be checked.
Corruption detection is enabled only when `VMA_DEBUG_DETECT_CORRUPTION` macro is defined to nonzero,
`VMA_DEBUG_MARGIN` is defined to nonzero and only for memory types that are
`HOST_VISIBLE` and `HOST_COHERENT`. For more information, see [Corruption detection](@ref debugging_memory_usage_corruption_detection).
Possible return values:
- `VK_ERROR_FEATURE_NOT_PRESENT` - corruption detection is not enabled for any of specified memory types.
- `VK_SUCCESS` - corruption detection has been performed and succeeded.
- `VK_ERROR_VALIDATION_FAILED_EXT` - corruption detection has been performed and found memory corruptions around one of the allocations.
`VMA_ASSERT` is also fired in that case.
- Other value: Error returned by Vulkan, e.g. memory mapping failure.
*/
VkResult vmaCheckCorruption(VmaAllocator allocator, uint32_t memoryTypeBits);
/** \brief Optional configuration parameters to be passed to function vmaDefragment(). */
typedef struct VmaDefragmentationInfo {
/** \brief Maximum total numbers of bytes that can be copied while moving allocations to different places.
Default is `VK_WHOLE_SIZE`, which means no limit.
*/
VkDeviceSize maxBytesToMove;
/** \brief Maximum number of allocations that can be moved to different place.
Default is `UINT32_MAX`, which means no limit.
*/
uint32_t maxAllocationsToMove;
} VmaDefragmentationInfo;
/** \brief Statistics returned by function vmaDefragment(). */
typedef struct VmaDefragmentationStats {
/// Total number of bytes that have been copied while moving allocations to different places.
VkDeviceSize bytesMoved;
/// Total number of bytes that have been released to the system by freeing empty `VkDeviceMemory` objects.
VkDeviceSize bytesFreed;
/// Number of allocations that have been moved to different places.
uint32_t allocationsMoved;
/// Number of empty `VkDeviceMemory` objects that have been released to the system.
uint32_t deviceMemoryBlocksFreed;
} VmaDefragmentationStats;
/** \brief Compacts memory by moving allocations.
@param pAllocations Array of allocations that can be moved during this compation.
@param allocationCount Number of elements in pAllocations and pAllocationsChanged arrays.
@param[out] pAllocationsChanged Array of boolean values that will indicate whether matching allocation in pAllocations array has been moved. This parameter is optional. Pass null if you don't need this information.
@param pDefragmentationInfo Configuration parameters. Optional - pass null to use default values.
@param[out] pDefragmentationStats Statistics returned by the function. Optional - pass null if you don't need this information.
@return VK_SUCCESS if completed, VK_INCOMPLETE if succeeded but didn't make all possible optimizations because limits specified in pDefragmentationInfo have been reached, negative error code in case of error.
This function works by moving allocations to different places (different
`VkDeviceMemory` objects and/or different offsets) in order to optimize memory
usage. Only allocations that are in pAllocations array can be moved. All other
allocations are considered nonmovable in this call. Basic rules:
- Only allocations made in memory types that have
`VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT` and `VK_MEMORY_PROPERTY_HOST_COHERENT_BIT`
flags can be compacted. You may pass other allocations but it makes no sense -
these will never be moved.
- Custom pools created with #VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT flag are not
defragmented. Allocations passed to this function that come from such pools
are ignored.
- Allocations created with #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT or
created as dedicated allocations for any other reason are also ignored.
- Both allocations made with or without #VMA_ALLOCATION_CREATE_MAPPED_BIT
flag can be compacted. If not persistently mapped, memory will be mapped
temporarily inside this function if needed.
- You must not pass same #VmaAllocation object multiple times in pAllocations array.
The function also frees empty `VkDeviceMemory` blocks.
After allocation has been moved, its VmaAllocationInfo::deviceMemory and/or
VmaAllocationInfo::offset changes. You must query them again using
vmaGetAllocationInfo() if you need them.
If an allocation has been moved, data in memory is copied to new place
automatically, but if it was bound to a buffer or an image, you must destroy
that object yourself, create new one and bind it to the new memory pointed by
the allocation. You must use `vkDestroyBuffer()`, `vkDestroyImage()`,
`vkCreateBuffer()`, `vkCreateImage()` for that purpose and NOT vmaDestroyBuffer(),
vmaDestroyImage(), vmaCreateBuffer(), vmaCreateImage()! Example:
\code
VkDevice device = ...;
VmaAllocator allocator = ...;
std::vector<VkBuffer> buffers = ...;
std::vector<VmaAllocation> allocations = ...;
std::vector<VkBool32> allocationsChanged(allocations.size());
vmaDefragment(allocator, allocations.data(), allocations.size(), allocationsChanged.data(), nullptr, nullptr);
for(size_t i = 0; i < allocations.size(); ++i)
{
if(allocationsChanged[i])
{
VmaAllocationInfo allocInfo;
vmaGetAllocationInfo(allocator, allocations[i], &allocInfo);
vkDestroyBuffer(device, buffers[i], nullptr);
VkBufferCreateInfo bufferInfo = ...;
vkCreateBuffer(device, &bufferInfo, nullptr, &buffers[i]);
// You can make dummy call to vkGetBufferMemoryRequirements here to silence validation layer warning.
vkBindBufferMemory(device, buffers[i], allocInfo.deviceMemory, allocInfo.offset);
}
}
\endcode
Note: Please don't expect memory to be fully compacted after this call.
Algorithms inside are based on some heuristics that try to maximize number of Vulkan
memory blocks to make totally empty to release them, as well as to maximimze continuous
empty space inside remaining blocks, while minimizing the number and size of data that
needs to be moved. Some fragmentation still remains after this call. This is normal.
Warning: This function is not 100% correct according to Vulkan specification. Use it
at your own risk. That's because Vulkan doesn't guarantee that memory
requirements (size and alignment) for a new buffer or image are consistent. They
may be different even for subsequent calls with the same parameters. It really
does happen on some platforms, especially with images.
Warning: This function may be time-consuming, so you shouldn't call it too often
(like every frame or after every resource creation/destruction).
You can call it on special occasions (like when reloading a game level or
when you just destroyed a lot of objects).
*/
VkResult vmaDefragment(
VmaAllocator allocator,
VmaAllocation* pAllocations,
size_t allocationCount,
VkBool32* pAllocationsChanged,
const VmaDefragmentationInfo *pDefragmentationInfo,
VmaDefragmentationStats* pDefragmentationStats);
/** \brief Binds buffer to allocation.
Binds specified buffer to region of memory represented by specified allocation.
Gets `VkDeviceMemory` handle and offset from the allocation.
If you want to create a buffer, allocate memory for it and bind them together separately,
you should use this function for binding instead of standard `vkBindBufferMemory()`,
because it ensures proper synchronization so that when a `VkDeviceMemory` object is used by multiple
allocations, calls to `vkBind*Memory()` or `vkMapMemory()` won't happen from multiple threads simultaneously
(which is illegal in Vulkan).
It is recommended to use function vmaCreateBuffer() instead of this one.
*/
VkResult vmaBindBufferMemory(
VmaAllocator allocator,
VmaAllocation allocation,
VkBuffer buffer);
/** \brief Binds image to allocation.
Binds specified image to region of memory represented by specified allocation.
Gets `VkDeviceMemory` handle and offset from the allocation.
If you want to create an image, allocate memory for it and bind them together separately,
you should use this function for binding instead of standard `vkBindImageMemory()`,
because it ensures proper synchronization so that when a `VkDeviceMemory` object is used by multiple
allocations, calls to `vkBind*Memory()` or `vkMapMemory()` won't happen from multiple threads simultaneously
(which is illegal in Vulkan).
It is recommended to use function vmaCreateImage() instead of this one.
*/
VkResult vmaBindImageMemory(
VmaAllocator allocator,
VmaAllocation allocation,
VkImage image);
/**
@param[out] pBuffer Buffer that was created.
@param[out] pAllocation Allocation that was created.
@param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo().
This function automatically:
-# Creates buffer.
-# Allocates appropriate memory for it.
-# Binds the buffer with the memory.
If any of these operations fail, buffer and allocation are not created,
returned value is negative error code, *pBuffer and *pAllocation are null.
If the function succeeded, you must destroy both buffer and allocation when you
no longer need them using either convenience function vmaDestroyBuffer() or
separately, using `vkDestroyBuffer()` and vmaFreeMemory().
If VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT flag was used,
VK_KHR_dedicated_allocation extension is used internally to query driver whether
it requires or prefers the new buffer to have dedicated allocation. If yes,
and if dedicated allocation is possible (VmaAllocationCreateInfo::pool is null
and VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT is not used), it creates dedicated
allocation for this buffer, just like when using
VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT.
*/
VkResult vmaCreateBuffer(
VmaAllocator allocator,
const VkBufferCreateInfo* pBufferCreateInfo,
const VmaAllocationCreateInfo* pAllocationCreateInfo,
VkBuffer* pBuffer,
VmaAllocation* pAllocation,
VmaAllocationInfo* pAllocationInfo);
/** \brief Destroys Vulkan buffer and frees allocated memory.
This is just a convenience function equivalent to:
\code
vkDestroyBuffer(device, buffer, allocationCallbacks);
vmaFreeMemory(allocator, allocation);
\endcode
It it safe to pass null as buffer and/or allocation.
*/
void vmaDestroyBuffer(
VmaAllocator allocator,
VkBuffer buffer,
VmaAllocation allocation);
/// Function similar to vmaCreateBuffer().
VkResult vmaCreateImage(
VmaAllocator allocator,
const VkImageCreateInfo* pImageCreateInfo,
const VmaAllocationCreateInfo* pAllocationCreateInfo,
VkImage* pImage,
VmaAllocation* pAllocation,
VmaAllocationInfo* pAllocationInfo);
/** \brief Destroys Vulkan image and frees allocated memory.
This is just a convenience function equivalent to:
\code
vkDestroyImage(device, image, allocationCallbacks);
vmaFreeMemory(allocator, allocation);
\endcode
It it safe to pass null as image and/or allocation.
*/
void vmaDestroyImage(
VmaAllocator allocator,
VkImage image,
VmaAllocation allocation);
#ifdef __cplusplus
}
#endif
#endif // AMD_VULKAN_MEMORY_ALLOCATOR_H
// For Visual Studio IntelliSense.
#if defined(__cplusplus) && defined(__INTELLISENSE__)
#define VMA_IMPLEMENTATION
#endif
#ifdef VMA_IMPLEMENTATION
#undef VMA_IMPLEMENTATION
#include <cstdint>
#include <cstdlib>
#include <cstring>
/*******************************************************************************
CONFIGURATION SECTION
Define some of these macros before each #include of this header or change them
here if you need other then default behavior depending on your environment.
*/
/*
Define this macro to 1 to make the library fetch pointers to Vulkan functions
internally, like:
vulkanFunctions.vkAllocateMemory = &vkAllocateMemory;
Define to 0 if you are going to provide you own pointers to Vulkan functions via
VmaAllocatorCreateInfo::pVulkanFunctions.
*/
#if !defined(VMA_STATIC_VULKAN_FUNCTIONS) && !defined(VK_NO_PROTOTYPES)
#define VMA_STATIC_VULKAN_FUNCTIONS 1
#endif
// Define this macro to 1 to make the library use STL containers instead of its own implementation.
//#define VMA_USE_STL_CONTAINERS 1
/* Set this macro to 1 to make the library including and using STL containers:
std::pair, std::vector, std::list, std::unordered_map.
Set it to 0 or undefined to make the library using its own implementation of
the containers.
*/
#if VMA_USE_STL_CONTAINERS
#define VMA_USE_STL_VECTOR 1
#define VMA_USE_STL_UNORDERED_MAP 1
#define VMA_USE_STL_LIST 1
#endif
#if VMA_USE_STL_VECTOR
#include <vector>
#endif
#if VMA_USE_STL_UNORDERED_MAP
#include <unordered_map>
#endif
#if VMA_USE_STL_LIST
#include <list>
#endif
/*
Following headers are used in this CONFIGURATION section only, so feel free to
remove them if not needed.
*/
#include <cassert> // for assert
#include <algorithm> // for min, max
#include <mutex> // for std::mutex
#include <atomic> // for std::atomic
#ifndef VMA_NULL
// Value used as null pointer. Define it to e.g.: nullptr, NULL, 0, (void*)0.
#define VMA_NULL nullptr
#endif
#if defined(__APPLE__) || defined(__ANDROID__)
#include <cstdlib>
void *aligned_alloc(size_t alignment, size_t size)
{
// alignment must be >= sizeof(void*)
if(alignment < sizeof(void*))
{
alignment = sizeof(void*);
}
void *pointer;
if(posix_memalign(&pointer, alignment, size) == 0)
return pointer;
return VMA_NULL;
}
#endif
// If your compiler is not compatible with C++11 and definition of
// aligned_alloc() function is missing, uncommeting following line may help:
//#include <malloc.h>
// Normal assert to check for programmer's errors, especially in Debug configuration.
#ifndef VMA_ASSERT
#ifdef _DEBUG
#define VMA_ASSERT(expr) assert(expr)
#else
#define VMA_ASSERT(expr)
#endif
#endif
// Assert that will be called very often, like inside data structures e.g. operator[].
// Making it non-empty can make program slow.
#ifndef VMA_HEAVY_ASSERT
#ifdef _DEBUG
#define VMA_HEAVY_ASSERT(expr) //VMA_ASSERT(expr)
#else
#define VMA_HEAVY_ASSERT(expr)
#endif
#endif
#ifndef VMA_ALIGN_OF
#define VMA_ALIGN_OF(type) (__alignof(type))
#endif
#ifndef VMA_SYSTEM_ALIGNED_MALLOC
#if defined(_WIN32)
#define VMA_SYSTEM_ALIGNED_MALLOC(size, alignment) (_aligned_malloc((size), (alignment)))
#else
#define VMA_SYSTEM_ALIGNED_MALLOC(size, alignment) (aligned_alloc((alignment), (size) ))
#endif
#endif
#ifndef VMA_SYSTEM_FREE
#if defined(_WIN32)
#define VMA_SYSTEM_FREE(ptr) _aligned_free(ptr)
#else
#define VMA_SYSTEM_FREE(ptr) free(ptr)
#endif
#endif
#ifndef VMA_MIN
#define VMA_MIN(v1, v2) (std::min((v1), (v2)))
#endif
#ifndef VMA_MAX
#define VMA_MAX(v1, v2) (std::max((v1), (v2)))
#endif
#ifndef VMA_SWAP
#define VMA_SWAP(v1, v2) std::swap((v1), (v2))
#endif
#ifndef VMA_SORT
#define VMA_SORT(beg, end, cmp) std::sort(beg, end, cmp)
#endif
#ifndef VMA_DEBUG_LOG
#define VMA_DEBUG_LOG(format, ...)
/*
#define VMA_DEBUG_LOG(format, ...) do { \
printf(format, __VA_ARGS__); \
printf("\n"); \
} while(false)
*/
#endif
// Define this macro to 1 to enable functions: vmaBuildStatsString, vmaFreeStatsString.
#if VMA_STATS_STRING_ENABLED
static inline void VmaUint32ToStr(char* outStr, size_t strLen, uint32_t num)
{
snprintf(outStr, strLen, "%u", static_cast<unsigned int>(num));
}
static inline void VmaUint64ToStr(char* outStr, size_t strLen, uint64_t num)
{
snprintf(outStr, strLen, "%llu", static_cast<unsigned long long>(num));
}
static inline void VmaPtrToStr(char* outStr, size_t strLen, const void* ptr)
{
snprintf(outStr, strLen, "%p", ptr);
}
#endif
#ifndef VMA_MUTEX
class VmaMutex
{
public:
VmaMutex() { }
~VmaMutex() { }
void Lock() { m_Mutex.lock(); }
void Unlock() { m_Mutex.unlock(); }
private:
std::mutex m_Mutex;
};
#define VMA_MUTEX VmaMutex
#endif
/*
If providing your own implementation, you need to implement a subset of std::atomic:
- Constructor(uint32_t desired)
- uint32_t load() const
- void store(uint32_t desired)
- bool compare_exchange_weak(uint32_t& expected, uint32_t desired)
*/
#ifndef VMA_ATOMIC_UINT32
#define VMA_ATOMIC_UINT32 std::atomic<uint32_t>
#endif
#ifndef VMA_BEST_FIT
/**
Main parameter for function assessing how good is a free suballocation for a new
allocation request.
- Set to 1 to use Best-Fit algorithm - prefer smaller blocks, as close to the
size of requested allocations as possible.
- Set to 0 to use Worst-Fit algorithm - prefer larger blocks, as large as
possible.
Experiments in special testing environment showed that Best-Fit algorithm is
better.
*/
#define VMA_BEST_FIT (1)
#endif
#ifndef VMA_DEBUG_ALWAYS_DEDICATED_MEMORY
/**
Every allocation will have its own memory block.
Define to 1 for debugging purposes only.
*/
#define VMA_DEBUG_ALWAYS_DEDICATED_MEMORY (0)
#endif
#ifndef VMA_DEBUG_ALIGNMENT
/**
Minimum alignment of all allocations, in bytes.
Set to more than 1 for debugging purposes only. Must be power of two.
*/
#define VMA_DEBUG_ALIGNMENT (1)
#endif
#ifndef VMA_DEBUG_MARGIN
/**
Minimum margin before and after every allocation, in bytes.
Set nonzero for debugging purposes only.
*/
#define VMA_DEBUG_MARGIN (0)
#endif
#ifndef VMA_DEBUG_INITIALIZE_ALLOCATIONS
/**
Define this macro to 1 to automatically fill new allocations and destroyed
allocations with some bit pattern.
*/
#define VMA_DEBUG_INITIALIZE_ALLOCATIONS (0)
#endif
#ifndef VMA_DEBUG_DETECT_CORRUPTION
/**
Define this macro to 1 together with non-zero value of VMA_DEBUG_MARGIN to
enable writing magic value to the margin before and after every allocation and
validating it, so that memory corruptions (out-of-bounds writes) are detected.
*/
#define VMA_DEBUG_DETECT_CORRUPTION (0)
#endif
#ifndef VMA_DEBUG_GLOBAL_MUTEX
/**
Set this to 1 for debugging purposes only, to enable single mutex protecting all
entry calls to the library. Can be useful for debugging multithreading issues.
*/
#define VMA_DEBUG_GLOBAL_MUTEX (0)
#endif
#ifndef VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY
/**
Minimum value for VkPhysicalDeviceLimits::bufferImageGranularity.
Set to more than 1 for debugging purposes only. Must be power of two.
*/
#define VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY (1)
#endif
#ifndef VMA_SMALL_HEAP_MAX_SIZE
/// Maximum size of a memory heap in Vulkan to consider it "small".
#define VMA_SMALL_HEAP_MAX_SIZE (1024ull * 1024 * 1024)
#endif
#ifndef VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE
/// Default size of a block allocated as single VkDeviceMemory from a "large" heap.
#define VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE (256ull * 1024 * 1024)
#endif
#ifndef VMA_CLASS_NO_COPY
#define VMA_CLASS_NO_COPY(className) \
private: \
className(const className&) = delete; \
className& operator=(const className&) = delete;
#endif
static const uint32_t VMA_FRAME_INDEX_LOST = UINT32_MAX;
// Decimal 2139416166, float NaN, little-endian binary 66 E6 84 7F.
static const uint32_t VMA_CORRUPTION_DETECTION_MAGIC_VALUE = 0x7F84E666;
static const uint8_t VMA_ALLOCATION_FILL_PATTERN_CREATED = 0xDC;
static const uint8_t VMA_ALLOCATION_FILL_PATTERN_DESTROYED = 0xEF;
/*******************************************************************************
END OF CONFIGURATION
*/
static VkAllocationCallbacks VmaEmptyAllocationCallbacks = {
VMA_NULL, VMA_NULL, VMA_NULL, VMA_NULL, VMA_NULL, VMA_NULL };
// Returns number of bits set to 1 in (v).
static inline uint32_t VmaCountBitsSet(uint32_t v)
{
uint32_t c = v - ((v >> 1) & 0x55555555);
c = ((c >> 2) & 0x33333333) + (c & 0x33333333);
c = ((c >> 4) + c) & 0x0F0F0F0F;
c = ((c >> 8) + c) & 0x00FF00FF;
c = ((c >> 16) + c) & 0x0000FFFF;
return c;
}
// Aligns given value up to nearest multiply of align value. For example: VmaAlignUp(11, 8) = 16.
// Use types like uint32_t, uint64_t as T.
template <typename T>
static inline T VmaAlignUp(T val, T align)
{
return (val + align - 1) / align * align;
}
// Aligns given value down to nearest multiply of align value. For example: VmaAlignUp(11, 8) = 8.
// Use types like uint32_t, uint64_t as T.
template <typename T>
static inline T VmaAlignDown(T val, T align)
{
return val / align * align;
}
// Division with mathematical rounding to nearest number.
template <typename T>
inline T VmaRoundDiv(T x, T y)
{
return (x + (y / (T)2)) / y;
}
static inline bool VmaStrIsEmpty(const char* pStr)
{
return pStr == VMA_NULL || *pStr == '\0';
}
#ifndef VMA_SORT
template<typename Iterator, typename Compare>
Iterator VmaQuickSortPartition(Iterator beg, Iterator end, Compare cmp)
{
Iterator centerValue = end; --centerValue;
Iterator insertIndex = beg;
for(Iterator memTypeIndex = beg; memTypeIndex < centerValue; ++memTypeIndex)
{
if(cmp(*memTypeIndex, *centerValue))
{
if(insertIndex != memTypeIndex)
{
VMA_SWAP(*memTypeIndex, *insertIndex);
}
++insertIndex;
}
}
if(insertIndex != centerValue)
{
VMA_SWAP(*insertIndex, *centerValue);
}
return insertIndex;
}
template<typename Iterator, typename Compare>
void VmaQuickSort(Iterator beg, Iterator end, Compare cmp)
{
if(beg < end)
{
Iterator it = VmaQuickSortPartition<Iterator, Compare>(beg, end, cmp);
VmaQuickSort<Iterator, Compare>(beg, it, cmp);
VmaQuickSort<Iterator, Compare>(it + 1, end, cmp);
}
}
#define VMA_SORT(beg, end, cmp) VmaQuickSort(beg, end, cmp)
#endif // #ifndef VMA_SORT
/*
Returns true if two memory blocks occupy overlapping pages.
ResourceA must be in less memory offset than ResourceB.
Algorithm is based on "Vulkan 1.0.39 - A Specification (with all registered Vulkan extensions)"
chapter 11.6 "Resource Memory Association", paragraph "Buffer-Image Granularity".
*/
static inline bool VmaBlocksOnSamePage(
VkDeviceSize resourceAOffset,
VkDeviceSize resourceASize,
VkDeviceSize resourceBOffset,
VkDeviceSize pageSize)
{
VMA_ASSERT(resourceAOffset + resourceASize <= resourceBOffset && resourceASize > 0 && pageSize > 0);
VkDeviceSize resourceAEnd = resourceAOffset + resourceASize - 1;
VkDeviceSize resourceAEndPage = resourceAEnd & ~(pageSize - 1);
VkDeviceSize resourceBStart = resourceBOffset;
VkDeviceSize resourceBStartPage = resourceBStart & ~(pageSize - 1);
return resourceAEndPage == resourceBStartPage;
}
enum VmaSuballocationType
{
VMA_SUBALLOCATION_TYPE_FREE = 0,
VMA_SUBALLOCATION_TYPE_UNKNOWN = 1,
VMA_SUBALLOCATION_TYPE_BUFFER = 2,
VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN = 3,
VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR = 4,
VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL = 5,
VMA_SUBALLOCATION_TYPE_MAX_ENUM = 0x7FFFFFFF
};
/*
Returns true if given suballocation types could conflict and must respect
VkPhysicalDeviceLimits::bufferImageGranularity. They conflict if one is buffer
or linear image and another one is optimal image. If type is unknown, behave
conservatively.
*/
static inline bool VmaIsBufferImageGranularityConflict(
VmaSuballocationType suballocType1,
VmaSuballocationType suballocType2)
{
if(suballocType1 > suballocType2)
{
VMA_SWAP(suballocType1, suballocType2);
}
switch(suballocType1)
{
case VMA_SUBALLOCATION_TYPE_FREE:
return false;
case VMA_SUBALLOCATION_TYPE_UNKNOWN:
return true;
case VMA_SUBALLOCATION_TYPE_BUFFER:
return
suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN ||
suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL;
case VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN:
return
suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN ||
suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR ||
suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL;
case VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR:
return
suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL;
case VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL:
return false;
default:
VMA_ASSERT(0);
return true;
}
}
static void VmaWriteMagicValue(void* pData, VkDeviceSize offset)
{
uint32_t* pDst = (uint32_t*)((char*)pData + offset);
const size_t numberCount = VMA_DEBUG_MARGIN / sizeof(uint32_t);
for(size_t i = 0; i < numberCount; ++i, ++pDst)
{
*pDst = VMA_CORRUPTION_DETECTION_MAGIC_VALUE;
}
}
static bool VmaValidateMagicValue(const void* pData, VkDeviceSize offset)
{
const uint32_t* pSrc = (const uint32_t*)((const char*)pData + offset);
const size_t numberCount = VMA_DEBUG_MARGIN / sizeof(uint32_t);
for(size_t i = 0; i < numberCount; ++i, ++pSrc)
{
if(*pSrc != VMA_CORRUPTION_DETECTION_MAGIC_VALUE)
{
return false;
}
}
return true;
}
// Helper RAII class to lock a mutex in constructor and unlock it in destructor (at the end of scope).
struct VmaMutexLock
{
VMA_CLASS_NO_COPY(VmaMutexLock)
public:
VmaMutexLock(VMA_MUTEX& mutex, bool useMutex) :
m_pMutex(useMutex ? &mutex : VMA_NULL)
{
if(m_pMutex)
{
m_pMutex->Lock();
}
}
~VmaMutexLock()
{
if(m_pMutex)
{
m_pMutex->Unlock();
}
}
private:
VMA_MUTEX* m_pMutex;
};
#if VMA_DEBUG_GLOBAL_MUTEX
static VMA_MUTEX gDebugGlobalMutex;
#define VMA_DEBUG_GLOBAL_MUTEX_LOCK VmaMutexLock debugGlobalMutexLock(gDebugGlobalMutex, true);
#else
#define VMA_DEBUG_GLOBAL_MUTEX_LOCK
#endif
// Minimum size of a free suballocation to register it in the free suballocation collection.
static const VkDeviceSize VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER = 16;
/*
Performs binary search and returns iterator to first element that is greater or
equal to (key), according to comparison (cmp).
Cmp should return true if first argument is less than second argument.
Returned value is the found element, if present in the collection or place where
new element with value (key) should be inserted.
*/
template <typename CmpLess, typename IterT, typename KeyT>
static IterT VmaBinaryFindFirstNotLess(IterT beg, IterT end, const KeyT &key, CmpLess cmp)
{
size_t down = 0, up = (end - beg);
while(down < up)
{
const size_t mid = (down + up) / 2;
if(cmp(*(beg+mid), key))
{
down = mid + 1;
}
else
{
up = mid;
}
}
return beg + down;
}
////////////////////////////////////////////////////////////////////////////////
// Memory allocation
static void* VmaMalloc(const VkAllocationCallbacks* pAllocationCallbacks, size_t size, size_t alignment)
{
if((pAllocationCallbacks != VMA_NULL) &&
(pAllocationCallbacks->pfnAllocation != VMA_NULL))
{
return (*pAllocationCallbacks->pfnAllocation)(
pAllocationCallbacks->pUserData,
size,
alignment,
VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
}
else
{
return VMA_SYSTEM_ALIGNED_MALLOC(size, alignment);
}
}
static void VmaFree(const VkAllocationCallbacks* pAllocationCallbacks, void* ptr)
{
if((pAllocationCallbacks != VMA_NULL) &&
(pAllocationCallbacks->pfnFree != VMA_NULL))
{
(*pAllocationCallbacks->pfnFree)(pAllocationCallbacks->pUserData, ptr);
}
else
{
VMA_SYSTEM_FREE(ptr);
}
}
template<typename T>
static T* VmaAllocate(const VkAllocationCallbacks* pAllocationCallbacks)
{
return (T*)VmaMalloc(pAllocationCallbacks, sizeof(T), VMA_ALIGN_OF(T));
}
template<typename T>
static T* VmaAllocateArray(const VkAllocationCallbacks* pAllocationCallbacks, size_t count)
{
return (T*)VmaMalloc(pAllocationCallbacks, sizeof(T) * count, VMA_ALIGN_OF(T));
}
#define vma_new(allocator, type) new(VmaAllocate<type>(allocator))(type)
#define vma_new_array(allocator, type, count) new(VmaAllocateArray<type>((allocator), (count)))(type)
template<typename T>
static void vma_delete(const VkAllocationCallbacks* pAllocationCallbacks, T* ptr)
{
ptr->~T();
VmaFree(pAllocationCallbacks, ptr);
}
template<typename T>
static void vma_delete_array(const VkAllocationCallbacks* pAllocationCallbacks, T* ptr, size_t count)
{
if(ptr != VMA_NULL)
{
for(size_t i = count; i--; )
{
ptr[i].~T();
}
VmaFree(pAllocationCallbacks, ptr);
}
}
// STL-compatible allocator.
template<typename T>
class VmaStlAllocator
{
public:
const VkAllocationCallbacks* const m_pCallbacks;
typedef T value_type;
VmaStlAllocator(const VkAllocationCallbacks* pCallbacks) : m_pCallbacks(pCallbacks) { }
template<typename U> VmaStlAllocator(const VmaStlAllocator<U>& src) : m_pCallbacks(src.m_pCallbacks) { }
T* allocate(size_t n) { return VmaAllocateArray<T>(m_pCallbacks, n); }
void deallocate(T* p, size_t n) { VmaFree(m_pCallbacks, p); }
template<typename U>
bool operator==(const VmaStlAllocator<U>& rhs) const
{
return m_pCallbacks == rhs.m_pCallbacks;
}
template<typename U>
bool operator!=(const VmaStlAllocator<U>& rhs) const
{
return m_pCallbacks != rhs.m_pCallbacks;
}
VmaStlAllocator& operator=(const VmaStlAllocator& x) = delete;
};
#if VMA_USE_STL_VECTOR
#define VmaVector std::vector
template<typename T, typename allocatorT>
static void VmaVectorInsert(std::vector<T, allocatorT>& vec, size_t index, const T& item)
{
vec.insert(vec.begin() + index, item);
}
template<typename T, typename allocatorT>
static void VmaVectorRemove(std::vector<T, allocatorT>& vec, size_t index)
{
vec.erase(vec.begin() + index);
}
#else // #if VMA_USE_STL_VECTOR
/* Class with interface compatible with subset of std::vector.
T must be POD because constructors and destructors are not called and memcpy is
used for these objects. */
template<typename T, typename AllocatorT>
class VmaVector
{
public:
typedef T value_type;
VmaVector(const AllocatorT& allocator) :
m_Allocator(allocator),
m_pArray(VMA_NULL),
m_Count(0),
m_Capacity(0)
{
}
VmaVector(size_t count, const AllocatorT& allocator) :
m_Allocator(allocator),
m_pArray(count ? (T*)VmaAllocateArray<T>(allocator.m_pCallbacks, count) : VMA_NULL),
m_Count(count),
m_Capacity(count)
{
}
VmaVector(const VmaVector<T, AllocatorT>& src) :
m_Allocator(src.m_Allocator),
m_pArray(src.m_Count ? (T*)VmaAllocateArray<T>(src.m_Allocator.m_pCallbacks, src.m_Count) : VMA_NULL),
m_Count(src.m_Count),
m_Capacity(src.m_Count)
{
if(m_Count != 0)
{
memcpy(m_pArray, src.m_pArray, m_Count * sizeof(T));
}
}
~VmaVector()
{
VmaFree(m_Allocator.m_pCallbacks, m_pArray);
}
VmaVector& operator=(const VmaVector<T, AllocatorT>& rhs)
{
if(&rhs != this)
{
resize(rhs.m_Count);
if(m_Count != 0)
{
memcpy(m_pArray, rhs.m_pArray, m_Count * sizeof(T));
}
}
return *this;
}
bool empty() const { return m_Count == 0; }
size_t size() const { return m_Count; }
T* data() { return m_pArray; }
const T* data() const { return m_pArray; }
T& operator[](size_t index)
{
VMA_HEAVY_ASSERT(index < m_Count);
return m_pArray[index];
}
const T& operator[](size_t index) const
{
VMA_HEAVY_ASSERT(index < m_Count);
return m_pArray[index];
}
T& front()
{
VMA_HEAVY_ASSERT(m_Count > 0);
return m_pArray[0];
}
const T& front() const
{
VMA_HEAVY_ASSERT(m_Count > 0);
return m_pArray[0];
}
T& back()
{
VMA_HEAVY_ASSERT(m_Count > 0);
return m_pArray[m_Count - 1];
}
const T& back() const
{
VMA_HEAVY_ASSERT(m_Count > 0);
return m_pArray[m_Count - 1];
}
void reserve(size_t newCapacity, bool freeMemory = false)
{
newCapacity = VMA_MAX(newCapacity, m_Count);
if((newCapacity < m_Capacity) && !freeMemory)
{
newCapacity = m_Capacity;
}
if(newCapacity != m_Capacity)
{
T* const newArray = newCapacity ? VmaAllocateArray<T>(m_Allocator, newCapacity) : VMA_NULL;
if(m_Count != 0)
{
memcpy(newArray, m_pArray, m_Count * sizeof(T));
}
VmaFree(m_Allocator.m_pCallbacks, m_pArray);
m_Capacity = newCapacity;
m_pArray = newArray;
}
}
void resize(size_t newCount, bool freeMemory = false)
{
size_t newCapacity = m_Capacity;
if(newCount > m_Capacity)
{
newCapacity = VMA_MAX(newCount, VMA_MAX(m_Capacity * 3 / 2, (size_t)8));
}
else if(freeMemory)
{
newCapacity = newCount;
}
if(newCapacity != m_Capacity)
{
T* const newArray = newCapacity ? VmaAllocateArray<T>(m_Allocator.m_pCallbacks, newCapacity) : VMA_NULL;
const size_t elementsToCopy = VMA_MIN(m_Count, newCount);
if(elementsToCopy != 0)
{
memcpy(newArray, m_pArray, elementsToCopy * sizeof(T));
}
VmaFree(m_Allocator.m_pCallbacks, m_pArray);
m_Capacity = newCapacity;
m_pArray = newArray;
}
m_Count = newCount;
}
void clear(bool freeMemory = false)
{
resize(0, freeMemory);
}
void insert(size_t index, const T& src)
{
VMA_HEAVY_ASSERT(index <= m_Count);
const size_t oldCount = size();
resize(oldCount + 1);
if(index < oldCount)
{
memmove(m_pArray + (index + 1), m_pArray + index, (oldCount - index) * sizeof(T));
}
m_pArray[index] = src;
}
void remove(size_t index)
{
VMA_HEAVY_ASSERT(index < m_Count);
const size_t oldCount = size();
if(index < oldCount - 1)
{
memmove(m_pArray + index, m_pArray + (index + 1), (oldCount - index - 1) * sizeof(T));
}
resize(oldCount - 1);
}
void push_back(const T& src)
{
const size_t newIndex = size();
resize(newIndex + 1);
m_pArray[newIndex] = src;
}
void pop_back()
{
VMA_HEAVY_ASSERT(m_Count > 0);
resize(size() - 1);
}
void push_front(const T& src)
{
insert(0, src);
}
void pop_front()
{
VMA_HEAVY_ASSERT(m_Count > 0);
remove(0);
}
typedef T* iterator;
iterator begin() { return m_pArray; }
iterator end() { return m_pArray + m_Count; }
private:
AllocatorT m_Allocator;
T* m_pArray;
size_t m_Count;
size_t m_Capacity;
};
template<typename T, typename allocatorT>
static void VmaVectorInsert(VmaVector<T, allocatorT>& vec, size_t index, const T& item)
{
vec.insert(index, item);
}
template<typename T, typename allocatorT>
static void VmaVectorRemove(VmaVector<T, allocatorT>& vec, size_t index)
{
vec.remove(index);
}
#endif // #if VMA_USE_STL_VECTOR
template<typename CmpLess, typename VectorT>
size_t VmaVectorInsertSorted(VectorT& vector, const typename VectorT::value_type& value)
{
const size_t indexToInsert = VmaBinaryFindFirstNotLess(
vector.data(),
vector.data() + vector.size(),
value,
CmpLess()) - vector.data();
VmaVectorInsert(vector, indexToInsert, value);
return indexToInsert;
}
template<typename CmpLess, typename VectorT>
bool VmaVectorRemoveSorted(VectorT& vector, const typename VectorT::value_type& value)
{
CmpLess comparator;
typename VectorT::iterator it = VmaBinaryFindFirstNotLess(
vector.begin(),
vector.end(),
value,
comparator);
if((it != vector.end()) && !comparator(*it, value) && !comparator(value, *it))
{
size_t indexToRemove = it - vector.begin();
VmaVectorRemove(vector, indexToRemove);
return true;
}
return false;
}
template<typename CmpLess, typename IterT, typename KeyT>
IterT VmaVectorFindSorted(const IterT& beg, const IterT& end, const KeyT& value)
{
CmpLess comparator;
IterT it = VmaBinaryFindFirstNotLess<CmpLess, IterT, KeyT>(
beg, end, value, comparator);
if(it == end ||
(!comparator(*it, value) && !comparator(value, *it)))
{
return it;
}
return end;
}
////////////////////////////////////////////////////////////////////////////////
// class VmaPoolAllocator
/*
Allocator for objects of type T using a list of arrays (pools) to speed up
allocation. Number of elements that can be allocated is not bounded because
allocator can create multiple blocks.
*/
template<typename T>
class VmaPoolAllocator
{
VMA_CLASS_NO_COPY(VmaPoolAllocator)
public:
VmaPoolAllocator(const VkAllocationCallbacks* pAllocationCallbacks, size_t itemsPerBlock);
~VmaPoolAllocator();
void Clear();
T* Alloc();
void Free(T* ptr);
private:
union Item
{
uint32_t NextFreeIndex;
T Value;
};
struct ItemBlock
{
Item* pItems;
uint32_t FirstFreeIndex;
};
const VkAllocationCallbacks* m_pAllocationCallbacks;
size_t m_ItemsPerBlock;
VmaVector< ItemBlock, VmaStlAllocator<ItemBlock> > m_ItemBlocks;
ItemBlock& CreateNewBlock();
};
template<typename T>
VmaPoolAllocator<T>::VmaPoolAllocator(const VkAllocationCallbacks* pAllocationCallbacks, size_t itemsPerBlock) :
m_pAllocationCallbacks(pAllocationCallbacks),
m_ItemsPerBlock(itemsPerBlock),
m_ItemBlocks(VmaStlAllocator<ItemBlock>(pAllocationCallbacks))
{
VMA_ASSERT(itemsPerBlock > 0);
}
template<typename T>
VmaPoolAllocator<T>::~VmaPoolAllocator()
{
Clear();
}
template<typename T>
void VmaPoolAllocator<T>::Clear()
{
for(size_t i = m_ItemBlocks.size(); i--; )
vma_delete_array(m_pAllocationCallbacks, m_ItemBlocks[i].pItems, m_ItemsPerBlock);
m_ItemBlocks.clear();
}
template<typename T>
T* VmaPoolAllocator<T>::Alloc()
{
for(size_t i = m_ItemBlocks.size(); i--; )
{
ItemBlock& block = m_ItemBlocks[i];
// This block has some free items: Use first one.
if(block.FirstFreeIndex != UINT32_MAX)
{
Item* const pItem = &block.pItems[block.FirstFreeIndex];
block.FirstFreeIndex = pItem->NextFreeIndex;
return &pItem->Value;
}
}
// No block has free item: Create new one and use it.
ItemBlock& newBlock = CreateNewBlock();
Item* const pItem = &newBlock.pItems[0];
newBlock.FirstFreeIndex = pItem->NextFreeIndex;
return &pItem->Value;
}
template<typename T>
void VmaPoolAllocator<T>::Free(T* ptr)
{
// Search all memory blocks to find ptr.
for(size_t i = 0; i < m_ItemBlocks.size(); ++i)
{
ItemBlock& block = m_ItemBlocks[i];
// Casting to union.
Item* pItemPtr;
memcpy(&pItemPtr, &ptr, sizeof(pItemPtr));
// Check if pItemPtr is in address range of this block.
if((pItemPtr >= block.pItems) && (pItemPtr < block.pItems + m_ItemsPerBlock))
{
const uint32_t index = static_cast<uint32_t>(pItemPtr - block.pItems);
pItemPtr->NextFreeIndex = block.FirstFreeIndex;
block.FirstFreeIndex = index;
return;
}
}
VMA_ASSERT(0 && "Pointer doesn't belong to this memory pool.");
}
template<typename T>
typename VmaPoolAllocator<T>::ItemBlock& VmaPoolAllocator<T>::CreateNewBlock()
{
ItemBlock newBlock = {
vma_new_array(m_pAllocationCallbacks, Item, m_ItemsPerBlock), 0 };
m_ItemBlocks.push_back(newBlock);
// Setup singly-linked list of all free items in this block.
for(uint32_t i = 0; i < m_ItemsPerBlock - 1; ++i)
newBlock.pItems[i].NextFreeIndex = i + 1;
newBlock.pItems[m_ItemsPerBlock - 1].NextFreeIndex = UINT32_MAX;
return m_ItemBlocks.back();
}
////////////////////////////////////////////////////////////////////////////////
// class VmaRawList, VmaList
#if VMA_USE_STL_LIST
#define VmaList std::list
#else // #if VMA_USE_STL_LIST
template<typename T>
struct VmaListItem
{
VmaListItem* pPrev;
VmaListItem* pNext;
T Value;
};
// Doubly linked list.
template<typename T>
class VmaRawList
{
VMA_CLASS_NO_COPY(VmaRawList)
public:
typedef VmaListItem<T> ItemType;
VmaRawList(const VkAllocationCallbacks* pAllocationCallbacks);
~VmaRawList();
void Clear();
size_t GetCount() const { return m_Count; }
bool IsEmpty() const { return m_Count == 0; }
ItemType* Front() { return m_pFront; }
const ItemType* Front() const { return m_pFront; }
ItemType* Back() { return m_pBack; }
const ItemType* Back() const { return m_pBack; }
ItemType* PushBack();
ItemType* PushFront();
ItemType* PushBack(const T& value);
ItemType* PushFront(const T& value);
void PopBack();
void PopFront();
// Item can be null - it means PushBack.
ItemType* InsertBefore(ItemType* pItem);
// Item can be null - it means PushFront.
ItemType* InsertAfter(ItemType* pItem);
ItemType* InsertBefore(ItemType* pItem, const T& value);
ItemType* InsertAfter(ItemType* pItem, const T& value);
void Remove(ItemType* pItem);
private:
const VkAllocationCallbacks* const m_pAllocationCallbacks;
VmaPoolAllocator<ItemType> m_ItemAllocator;
ItemType* m_pFront;
ItemType* m_pBack;
size_t m_Count;
};
template<typename T>
VmaRawList<T>::VmaRawList(const VkAllocationCallbacks* pAllocationCallbacks) :
m_pAllocationCallbacks(pAllocationCallbacks),
m_ItemAllocator(pAllocationCallbacks, 128),
m_pFront(VMA_NULL),
m_pBack(VMA_NULL),
m_Count(0)
{
}
template<typename T>
VmaRawList<T>::~VmaRawList()
{
// Intentionally not calling Clear, because that would be unnecessary
// computations to return all items to m_ItemAllocator as free.
}
template<typename T>
void VmaRawList<T>::Clear()
{
if(IsEmpty() == false)
{
ItemType* pItem = m_pBack;
while(pItem != VMA_NULL)
{
ItemType* const pPrevItem = pItem->pPrev;
m_ItemAllocator.Free(pItem);
pItem = pPrevItem;
}
m_pFront = VMA_NULL;
m_pBack = VMA_NULL;
m_Count = 0;
}
}
template<typename T>
VmaListItem<T>* VmaRawList<T>::PushBack()
{
ItemType* const pNewItem = m_ItemAllocator.Alloc();
pNewItem->pNext = VMA_NULL;
if(IsEmpty())
{
pNewItem->pPrev = VMA_NULL;
m_pFront = pNewItem;
m_pBack = pNewItem;
m_Count = 1;
}
else
{
pNewItem->pPrev = m_pBack;
m_pBack->pNext = pNewItem;
m_pBack = pNewItem;
++m_Count;
}
return pNewItem;
}
template<typename T>
VmaListItem<T>* VmaRawList<T>::PushFront()
{
ItemType* const pNewItem = m_ItemAllocator.Alloc();
pNewItem->pPrev = VMA_NULL;
if(IsEmpty())
{
pNewItem->pNext = VMA_NULL;
m_pFront = pNewItem;
m_pBack = pNewItem;
m_Count = 1;
}
else
{
pNewItem->pNext = m_pFront;
m_pFront->pPrev = pNewItem;
m_pFront = pNewItem;
++m_Count;
}
return pNewItem;
}
template<typename T>
VmaListItem<T>* VmaRawList<T>::PushBack(const T& value)
{
ItemType* const pNewItem = PushBack();
pNewItem->Value = value;
return pNewItem;
}
template<typename T>
VmaListItem<T>* VmaRawList<T>::PushFront(const T& value)
{
ItemType* const pNewItem = PushFront();
pNewItem->Value = value;
return pNewItem;
}
template<typename T>
void VmaRawList<T>::PopBack()
{
VMA_HEAVY_ASSERT(m_Count > 0);
ItemType* const pBackItem = m_pBack;
ItemType* const pPrevItem = pBackItem->pPrev;
if(pPrevItem != VMA_NULL)
{
pPrevItem->pNext = VMA_NULL;
}
m_pBack = pPrevItem;
m_ItemAllocator.Free(pBackItem);
--m_Count;
}
template<typename T>
void VmaRawList<T>::PopFront()
{
VMA_HEAVY_ASSERT(m_Count > 0);
ItemType* const pFrontItem = m_pFront;
ItemType* const pNextItem = pFrontItem->pNext;
if(pNextItem != VMA_NULL)
{
pNextItem->pPrev = VMA_NULL;
}
m_pFront = pNextItem;
m_ItemAllocator.Free(pFrontItem);
--m_Count;
}
template<typename T>
void VmaRawList<T>::Remove(ItemType* pItem)
{
VMA_HEAVY_ASSERT(pItem != VMA_NULL);
VMA_HEAVY_ASSERT(m_Count > 0);
if(pItem->pPrev != VMA_NULL)
{
pItem->pPrev->pNext = pItem->pNext;
}
else
{
VMA_HEAVY_ASSERT(m_pFront == pItem);
m_pFront = pItem->pNext;
}
if(pItem->pNext != VMA_NULL)
{
pItem->pNext->pPrev = pItem->pPrev;
}
else
{
VMA_HEAVY_ASSERT(m_pBack == pItem);
m_pBack = pItem->pPrev;
}
m_ItemAllocator.Free(pItem);
--m_Count;
}
template<typename T>
VmaListItem<T>* VmaRawList<T>::InsertBefore(ItemType* pItem)
{
if(pItem != VMA_NULL)
{
ItemType* const prevItem = pItem->pPrev;
ItemType* const newItem = m_ItemAllocator.Alloc();
newItem->pPrev = prevItem;
newItem->pNext = pItem;
pItem->pPrev = newItem;
if(prevItem != VMA_NULL)
{
prevItem->pNext = newItem;
}
else
{
VMA_HEAVY_ASSERT(m_pFront == pItem);
m_pFront = newItem;
}
++m_Count;
return newItem;
}
else
return PushBack();
}
template<typename T>
VmaListItem<T>* VmaRawList<T>::InsertAfter(ItemType* pItem)
{
if(pItem != VMA_NULL)
{
ItemType* const nextItem = pItem->pNext;
ItemType* const newItem = m_ItemAllocator.Alloc();
newItem->pNext = nextItem;
newItem->pPrev = pItem;
pItem->pNext = newItem;
if(nextItem != VMA_NULL)
{
nextItem->pPrev = newItem;
}
else
{
VMA_HEAVY_ASSERT(m_pBack == pItem);
m_pBack = newItem;
}
++m_Count;
return newItem;
}
else
return PushFront();
}
template<typename T>
VmaListItem<T>* VmaRawList<T>::InsertBefore(ItemType* pItem, const T& value)
{
ItemType* const newItem = InsertBefore(pItem);
newItem->Value = value;
return newItem;
}
template<typename T>
VmaListItem<T>* VmaRawList<T>::InsertAfter(ItemType* pItem, const T& value)
{
ItemType* const newItem = InsertAfter(pItem);
newItem->Value = value;
return newItem;
}
template<typename T, typename AllocatorT>
class VmaList
{
VMA_CLASS_NO_COPY(VmaList)
public:
class iterator
{
public:
iterator() :
m_pList(VMA_NULL),
m_pItem(VMA_NULL)
{
}
T& operator*() const
{
VMA_HEAVY_ASSERT(m_pItem != VMA_NULL);
return m_pItem->Value;
}
T* operator->() const
{
VMA_HEAVY_ASSERT(m_pItem != VMA_NULL);
return &m_pItem->Value;
}
iterator& operator++()
{
VMA_HEAVY_ASSERT(m_pItem != VMA_NULL);
m_pItem = m_pItem->pNext;
return *this;
}
iterator& operator--()
{
if(m_pItem != VMA_NULL)
{
m_pItem = m_pItem->pPrev;
}
else
{
VMA_HEAVY_ASSERT(!m_pList->IsEmpty());
m_pItem = m_pList->Back();
}
return *this;
}
iterator operator++(int)
{
iterator result = *this;
++*this;
return result;
}
iterator operator--(int)
{
iterator result = *this;
--*this;
return result;
}
bool operator==(const iterator& rhs) const
{
VMA_HEAVY_ASSERT(m_pList == rhs.m_pList);
return m_pItem == rhs.m_pItem;
}
bool operator!=(const iterator& rhs) const
{
VMA_HEAVY_ASSERT(m_pList == rhs.m_pList);
return m_pItem != rhs.m_pItem;
}
private:
VmaRawList<T>* m_pList;
VmaListItem<T>* m_pItem;
iterator(VmaRawList<T>* pList, VmaListItem<T>* pItem) :
m_pList(pList),
m_pItem(pItem)
{
}
friend class VmaList<T, AllocatorT>;
};
class const_iterator
{
public:
const_iterator() :
m_pList(VMA_NULL),
m_pItem(VMA_NULL)
{
}
const_iterator(const iterator& src) :
m_pList(src.m_pList),
m_pItem(src.m_pItem)
{
}
const T& operator*() const
{
VMA_HEAVY_ASSERT(m_pItem != VMA_NULL);
return m_pItem->Value;
}
const T* operator->() const
{
VMA_HEAVY_ASSERT(m_pItem != VMA_NULL);
return &m_pItem->Value;
}
const_iterator& operator++()
{
VMA_HEAVY_ASSERT(m_pItem != VMA_NULL);
m_pItem = m_pItem->pNext;
return *this;
}
const_iterator& operator--()
{
if(m_pItem != VMA_NULL)
{
m_pItem = m_pItem->pPrev;
}
else
{
VMA_HEAVY_ASSERT(!m_pList->IsEmpty());
m_pItem = m_pList->Back();
}
return *this;
}
const_iterator operator++(int)
{
const_iterator result = *this;
++*this;
return result;
}
const_iterator operator--(int)
{
const_iterator result = *this;
--*this;
return result;
}
bool operator==(const const_iterator& rhs) const
{
VMA_HEAVY_ASSERT(m_pList == rhs.m_pList);
return m_pItem == rhs.m_pItem;
}
bool operator!=(const const_iterator& rhs) const
{
VMA_HEAVY_ASSERT(m_pList == rhs.m_pList);
return m_pItem != rhs.m_pItem;
}
private:
const_iterator(const VmaRawList<T>* pList, const VmaListItem<T>* pItem) :
m_pList(pList),
m_pItem(pItem)
{
}
const VmaRawList<T>* m_pList;
const VmaListItem<T>* m_pItem;
friend class VmaList<T, AllocatorT>;
};
VmaList(const AllocatorT& allocator) : m_RawList(allocator.m_pCallbacks) { }
bool empty() const { return m_RawList.IsEmpty(); }
size_t size() const { return m_RawList.GetCount(); }
iterator begin() { return iterator(&m_RawList, m_RawList.Front()); }
iterator end() { return iterator(&m_RawList, VMA_NULL); }
const_iterator cbegin() const { return const_iterator(&m_RawList, m_RawList.Front()); }
const_iterator cend() const { return const_iterator(&m_RawList, VMA_NULL); }
void clear() { m_RawList.Clear(); }
void push_back(const T& value) { m_RawList.PushBack(value); }
void erase(iterator it) { m_RawList.Remove(it.m_pItem); }
iterator insert(iterator it, const T& value) { return iterator(&m_RawList, m_RawList.InsertBefore(it.m_pItem, value)); }
private:
VmaRawList<T> m_RawList;
};
#endif // #if VMA_USE_STL_LIST
////////////////////////////////////////////////////////////////////////////////
// class VmaMap
// Unused in this version.
#if 0
#if VMA_USE_STL_UNORDERED_MAP
#define VmaPair std::pair
#define VMA_MAP_TYPE(KeyT, ValueT) \
std::unordered_map< KeyT, ValueT, std::hash<KeyT>, std::equal_to<KeyT>, VmaStlAllocator< std::pair<KeyT, ValueT> > >
#else // #if VMA_USE_STL_UNORDERED_MAP
template<typename T1, typename T2>
struct VmaPair
{
T1 first;
T2 second;
VmaPair() : first(), second() { }
VmaPair(const T1& firstSrc, const T2& secondSrc) : first(firstSrc), second(secondSrc) { }
};
/* Class compatible with subset of interface of std::unordered_map.
KeyT, ValueT must be POD because they will be stored in VmaVector.
*/
template<typename KeyT, typename ValueT>
class VmaMap
{
public:
typedef VmaPair<KeyT, ValueT> PairType;
typedef PairType* iterator;
VmaMap(const VmaStlAllocator<PairType>& allocator) : m_Vector(allocator) { }
iterator begin() { return m_Vector.begin(); }
iterator end() { return m_Vector.end(); }
void insert(const PairType& pair);
iterator find(const KeyT& key);
void erase(iterator it);
private:
VmaVector< PairType, VmaStlAllocator<PairType> > m_Vector;
};
#define VMA_MAP_TYPE(KeyT, ValueT) VmaMap<KeyT, ValueT>
template<typename FirstT, typename SecondT>
struct VmaPairFirstLess
{
bool operator()(const VmaPair<FirstT, SecondT>& lhs, const VmaPair<FirstT, SecondT>& rhs) const
{
return lhs.first < rhs.first;
}
bool operator()(const VmaPair<FirstT, SecondT>& lhs, const FirstT& rhsFirst) const
{
return lhs.first < rhsFirst;
}
};
template<typename KeyT, typename ValueT>
void VmaMap<KeyT, ValueT>::insert(const PairType& pair)
{
const size_t indexToInsert = VmaBinaryFindFirstNotLess(
m_Vector.data(),
m_Vector.data() + m_Vector.size(),
pair,
VmaPairFirstLess<KeyT, ValueT>()) - m_Vector.data();
VmaVectorInsert(m_Vector, indexToInsert, pair);
}
template<typename KeyT, typename ValueT>
VmaPair<KeyT, ValueT>* VmaMap<KeyT, ValueT>::find(const KeyT& key)
{
PairType* it = VmaBinaryFindFirstNotLess(
m_Vector.data(),
m_Vector.data() + m_Vector.size(),
key,
VmaPairFirstLess<KeyT, ValueT>());
if((it != m_Vector.end()) && (it->first == key))
{
return it;
}
else
{
return m_Vector.end();
}
}
template<typename KeyT, typename ValueT>
void VmaMap<KeyT, ValueT>::erase(iterator it)
{
VmaVectorRemove(m_Vector, it - m_Vector.begin());
}
#endif // #if VMA_USE_STL_UNORDERED_MAP
#endif // #if 0
////////////////////////////////////////////////////////////////////////////////
class VmaDeviceMemoryBlock;
enum VMA_CACHE_OPERATION { VMA_CACHE_FLUSH, VMA_CACHE_INVALIDATE };
struct VmaAllocation_T
{
VMA_CLASS_NO_COPY(VmaAllocation_T)
private:
static const uint8_t MAP_COUNT_FLAG_PERSISTENT_MAP = 0x80;
enum FLAGS
{
FLAG_USER_DATA_STRING = 0x01,
};
public:
enum ALLOCATION_TYPE
{
ALLOCATION_TYPE_NONE,
ALLOCATION_TYPE_BLOCK,
ALLOCATION_TYPE_DEDICATED,
};
VmaAllocation_T(uint32_t currentFrameIndex, bool userDataString) :
m_Alignment(1),
m_Size(0),
m_pUserData(VMA_NULL),
m_LastUseFrameIndex(currentFrameIndex),
m_Type((uint8_t)ALLOCATION_TYPE_NONE),
m_SuballocationType((uint8_t)VMA_SUBALLOCATION_TYPE_UNKNOWN),
m_MapCount(0),
m_Flags(userDataString ? (uint8_t)FLAG_USER_DATA_STRING : 0)
{
#if VMA_STATS_STRING_ENABLED
m_CreationFrameIndex = currentFrameIndex;
m_BufferImageUsage = 0;
#endif
}
~VmaAllocation_T()
{
VMA_ASSERT((m_MapCount & ~MAP_COUNT_FLAG_PERSISTENT_MAP) == 0 && "Allocation was not unmapped before destruction.");
// Check if owned string was freed.
VMA_ASSERT(m_pUserData == VMA_NULL);
}
void InitBlockAllocation(
VmaPool hPool,
VmaDeviceMemoryBlock* block,
VkDeviceSize offset,
VkDeviceSize alignment,
VkDeviceSize size,
VmaSuballocationType suballocationType,
bool mapped,
bool canBecomeLost)
{
VMA_ASSERT(m_Type == ALLOCATION_TYPE_NONE);
VMA_ASSERT(block != VMA_NULL);
m_Type = (uint8_t)ALLOCATION_TYPE_BLOCK;
m_Alignment = alignment;
m_Size = size;
m_MapCount = mapped ? MAP_COUNT_FLAG_PERSISTENT_MAP : 0;
m_SuballocationType = (uint8_t)suballocationType;
m_BlockAllocation.m_hPool = hPool;
m_BlockAllocation.m_Block = block;
m_BlockAllocation.m_Offset = offset;
m_BlockAllocation.m_CanBecomeLost = canBecomeLost;
}
void InitLost()
{
VMA_ASSERT(m_Type == ALLOCATION_TYPE_NONE);
VMA_ASSERT(m_LastUseFrameIndex.load() == VMA_FRAME_INDEX_LOST);
m_Type = (uint8_t)ALLOCATION_TYPE_BLOCK;
m_BlockAllocation.m_hPool = VK_NULL_HANDLE;
m_BlockAllocation.m_Block = VMA_NULL;
m_BlockAllocation.m_Offset = 0;
m_BlockAllocation.m_CanBecomeLost = true;
}
void ChangeBlockAllocation(
VmaAllocator hAllocator,
VmaDeviceMemoryBlock* block,
VkDeviceSize offset);
// pMappedData not null means allocation is created with MAPPED flag.
void InitDedicatedAllocation(
uint32_t memoryTypeIndex,
VkDeviceMemory hMemory,
VmaSuballocationType suballocationType,
void* pMappedData,
VkDeviceSize size)
{
VMA_ASSERT(m_Type == ALLOCATION_TYPE_NONE);
VMA_ASSERT(hMemory != VK_NULL_HANDLE);
m_Type = (uint8_t)ALLOCATION_TYPE_DEDICATED;
m_Alignment = 0;
m_Size = size;
m_SuballocationType = (uint8_t)suballocationType;
m_MapCount = (pMappedData != VMA_NULL) ? MAP_COUNT_FLAG_PERSISTENT_MAP : 0;
m_DedicatedAllocation.m_MemoryTypeIndex = memoryTypeIndex;
m_DedicatedAllocation.m_hMemory = hMemory;
m_DedicatedAllocation.m_pMappedData = pMappedData;
}
ALLOCATION_TYPE GetType() const { return (ALLOCATION_TYPE)m_Type; }
VkDeviceSize GetAlignment() const { return m_Alignment; }
VkDeviceSize GetSize() const { return m_Size; }
bool IsUserDataString() const { return (m_Flags & FLAG_USER_DATA_STRING) != 0; }
void* GetUserData() const { return m_pUserData; }
void SetUserData(VmaAllocator hAllocator, void* pUserData);
VmaSuballocationType GetSuballocationType() const { return (VmaSuballocationType)m_SuballocationType; }
VmaDeviceMemoryBlock* GetBlock() const
{
VMA_ASSERT(m_Type == ALLOCATION_TYPE_BLOCK);
return m_BlockAllocation.m_Block;
}
VkDeviceSize GetOffset() const;
VkDeviceMemory GetMemory() const;
uint32_t GetMemoryTypeIndex() const;
bool IsPersistentMap() const { return (m_MapCount & MAP_COUNT_FLAG_PERSISTENT_MAP) != 0; }
void* GetMappedData() const;
bool CanBecomeLost() const;
VmaPool GetPool() const;
uint32_t GetLastUseFrameIndex() const
{
return m_LastUseFrameIndex.load();
}
bool CompareExchangeLastUseFrameIndex(uint32_t& expected, uint32_t desired)
{
return m_LastUseFrameIndex.compare_exchange_weak(expected, desired);
}
/*
- If hAllocation.LastUseFrameIndex + frameInUseCount < allocator.CurrentFrameIndex,
makes it lost by setting LastUseFrameIndex = VMA_FRAME_INDEX_LOST and returns true.
- Else, returns false.
If hAllocation is already lost, assert - you should not call it then.
If hAllocation was not created with CAN_BECOME_LOST_BIT, assert.
*/
bool MakeLost(uint32_t currentFrameIndex, uint32_t frameInUseCount);
void DedicatedAllocCalcStatsInfo(VmaStatInfo& outInfo)
{
VMA_ASSERT(m_Type == ALLOCATION_TYPE_DEDICATED);
outInfo.blockCount = 1;
outInfo.allocationCount = 1;
outInfo.unusedRangeCount = 0;
outInfo.usedBytes = m_Size;
outInfo.unusedBytes = 0;
outInfo.allocationSizeMin = outInfo.allocationSizeMax = m_Size;
outInfo.unusedRangeSizeMin = UINT64_MAX;
outInfo.unusedRangeSizeMax = 0;
}
void BlockAllocMap();
void BlockAllocUnmap();
VkResult DedicatedAllocMap(VmaAllocator hAllocator, void** ppData);
void DedicatedAllocUnmap(VmaAllocator hAllocator);
#if VMA_STATS_STRING_ENABLED
uint32_t GetCreationFrameIndex() const { return m_CreationFrameIndex; }
uint32_t GetBufferImageUsage() const { return m_BufferImageUsage; }
void InitBufferImageUsage(uint32_t bufferImageUsage)
{
VMA_ASSERT(m_BufferImageUsage == 0);
m_BufferImageUsage = bufferImageUsage;
}
void PrintParameters(class VmaJsonWriter& json) const;
#endif
private:
VkDeviceSize m_Alignment;
VkDeviceSize m_Size;
void* m_pUserData;
VMA_ATOMIC_UINT32 m_LastUseFrameIndex;
uint8_t m_Type; // ALLOCATION_TYPE
uint8_t m_SuballocationType; // VmaSuballocationType
// Bit 0x80 is set when allocation was created with VMA_ALLOCATION_CREATE_MAPPED_BIT.
// Bits with mask 0x7F are reference counter for vmaMapMemory()/vmaUnmapMemory().
uint8_t m_MapCount;
uint8_t m_Flags; // enum FLAGS
// Allocation out of VmaDeviceMemoryBlock.
struct BlockAllocation
{
VmaPool m_hPool; // Null if belongs to general memory.
VmaDeviceMemoryBlock* m_Block;
VkDeviceSize m_Offset;
bool m_CanBecomeLost;
};
// Allocation for an object that has its own private VkDeviceMemory.
struct DedicatedAllocation
{
uint32_t m_MemoryTypeIndex;
VkDeviceMemory m_hMemory;
void* m_pMappedData; // Not null means memory is mapped.
};
union
{
// Allocation out of VmaDeviceMemoryBlock.
BlockAllocation m_BlockAllocation;
// Allocation for an object that has its own private VkDeviceMemory.
DedicatedAllocation m_DedicatedAllocation;
};
#if VMA_STATS_STRING_ENABLED
uint32_t m_CreationFrameIndex;
uint32_t m_BufferImageUsage; // 0 if unknown.
#endif
void FreeUserDataString(VmaAllocator hAllocator);
};
/*
Represents a region of VmaDeviceMemoryBlock that is either assigned and returned as
allocated memory block or free.
*/
struct VmaSuballocation
{
VkDeviceSize offset;
VkDeviceSize size;
VmaAllocation hAllocation;
VmaSuballocationType type;
};
// Comparator for offsets.
struct VmaSuballocationOffsetLess
{
bool operator()(const VmaSuballocation& lhs, const VmaSuballocation& rhs) const
{
return lhs.offset < rhs.offset;
}
};
struct VmaSuballocationOffsetGreater
{
bool operator()(const VmaSuballocation& lhs, const VmaSuballocation& rhs) const
{
return lhs.offset > rhs.offset;
}
};
typedef VmaList< VmaSuballocation, VmaStlAllocator<VmaSuballocation> > VmaSuballocationList;
// Cost of one additional allocation lost, as equivalent in bytes.
static const VkDeviceSize VMA_LOST_ALLOCATION_COST = 1048576;
/*
Parameters of planned allocation inside a VmaDeviceMemoryBlock.
If canMakeOtherLost was false:
- item points to a FREE suballocation.
- itemsToMakeLostCount is 0.
If canMakeOtherLost was true:
- item points to first of sequence of suballocations, which are either FREE,
or point to VmaAllocations that can become lost.
- itemsToMakeLostCount is the number of VmaAllocations that need to be made lost for
the requested allocation to succeed.
*/
struct VmaAllocationRequest
{
VkDeviceSize offset;
VkDeviceSize sumFreeSize; // Sum size of free items that overlap with proposed allocation.
VkDeviceSize sumItemSize; // Sum size of items to make lost that overlap with proposed allocation.
VmaSuballocationList::iterator item;
size_t itemsToMakeLostCount;
VkDeviceSize CalcCost() const
{
return sumItemSize + itemsToMakeLostCount * VMA_LOST_ALLOCATION_COST;
}
};
/*
Data structure used for bookkeeping of allocations and unused ranges of memory
in a single VkDeviceMemory block.
*/
class VmaBlockMetadata
{
public:
VmaBlockMetadata() : m_Size(0) { }
virtual ~VmaBlockMetadata() { }
virtual void Init(VkDeviceSize size) { m_Size = size; }
// Validates all data structures inside this object. If not valid, returns false.
virtual bool Validate() const = 0;
VkDeviceSize GetSize() const { return m_Size; }
virtual size_t GetAllocationCount() const = 0;
virtual VkDeviceSize GetSumFreeSize() const = 0;
virtual VkDeviceSize GetUnusedRangeSizeMax() const = 0;
// Returns true if this block is empty - contains only single free suballocation.
virtual bool IsEmpty() const = 0;
virtual void CalcAllocationStatInfo(VmaStatInfo& outInfo) const = 0;
// Shouldn't modify blockCount.
virtual void AddPoolStats(VmaPoolStats& inoutStats) const = 0;
#if VMA_STATS_STRING_ENABLED
virtual void PrintDetailedMap(class VmaJsonWriter& json) const = 0;
#endif
// Tries to find a place for suballocation with given parameters inside this block.
// If succeeded, fills pAllocationRequest and returns true.
// If failed, returns false.
virtual bool CreateAllocationRequest(
uint32_t currentFrameIndex,
uint32_t frameInUseCount,
VkDeviceSize bufferImageGranularity,
VkDeviceSize allocSize,
VkDeviceSize allocAlignment,
bool upperAddress,
VmaSuballocationType allocType,
bool canMakeOtherLost,
VmaAllocationRequest* pAllocationRequest) = 0;
virtual bool MakeRequestedAllocationsLost(
uint32_t currentFrameIndex,
uint32_t frameInUseCount,
VmaAllocationRequest* pAllocationRequest) = 0;
virtual uint32_t MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount) = 0;
virtual VkResult CheckCorruption(const void* pBlockData) = 0;
// Makes actual allocation based on request. Request must already be checked and valid.
virtual void Alloc(
const VmaAllocationRequest& request,
VmaSuballocationType type,
VkDeviceSize allocSize,
bool upperAddress,
VmaAllocation hAllocation) = 0;
// Frees suballocation assigned to given memory region.
virtual void Free(const VmaAllocation allocation) = 0;
virtual void FreeAtOffset(VkDeviceSize offset) = 0;
protected:
#if VMA_STATS_STRING_ENABLED
void PrintDetailedMap_Begin(class VmaJsonWriter& json,
VkDeviceSize unusedBytes,
size_t allocationCount,
size_t unusedRangeCount) const;
void PrintDetailedMap_Allocation(class VmaJsonWriter& json,
VkDeviceSize offset,
VmaAllocation hAllocation) const;
void PrintDetailedMap_UnusedRange(class VmaJsonWriter& json,
VkDeviceSize offset,
VkDeviceSize size) const;
void PrintDetailedMap_End(class VmaJsonWriter& json) const;
#endif
private:
VkDeviceSize m_Size;
};
class VmaBlockMetadata_Generic : public VmaBlockMetadata
{
VMA_CLASS_NO_COPY(VmaBlockMetadata_Generic)
public:
VmaBlockMetadata_Generic(VmaAllocator hAllocator);
virtual ~VmaBlockMetadata_Generic();
virtual void Init(VkDeviceSize size);
virtual bool Validate() const;
virtual size_t GetAllocationCount() const { return m_Suballocations.size() - m_FreeCount; }
virtual VkDeviceSize GetSumFreeSize() const { return m_SumFreeSize; }
virtual VkDeviceSize GetUnusedRangeSizeMax() const;
virtual bool IsEmpty() const;
virtual void CalcAllocationStatInfo(VmaStatInfo& outInfo) const;
virtual void AddPoolStats(VmaPoolStats& inoutStats) const;
#if VMA_STATS_STRING_ENABLED
virtual void PrintDetailedMap(class VmaJsonWriter& json) const;
#endif
virtual bool CreateAllocationRequest(
uint32_t currentFrameIndex,
uint32_t frameInUseCount,
VkDeviceSize bufferImageGranularity,
VkDeviceSize allocSize,
VkDeviceSize allocAlignment,
bool upperAddress,
VmaSuballocationType allocType,
bool canMakeOtherLost,
VmaAllocationRequest* pAllocationRequest);
virtual bool MakeRequestedAllocationsLost(
uint32_t currentFrameIndex,
uint32_t frameInUseCount,
VmaAllocationRequest* pAllocationRequest);
virtual uint32_t MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount);
virtual VkResult CheckCorruption(const void* pBlockData);
virtual void Alloc(
const VmaAllocationRequest& request,
VmaSuballocationType type,
VkDeviceSize allocSize,
bool upperAddress,
VmaAllocation hAllocation);
virtual void Free(const VmaAllocation allocation);
virtual void FreeAtOffset(VkDeviceSize offset);
private:
uint32_t m_FreeCount;
VkDeviceSize m_SumFreeSize;
VmaSuballocationList m_Suballocations;
// Suballocations that are free and have size greater than certain threshold.
// Sorted by size, ascending.
VmaVector< VmaSuballocationList::iterator, VmaStlAllocator< VmaSuballocationList::iterator > > m_FreeSuballocationsBySize;
bool ValidateFreeSuballocationList() const;
// Checks if requested suballocation with given parameters can be placed in given pFreeSuballocItem.
// If yes, fills pOffset and returns true. If no, returns false.
bool CheckAllocation(
uint32_t currentFrameIndex,
uint32_t frameInUseCount,
VkDeviceSize bufferImageGranularity,
VkDeviceSize allocSize,
VkDeviceSize allocAlignment,
VmaSuballocationType allocType,
VmaSuballocationList::const_iterator suballocItem,
bool canMakeOtherLost,
VkDeviceSize* pOffset,
size_t* itemsToMakeLostCount,
VkDeviceSize* pSumFreeSize,
VkDeviceSize* pSumItemSize) const;
// Given free suballocation, it merges it with following one, which must also be free.
void MergeFreeWithNext(VmaSuballocationList::iterator item);
// Releases given suballocation, making it free.
// Merges it with adjacent free suballocations if applicable.
// Returns iterator to new free suballocation at this place.
VmaSuballocationList::iterator FreeSuballocation(VmaSuballocationList::iterator suballocItem);
// Given free suballocation, it inserts it into sorted list of
// m_FreeSuballocationsBySize if it's suitable.
void RegisterFreeSuballocation(VmaSuballocationList::iterator item);
// Given free suballocation, it removes it from sorted list of
// m_FreeSuballocationsBySize if it's suitable.
void UnregisterFreeSuballocation(VmaSuballocationList::iterator item);
};
/*
Allocations and their references in internal data structure look like this:
if(m_2ndVectorMode == SECOND_VECTOR_EMPTY):
0 +-------+
| |
| |
| |
+-------+
| Alloc | 1st[m_1stNullItemsBeginCount]
+-------+
| Alloc | 1st[m_1stNullItemsBeginCount + 1]
+-------+
| ... |
+-------+
| Alloc | 1st[1st.size() - 1]
+-------+
| |
| |
| |
GetSize() +-------+
if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER):
0 +-------+
| Alloc | 2nd[0]
+-------+
| Alloc | 2nd[1]
+-------+
| ... |
+-------+
| Alloc | 2nd[2nd.size() - 1]
+-------+
| |
| |
| |
+-------+
| Alloc | 1st[m_1stNullItemsBeginCount]
+-------+
| Alloc | 1st[m_1stNullItemsBeginCount + 1]
+-------+
| ... |
+-------+
| Alloc | 1st[1st.size() - 1]
+-------+
| |
GetSize() +-------+
if(m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK):
0 +-------+
| |
| |
| |
+-------+
| Alloc | 1st[m_1stNullItemsBeginCount]
+-------+
| Alloc | 1st[m_1stNullItemsBeginCount + 1]
+-------+
| ... |
+-------+
| Alloc | 1st[1st.size() - 1]
+-------+
| |
| |
| |
+-------+
| Alloc | 2nd[2nd.size() - 1]
+-------+
| ... |
+-------+
| Alloc | 2nd[1]
+-------+
| Alloc | 2nd[0]
GetSize() +-------+
*/
class VmaBlockMetadata_Linear : public VmaBlockMetadata
{
VMA_CLASS_NO_COPY(VmaBlockMetadata_Linear)
public:
VmaBlockMetadata_Linear(VmaAllocator hAllocator);
virtual ~VmaBlockMetadata_Linear();
virtual void Init(VkDeviceSize size);
virtual bool Validate() const;
virtual size_t GetAllocationCount() const;
virtual VkDeviceSize GetSumFreeSize() const { return m_SumFreeSize; }
virtual VkDeviceSize GetUnusedRangeSizeMax() const;
virtual bool IsEmpty() const { return GetAllocationCount() == 0; }
virtual void CalcAllocationStatInfo(VmaStatInfo& outInfo) const;
virtual void AddPoolStats(VmaPoolStats& inoutStats) const;
#if VMA_STATS_STRING_ENABLED
virtual void PrintDetailedMap(class VmaJsonWriter& json) const;
#endif
virtual bool CreateAllocationRequest(
uint32_t currentFrameIndex,
uint32_t frameInUseCount,
VkDeviceSize bufferImageGranularity,
VkDeviceSize allocSize,
VkDeviceSize allocAlignment,
bool upperAddress,
VmaSuballocationType allocType,
bool canMakeOtherLost,
VmaAllocationRequest* pAllocationRequest);
virtual bool MakeRequestedAllocationsLost(
uint32_t currentFrameIndex,
uint32_t frameInUseCount,
VmaAllocationRequest* pAllocationRequest);
virtual uint32_t MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount);
virtual VkResult CheckCorruption(const void* pBlockData);
virtual void Alloc(
const VmaAllocationRequest& request,
VmaSuballocationType type,
VkDeviceSize allocSize,
bool upperAddress,
VmaAllocation hAllocation);
virtual void Free(const VmaAllocation allocation);
virtual void FreeAtOffset(VkDeviceSize offset);
private:
/*
There are two suballocation vectors, used in ping-pong way.
The one with index m_1stVectorIndex is called 1st.
The one with index (m_1stVectorIndex ^ 1) is called 2nd.
2nd can be non-empty only when 1st is not empty.
When 2nd is not empty, m_2ndVectorMode indicates its mode of operation.
*/
typedef VmaVector< VmaSuballocation, VmaStlAllocator<VmaSuballocation> > SuballocationVectorType;
enum SECOND_VECTOR_MODE
{
SECOND_VECTOR_EMPTY,
/*
Suballocations in 2nd vector are created later than the ones in 1st, but they
all have smaller offset.
*/
SECOND_VECTOR_RING_BUFFER,
/*
Suballocations in 2nd vector are upper side of double stack.
They all have offsets higher than those in 1st vector.
Top of this stack means smaller offsets, but higher indices in this vector.
*/
SECOND_VECTOR_DOUBLE_STACK,
};
VkDeviceSize m_SumFreeSize;
SuballocationVectorType m_Suballocations0, m_Suballocations1;
uint32_t m_1stVectorIndex;
SECOND_VECTOR_MODE m_2ndVectorMode;
SuballocationVectorType& AccessSuballocations1st() { return m_1stVectorIndex ? m_Suballocations1 : m_Suballocations0; }
SuballocationVectorType& AccessSuballocations2nd() { return m_1stVectorIndex ? m_Suballocations0 : m_Suballocations1; }
const SuballocationVectorType& AccessSuballocations1st() const { return m_1stVectorIndex ? m_Suballocations1 : m_Suballocations0; }
const SuballocationVectorType& AccessSuballocations2nd() const { return m_1stVectorIndex ? m_Suballocations0 : m_Suballocations1; }
// Number of items in 1st vector with hAllocation = null at the beginning.
size_t m_1stNullItemsBeginCount;
// Number of other items in 1st vector with hAllocation = null somewhere in the middle.
size_t m_1stNullItemsMiddleCount;
// Number of items in 2nd vector with hAllocation = null.
size_t m_2ndNullItemsCount;
bool ShouldCompact1st() const;
void CleanupAfterFree();
};
/*
Represents a single block of device memory (`VkDeviceMemory`) with all the
data about its regions (aka suballocations, #VmaAllocation), assigned and free.
Thread-safety: This class must be externally synchronized.
*/
class VmaDeviceMemoryBlock
{
VMA_CLASS_NO_COPY(VmaDeviceMemoryBlock)
public:
VmaBlockMetadata* m_pMetadata;
VmaDeviceMemoryBlock(VmaAllocator hAllocator);
~VmaDeviceMemoryBlock()
{
VMA_ASSERT(m_MapCount == 0 && "VkDeviceMemory block is being destroyed while it is still mapped.");
VMA_ASSERT(m_hMemory == VK_NULL_HANDLE);
}
// Always call after construction.
void Init(
VmaAllocator hAllocator,
uint32_t newMemoryTypeIndex,
VkDeviceMemory newMemory,
VkDeviceSize newSize,
uint32_t id,
bool linearAlgorithm);
// Always call before destruction.
void Destroy(VmaAllocator allocator);
VkDeviceMemory GetDeviceMemory() const { return m_hMemory; }
uint32_t GetMemoryTypeIndex() const { return m_MemoryTypeIndex; }
uint32_t GetId() const { return m_Id; }
void* GetMappedData() const { return m_pMappedData; }
// Validates all data structures inside this object. If not valid, returns false.
bool Validate() const;
VkResult CheckCorruption(VmaAllocator hAllocator);
// ppData can be null.
VkResult Map(VmaAllocator hAllocator, uint32_t count, void** ppData);
void Unmap(VmaAllocator hAllocator, uint32_t count);
VkResult WriteMagicValueAroundAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize);
VkResult ValidateMagicValueAroundAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize);
VkResult BindBufferMemory(
const VmaAllocator hAllocator,
const VmaAllocation hAllocation,
VkBuffer hBuffer);
VkResult BindImageMemory(
const VmaAllocator hAllocator,
const VmaAllocation hAllocation,
VkImage hImage);
private:
uint32_t m_MemoryTypeIndex;
uint32_t m_Id;
VkDeviceMemory m_hMemory;
// Protects access to m_hMemory so it's not used by multiple threads simultaneously, e.g. vkMapMemory, vkBindBufferMemory.
// Also protects m_MapCount, m_pMappedData.
VMA_MUTEX m_Mutex;
uint32_t m_MapCount;
void* m_pMappedData;
};
struct VmaPointerLess
{
bool operator()(const void* lhs, const void* rhs) const
{
return lhs < rhs;
}
};
class VmaDefragmentator;
/*
Sequence of VmaDeviceMemoryBlock. Represents memory blocks allocated for a specific
Vulkan memory type.
Synchronized internally with a mutex.
*/
struct VmaBlockVector
{
VMA_CLASS_NO_COPY(VmaBlockVector)
public:
VmaBlockVector(
VmaAllocator hAllocator,
uint32_t memoryTypeIndex,
VkDeviceSize preferredBlockSize,
size_t minBlockCount,
size_t maxBlockCount,
VkDeviceSize bufferImageGranularity,
uint32_t frameInUseCount,
bool isCustomPool,
bool explicitBlockSize,
bool linearAlgorithm);
~VmaBlockVector();
VkResult CreateMinBlocks();
uint32_t GetMemoryTypeIndex() const { return m_MemoryTypeIndex; }
VkDeviceSize GetPreferredBlockSize() const { return m_PreferredBlockSize; }
VkDeviceSize GetBufferImageGranularity() const { return m_BufferImageGranularity; }
uint32_t GetFrameInUseCount() const { return m_FrameInUseCount; }
bool UsesLinearAlgorithm() const { return m_LinearAlgorithm; }
void GetPoolStats(VmaPoolStats* pStats);
bool IsEmpty() const { return m_Blocks.empty(); }
bool IsCorruptionDetectionEnabled() const;
VkResult Allocate(
VmaPool hCurrentPool,
uint32_t currentFrameIndex,
VkDeviceSize size,
VkDeviceSize alignment,
const VmaAllocationCreateInfo& createInfo,
VmaSuballocationType suballocType,
VmaAllocation* pAllocation);
void Free(
VmaAllocation hAllocation);
// Adds statistics of this BlockVector to pStats.
void AddStats(VmaStats* pStats);
#if VMA_STATS_STRING_ENABLED
void PrintDetailedMap(class VmaJsonWriter& json);
#endif
void MakePoolAllocationsLost(
uint32_t currentFrameIndex,
size_t* pLostAllocationCount);
VkResult CheckCorruption();
VmaDefragmentator* EnsureDefragmentator(
VmaAllocator hAllocator,
uint32_t currentFrameIndex);
VkResult Defragment(
VmaDefragmentationStats* pDefragmentationStats,
VkDeviceSize& maxBytesToMove,
uint32_t& maxAllocationsToMove);
void DestroyDefragmentator();
private:
friend class VmaDefragmentator;
const VmaAllocator m_hAllocator;
const uint32_t m_MemoryTypeIndex;
const VkDeviceSize m_PreferredBlockSize;
const size_t m_MinBlockCount;
const size_t m_MaxBlockCount;
const VkDeviceSize m_BufferImageGranularity;
const uint32_t m_FrameInUseCount;
const bool m_IsCustomPool;
const bool m_ExplicitBlockSize;
const bool m_LinearAlgorithm;
bool m_HasEmptyBlock;
VMA_MUTEX m_Mutex;
// Incrementally sorted by sumFreeSize, ascending.
VmaVector< VmaDeviceMemoryBlock*, VmaStlAllocator<VmaDeviceMemoryBlock*> > m_Blocks;
/* There can be at most one allocation that is completely empty - a
hysteresis to avoid pessimistic case of alternating creation and destruction
of a VkDeviceMemory. */
VmaDefragmentator* m_pDefragmentator;
uint32_t m_NextBlockId;
VkDeviceSize CalcMaxBlockSize() const;
// Finds and removes given block from vector.
void Remove(VmaDeviceMemoryBlock* pBlock);
// Performs single step in sorting m_Blocks. They may not be fully sorted
// after this call.
void IncrementallySortBlocks();
// To be used only without CAN_MAKE_OTHER_LOST flag.
VkResult AllocateFromBlock(
VmaDeviceMemoryBlock* pBlock,
VmaPool hCurrentPool,
uint32_t currentFrameIndex,
VkDeviceSize size,
VkDeviceSize alignment,
VmaAllocationCreateFlags allocFlags,
void* pUserData,
VmaSuballocationType suballocType,
VmaAllocation* pAllocation);
VkResult CreateBlock(VkDeviceSize blockSize, size_t* pNewBlockIndex);
};
struct VmaPool_T
{
VMA_CLASS_NO_COPY(VmaPool_T)
public:
VmaBlockVector m_BlockVector;
VmaPool_T(
VmaAllocator hAllocator,
const VmaPoolCreateInfo& createInfo,
VkDeviceSize preferredBlockSize);
~VmaPool_T();
uint32_t GetId() const { return m_Id; }
void SetId(uint32_t id) { VMA_ASSERT(m_Id == 0); m_Id = id; }
#if VMA_STATS_STRING_ENABLED
//void PrintDetailedMap(class VmaStringBuilder& sb);
#endif
private:
uint32_t m_Id;
};
class VmaDefragmentator
{
VMA_CLASS_NO_COPY(VmaDefragmentator)
private:
const VmaAllocator m_hAllocator;
VmaBlockVector* const m_pBlockVector;
uint32_t m_CurrentFrameIndex;
VkDeviceSize m_BytesMoved;
uint32_t m_AllocationsMoved;
struct AllocationInfo
{
VmaAllocation m_hAllocation;
VkBool32* m_pChanged;
AllocationInfo() :
m_hAllocation(VK_NULL_HANDLE),
m_pChanged(VMA_NULL)
{
}
};
struct AllocationInfoSizeGreater
{
bool operator()(const AllocationInfo& lhs, const AllocationInfo& rhs) const
{
return lhs.m_hAllocation->GetSize() > rhs.m_hAllocation->GetSize();
}
};
// Used between AddAllocation and Defragment.
VmaVector< AllocationInfo, VmaStlAllocator<AllocationInfo> > m_Allocations;
struct BlockInfo
{
VmaDeviceMemoryBlock* m_pBlock;
bool m_HasNonMovableAllocations;
VmaVector< AllocationInfo, VmaStlAllocator<AllocationInfo> > m_Allocations;
BlockInfo(const VkAllocationCallbacks* pAllocationCallbacks) :
m_pBlock(VMA_NULL),
m_HasNonMovableAllocations(true),
m_Allocations(pAllocationCallbacks),
m_pMappedDataForDefragmentation(VMA_NULL)
{
}
void CalcHasNonMovableAllocations()
{
const size_t blockAllocCount = m_pBlock->m_pMetadata->GetAllocationCount();
const size_t defragmentAllocCount = m_Allocations.size();
m_HasNonMovableAllocations = blockAllocCount != defragmentAllocCount;
}
void SortAllocationsBySizeDescecnding()
{
VMA_SORT(m_Allocations.begin(), m_Allocations.end(), AllocationInfoSizeGreater());
}
VkResult EnsureMapping(VmaAllocator hAllocator, void** ppMappedData);
void Unmap(VmaAllocator hAllocator);
private:
// Not null if mapped for defragmentation only, not originally mapped.
void* m_pMappedDataForDefragmentation;
};
struct BlockPointerLess
{
bool operator()(const BlockInfo* pLhsBlockInfo, const VmaDeviceMemoryBlock* pRhsBlock) const
{
return pLhsBlockInfo->m_pBlock < pRhsBlock;
}
bool operator()(const BlockInfo* pLhsBlockInfo, const BlockInfo* pRhsBlockInfo) const
{
return pLhsBlockInfo->m_pBlock < pRhsBlockInfo->m_pBlock;
}
};
// 1. Blocks with some non-movable allocations go first.
// 2. Blocks with smaller sumFreeSize go first.
struct BlockInfoCompareMoveDestination
{
bool operator()(const BlockInfo* pLhsBlockInfo, const BlockInfo* pRhsBlockInfo) const
{
if(pLhsBlockInfo->m_HasNonMovableAllocations && !pRhsBlockInfo->m_HasNonMovableAllocations)
{
return true;
}
if(!pLhsBlockInfo->m_HasNonMovableAllocations && pRhsBlockInfo->m_HasNonMovableAllocations)
{
return false;
}
if(pLhsBlockInfo->m_pBlock->m_pMetadata->GetSumFreeSize() < pRhsBlockInfo->m_pBlock->m_pMetadata->GetSumFreeSize())
{
return true;
}
return false;
}
};
typedef VmaVector< BlockInfo*, VmaStlAllocator<BlockInfo*> > BlockInfoVector;
BlockInfoVector m_Blocks;
VkResult DefragmentRound(
VkDeviceSize maxBytesToMove,
uint32_t maxAllocationsToMove);
static bool MoveMakesSense(
size_t dstBlockIndex, VkDeviceSize dstOffset,
size_t srcBlockIndex, VkDeviceSize srcOffset);
public:
VmaDefragmentator(
VmaAllocator hAllocator,
VmaBlockVector* pBlockVector,
uint32_t currentFrameIndex);
~VmaDefragmentator();
VkDeviceSize GetBytesMoved() const { return m_BytesMoved; }
uint32_t GetAllocationsMoved() const { return m_AllocationsMoved; }
void AddAllocation(VmaAllocation hAlloc, VkBool32* pChanged);
VkResult Defragment(
VkDeviceSize maxBytesToMove,
uint32_t maxAllocationsToMove);
};
#if VMA_RECORDING_ENABLED
class VmaRecorder
{
public:
VmaRecorder();
VkResult Init(const VmaRecordSettings& settings, bool useMutex);
void WriteConfiguration(
const VkPhysicalDeviceProperties& devProps,
const VkPhysicalDeviceMemoryProperties& memProps,
bool dedicatedAllocationExtensionEnabled);
~VmaRecorder();
void RecordCreateAllocator(uint32_t frameIndex);
void RecordDestroyAllocator(uint32_t frameIndex);
void RecordCreatePool(uint32_t frameIndex,
const VmaPoolCreateInfo& createInfo,
VmaPool pool);
void RecordDestroyPool(uint32_t frameIndex, VmaPool pool);
void RecordAllocateMemory(uint32_t frameIndex,
const VkMemoryRequirements& vkMemReq,
const VmaAllocationCreateInfo& createInfo,
VmaAllocation allocation);
void RecordAllocateMemoryForBuffer(uint32_t frameIndex,
const VkMemoryRequirements& vkMemReq,
bool requiresDedicatedAllocation,
bool prefersDedicatedAllocation,
const VmaAllocationCreateInfo& createInfo,
VmaAllocation allocation);
void RecordAllocateMemoryForImage(uint32_t frameIndex,
const VkMemoryRequirements& vkMemReq,
bool requiresDedicatedAllocation,
bool prefersDedicatedAllocation,
const VmaAllocationCreateInfo& createInfo,
VmaAllocation allocation);
void RecordFreeMemory(uint32_t frameIndex,
VmaAllocation allocation);
void RecordSetAllocationUserData(uint32_t frameIndex,
VmaAllocation allocation,
const void* pUserData);
void RecordCreateLostAllocation(uint32_t frameIndex,
VmaAllocation allocation);
void RecordMapMemory(uint32_t frameIndex,
VmaAllocation allocation);
void RecordUnmapMemory(uint32_t frameIndex,
VmaAllocation allocation);
void RecordFlushAllocation(uint32_t frameIndex,
VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size);
void RecordInvalidateAllocation(uint32_t frameIndex,
VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size);
void RecordCreateBuffer(uint32_t frameIndex,
const VkBufferCreateInfo& bufCreateInfo,
const VmaAllocationCreateInfo& allocCreateInfo,
VmaAllocation allocation);
void RecordCreateImage(uint32_t frameIndex,
const VkImageCreateInfo& imageCreateInfo,
const VmaAllocationCreateInfo& allocCreateInfo,
VmaAllocation allocation);
void RecordDestroyBuffer(uint32_t frameIndex,
VmaAllocation allocation);
void RecordDestroyImage(uint32_t frameIndex,
VmaAllocation allocation);
void RecordTouchAllocation(uint32_t frameIndex,
VmaAllocation allocation);
void RecordGetAllocationInfo(uint32_t frameIndex,
VmaAllocation allocation);
void RecordMakePoolAllocationsLost(uint32_t frameIndex,
VmaPool pool);
private:
struct CallParams
{
uint32_t threadId;
double time;
};
class UserDataString
{
public:
UserDataString(VmaAllocationCreateFlags allocFlags, const void* pUserData);
const char* GetString() const { return m_Str; }
private:
char m_PtrStr[17];
const char* m_Str;
};
bool m_UseMutex;
VmaRecordFlags m_Flags;
FILE* m_File;
VMA_MUTEX m_FileMutex;
int64_t m_Freq;
int64_t m_StartCounter;
void GetBasicParams(CallParams& outParams);
void Flush();
};
#endif // #if VMA_RECORDING_ENABLED
// Main allocator object.
struct VmaAllocator_T
{
VMA_CLASS_NO_COPY(VmaAllocator_T)
public:
bool m_UseMutex;
bool m_UseKhrDedicatedAllocation;
VkDevice m_hDevice;
bool m_AllocationCallbacksSpecified;
VkAllocationCallbacks m_AllocationCallbacks;
VmaDeviceMemoryCallbacks m_DeviceMemoryCallbacks;
// Number of bytes free out of limit, or VK_WHOLE_SIZE if not limit for that heap.
VkDeviceSize m_HeapSizeLimit[VK_MAX_MEMORY_HEAPS];
VMA_MUTEX m_HeapSizeLimitMutex;
VkPhysicalDeviceProperties m_PhysicalDeviceProperties;
VkPhysicalDeviceMemoryProperties m_MemProps;
// Default pools.
VmaBlockVector* m_pBlockVectors[VK_MAX_MEMORY_TYPES];
// Each vector is sorted by memory (handle value).
typedef VmaVector< VmaAllocation, VmaStlAllocator<VmaAllocation> > AllocationVectorType;
AllocationVectorType* m_pDedicatedAllocations[VK_MAX_MEMORY_TYPES];
VMA_MUTEX m_DedicatedAllocationsMutex[VK_MAX_MEMORY_TYPES];
VmaAllocator_T(const VmaAllocatorCreateInfo* pCreateInfo);
VkResult Init(const VmaAllocatorCreateInfo* pCreateInfo);
~VmaAllocator_T();
const VkAllocationCallbacks* GetAllocationCallbacks() const
{
return m_AllocationCallbacksSpecified ? &m_AllocationCallbacks : 0;
}
const VmaVulkanFunctions& GetVulkanFunctions() const
{
return m_VulkanFunctions;
}
VkDeviceSize GetBufferImageGranularity() const
{
return VMA_MAX(
static_cast<VkDeviceSize>(VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY),
m_PhysicalDeviceProperties.limits.bufferImageGranularity);
}
uint32_t GetMemoryHeapCount() const { return m_MemProps.memoryHeapCount; }
uint32_t GetMemoryTypeCount() const { return m_MemProps.memoryTypeCount; }
uint32_t MemoryTypeIndexToHeapIndex(uint32_t memTypeIndex) const
{
VMA_ASSERT(memTypeIndex < m_MemProps.memoryTypeCount);
return m_MemProps.memoryTypes[memTypeIndex].heapIndex;
}
// True when specific memory type is HOST_VISIBLE but not HOST_COHERENT.
bool IsMemoryTypeNonCoherent(uint32_t memTypeIndex) const
{
return (m_MemProps.memoryTypes[memTypeIndex].propertyFlags & (VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) ==
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
}
// Minimum alignment for all allocations in specific memory type.
VkDeviceSize GetMemoryTypeMinAlignment(uint32_t memTypeIndex) const
{
return IsMemoryTypeNonCoherent(memTypeIndex) ?
VMA_MAX((VkDeviceSize)VMA_DEBUG_ALIGNMENT, m_PhysicalDeviceProperties.limits.nonCoherentAtomSize) :
(VkDeviceSize)VMA_DEBUG_ALIGNMENT;
}
bool IsIntegratedGpu() const
{
return m_PhysicalDeviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU;
}
#if VMA_RECORDING_ENABLED
VmaRecorder* GetRecorder() const { return m_pRecorder; }
#endif
void GetBufferMemoryRequirements(
VkBuffer hBuffer,
VkMemoryRequirements& memReq,
bool& requiresDedicatedAllocation,
bool& prefersDedicatedAllocation) const;
void GetImageMemoryRequirements(
VkImage hImage,
VkMemoryRequirements& memReq,
bool& requiresDedicatedAllocation,
bool& prefersDedicatedAllocation) const;
// Main allocation function.
VkResult AllocateMemory(
const VkMemoryRequirements& vkMemReq,
bool requiresDedicatedAllocation,
bool prefersDedicatedAllocation,
VkBuffer dedicatedBuffer,
VkImage dedicatedImage,
const VmaAllocationCreateInfo& createInfo,
VmaSuballocationType suballocType,
VmaAllocation* pAllocation);
// Main deallocation function.
void FreeMemory(const VmaAllocation allocation);
void CalculateStats(VmaStats* pStats);
#if VMA_STATS_STRING_ENABLED
void PrintDetailedMap(class VmaJsonWriter& json);
#endif
VkResult Defragment(
VmaAllocation* pAllocations,
size_t allocationCount,
VkBool32* pAllocationsChanged,
const VmaDefragmentationInfo* pDefragmentationInfo,
VmaDefragmentationStats* pDefragmentationStats);
void GetAllocationInfo(VmaAllocation hAllocation, VmaAllocationInfo* pAllocationInfo);
bool TouchAllocation(VmaAllocation hAllocation);
VkResult CreatePool(const VmaPoolCreateInfo* pCreateInfo, VmaPool* pPool);
void DestroyPool(VmaPool pool);
void GetPoolStats(VmaPool pool, VmaPoolStats* pPoolStats);
void SetCurrentFrameIndex(uint32_t frameIndex);
uint32_t GetCurrentFrameIndex() const { return m_CurrentFrameIndex.load(); }
void MakePoolAllocationsLost(
VmaPool hPool,
size_t* pLostAllocationCount);
VkResult CheckPoolCorruption(VmaPool hPool);
VkResult CheckCorruption(uint32_t memoryTypeBits);
void CreateLostAllocation(VmaAllocation* pAllocation);
VkResult AllocateVulkanMemory(const VkMemoryAllocateInfo* pAllocateInfo, VkDeviceMemory* pMemory);
void FreeVulkanMemory(uint32_t memoryType, VkDeviceSize size, VkDeviceMemory hMemory);
VkResult Map(VmaAllocation hAllocation, void** ppData);
void Unmap(VmaAllocation hAllocation);
VkResult BindBufferMemory(VmaAllocation hAllocation, VkBuffer hBuffer);
VkResult BindImageMemory(VmaAllocation hAllocation, VkImage hImage);
void FlushOrInvalidateAllocation(
VmaAllocation hAllocation,
VkDeviceSize offset, VkDeviceSize size,
VMA_CACHE_OPERATION op);
void FillAllocation(const VmaAllocation hAllocation, uint8_t pattern);
private:
VkDeviceSize m_PreferredLargeHeapBlockSize;
VkPhysicalDevice m_PhysicalDevice;
VMA_ATOMIC_UINT32 m_CurrentFrameIndex;
VMA_MUTEX m_PoolsMutex;
// Protected by m_PoolsMutex. Sorted by pointer value.
VmaVector<VmaPool, VmaStlAllocator<VmaPool> > m_Pools;
uint32_t m_NextPoolId;
VmaVulkanFunctions m_VulkanFunctions;
#if VMA_RECORDING_ENABLED
VmaRecorder* m_pRecorder;
#endif
void ImportVulkanFunctions(const VmaVulkanFunctions* pVulkanFunctions);
VkDeviceSize CalcPreferredBlockSize(uint32_t memTypeIndex);
VkResult AllocateMemoryOfType(
VkDeviceSize size,
VkDeviceSize alignment,
bool dedicatedAllocation,
VkBuffer dedicatedBuffer,
VkImage dedicatedImage,
const VmaAllocationCreateInfo& createInfo,
uint32_t memTypeIndex,
VmaSuballocationType suballocType,
VmaAllocation* pAllocation);
// Allocates and registers new VkDeviceMemory specifically for single allocation.
VkResult AllocateDedicatedMemory(
VkDeviceSize size,
VmaSuballocationType suballocType,
uint32_t memTypeIndex,
bool map,
bool isUserDataString,
void* pUserData,
VkBuffer dedicatedBuffer,
VkImage dedicatedImage,
VmaAllocation* pAllocation);
// Tries to free pMemory as Dedicated Memory. Returns true if found and freed.
void FreeDedicatedMemory(VmaAllocation allocation);
};
////////////////////////////////////////////////////////////////////////////////
// Memory allocation #2 after VmaAllocator_T definition
static void* VmaMalloc(VmaAllocator hAllocator, size_t size, size_t alignment)
{
return VmaMalloc(&hAllocator->m_AllocationCallbacks, size, alignment);
}
static void VmaFree(VmaAllocator hAllocator, void* ptr)
{
VmaFree(&hAllocator->m_AllocationCallbacks, ptr);
}
template<typename T>
static T* VmaAllocate(VmaAllocator hAllocator)
{
return (T*)VmaMalloc(hAllocator, sizeof(T), VMA_ALIGN_OF(T));
}
template<typename T>
static T* VmaAllocateArray(VmaAllocator hAllocator, size_t count)
{
return (T*)VmaMalloc(hAllocator, sizeof(T) * count, VMA_ALIGN_OF(T));
}
template<typename T>
static void vma_delete(VmaAllocator hAllocator, T* ptr)
{
if(ptr != VMA_NULL)
{
ptr->~T();
VmaFree(hAllocator, ptr);
}
}
template<typename T>
static void vma_delete_array(VmaAllocator hAllocator, T* ptr, size_t count)
{
if(ptr != VMA_NULL)
{
for(size_t i = count; i--; )
ptr[i].~T();
VmaFree(hAllocator, ptr);
}
}
////////////////////////////////////////////////////////////////////////////////
// VmaStringBuilder
#if VMA_STATS_STRING_ENABLED
class VmaStringBuilder
{
public:
VmaStringBuilder(VmaAllocator alloc) : m_Data(VmaStlAllocator<char>(alloc->GetAllocationCallbacks())) { }
size_t GetLength() const { return m_Data.size(); }
const char* GetData() const { return m_Data.data(); }
void Add(char ch) { m_Data.push_back(ch); }
void Add(const char* pStr);
void AddNewLine() { Add('\n'); }
void AddNumber(uint32_t num);
void AddNumber(uint64_t num);
void AddPointer(const void* ptr);
private:
VmaVector< char, VmaStlAllocator<char> > m_Data;
};
void VmaStringBuilder::Add(const char* pStr)
{
const size_t strLen = strlen(pStr);
if(strLen > 0)
{
const size_t oldCount = m_Data.size();
m_Data.resize(oldCount + strLen);
memcpy(m_Data.data() + oldCount, pStr, strLen);
}
}
void VmaStringBuilder::AddNumber(uint32_t num)
{
char buf[11];
VmaUint32ToStr(buf, sizeof(buf), num);
Add(buf);
}
void VmaStringBuilder::AddNumber(uint64_t num)
{
char buf[21];
VmaUint64ToStr(buf, sizeof(buf), num);
Add(buf);
}
void VmaStringBuilder::AddPointer(const void* ptr)
{
char buf[21];
VmaPtrToStr(buf, sizeof(buf), ptr);
Add(buf);
}
#endif // #if VMA_STATS_STRING_ENABLED
////////////////////////////////////////////////////////////////////////////////
// VmaJsonWriter
#if VMA_STATS_STRING_ENABLED
class VmaJsonWriter
{
VMA_CLASS_NO_COPY(VmaJsonWriter)
public:
VmaJsonWriter(const VkAllocationCallbacks* pAllocationCallbacks, VmaStringBuilder& sb);
~VmaJsonWriter();
void BeginObject(bool singleLine = false);
void EndObject();
void BeginArray(bool singleLine = false);
void EndArray();
void WriteString(const char* pStr);
void BeginString(const char* pStr = VMA_NULL);
void ContinueString(const char* pStr);
void ContinueString(uint32_t n);
void ContinueString(uint64_t n);
void ContinueString_Pointer(const void* ptr);
void EndString(const char* pStr = VMA_NULL);
void WriteNumber(uint32_t n);
void WriteNumber(uint64_t n);
void WriteBool(bool b);
void WriteNull();
private:
static const char* const INDENT;
enum COLLECTION_TYPE
{
COLLECTION_TYPE_OBJECT,
COLLECTION_TYPE_ARRAY,
};
struct StackItem
{
COLLECTION_TYPE type;
uint32_t valueCount;
bool singleLineMode;
};
VmaStringBuilder& m_SB;
VmaVector< StackItem, VmaStlAllocator<StackItem> > m_Stack;
bool m_InsideString;
void BeginValue(bool isString);
void WriteIndent(bool oneLess = false);
};
const char* const VmaJsonWriter::INDENT = " ";
VmaJsonWriter::VmaJsonWriter(const VkAllocationCallbacks* pAllocationCallbacks, VmaStringBuilder& sb) :
m_SB(sb),
m_Stack(VmaStlAllocator<StackItem>(pAllocationCallbacks)),
m_InsideString(false)
{
}
VmaJsonWriter::~VmaJsonWriter()
{
VMA_ASSERT(!m_InsideString);
VMA_ASSERT(m_Stack.empty());
}
void VmaJsonWriter::BeginObject(bool singleLine)
{
VMA_ASSERT(!m_InsideString);
BeginValue(false);
m_SB.Add('{');
StackItem item;
item.type = COLLECTION_TYPE_OBJECT;
item.valueCount = 0;
item.singleLineMode = singleLine;
m_Stack.push_back(item);
}
void VmaJsonWriter::EndObject()
{
VMA_ASSERT(!m_InsideString);
WriteIndent(true);
m_SB.Add('}');
VMA_ASSERT(!m_Stack.empty() && m_Stack.back().type == COLLECTION_TYPE_OBJECT);
m_Stack.pop_back();
}
void VmaJsonWriter::BeginArray(bool singleLine)
{
VMA_ASSERT(!m_InsideString);
BeginValue(false);
m_SB.Add('[');
StackItem item;
item.type = COLLECTION_TYPE_ARRAY;
item.valueCount = 0;
item.singleLineMode = singleLine;
m_Stack.push_back(item);
}
void VmaJsonWriter::EndArray()
{
VMA_ASSERT(!m_InsideString);
WriteIndent(true);
m_SB.Add(']');
VMA_ASSERT(!m_Stack.empty() && m_Stack.back().type == COLLECTION_TYPE_ARRAY);
m_Stack.pop_back();
}
void VmaJsonWriter::WriteString(const char* pStr)
{
BeginString(pStr);
EndString();
}
void VmaJsonWriter::BeginString(const char* pStr)
{
VMA_ASSERT(!m_InsideString);
BeginValue(true);
m_SB.Add('"');
m_InsideString = true;
if(pStr != VMA_NULL && pStr[0] != '\0')
{
ContinueString(pStr);
}
}
void VmaJsonWriter::ContinueString(const char* pStr)
{
VMA_ASSERT(m_InsideString);
const size_t strLen = strlen(pStr);
for(size_t i = 0; i < strLen; ++i)
{
char ch = pStr[i];
if(ch == '\\')
{
m_SB.Add("\\\\");
}
else if(ch == '"')
{
m_SB.Add("\\\"");
}
else if(ch >= 32)
{
m_SB.Add(ch);
}
else switch(ch)
{
case '\b':
m_SB.Add("\\b");
break;
case '\f':
m_SB.Add("\\f");
break;
case '\n':
m_SB.Add("\\n");
break;
case '\r':
m_SB.Add("\\r");
break;
case '\t':
m_SB.Add("\\t");
break;
default:
VMA_ASSERT(0 && "Character not currently supported.");
break;
}
}
}
void VmaJsonWriter::ContinueString(uint32_t n)
{
VMA_ASSERT(m_InsideString);
m_SB.AddNumber(n);
}
void VmaJsonWriter::ContinueString(uint64_t n)
{
VMA_ASSERT(m_InsideString);
m_SB.AddNumber(n);
}
void VmaJsonWriter::ContinueString_Pointer(const void* ptr)
{
VMA_ASSERT(m_InsideString);
m_SB.AddPointer(ptr);
}
void VmaJsonWriter::EndString(const char* pStr)
{
VMA_ASSERT(m_InsideString);
if(pStr != VMA_NULL && pStr[0] != '\0')
{
ContinueString(pStr);
}
m_SB.Add('"');
m_InsideString = false;
}
void VmaJsonWriter::WriteNumber(uint32_t n)
{
VMA_ASSERT(!m_InsideString);
BeginValue(false);
m_SB.AddNumber(n);
}
void VmaJsonWriter::WriteNumber(uint64_t n)
{
VMA_ASSERT(!m_InsideString);
BeginValue(false);
m_SB.AddNumber(n);
}
void VmaJsonWriter::WriteBool(bool b)
{
VMA_ASSERT(!m_InsideString);
BeginValue(false);
m_SB.Add(b ? "true" : "false");
}
void VmaJsonWriter::WriteNull()
{
VMA_ASSERT(!m_InsideString);
BeginValue(false);
m_SB.Add("null");
}
void VmaJsonWriter::BeginValue(bool isString)
{
if(!m_Stack.empty())
{
StackItem& currItem = m_Stack.back();
if(currItem.type == COLLECTION_TYPE_OBJECT &&
currItem.valueCount % 2 == 0)
{
VMA_ASSERT(isString);
}
if(currItem.type == COLLECTION_TYPE_OBJECT &&
currItem.valueCount % 2 != 0)
{
m_SB.Add(": ");
}
else if(currItem.valueCount > 0)
{
m_SB.Add(", ");
WriteIndent();
}
else
{
WriteIndent();
}
++currItem.valueCount;
}
}
void VmaJsonWriter::WriteIndent(bool oneLess)
{
if(!m_Stack.empty() && !m_Stack.back().singleLineMode)
{
m_SB.AddNewLine();
size_t count = m_Stack.size();
if(count > 0 && oneLess)
{
--count;
}
for(size_t i = 0; i < count; ++i)
{
m_SB.Add(INDENT);
}
}
}
#endif // #if VMA_STATS_STRING_ENABLED
////////////////////////////////////////////////////////////////////////////////
void VmaAllocation_T::SetUserData(VmaAllocator hAllocator, void* pUserData)
{
if(IsUserDataString())
{
VMA_ASSERT(pUserData == VMA_NULL || pUserData != m_pUserData);
FreeUserDataString(hAllocator);
if(pUserData != VMA_NULL)
{
const char* const newStrSrc = (char*)pUserData;
const size_t newStrLen = strlen(newStrSrc);
char* const newStrDst = vma_new_array(hAllocator, char, newStrLen + 1);
memcpy(newStrDst, newStrSrc, newStrLen + 1);
m_pUserData = newStrDst;
}
}
else
{
m_pUserData = pUserData;
}
}
void VmaAllocation_T::ChangeBlockAllocation(
VmaAllocator hAllocator,
VmaDeviceMemoryBlock* block,
VkDeviceSize offset)
{
VMA_ASSERT(block != VMA_NULL);
VMA_ASSERT(m_Type == ALLOCATION_TYPE_BLOCK);
// Move mapping reference counter from old block to new block.
if(block != m_BlockAllocation.m_Block)
{
uint32_t mapRefCount = m_MapCount & ~MAP_COUNT_FLAG_PERSISTENT_MAP;
if(IsPersistentMap())
++mapRefCount;
m_BlockAllocation.m_Block->Unmap(hAllocator, mapRefCount);
block->Map(hAllocator, mapRefCount, VMA_NULL);
}
m_BlockAllocation.m_Block = block;
m_BlockAllocation.m_Offset = offset;
}
VkDeviceSize VmaAllocation_T::GetOffset() const
{
switch(m_Type)
{
case ALLOCATION_TYPE_BLOCK:
return m_BlockAllocation.m_Offset;
case ALLOCATION_TYPE_DEDICATED:
return 0;
default:
VMA_ASSERT(0);
return 0;
}
}
VkDeviceMemory VmaAllocation_T::GetMemory() const
{
switch(m_Type)
{
case ALLOCATION_TYPE_BLOCK:
return m_BlockAllocation.m_Block->GetDeviceMemory();
case ALLOCATION_TYPE_DEDICATED:
return m_DedicatedAllocation.m_hMemory;
default:
VMA_ASSERT(0);
return VK_NULL_HANDLE;
}
}
uint32_t VmaAllocation_T::GetMemoryTypeIndex() const
{
switch(m_Type)
{
case ALLOCATION_TYPE_BLOCK:
return m_BlockAllocation.m_Block->GetMemoryTypeIndex();
case ALLOCATION_TYPE_DEDICATED:
return m_DedicatedAllocation.m_MemoryTypeIndex;
default:
VMA_ASSERT(0);
return UINT32_MAX;
}
}
void* VmaAllocation_T::GetMappedData() const
{
switch(m_Type)
{
case ALLOCATION_TYPE_BLOCK:
if(m_MapCount != 0)
{
void* pBlockData = m_BlockAllocation.m_Block->GetMappedData();
VMA_ASSERT(pBlockData != VMA_NULL);
return (char*)pBlockData + m_BlockAllocation.m_Offset;
}
else
{
return VMA_NULL;
}
break;
case ALLOCATION_TYPE_DEDICATED:
VMA_ASSERT((m_DedicatedAllocation.m_pMappedData != VMA_NULL) == (m_MapCount != 0));
return m_DedicatedAllocation.m_pMappedData;
default:
VMA_ASSERT(0);
return VMA_NULL;
}
}
bool VmaAllocation_T::CanBecomeLost() const
{
switch(m_Type)
{
case ALLOCATION_TYPE_BLOCK:
return m_BlockAllocation.m_CanBecomeLost;
case ALLOCATION_TYPE_DEDICATED:
return false;
default:
VMA_ASSERT(0);
return false;
}
}
VmaPool VmaAllocation_T::GetPool() const
{
VMA_ASSERT(m_Type == ALLOCATION_TYPE_BLOCK);
return m_BlockAllocation.m_hPool;
}
bool VmaAllocation_T::MakeLost(uint32_t currentFrameIndex, uint32_t frameInUseCount)
{
VMA_ASSERT(CanBecomeLost());
/*
Warning: This is a carefully designed algorithm.
Do not modify unless you really know what you're doing :)
*/
uint32_t localLastUseFrameIndex = GetLastUseFrameIndex();
for(;;)
{
if(localLastUseFrameIndex == VMA_FRAME_INDEX_LOST)
{
VMA_ASSERT(0);
return false;
}
else if(localLastUseFrameIndex + frameInUseCount >= currentFrameIndex)
{
return false;
}
else // Last use time earlier than current time.
{
if(CompareExchangeLastUseFrameIndex(localLastUseFrameIndex, VMA_FRAME_INDEX_LOST))
{
// Setting hAllocation.LastUseFrameIndex atomic to VMA_FRAME_INDEX_LOST is enough to mark it as LOST.
// Calling code just needs to unregister this allocation in owning VmaDeviceMemoryBlock.
return true;
}
}
}
}
#if VMA_STATS_STRING_ENABLED
// Correspond to values of enum VmaSuballocationType.
static const char* VMA_SUBALLOCATION_TYPE_NAMES[] = {
"FREE",
"UNKNOWN",
"BUFFER",
"IMAGE_UNKNOWN",
"IMAGE_LINEAR",
"IMAGE_OPTIMAL",
};
void VmaAllocation_T::PrintParameters(class VmaJsonWriter& json) const
{
json.WriteString("Type");
json.WriteString(VMA_SUBALLOCATION_TYPE_NAMES[m_SuballocationType]);
json.WriteString("Size");
json.WriteNumber(m_Size);
if(m_pUserData != VMA_NULL)
{
json.WriteString("UserData");
if(IsUserDataString())
{
json.WriteString((const char*)m_pUserData);
}
else
{
json.BeginString();
json.ContinueString_Pointer(m_pUserData);
json.EndString();
}
}
json.WriteString("CreationFrameIndex");
json.WriteNumber(m_CreationFrameIndex);
json.WriteString("LastUseFrameIndex");
json.WriteNumber(GetLastUseFrameIndex());
if(m_BufferImageUsage != 0)
{
json.WriteString("Usage");
json.WriteNumber(m_BufferImageUsage);
}
}
#endif
void VmaAllocation_T::FreeUserDataString(VmaAllocator hAllocator)
{
VMA_ASSERT(IsUserDataString());
if(m_pUserData != VMA_NULL)
{
char* const oldStr = (char*)m_pUserData;
const size_t oldStrLen = strlen(oldStr);
vma_delete_array(hAllocator, oldStr, oldStrLen + 1);
m_pUserData = VMA_NULL;
}
}
void VmaAllocation_T::BlockAllocMap()
{
VMA_ASSERT(GetType() == ALLOCATION_TYPE_BLOCK);
if((m_MapCount & ~MAP_COUNT_FLAG_PERSISTENT_MAP) < 0x7F)
{
++m_MapCount;
}
else
{
VMA_ASSERT(0 && "Allocation mapped too many times simultaneously.");
}
}
void VmaAllocation_T::BlockAllocUnmap()
{
VMA_ASSERT(GetType() == ALLOCATION_TYPE_BLOCK);
if((m_MapCount & ~MAP_COUNT_FLAG_PERSISTENT_MAP) != 0)
{
--m_MapCount;
}
else
{
VMA_ASSERT(0 && "Unmapping allocation not previously mapped.");
}
}
VkResult VmaAllocation_T::DedicatedAllocMap(VmaAllocator hAllocator, void** ppData)
{
VMA_ASSERT(GetType() == ALLOCATION_TYPE_DEDICATED);
if(m_MapCount != 0)
{
if((m_MapCount & ~MAP_COUNT_FLAG_PERSISTENT_MAP) < 0x7F)
{
VMA_ASSERT(m_DedicatedAllocation.m_pMappedData != VMA_NULL);
*ppData = m_DedicatedAllocation.m_pMappedData;
++m_MapCount;
return VK_SUCCESS;
}
else
{
VMA_ASSERT(0 && "Dedicated allocation mapped too many times simultaneously.");
return VK_ERROR_MEMORY_MAP_FAILED;
}
}
else
{
VkResult result = (*hAllocator->GetVulkanFunctions().vkMapMemory)(
hAllocator->m_hDevice,
m_DedicatedAllocation.m_hMemory,
0, // offset
VK_WHOLE_SIZE,
0, // flags
ppData);
if(result == VK_SUCCESS)
{
m_DedicatedAllocation.m_pMappedData = *ppData;
m_MapCount = 1;
}
return result;
}
}
void VmaAllocation_T::DedicatedAllocUnmap(VmaAllocator hAllocator)
{
VMA_ASSERT(GetType() == ALLOCATION_TYPE_DEDICATED);
if((m_MapCount & ~MAP_COUNT_FLAG_PERSISTENT_MAP) != 0)
{
--m_MapCount;
if(m_MapCount == 0)
{
m_DedicatedAllocation.m_pMappedData = VMA_NULL;
(*hAllocator->GetVulkanFunctions().vkUnmapMemory)(
hAllocator->m_hDevice,
m_DedicatedAllocation.m_hMemory);
}
}
else
{
VMA_ASSERT(0 && "Unmapping dedicated allocation not previously mapped.");
}
}
#if VMA_STATS_STRING_ENABLED
static void VmaPrintStatInfo(VmaJsonWriter& json, const VmaStatInfo& stat)
{
json.BeginObject();
json.WriteString("Blocks");
json.WriteNumber(stat.blockCount);
json.WriteString("Allocations");
json.WriteNumber(stat.allocationCount);
json.WriteString("UnusedRanges");
json.WriteNumber(stat.unusedRangeCount);
json.WriteString("UsedBytes");
json.WriteNumber(stat.usedBytes);
json.WriteString("UnusedBytes");
json.WriteNumber(stat.unusedBytes);
if(stat.allocationCount > 1)
{
json.WriteString("AllocationSize");
json.BeginObject(true);
json.WriteString("Min");
json.WriteNumber(stat.allocationSizeMin);
json.WriteString("Avg");
json.WriteNumber(stat.allocationSizeAvg);
json.WriteString("Max");
json.WriteNumber(stat.allocationSizeMax);
json.EndObject();
}
if(stat.unusedRangeCount > 1)
{
json.WriteString("UnusedRangeSize");
json.BeginObject(true);
json.WriteString("Min");
json.WriteNumber(stat.unusedRangeSizeMin);
json.WriteString("Avg");
json.WriteNumber(stat.unusedRangeSizeAvg);
json.WriteString("Max");
json.WriteNumber(stat.unusedRangeSizeMax);
json.EndObject();
}
json.EndObject();
}
#endif // #if VMA_STATS_STRING_ENABLED
struct VmaSuballocationItemSizeLess
{
bool operator()(
const VmaSuballocationList::iterator lhs,
const VmaSuballocationList::iterator rhs) const
{
return lhs->size < rhs->size;
}
bool operator()(
const VmaSuballocationList::iterator lhs,
VkDeviceSize rhsSize) const
{
return lhs->size < rhsSize;
}
};
////////////////////////////////////////////////////////////////////////////////
// class VmaBlockMetadata
#if VMA_STATS_STRING_ENABLED
void VmaBlockMetadata::PrintDetailedMap_Begin(class VmaJsonWriter& json,
VkDeviceSize unusedBytes,
size_t allocationCount,
size_t unusedRangeCount) const
{
json.BeginObject();
json.WriteString("TotalBytes");
json.WriteNumber(GetSize());
json.WriteString("UnusedBytes");
json.WriteNumber(unusedBytes);
json.WriteString("Allocations");
json.WriteNumber((uint64_t)allocationCount);
json.WriteString("UnusedRanges");
json.WriteNumber((uint64_t)unusedRangeCount);
json.WriteString("Suballocations");
json.BeginArray();
}
void VmaBlockMetadata::PrintDetailedMap_Allocation(class VmaJsonWriter& json,
VkDeviceSize offset,
VmaAllocation hAllocation) const
{
json.BeginObject(true);
json.WriteString("Offset");
json.WriteNumber(offset);
hAllocation->PrintParameters(json);
json.EndObject();
}
void VmaBlockMetadata::PrintDetailedMap_UnusedRange(class VmaJsonWriter& json,
VkDeviceSize offset,
VkDeviceSize size) const
{
json.BeginObject(true);
json.WriteString("Offset");
json.WriteNumber(offset);
json.WriteString("Type");
json.WriteString(VMA_SUBALLOCATION_TYPE_NAMES[VMA_SUBALLOCATION_TYPE_FREE]);
json.WriteString("Size");
json.WriteNumber(size);
json.EndObject();
}
void VmaBlockMetadata::PrintDetailedMap_End(class VmaJsonWriter& json) const
{
json.EndArray();
json.EndObject();
}
#endif // #if VMA_STATS_STRING_ENABLED
////////////////////////////////////////////////////////////////////////////////
// class VmaBlockMetadata_Generic
VmaBlockMetadata_Generic::VmaBlockMetadata_Generic(VmaAllocator hAllocator) :
m_FreeCount(0),
m_SumFreeSize(0),
m_Suballocations(VmaStlAllocator<VmaSuballocation>(hAllocator->GetAllocationCallbacks())),
m_FreeSuballocationsBySize(VmaStlAllocator<VmaSuballocationList::iterator>(hAllocator->GetAllocationCallbacks()))
{
}
VmaBlockMetadata_Generic::~VmaBlockMetadata_Generic()
{
}
void VmaBlockMetadata_Generic::Init(VkDeviceSize size)
{
VmaBlockMetadata::Init(size);
m_FreeCount = 1;
m_SumFreeSize = size;
VmaSuballocation suballoc = {};
suballoc.offset = 0;
suballoc.size = size;
suballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
suballoc.hAllocation = VK_NULL_HANDLE;
m_Suballocations.push_back(suballoc);
VmaSuballocationList::iterator suballocItem = m_Suballocations.end();
--suballocItem;
m_FreeSuballocationsBySize.push_back(suballocItem);
}
bool VmaBlockMetadata_Generic::Validate() const
{
if(m_Suballocations.empty())
{
return false;
}
// Expected offset of new suballocation as calculated from previous ones.
VkDeviceSize calculatedOffset = 0;
// Expected number of free suballocations as calculated from traversing their list.
uint32_t calculatedFreeCount = 0;
// Expected sum size of free suballocations as calculated from traversing their list.
VkDeviceSize calculatedSumFreeSize = 0;
// Expected number of free suballocations that should be registered in
// m_FreeSuballocationsBySize calculated from traversing their list.
size_t freeSuballocationsToRegister = 0;
// True if previous visited suballocation was free.
bool prevFree = false;
for(VmaSuballocationList::const_iterator suballocItem = m_Suballocations.cbegin();
suballocItem != m_Suballocations.cend();
++suballocItem)
{
const VmaSuballocation& subAlloc = *suballocItem;
// Actual offset of this suballocation doesn't match expected one.
if(subAlloc.offset != calculatedOffset)
{
return false;
}
const bool currFree = (subAlloc.type == VMA_SUBALLOCATION_TYPE_FREE);
// Two adjacent free suballocations are invalid. They should be merged.
if(prevFree && currFree)
{
return false;
}
if(currFree != (subAlloc.hAllocation == VK_NULL_HANDLE))
{
return false;
}
if(currFree)
{
calculatedSumFreeSize += subAlloc.size;
++calculatedFreeCount;
if(subAlloc.size >= VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER)
{
++freeSuballocationsToRegister;
}
// Margin required between allocations - every free space must be at least that large.
if(subAlloc.size < VMA_DEBUG_MARGIN)
{
return false;
}
}
else
{
if(subAlloc.hAllocation->GetOffset() != subAlloc.offset)
{
return false;
}
if(subAlloc.hAllocation->GetSize() != subAlloc.size)
{
return false;
}
// Margin required between allocations - previous allocation must be free.
if(VMA_DEBUG_MARGIN > 0 && !prevFree)
{
return false;
}
}
calculatedOffset += subAlloc.size;
prevFree = currFree;
}
// Number of free suballocations registered in m_FreeSuballocationsBySize doesn't
// match expected one.
if(m_FreeSuballocationsBySize.size() != freeSuballocationsToRegister)
{
return false;
}
VkDeviceSize lastSize = 0;
for(size_t i = 0; i < m_FreeSuballocationsBySize.size(); ++i)
{
VmaSuballocationList::iterator suballocItem = m_FreeSuballocationsBySize[i];
// Only free suballocations can be registered in m_FreeSuballocationsBySize.
if(suballocItem->type != VMA_SUBALLOCATION_TYPE_FREE)
{
return false;
}
// They must be sorted by size ascending.
if(suballocItem->size < lastSize)
{
return false;
}
lastSize = suballocItem->size;
}
// Check if totals match calculacted values.
if(!ValidateFreeSuballocationList() ||
(calculatedOffset != GetSize()) ||
(calculatedSumFreeSize != m_SumFreeSize) ||
(calculatedFreeCount != m_FreeCount))
{
return false;
}
return true;
}
VkDeviceSize VmaBlockMetadata_Generic::GetUnusedRangeSizeMax() const
{
if(!m_FreeSuballocationsBySize.empty())
{
return m_FreeSuballocationsBySize.back()->size;
}
else
{
return 0;
}
}
bool VmaBlockMetadata_Generic::IsEmpty() const
{
return (m_Suballocations.size() == 1) && (m_FreeCount == 1);
}
void VmaBlockMetadata_Generic::CalcAllocationStatInfo(VmaStatInfo& outInfo) const
{
outInfo.blockCount = 1;
const uint32_t rangeCount = (uint32_t)m_Suballocations.size();
outInfo.allocationCount = rangeCount - m_FreeCount;
outInfo.unusedRangeCount = m_FreeCount;
outInfo.unusedBytes = m_SumFreeSize;
outInfo.usedBytes = GetSize() - outInfo.unusedBytes;
outInfo.allocationSizeMin = UINT64_MAX;
outInfo.allocationSizeMax = 0;
outInfo.unusedRangeSizeMin = UINT64_MAX;
outInfo.unusedRangeSizeMax = 0;
for(VmaSuballocationList::const_iterator suballocItem = m_Suballocations.cbegin();
suballocItem != m_Suballocations.cend();
++suballocItem)
{
const VmaSuballocation& suballoc = *suballocItem;
if(suballoc.type != VMA_SUBALLOCATION_TYPE_FREE)
{
outInfo.allocationSizeMin = VMA_MIN(outInfo.allocationSizeMin, suballoc.size);
outInfo.allocationSizeMax = VMA_MAX(outInfo.allocationSizeMax, suballoc.size);
}
else
{
outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, suballoc.size);
outInfo.unusedRangeSizeMax = VMA_MAX(outInfo.unusedRangeSizeMax, suballoc.size);
}
}
}
void VmaBlockMetadata_Generic::AddPoolStats(VmaPoolStats& inoutStats) const
{
const uint32_t rangeCount = (uint32_t)m_Suballocations.size();
inoutStats.size += GetSize();
inoutStats.unusedSize += m_SumFreeSize;
inoutStats.allocationCount += rangeCount - m_FreeCount;
inoutStats.unusedRangeCount += m_FreeCount;
inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, GetUnusedRangeSizeMax());
}
#if VMA_STATS_STRING_ENABLED
void VmaBlockMetadata_Generic::PrintDetailedMap(class VmaJsonWriter& json) const
{
PrintDetailedMap_Begin(json,
m_SumFreeSize, // unusedBytes
m_Suballocations.size() - (size_t)m_FreeCount, // allocationCount
m_FreeCount); // unusedRangeCount
size_t i = 0;
for(VmaSuballocationList::const_iterator suballocItem = m_Suballocations.cbegin();
suballocItem != m_Suballocations.cend();
++suballocItem, ++i)
{
if(suballocItem->type == VMA_SUBALLOCATION_TYPE_FREE)
{
PrintDetailedMap_UnusedRange(json, suballocItem->offset, suballocItem->size);
}
else
{
PrintDetailedMap_Allocation(json, suballocItem->offset, suballocItem->hAllocation);
}
}
PrintDetailedMap_End(json);
}
#endif // #if VMA_STATS_STRING_ENABLED
/*
How many suitable free suballocations to analyze before choosing best one.
- Set to 1 to use First-Fit algorithm - first suitable free suballocation will
be chosen.
- Set to UINT32_MAX to use Best-Fit/Worst-Fit algorithm - all suitable free
suballocations will be analized and best one will be chosen.
- Any other value is also acceptable.
*/
//static const uint32_t MAX_SUITABLE_SUBALLOCATIONS_TO_CHECK = 8;
bool VmaBlockMetadata_Generic::CreateAllocationRequest(
uint32_t currentFrameIndex,
uint32_t frameInUseCount,
VkDeviceSize bufferImageGranularity,
VkDeviceSize allocSize,
VkDeviceSize allocAlignment,
bool upperAddress,
VmaSuballocationType allocType,
bool canMakeOtherLost,
VmaAllocationRequest* pAllocationRequest)
{
VMA_ASSERT(allocSize > 0);
VMA_ASSERT(!upperAddress);
VMA_ASSERT(allocType != VMA_SUBALLOCATION_TYPE_FREE);
VMA_ASSERT(pAllocationRequest != VMA_NULL);
VMA_HEAVY_ASSERT(Validate());
// There is not enough total free space in this block to fullfill the request: Early return.
if(canMakeOtherLost == false && m_SumFreeSize < allocSize + 2 * VMA_DEBUG_MARGIN)
{
return false;
}
// New algorithm, efficiently searching freeSuballocationsBySize.
const size_t freeSuballocCount = m_FreeSuballocationsBySize.size();
if(freeSuballocCount > 0)
{
if(VMA_BEST_FIT)
{
// Find first free suballocation with size not less than allocSize + 2 * VMA_DEBUG_MARGIN.
VmaSuballocationList::iterator* const it = VmaBinaryFindFirstNotLess(
m_FreeSuballocationsBySize.data(),
m_FreeSuballocationsBySize.data() + freeSuballocCount,
allocSize + 2 * VMA_DEBUG_MARGIN,
VmaSuballocationItemSizeLess());
size_t index = it - m_FreeSuballocationsBySize.data();
for(; index < freeSuballocCount; ++index)
{
if(CheckAllocation(
currentFrameIndex,
frameInUseCount,
bufferImageGranularity,
allocSize,
allocAlignment,
allocType,
m_FreeSuballocationsBySize[index],
false, // canMakeOtherLost
&pAllocationRequest->offset,
&pAllocationRequest->itemsToMakeLostCount,
&pAllocationRequest->sumFreeSize,
&pAllocationRequest->sumItemSize))
{
pAllocationRequest->item = m_FreeSuballocationsBySize[index];
return true;
}
}
}
else
{
// Search staring from biggest suballocations.
for(size_t index = freeSuballocCount; index--; )
{
if(CheckAllocation(
currentFrameIndex,
frameInUseCount,
bufferImageGranularity,
allocSize,
allocAlignment,
allocType,
m_FreeSuballocationsBySize[index],
false, // canMakeOtherLost
&pAllocationRequest->offset,
&pAllocationRequest->itemsToMakeLostCount,
&pAllocationRequest->sumFreeSize,
&pAllocationRequest->sumItemSize))
{
pAllocationRequest->item = m_FreeSuballocationsBySize[index];
return true;
}
}
}
}
if(canMakeOtherLost)
{
// Brute-force algorithm. TODO: Come up with something better.
pAllocationRequest->sumFreeSize = VK_WHOLE_SIZE;
pAllocationRequest->sumItemSize = VK_WHOLE_SIZE;
VmaAllocationRequest tmpAllocRequest = {};
for(VmaSuballocationList::iterator suballocIt = m_Suballocations.begin();
suballocIt != m_Suballocations.end();
++suballocIt)
{
if(suballocIt->type == VMA_SUBALLOCATION_TYPE_FREE ||
suballocIt->hAllocation->CanBecomeLost())
{
if(CheckAllocation(
currentFrameIndex,
frameInUseCount,
bufferImageGranularity,
allocSize,
allocAlignment,
allocType,
suballocIt,
canMakeOtherLost,
&tmpAllocRequest.offset,
&tmpAllocRequest.itemsToMakeLostCount,
&tmpAllocRequest.sumFreeSize,
&tmpAllocRequest.sumItemSize))
{
tmpAllocRequest.item = suballocIt;
if(tmpAllocRequest.CalcCost() < pAllocationRequest->CalcCost())
{
*pAllocationRequest = tmpAllocRequest;
}
}
}
}
if(pAllocationRequest->sumItemSize != VK_WHOLE_SIZE)
{
return true;
}
}
return false;
}
bool VmaBlockMetadata_Generic::MakeRequestedAllocationsLost(
uint32_t currentFrameIndex,
uint32_t frameInUseCount,
VmaAllocationRequest* pAllocationRequest)
{
while(pAllocationRequest->itemsToMakeLostCount > 0)
{
if(pAllocationRequest->item->type == VMA_SUBALLOCATION_TYPE_FREE)
{
++pAllocationRequest->item;
}
VMA_ASSERT(pAllocationRequest->item != m_Suballocations.end());
VMA_ASSERT(pAllocationRequest->item->hAllocation != VK_NULL_HANDLE);
VMA_ASSERT(pAllocationRequest->item->hAllocation->CanBecomeLost());
if(pAllocationRequest->item->hAllocation->MakeLost(currentFrameIndex, frameInUseCount))
{
pAllocationRequest->item = FreeSuballocation(pAllocationRequest->item);
--pAllocationRequest->itemsToMakeLostCount;
}
else
{
return false;
}
}
VMA_HEAVY_ASSERT(Validate());
VMA_ASSERT(pAllocationRequest->item != m_Suballocations.end());
VMA_ASSERT(pAllocationRequest->item->type == VMA_SUBALLOCATION_TYPE_FREE);
return true;
}
uint32_t VmaBlockMetadata_Generic::MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount)
{
uint32_t lostAllocationCount = 0;
for(VmaSuballocationList::iterator it = m_Suballocations.begin();
it != m_Suballocations.end();
++it)
{
if(it->type != VMA_SUBALLOCATION_TYPE_FREE &&
it->hAllocation->CanBecomeLost() &&
it->hAllocation->MakeLost(currentFrameIndex, frameInUseCount))
{
it = FreeSuballocation(it);
++lostAllocationCount;
}
}
return lostAllocationCount;
}
VkResult VmaBlockMetadata_Generic::CheckCorruption(const void* pBlockData)
{
for(VmaSuballocationList::iterator it = m_Suballocations.begin();
it != m_Suballocations.end();
++it)
{
if(it->type != VMA_SUBALLOCATION_TYPE_FREE)
{
if(!VmaValidateMagicValue(pBlockData, it->offset - VMA_DEBUG_MARGIN))
{
VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED BEFORE VALIDATED ALLOCATION!");
return VK_ERROR_VALIDATION_FAILED_EXT;
}
if(!VmaValidateMagicValue(pBlockData, it->offset + it->size))
{
VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER VALIDATED ALLOCATION!");
return VK_ERROR_VALIDATION_FAILED_EXT;
}
}
}
return VK_SUCCESS;
}
void VmaBlockMetadata_Generic::Alloc(
const VmaAllocationRequest& request,
VmaSuballocationType type,
VkDeviceSize allocSize,
bool upperAddress,
VmaAllocation hAllocation)
{
VMA_ASSERT(!upperAddress);
VMA_ASSERT(request.item != m_Suballocations.end());
VmaSuballocation& suballoc = *request.item;
// Given suballocation is a free block.
VMA_ASSERT(suballoc.type == VMA_SUBALLOCATION_TYPE_FREE);
// Given offset is inside this suballocation.
VMA_ASSERT(request.offset >= suballoc.offset);
const VkDeviceSize paddingBegin = request.offset - suballoc.offset;
VMA_ASSERT(suballoc.size >= paddingBegin + allocSize);
const VkDeviceSize paddingEnd = suballoc.size - paddingBegin - allocSize;
// Unregister this free suballocation from m_FreeSuballocationsBySize and update
// it to become used.
UnregisterFreeSuballocation(request.item);
suballoc.offset = request.offset;
suballoc.size = allocSize;
suballoc.type = type;
suballoc.hAllocation = hAllocation;
// If there are any free bytes remaining at the end, insert new free suballocation after current one.
if(paddingEnd)
{
VmaSuballocation paddingSuballoc = {};
paddingSuballoc.offset = request.offset + allocSize;
paddingSuballoc.size = paddingEnd;
paddingSuballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
VmaSuballocationList::iterator next = request.item;
++next;
const VmaSuballocationList::iterator paddingEndItem =
m_Suballocations.insert(next, paddingSuballoc);
RegisterFreeSuballocation(paddingEndItem);
}
// If there are any free bytes remaining at the beginning, insert new free suballocation before current one.
if(paddingBegin)
{
VmaSuballocation paddingSuballoc = {};
paddingSuballoc.offset = request.offset - paddingBegin;
paddingSuballoc.size = paddingBegin;
paddingSuballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
const VmaSuballocationList::iterator paddingBeginItem =
m_Suballocations.insert(request.item, paddingSuballoc);
RegisterFreeSuballocation(paddingBeginItem);
}
// Update totals.
m_FreeCount = m_FreeCount - 1;
if(paddingBegin > 0)
{
++m_FreeCount;
}
if(paddingEnd > 0)
{
++m_FreeCount;
}
m_SumFreeSize -= allocSize;
}
void VmaBlockMetadata_Generic::Free(const VmaAllocation allocation)
{
for(VmaSuballocationList::iterator suballocItem = m_Suballocations.begin();
suballocItem != m_Suballocations.end();
++suballocItem)
{
VmaSuballocation& suballoc = *suballocItem;
if(suballoc.hAllocation == allocation)
{
FreeSuballocation(suballocItem);
VMA_HEAVY_ASSERT(Validate());
return;
}
}
VMA_ASSERT(0 && "Not found!");
}
void VmaBlockMetadata_Generic::FreeAtOffset(VkDeviceSize offset)
{
for(VmaSuballocationList::iterator suballocItem = m_Suballocations.begin();
suballocItem != m_Suballocations.end();
++suballocItem)
{
VmaSuballocation& suballoc = *suballocItem;
if(suballoc.offset == offset)
{
FreeSuballocation(suballocItem);
return;
}
}
VMA_ASSERT(0 && "Not found!");
}
bool VmaBlockMetadata_Generic::ValidateFreeSuballocationList() const
{
VkDeviceSize lastSize = 0;
for(size_t i = 0, count = m_FreeSuballocationsBySize.size(); i < count; ++i)
{
const VmaSuballocationList::iterator it = m_FreeSuballocationsBySize[i];
if(it->type != VMA_SUBALLOCATION_TYPE_FREE)
{
VMA_ASSERT(0);
return false;
}
if(it->size < VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER)
{
VMA_ASSERT(0);
return false;
}
if(it->size < lastSize)
{
VMA_ASSERT(0);
return false;
}
lastSize = it->size;
}
return true;
}
bool VmaBlockMetadata_Generic::CheckAllocation(
uint32_t currentFrameIndex,
uint32_t frameInUseCount,
VkDeviceSize bufferImageGranularity,
VkDeviceSize allocSize,
VkDeviceSize allocAlignment,
VmaSuballocationType allocType,
VmaSuballocationList::const_iterator suballocItem,
bool canMakeOtherLost,
VkDeviceSize* pOffset,
size_t* itemsToMakeLostCount,
VkDeviceSize* pSumFreeSize,
VkDeviceSize* pSumItemSize) const
{
VMA_ASSERT(allocSize > 0);
VMA_ASSERT(allocType != VMA_SUBALLOCATION_TYPE_FREE);
VMA_ASSERT(suballocItem != m_Suballocations.cend());
VMA_ASSERT(pOffset != VMA_NULL);
*itemsToMakeLostCount = 0;
*pSumFreeSize = 0;
*pSumItemSize = 0;
if(canMakeOtherLost)
{
if(suballocItem->type == VMA_SUBALLOCATION_TYPE_FREE)
{
*pSumFreeSize = suballocItem->size;
}
else
{
if(suballocItem->hAllocation->CanBecomeLost() &&
suballocItem->hAllocation->GetLastUseFrameIndex() + frameInUseCount < currentFrameIndex)
{
++*itemsToMakeLostCount;
*pSumItemSize = suballocItem->size;
}
else
{
return false;
}
}
// Remaining size is too small for this request: Early return.
if(GetSize() - suballocItem->offset < allocSize)
{
return false;
}
// Start from offset equal to beginning of this suballocation.
*pOffset = suballocItem->offset;
// Apply VMA_DEBUG_MARGIN at the beginning.
if(VMA_DEBUG_MARGIN > 0)
{
*pOffset += VMA_DEBUG_MARGIN;
}
// Apply alignment.
*pOffset = VmaAlignUp(*pOffset, allocAlignment);
// Check previous suballocations for BufferImageGranularity conflicts.
// Make bigger alignment if necessary.
if(bufferImageGranularity > 1)
{
bool bufferImageGranularityConflict = false;
VmaSuballocationList::const_iterator prevSuballocItem = suballocItem;
while(prevSuballocItem != m_Suballocations.cbegin())
{
--prevSuballocItem;
const VmaSuballocation& prevSuballoc = *prevSuballocItem;
if(VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, *pOffset, bufferImageGranularity))
{
if(VmaIsBufferImageGranularityConflict(prevSuballoc.type, allocType))
{
bufferImageGranularityConflict = true;
break;
}
}
else
// Already on previous page.
break;
}
if(bufferImageGranularityConflict)
{
*pOffset = VmaAlignUp(*pOffset, bufferImageGranularity);
}
}
// Now that we have final *pOffset, check if we are past suballocItem.
// If yes, return false - this function should be called for another suballocItem as starting point.
if(*pOffset >= suballocItem->offset + suballocItem->size)
{
return false;
}
// Calculate padding at the beginning based on current offset.
const VkDeviceSize paddingBegin = *pOffset - suballocItem->offset;
// Calculate required margin at the end.
const VkDeviceSize requiredEndMargin = VMA_DEBUG_MARGIN;
const VkDeviceSize totalSize = paddingBegin + allocSize + requiredEndMargin;
// Another early return check.
if(suballocItem->offset + totalSize > GetSize())
{
return false;
}
// Advance lastSuballocItem until desired size is reached.
// Update itemsToMakeLostCount.
VmaSuballocationList::const_iterator lastSuballocItem = suballocItem;
if(totalSize > suballocItem->size)
{
VkDeviceSize remainingSize = totalSize - suballocItem->size;
while(remainingSize > 0)
{
++lastSuballocItem;
if(lastSuballocItem == m_Suballocations.cend())
{
return false;
}
if(lastSuballocItem->type == VMA_SUBALLOCATION_TYPE_FREE)
{
*pSumFreeSize += lastSuballocItem->size;
}
else
{
VMA_ASSERT(lastSuballocItem->hAllocation != VK_NULL_HANDLE);
if(lastSuballocItem->hAllocation->CanBecomeLost() &&
lastSuballocItem->hAllocation->GetLastUseFrameIndex() + frameInUseCount < currentFrameIndex)
{
++*itemsToMakeLostCount;
*pSumItemSize += lastSuballocItem->size;
}
else
{
return false;
}
}
remainingSize = (lastSuballocItem->size < remainingSize) ?
remainingSize - lastSuballocItem->size : 0;
}
}
// Check next suballocations for BufferImageGranularity conflicts.
// If conflict exists, we must mark more allocations lost or fail.
if(bufferImageGranularity > 1)
{
VmaSuballocationList::const_iterator nextSuballocItem = lastSuballocItem;
++nextSuballocItem;
while(nextSuballocItem != m_Suballocations.cend())
{
const VmaSuballocation& nextSuballoc = *nextSuballocItem;
if(VmaBlocksOnSamePage(*pOffset, allocSize, nextSuballoc.offset, bufferImageGranularity))
{
if(VmaIsBufferImageGranularityConflict(allocType, nextSuballoc.type))
{
VMA_ASSERT(nextSuballoc.hAllocation != VK_NULL_HANDLE);
if(nextSuballoc.hAllocation->CanBecomeLost() &&
nextSuballoc.hAllocation->GetLastUseFrameIndex() + frameInUseCount < currentFrameIndex)
{
++*itemsToMakeLostCount;
}
else
{
return false;
}
}
}
else
{
// Already on next page.
break;
}
++nextSuballocItem;
}
}
}
else
{
const VmaSuballocation& suballoc = *suballocItem;
VMA_ASSERT(suballoc.type == VMA_SUBALLOCATION_TYPE_FREE);
*pSumFreeSize = suballoc.size;
// Size of this suballocation is too small for this request: Early return.
if(suballoc.size < allocSize)
{
return false;
}
// Start from offset equal to beginning of this suballocation.
*pOffset = suballoc.offset;
// Apply VMA_DEBUG_MARGIN at the beginning.
if(VMA_DEBUG_MARGIN > 0)
{
*pOffset += VMA_DEBUG_MARGIN;
}
// Apply alignment.
*pOffset = VmaAlignUp(*pOffset, allocAlignment);
// Check previous suballocations for BufferImageGranularity conflicts.
// Make bigger alignment if necessary.
if(bufferImageGranularity > 1)
{
bool bufferImageGranularityConflict = false;
VmaSuballocationList::const_iterator prevSuballocItem = suballocItem;
while(prevSuballocItem != m_Suballocations.cbegin())
{
--prevSuballocItem;
const VmaSuballocation& prevSuballoc = *prevSuballocItem;
if(VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, *pOffset, bufferImageGranularity))
{
if(VmaIsBufferImageGranularityConflict(prevSuballoc.type, allocType))
{
bufferImageGranularityConflict = true;
break;
}
}
else
// Already on previous page.
break;
}
if(bufferImageGranularityConflict)
{
*pOffset = VmaAlignUp(*pOffset, bufferImageGranularity);
}
}
// Calculate padding at the beginning based on current offset.
const VkDeviceSize paddingBegin = *pOffset - suballoc.offset;
// Calculate required margin at the end.
const VkDeviceSize requiredEndMargin = VMA_DEBUG_MARGIN;
// Fail if requested size plus margin before and after is bigger than size of this suballocation.
if(paddingBegin + allocSize + requiredEndMargin > suballoc.size)
{
return false;
}
// Check next suballocations for BufferImageGranularity conflicts.
// If conflict exists, allocation cannot be made here.
if(bufferImageGranularity > 1)
{
VmaSuballocationList::const_iterator nextSuballocItem = suballocItem;
++nextSuballocItem;
while(nextSuballocItem != m_Suballocations.cend())
{
const VmaSuballocation& nextSuballoc = *nextSuballocItem;
if(VmaBlocksOnSamePage(*pOffset, allocSize, nextSuballoc.offset, bufferImageGranularity))
{
if(VmaIsBufferImageGranularityConflict(allocType, nextSuballoc.type))
{
return false;
}
}
else
{
// Already on next page.
break;
}
++nextSuballocItem;
}
}
}
// All tests passed: Success. pOffset is already filled.
return true;
}
void VmaBlockMetadata_Generic::MergeFreeWithNext(VmaSuballocationList::iterator item)
{
VMA_ASSERT(item != m_Suballocations.end());
VMA_ASSERT(item->type == VMA_SUBALLOCATION_TYPE_FREE);
VmaSuballocationList::iterator nextItem = item;
++nextItem;
VMA_ASSERT(nextItem != m_Suballocations.end());
VMA_ASSERT(nextItem->type == VMA_SUBALLOCATION_TYPE_FREE);
item->size += nextItem->size;
--m_FreeCount;
m_Suballocations.erase(nextItem);
}
VmaSuballocationList::iterator VmaBlockMetadata_Generic::FreeSuballocation(VmaSuballocationList::iterator suballocItem)
{
// Change this suballocation to be marked as free.
VmaSuballocation& suballoc = *suballocItem;
suballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
suballoc.hAllocation = VK_NULL_HANDLE;
// Update totals.
++m_FreeCount;
m_SumFreeSize += suballoc.size;
// Merge with previous and/or next suballocation if it's also free.
bool mergeWithNext = false;
bool mergeWithPrev = false;
VmaSuballocationList::iterator nextItem = suballocItem;
++nextItem;
if((nextItem != m_Suballocations.end()) && (nextItem->type == VMA_SUBALLOCATION_TYPE_FREE))
{
mergeWithNext = true;
}
VmaSuballocationList::iterator prevItem = suballocItem;
if(suballocItem != m_Suballocations.begin())
{
--prevItem;
if(prevItem->type == VMA_SUBALLOCATION_TYPE_FREE)
{
mergeWithPrev = true;
}
}
if(mergeWithNext)
{
UnregisterFreeSuballocation(nextItem);
MergeFreeWithNext(suballocItem);
}
if(mergeWithPrev)
{
UnregisterFreeSuballocation(prevItem);
MergeFreeWithNext(prevItem);
RegisterFreeSuballocation(prevItem);
return prevItem;
}
else
{
RegisterFreeSuballocation(suballocItem);
return suballocItem;
}
}
void VmaBlockMetadata_Generic::RegisterFreeSuballocation(VmaSuballocationList::iterator item)
{
VMA_ASSERT(item->type == VMA_SUBALLOCATION_TYPE_FREE);
VMA_ASSERT(item->size > 0);
// You may want to enable this validation at the beginning or at the end of
// this function, depending on what do you want to check.
VMA_HEAVY_ASSERT(ValidateFreeSuballocationList());
if(item->size >= VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER)
{
if(m_FreeSuballocationsBySize.empty())
{
m_FreeSuballocationsBySize.push_back(item);
}
else
{
VmaVectorInsertSorted<VmaSuballocationItemSizeLess>(m_FreeSuballocationsBySize, item);
}
}
//VMA_HEAVY_ASSERT(ValidateFreeSuballocationList());
}
void VmaBlockMetadata_Generic::UnregisterFreeSuballocation(VmaSuballocationList::iterator item)
{
VMA_ASSERT(item->type == VMA_SUBALLOCATION_TYPE_FREE);
VMA_ASSERT(item->size > 0);
// You may want to enable this validation at the beginning or at the end of
// this function, depending on what do you want to check.
VMA_HEAVY_ASSERT(ValidateFreeSuballocationList());
if(item->size >= VMA_MIN_FREE_SUBALLOCATION_SIZE_TO_REGISTER)
{
VmaSuballocationList::iterator* const it = VmaBinaryFindFirstNotLess(
m_FreeSuballocationsBySize.data(),
m_FreeSuballocationsBySize.data() + m_FreeSuballocationsBySize.size(),
item,
VmaSuballocationItemSizeLess());
for(size_t index = it - m_FreeSuballocationsBySize.data();
index < m_FreeSuballocationsBySize.size();
++index)
{
if(m_FreeSuballocationsBySize[index] == item)
{
VmaVectorRemove(m_FreeSuballocationsBySize, index);
return;
}
VMA_ASSERT((m_FreeSuballocationsBySize[index]->size == item->size) && "Not found.");
}
VMA_ASSERT(0 && "Not found.");
}
//VMA_HEAVY_ASSERT(ValidateFreeSuballocationList());
}
////////////////////////////////////////////////////////////////////////////////
// class VmaBlockMetadata_Linear
VmaBlockMetadata_Linear::VmaBlockMetadata_Linear(VmaAllocator hAllocator) :
m_SumFreeSize(0),
m_Suballocations0(VmaStlAllocator<VmaSuballocation>(hAllocator->GetAllocationCallbacks())),
m_Suballocations1(VmaStlAllocator<VmaSuballocation>(hAllocator->GetAllocationCallbacks())),
m_1stVectorIndex(0),
m_2ndVectorMode(SECOND_VECTOR_EMPTY),
m_1stNullItemsBeginCount(0),
m_1stNullItemsMiddleCount(0),
m_2ndNullItemsCount(0)
{
}
VmaBlockMetadata_Linear::~VmaBlockMetadata_Linear()
{
}
void VmaBlockMetadata_Linear::Init(VkDeviceSize size)
{
VmaBlockMetadata::Init(size);
m_SumFreeSize = size;
}
bool VmaBlockMetadata_Linear::Validate() const
{
const SuballocationVectorType& suballocations1st = AccessSuballocations1st();
const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
if(suballocations2nd.empty() != (m_2ndVectorMode == SECOND_VECTOR_EMPTY))
{
return false;
}
if(suballocations1st.empty() && !suballocations2nd.empty() &&
m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
{
return false;
}
if(!suballocations1st.empty())
{
// Null item at the beginning should be accounted into m_1stNullItemsBeginCount.
if(suballocations1st[m_1stNullItemsBeginCount].hAllocation == VK_NULL_HANDLE)
{
return false;
}
// Null item at the end should be just pop_back().
if(suballocations1st.back().hAllocation == VK_NULL_HANDLE)
{
return false;
}
}
if(!suballocations2nd.empty())
{
// Null item at the end should be just pop_back().
if(suballocations2nd.back().hAllocation == VK_NULL_HANDLE)
{
return false;
}
}
if(m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount > suballocations1st.size())
{
return false;
}
if(m_2ndNullItemsCount > suballocations2nd.size())
{
return false;
}
VkDeviceSize sumUsedSize = 0;
const size_t suballoc1stCount = suballocations1st.size();
VkDeviceSize offset = VMA_DEBUG_MARGIN;
if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
{
const size_t suballoc2ndCount = suballocations2nd.size();
size_t nullItem2ndCount = 0;
for(size_t i = 0; i < suballoc2ndCount; ++i)
{
const VmaSuballocation& suballoc = suballocations2nd[i];
const bool currFree = (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE);
if(currFree != (suballoc.hAllocation == VK_NULL_HANDLE))
{
return false;
}
if(suballoc.offset < offset)
{
return false;
}
if(!currFree)
{
if(suballoc.hAllocation->GetOffset() != suballoc.offset)
{
return false;
}
if(suballoc.hAllocation->GetSize() != suballoc.size)
{
return false;
}
sumUsedSize += suballoc.size;
}
else
{
++nullItem2ndCount;
}
offset = suballoc.offset + suballoc.size + VMA_DEBUG_MARGIN;
}
if(nullItem2ndCount != m_2ndNullItemsCount)
{
return false;
}
}
for(size_t i = 0; i < m_1stNullItemsBeginCount; ++i)
{
const VmaSuballocation& suballoc = suballocations1st[i];
if(suballoc.type != VMA_SUBALLOCATION_TYPE_FREE ||
suballoc.hAllocation != VK_NULL_HANDLE)
{
return false;
}
}
size_t nullItem1stCount = m_1stNullItemsBeginCount;
for(size_t i = m_1stNullItemsBeginCount; i < suballoc1stCount; ++i)
{
const VmaSuballocation& suballoc = suballocations1st[i];
const bool currFree = (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE);
if(currFree != (suballoc.hAllocation == VK_NULL_HANDLE))
{
return false;
}
if(suballoc.offset < offset)
{
return false;
}
if(i < m_1stNullItemsBeginCount && !currFree)
{
return false;
}
if(!currFree)
{
if(suballoc.hAllocation->GetOffset() != suballoc.offset)
{
return false;
}
if(suballoc.hAllocation->GetSize() != suballoc.size)
{
return false;
}
sumUsedSize += suballoc.size;
}
else
{
++nullItem1stCount;
}
offset = suballoc.offset + suballoc.size + VMA_DEBUG_MARGIN;
}
if(nullItem1stCount != m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount)
{
return false;
}
if(m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
{
const size_t suballoc2ndCount = suballocations2nd.size();
size_t nullItem2ndCount = 0;
for(size_t i = suballoc2ndCount; i--; )
{
const VmaSuballocation& suballoc = suballocations2nd[i];
const bool currFree = (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE);
if(currFree != (suballoc.hAllocation == VK_NULL_HANDLE))
{
return false;
}
if(suballoc.offset < offset)
{
return false;
}
if(!currFree)
{
if(suballoc.hAllocation->GetOffset() != suballoc.offset)
{
return false;
}
if(suballoc.hAllocation->GetSize() != suballoc.size)
{
return false;
}
sumUsedSize += suballoc.size;
}
else
{
++nullItem2ndCount;
}
offset = suballoc.offset + suballoc.size + VMA_DEBUG_MARGIN;
}
if(nullItem2ndCount != m_2ndNullItemsCount)
{
return false;
}
}
if(offset > GetSize())
{
return false;
}
if(m_SumFreeSize != GetSize() - sumUsedSize)
{
return false;
}
return true;
}
size_t VmaBlockMetadata_Linear::GetAllocationCount() const
{
return AccessSuballocations1st().size() - (m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount) +
AccessSuballocations2nd().size() - m_2ndNullItemsCount;
}
VkDeviceSize VmaBlockMetadata_Linear::GetUnusedRangeSizeMax() const
{
const VkDeviceSize size = GetSize();
/*
We don't consider gaps inside allocation vectors with freed allocations because
they are not suitable for reuse in linear allocator. We consider only space that
is available for new allocations.
*/
if(IsEmpty())
{
return size;
}
const SuballocationVectorType& suballocations1st = AccessSuballocations1st();
switch(m_2ndVectorMode)
{
case SECOND_VECTOR_EMPTY:
/*
Available space is after end of 1st, as well as before beginning of 1st (which
whould make it a ring buffer).
*/
{
const size_t suballocations1stCount = suballocations1st.size();
VMA_ASSERT(suballocations1stCount > m_1stNullItemsBeginCount);
const VmaSuballocation& firstSuballoc = suballocations1st[m_1stNullItemsBeginCount];
const VmaSuballocation& lastSuballoc = suballocations1st[suballocations1stCount - 1];
return VMA_MAX(
firstSuballoc.offset,
size - (lastSuballoc.offset + lastSuballoc.size));
}
break;
case SECOND_VECTOR_RING_BUFFER:
/*
Available space is only between end of 2nd and beginning of 1st.
*/
{
const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
const VmaSuballocation& lastSuballoc2nd = suballocations2nd.back();
const VmaSuballocation& firstSuballoc1st = suballocations1st[m_1stNullItemsBeginCount];
return firstSuballoc1st.offset - (lastSuballoc2nd.offset + lastSuballoc2nd.size);
}
break;
case SECOND_VECTOR_DOUBLE_STACK:
/*
Available space is only between end of 1st and top of 2nd.
*/
{
const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
const VmaSuballocation& topSuballoc2nd = suballocations2nd.back();
const VmaSuballocation& lastSuballoc1st = suballocations1st.back();
return topSuballoc2nd.offset - (lastSuballoc1st.offset + lastSuballoc1st.size);
}
break;
default:
VMA_ASSERT(0);
return 0;
}
}
void VmaBlockMetadata_Linear::CalcAllocationStatInfo(VmaStatInfo& outInfo) const
{
const VkDeviceSize size = GetSize();
const SuballocationVectorType& suballocations1st = AccessSuballocations1st();
const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
const size_t suballoc1stCount = suballocations1st.size();
const size_t suballoc2ndCount = suballocations2nd.size();
outInfo.blockCount = 1;
outInfo.allocationCount = (uint32_t)GetAllocationCount();
outInfo.unusedRangeCount = 0;
outInfo.usedBytes = 0;
outInfo.allocationSizeMin = UINT64_MAX;
outInfo.allocationSizeMax = 0;
outInfo.unusedRangeSizeMin = UINT64_MAX;
outInfo.unusedRangeSizeMax = 0;
VkDeviceSize lastOffset = 0;
if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
{
const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset;
size_t nextAlloc2ndIndex = 0;
while(lastOffset < freeSpace2ndTo1stEnd)
{
// Find next non-null allocation or move nextAllocIndex to the end.
while(nextAlloc2ndIndex < suballoc2ndCount &&
suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE)
{
++nextAlloc2ndIndex;
}
// Found non-null allocation.
if(nextAlloc2ndIndex < suballoc2ndCount)
{
const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
// 1. Process free space before this allocation.
if(lastOffset < suballoc.offset)
{
// There is free space from lastOffset to suballoc.offset.
const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
++outInfo.unusedRangeCount;
outInfo.unusedBytes += unusedRangeSize;
outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, unusedRangeSize);
outInfo.unusedRangeSizeMax = VMA_MIN(outInfo.unusedRangeSizeMax, unusedRangeSize);
}
// 2. Process this allocation.
// There is allocation with suballoc.offset, suballoc.size.
outInfo.usedBytes += suballoc.size;
outInfo.allocationSizeMin = VMA_MIN(outInfo.allocationSizeMin, suballoc.size);
outInfo.allocationSizeMax = VMA_MIN(outInfo.allocationSizeMax, suballoc.size);
// 3. Prepare for next iteration.
lastOffset = suballoc.offset + suballoc.size;
++nextAlloc2ndIndex;
}
// We are at the end.
else
{
// There is free space from lastOffset to freeSpace2ndTo1stEnd.
if(lastOffset < freeSpace2ndTo1stEnd)
{
const VkDeviceSize unusedRangeSize = freeSpace2ndTo1stEnd - lastOffset;
++outInfo.unusedRangeCount;
outInfo.unusedBytes += unusedRangeSize;
outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, unusedRangeSize);
outInfo.unusedRangeSizeMax = VMA_MIN(outInfo.unusedRangeSizeMax, unusedRangeSize);
}
// End of loop.
lastOffset = freeSpace2ndTo1stEnd;
}
}
}
size_t nextAlloc1stIndex = m_1stNullItemsBeginCount;
const VkDeviceSize freeSpace1stTo2ndEnd =
m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ? suballocations2nd.back().offset : size;
while(lastOffset < freeSpace1stTo2ndEnd)
{
// Find next non-null allocation or move nextAllocIndex to the end.
while(nextAlloc1stIndex < suballoc1stCount &&
suballocations1st[nextAlloc1stIndex].hAllocation == VK_NULL_HANDLE)
{
++nextAlloc1stIndex;
}
// Found non-null allocation.
if(nextAlloc1stIndex < suballoc1stCount)
{
const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex];
// 1. Process free space before this allocation.
if(lastOffset < suballoc.offset)
{
// There is free space from lastOffset to suballoc.offset.
const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
++outInfo.unusedRangeCount;
outInfo.unusedBytes += unusedRangeSize;
outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, unusedRangeSize);
outInfo.unusedRangeSizeMax = VMA_MIN(outInfo.unusedRangeSizeMax, unusedRangeSize);
}
// 2. Process this allocation.
// There is allocation with suballoc.offset, suballoc.size.
outInfo.usedBytes += suballoc.size;
outInfo.allocationSizeMin = VMA_MIN(outInfo.allocationSizeMin, suballoc.size);
outInfo.allocationSizeMax = VMA_MIN(outInfo.allocationSizeMax, suballoc.size);
// 3. Prepare for next iteration.
lastOffset = suballoc.offset + suballoc.size;
++nextAlloc1stIndex;
}
// We are at the end.
else
{
// There is free space from lastOffset to freeSpace1stTo2ndEnd.
if(lastOffset < freeSpace1stTo2ndEnd)
{
const VkDeviceSize unusedRangeSize = freeSpace1stTo2ndEnd - lastOffset;
++outInfo.unusedRangeCount;
outInfo.unusedBytes += unusedRangeSize;
outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, unusedRangeSize);
outInfo.unusedRangeSizeMax = VMA_MIN(outInfo.unusedRangeSizeMax, unusedRangeSize);
}
// End of loop.
lastOffset = freeSpace1stTo2ndEnd;
}
}
if(m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
{
size_t nextAlloc2ndIndex = suballocations2nd.size() - 1;
while(lastOffset < size)
{
// Find next non-null allocation or move nextAllocIndex to the end.
while(nextAlloc2ndIndex != SIZE_MAX &&
suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE)
{
--nextAlloc2ndIndex;
}
// Found non-null allocation.
if(nextAlloc2ndIndex != SIZE_MAX)
{
const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
// 1. Process free space before this allocation.
if(lastOffset < suballoc.offset)
{
// There is free space from lastOffset to suballoc.offset.
const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
++outInfo.unusedRangeCount;
outInfo.unusedBytes += unusedRangeSize;
outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, unusedRangeSize);
outInfo.unusedRangeSizeMax = VMA_MIN(outInfo.unusedRangeSizeMax, unusedRangeSize);
}
// 2. Process this allocation.
// There is allocation with suballoc.offset, suballoc.size.
outInfo.usedBytes += suballoc.size;
outInfo.allocationSizeMin = VMA_MIN(outInfo.allocationSizeMin, suballoc.size);
outInfo.allocationSizeMax = VMA_MIN(outInfo.allocationSizeMax, suballoc.size);
// 3. Prepare for next iteration.
lastOffset = suballoc.offset + suballoc.size;
--nextAlloc2ndIndex;
}
// We are at the end.
else
{
// There is free space from lastOffset to size.
if(lastOffset < size)
{
const VkDeviceSize unusedRangeSize = size - lastOffset;
++outInfo.unusedRangeCount;
outInfo.unusedBytes += unusedRangeSize;
outInfo.unusedRangeSizeMin = VMA_MIN(outInfo.unusedRangeSizeMin, unusedRangeSize);
outInfo.unusedRangeSizeMax = VMA_MIN(outInfo.unusedRangeSizeMax, unusedRangeSize);
}
// End of loop.
lastOffset = size;
}
}
}
outInfo.unusedBytes = size - outInfo.usedBytes;
}
void VmaBlockMetadata_Linear::AddPoolStats(VmaPoolStats& inoutStats) const
{
const SuballocationVectorType& suballocations1st = AccessSuballocations1st();
const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
const VkDeviceSize size = GetSize();
const size_t suballoc1stCount = suballocations1st.size();
const size_t suballoc2ndCount = suballocations2nd.size();
inoutStats.size += size;
VkDeviceSize lastOffset = 0;
if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
{
const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset;
size_t nextAlloc2ndIndex = m_1stNullItemsBeginCount;
while(lastOffset < freeSpace2ndTo1stEnd)
{
// Find next non-null allocation or move nextAlloc2ndIndex to the end.
while(nextAlloc2ndIndex < suballoc2ndCount &&
suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE)
{
++nextAlloc2ndIndex;
}
// Found non-null allocation.
if(nextAlloc2ndIndex < suballoc2ndCount)
{
const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
// 1. Process free space before this allocation.
if(lastOffset < suballoc.offset)
{
// There is free space from lastOffset to suballoc.offset.
const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
inoutStats.unusedSize += unusedRangeSize;
++inoutStats.unusedRangeCount;
inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, unusedRangeSize);
}
// 2. Process this allocation.
// There is allocation with suballoc.offset, suballoc.size.
++inoutStats.allocationCount;
// 3. Prepare for next iteration.
lastOffset = suballoc.offset + suballoc.size;
++nextAlloc2ndIndex;
}
// We are at the end.
else
{
if(lastOffset < freeSpace2ndTo1stEnd)
{
// There is free space from lastOffset to freeSpace2ndTo1stEnd.
const VkDeviceSize unusedRangeSize = freeSpace2ndTo1stEnd - lastOffset;
inoutStats.unusedSize += unusedRangeSize;
++inoutStats.unusedRangeCount;
inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, unusedRangeSize);
}
// End of loop.
lastOffset = freeSpace2ndTo1stEnd;
}
}
}
size_t nextAlloc1stIndex = m_1stNullItemsBeginCount;
const VkDeviceSize freeSpace1stTo2ndEnd =
m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ? suballocations2nd.back().offset : size;
while(lastOffset < freeSpace1stTo2ndEnd)
{
// Find next non-null allocation or move nextAllocIndex to the end.
while(nextAlloc1stIndex < suballoc1stCount &&
suballocations1st[nextAlloc1stIndex].hAllocation == VK_NULL_HANDLE)
{
++nextAlloc1stIndex;
}
// Found non-null allocation.
if(nextAlloc1stIndex < suballoc1stCount)
{
const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex];
// 1. Process free space before this allocation.
if(lastOffset < suballoc.offset)
{
// There is free space from lastOffset to suballoc.offset.
const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
inoutStats.unusedSize += unusedRangeSize;
++inoutStats.unusedRangeCount;
inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, unusedRangeSize);
}
// 2. Process this allocation.
// There is allocation with suballoc.offset, suballoc.size.
++inoutStats.allocationCount;
// 3. Prepare for next iteration.
lastOffset = suballoc.offset + suballoc.size;
++nextAlloc1stIndex;
}
// We are at the end.
else
{
if(lastOffset < freeSpace1stTo2ndEnd)
{
// There is free space from lastOffset to freeSpace1stTo2ndEnd.
const VkDeviceSize unusedRangeSize = freeSpace1stTo2ndEnd - lastOffset;
inoutStats.unusedSize += unusedRangeSize;
++inoutStats.unusedRangeCount;
inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, unusedRangeSize);
}
// End of loop.
lastOffset = freeSpace1stTo2ndEnd;
}
}
if(m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
{
size_t nextAlloc2ndIndex = suballocations2nd.size() - 1;
while(lastOffset < size)
{
// Find next non-null allocation or move nextAlloc2ndIndex to the end.
while(nextAlloc2ndIndex != SIZE_MAX &&
suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE)
{
--nextAlloc2ndIndex;
}
// Found non-null allocation.
if(nextAlloc2ndIndex != SIZE_MAX)
{
const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
// 1. Process free space before this allocation.
if(lastOffset < suballoc.offset)
{
// There is free space from lastOffset to suballoc.offset.
const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
inoutStats.unusedSize += unusedRangeSize;
++inoutStats.unusedRangeCount;
inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, unusedRangeSize);
}
// 2. Process this allocation.
// There is allocation with suballoc.offset, suballoc.size.
++inoutStats.allocationCount;
// 3. Prepare for next iteration.
lastOffset = suballoc.offset + suballoc.size;
--nextAlloc2ndIndex;
}
// We are at the end.
else
{
if(lastOffset < size)
{
// There is free space from lastOffset to size.
const VkDeviceSize unusedRangeSize = size - lastOffset;
inoutStats.unusedSize += unusedRangeSize;
++inoutStats.unusedRangeCount;
inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, unusedRangeSize);
}
// End of loop.
lastOffset = size;
}
}
}
}
#if VMA_STATS_STRING_ENABLED
void VmaBlockMetadata_Linear::PrintDetailedMap(class VmaJsonWriter& json) const
{
const VkDeviceSize size = GetSize();
const SuballocationVectorType& suballocations1st = AccessSuballocations1st();
const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
const size_t suballoc1stCount = suballocations1st.size();
const size_t suballoc2ndCount = suballocations2nd.size();
// FIRST PASS
size_t unusedRangeCount = 0;
VkDeviceSize usedBytes = 0;
VkDeviceSize lastOffset = 0;
size_t alloc2ndCount = 0;
if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
{
const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset;
size_t nextAlloc2ndIndex = 0;
while(lastOffset < freeSpace2ndTo1stEnd)
{
// Find next non-null allocation or move nextAlloc2ndIndex to the end.
while(nextAlloc2ndIndex < suballoc2ndCount &&
suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE)
{
++nextAlloc2ndIndex;
}
// Found non-null allocation.
if(nextAlloc2ndIndex < suballoc2ndCount)
{
const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
// 1. Process free space before this allocation.
if(lastOffset < suballoc.offset)
{
// There is free space from lastOffset to suballoc.offset.
++unusedRangeCount;
}
// 2. Process this allocation.
// There is allocation with suballoc.offset, suballoc.size.
++alloc2ndCount;
usedBytes += suballoc.size;
// 3. Prepare for next iteration.
lastOffset = suballoc.offset + suballoc.size;
++nextAlloc2ndIndex;
}
// We are at the end.
else
{
if(lastOffset < freeSpace2ndTo1stEnd)
{
// There is free space from lastOffset to freeSpace2ndTo1stEnd.
++unusedRangeCount;
}
// End of loop.
lastOffset = freeSpace2ndTo1stEnd;
}
}
}
size_t nextAlloc1stIndex = m_1stNullItemsBeginCount;
size_t alloc1stCount = 0;
const VkDeviceSize freeSpace1stTo2ndEnd =
m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ? suballocations2nd.back().offset : size;
while(lastOffset < freeSpace1stTo2ndEnd)
{
// Find next non-null allocation or move nextAllocIndex to the end.
while(nextAlloc1stIndex < suballoc1stCount &&
suballocations1st[nextAlloc1stIndex].hAllocation == VK_NULL_HANDLE)
{
++nextAlloc1stIndex;
}
// Found non-null allocation.
if(nextAlloc1stIndex < suballoc1stCount)
{
const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex];
// 1. Process free space before this allocation.
if(lastOffset < suballoc.offset)
{
// There is free space from lastOffset to suballoc.offset.
++unusedRangeCount;
}
// 2. Process this allocation.
// There is allocation with suballoc.offset, suballoc.size.
++alloc1stCount;
usedBytes += suballoc.size;
// 3. Prepare for next iteration.
lastOffset = suballoc.offset + suballoc.size;
++nextAlloc1stIndex;
}
// We are at the end.
else
{
if(lastOffset < size)
{
// There is free space from lastOffset to freeSpace1stTo2ndEnd.
++unusedRangeCount;
}
// End of loop.
lastOffset = freeSpace1stTo2ndEnd;
}
}
if(m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
{
size_t nextAlloc2ndIndex = suballocations2nd.size() - 1;
while(lastOffset < size)
{
// Find next non-null allocation or move nextAlloc2ndIndex to the end.
while(nextAlloc2ndIndex != SIZE_MAX &&
suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE)
{
--nextAlloc2ndIndex;
}
// Found non-null allocation.
if(nextAlloc2ndIndex != SIZE_MAX)
{
const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
// 1. Process free space before this allocation.
if(lastOffset < suballoc.offset)
{
// There is free space from lastOffset to suballoc.offset.
++unusedRangeCount;
}
// 2. Process this allocation.
// There is allocation with suballoc.offset, suballoc.size.
++alloc2ndCount;
usedBytes += suballoc.size;
// 3. Prepare for next iteration.
lastOffset = suballoc.offset + suballoc.size;
--nextAlloc2ndIndex;
}
// We are at the end.
else
{
if(lastOffset < size)
{
// There is free space from lastOffset to size.
++unusedRangeCount;
}
// End of loop.
lastOffset = size;
}
}
}
const VkDeviceSize unusedBytes = size - usedBytes;
PrintDetailedMap_Begin(json, unusedBytes, alloc1stCount + alloc2ndCount, unusedRangeCount);
// SECOND PASS
lastOffset = 0;
if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
{
const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset;
size_t nextAlloc2ndIndex = 0;
while(lastOffset < freeSpace2ndTo1stEnd)
{
// Find next non-null allocation or move nextAlloc2ndIndex to the end.
while(nextAlloc2ndIndex < suballoc2ndCount &&
suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE)
{
++nextAlloc2ndIndex;
}
// Found non-null allocation.
if(nextAlloc2ndIndex < suballoc2ndCount)
{
const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
// 1. Process free space before this allocation.
if(lastOffset < suballoc.offset)
{
// There is free space from lastOffset to suballoc.offset.
const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize);
}
// 2. Process this allocation.
// There is allocation with suballoc.offset, suballoc.size.
PrintDetailedMap_Allocation(json, suballoc.offset, suballoc.hAllocation);
// 3. Prepare for next iteration.
lastOffset = suballoc.offset + suballoc.size;
++nextAlloc2ndIndex;
}
// We are at the end.
else
{
if(lastOffset < freeSpace2ndTo1stEnd)
{
// There is free space from lastOffset to freeSpace2ndTo1stEnd.
const VkDeviceSize unusedRangeSize = freeSpace2ndTo1stEnd - lastOffset;
PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize);
}
// End of loop.
lastOffset = freeSpace2ndTo1stEnd;
}
}
}
nextAlloc1stIndex = m_1stNullItemsBeginCount;
while(lastOffset < freeSpace1stTo2ndEnd)
{
// Find next non-null allocation or move nextAllocIndex to the end.
while(nextAlloc1stIndex < suballoc1stCount &&
suballocations1st[nextAlloc1stIndex].hAllocation == VK_NULL_HANDLE)
{
++nextAlloc1stIndex;
}
// Found non-null allocation.
if(nextAlloc1stIndex < suballoc1stCount)
{
const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex];
// 1. Process free space before this allocation.
if(lastOffset < suballoc.offset)
{
// There is free space from lastOffset to suballoc.offset.
const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize);
}
// 2. Process this allocation.
// There is allocation with suballoc.offset, suballoc.size.
PrintDetailedMap_Allocation(json, suballoc.offset, suballoc.hAllocation);
// 3. Prepare for next iteration.
lastOffset = suballoc.offset + suballoc.size;
++nextAlloc1stIndex;
}
// We are at the end.
else
{
if(lastOffset < freeSpace1stTo2ndEnd)
{
// There is free space from lastOffset to freeSpace1stTo2ndEnd.
const VkDeviceSize unusedRangeSize = freeSpace1stTo2ndEnd - lastOffset;
PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize);
}
// End of loop.
lastOffset = freeSpace1stTo2ndEnd;
}
}
if(m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
{
size_t nextAlloc2ndIndex = suballocations2nd.size() - 1;
while(lastOffset < size)
{
// Find next non-null allocation or move nextAlloc2ndIndex to the end.
while(nextAlloc2ndIndex != SIZE_MAX &&
suballocations2nd[nextAlloc2ndIndex].hAllocation == VK_NULL_HANDLE)
{
--nextAlloc2ndIndex;
}
// Found non-null allocation.
if(nextAlloc2ndIndex != SIZE_MAX)
{
const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex];
// 1. Process free space before this allocation.
if(lastOffset < suballoc.offset)
{
// There is free space from lastOffset to suballoc.offset.
const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset;
PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize);
}
// 2. Process this allocation.
// There is allocation with suballoc.offset, suballoc.size.
PrintDetailedMap_Allocation(json, suballoc.offset, suballoc.hAllocation);
// 3. Prepare for next iteration.
lastOffset = suballoc.offset + suballoc.size;
--nextAlloc2ndIndex;
}
// We are at the end.
else
{
if(lastOffset < size)
{
// There is free space from lastOffset to size.
const VkDeviceSize unusedRangeSize = size - lastOffset;
PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize);
}
// End of loop.
lastOffset = size;
}
}
}
PrintDetailedMap_End(json);
}
#endif // #if VMA_STATS_STRING_ENABLED
bool VmaBlockMetadata_Linear::CreateAllocationRequest(
uint32_t currentFrameIndex,
uint32_t frameInUseCount,
VkDeviceSize bufferImageGranularity,
VkDeviceSize allocSize,
VkDeviceSize allocAlignment,
bool upperAddress,
VmaSuballocationType allocType,
bool canMakeOtherLost,
VmaAllocationRequest* pAllocationRequest)
{
VMA_ASSERT(allocSize > 0);
VMA_ASSERT(allocType != VMA_SUBALLOCATION_TYPE_FREE);
VMA_ASSERT(pAllocationRequest != VMA_NULL);
VMA_HEAVY_ASSERT(Validate());
const VkDeviceSize size = GetSize();
SuballocationVectorType& suballocations1st = AccessSuballocations1st();
SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
if(upperAddress)
{
if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
{
VMA_ASSERT(0 && "Trying to use pool with linear algorithm as double stack, while it is already being used as ring buffer.");
return false;
}
// Try to allocate before 2nd.back(), or end of block if 2nd.empty().
if(allocSize > size)
{
return false;
}
VkDeviceSize resultBaseOffset = size - allocSize;
if(!suballocations2nd.empty())
{
const VmaSuballocation& lastSuballoc = suballocations2nd.back();
resultBaseOffset = lastSuballoc.offset - allocSize;
if(allocSize > lastSuballoc.offset)
{
return false;
}
}
// Start from offset equal to end of free space.
VkDeviceSize resultOffset = resultBaseOffset;
// Apply VMA_DEBUG_MARGIN at the end.
if(VMA_DEBUG_MARGIN > 0)
{
if(resultOffset < VMA_DEBUG_MARGIN)
{
return false;
}
resultOffset -= VMA_DEBUG_MARGIN;
}
// Apply alignment.
resultOffset = VmaAlignDown(resultOffset, allocAlignment);
// Check next suballocations from 2nd for BufferImageGranularity conflicts.
// Make bigger alignment if necessary.
if(bufferImageGranularity > 1 && !suballocations2nd.empty())
{
bool bufferImageGranularityConflict = false;
for(size_t nextSuballocIndex = suballocations2nd.size(); nextSuballocIndex--; )
{
const VmaSuballocation& nextSuballoc = suballocations2nd[nextSuballocIndex];
if(VmaBlocksOnSamePage(resultOffset, allocSize, nextSuballoc.offset, bufferImageGranularity))
{
if(VmaIsBufferImageGranularityConflict(nextSuballoc.type, allocType))
{
bufferImageGranularityConflict = true;
break;
}
}
else
// Already on previous page.
break;
}
if(bufferImageGranularityConflict)
{
resultOffset = VmaAlignDown(resultOffset, bufferImageGranularity);
}
}
// There is enough free space.
const VkDeviceSize endOf1st = !suballocations1st.empty() ?
suballocations1st.back().offset + suballocations1st.back().size :
0;
if(endOf1st + VMA_DEBUG_MARGIN <= resultOffset)
{
// Check previous suballocations for BufferImageGranularity conflicts.
// If conflict exists, allocation cannot be made here.
if(bufferImageGranularity > 1)
{
for(size_t prevSuballocIndex = suballocations1st.size(); prevSuballocIndex--; )
{
const VmaSuballocation& prevSuballoc = suballocations1st[prevSuballocIndex];
if(VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, resultOffset, bufferImageGranularity))
{
if(VmaIsBufferImageGranularityConflict(allocType, prevSuballoc.type))
{
return false;
}
}
else
{
// Already on next page.
break;
}
}
}
// All tests passed: Success.
pAllocationRequest->offset = resultOffset;
pAllocationRequest->sumFreeSize = resultBaseOffset + allocSize - endOf1st;
pAllocationRequest->sumItemSize = 0;
// pAllocationRequest->item unused.
pAllocationRequest->itemsToMakeLostCount = 0;
return true;
}
}
else // !upperAddress
{
if(m_2ndVectorMode == SECOND_VECTOR_EMPTY || m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
{
// Try to allocate at the end of 1st vector.
VkDeviceSize resultBaseOffset = 0;
if(!suballocations1st.empty())
{
const VmaSuballocation& lastSuballoc = suballocations1st.back();
resultBaseOffset = lastSuballoc.offset + lastSuballoc.size;
}
// Start from offset equal to beginning of free space.
VkDeviceSize resultOffset = resultBaseOffset;
// Apply VMA_DEBUG_MARGIN at the beginning.
if(VMA_DEBUG_MARGIN > 0)
{
resultOffset += VMA_DEBUG_MARGIN;
}
// Apply alignment.
resultOffset = VmaAlignUp(resultOffset, allocAlignment);
// Check previous suballocations for BufferImageGranularity conflicts.
// Make bigger alignment if necessary.
if(bufferImageGranularity > 1 && !suballocations1st.empty())
{
bool bufferImageGranularityConflict = false;
for(size_t prevSuballocIndex = suballocations1st.size(); prevSuballocIndex--; )
{
const VmaSuballocation& prevSuballoc = suballocations1st[prevSuballocIndex];
if(VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, resultOffset, bufferImageGranularity))
{
if(VmaIsBufferImageGranularityConflict(prevSuballoc.type, allocType))
{
bufferImageGranularityConflict = true;
break;
}
}
else
// Already on previous page.
break;
}
if(bufferImageGranularityConflict)
{
resultOffset = VmaAlignUp(resultOffset, bufferImageGranularity);
}
}
const VkDeviceSize freeSpaceEnd = m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ?
suballocations2nd.back().offset : size;
// There is enough free space at the end after alignment.
if(resultOffset + allocSize + VMA_DEBUG_MARGIN <= freeSpaceEnd)
{
// Check next suballocations for BufferImageGranularity conflicts.
// If conflict exists, allocation cannot be made here.
if(bufferImageGranularity > 1 && m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
{
for(size_t nextSuballocIndex = suballocations2nd.size(); nextSuballocIndex--; )
{
const VmaSuballocation& nextSuballoc = suballocations2nd[nextSuballocIndex];
if(VmaBlocksOnSamePage(resultOffset, allocSize, nextSuballoc.offset, bufferImageGranularity))
{
if(VmaIsBufferImageGranularityConflict(allocType, nextSuballoc.type))
{
return false;
}
}
else
{
// Already on previous page.
break;
}
}
}
// All tests passed: Success.
pAllocationRequest->offset = resultOffset;
pAllocationRequest->sumFreeSize = freeSpaceEnd - resultBaseOffset;
pAllocationRequest->sumItemSize = 0;
// pAllocationRequest->item unused.
pAllocationRequest->itemsToMakeLostCount = 0;
return true;
}
}
// Wrap-around to end of 2nd vector. Try to allocate there, watching for the
// beginning of 1st vector as the end of free space.
if(m_2ndVectorMode == SECOND_VECTOR_EMPTY || m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
{
VMA_ASSERT(!suballocations1st.empty());
VkDeviceSize resultBaseOffset = 0;
if(!suballocations2nd.empty())
{
const VmaSuballocation& lastSuballoc = suballocations2nd.back();
resultBaseOffset = lastSuballoc.offset + lastSuballoc.size;
}
// Start from offset equal to beginning of free space.
VkDeviceSize resultOffset = resultBaseOffset;
// Apply VMA_DEBUG_MARGIN at the beginning.
if(VMA_DEBUG_MARGIN > 0)
{
resultOffset += VMA_DEBUG_MARGIN;
}
// Apply alignment.
resultOffset = VmaAlignUp(resultOffset, allocAlignment);
// Check previous suballocations for BufferImageGranularity conflicts.
// Make bigger alignment if necessary.
if(bufferImageGranularity > 1 && !suballocations2nd.empty())
{
bool bufferImageGranularityConflict = false;
for(size_t prevSuballocIndex = suballocations2nd.size(); prevSuballocIndex--; )
{
const VmaSuballocation& prevSuballoc = suballocations2nd[prevSuballocIndex];
if(VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, resultOffset, bufferImageGranularity))
{
if(VmaIsBufferImageGranularityConflict(prevSuballoc.type, allocType))
{
bufferImageGranularityConflict = true;
break;
}
}
else
// Already on previous page.
break;
}
if(bufferImageGranularityConflict)
{
resultOffset = VmaAlignUp(resultOffset, bufferImageGranularity);
}
}
pAllocationRequest->itemsToMakeLostCount = 0;
pAllocationRequest->sumItemSize = 0;
size_t index1st = m_1stNullItemsBeginCount;
if(canMakeOtherLost)
{
while(index1st < suballocations1st.size() &&
resultOffset + allocSize + VMA_DEBUG_MARGIN > suballocations1st[index1st].offset)
{
// Next colliding allocation at the beginning of 1st vector found. Try to make it lost.
const VmaSuballocation& suballoc = suballocations1st[index1st];
if(suballoc.type == VMA_SUBALLOCATION_TYPE_FREE)
{
// No problem.
}
else
{
VMA_ASSERT(suballoc.hAllocation != VK_NULL_HANDLE);
if(suballoc.hAllocation->CanBecomeLost() &&
suballoc.hAllocation->GetLastUseFrameIndex() + frameInUseCount < currentFrameIndex)
{
++pAllocationRequest->itemsToMakeLostCount;
pAllocationRequest->sumItemSize += suballoc.size;
}
else
{
return false;
}
}
++index1st;
}
// Check next suballocations for BufferImageGranularity conflicts.
// If conflict exists, we must mark more allocations lost or fail.
if(bufferImageGranularity > 1)
{
while(index1st < suballocations1st.size())
{
const VmaSuballocation& suballoc = suballocations1st[index1st];
if(VmaBlocksOnSamePage(resultOffset, allocSize, suballoc.offset, bufferImageGranularity))
{
if(suballoc.hAllocation != VK_NULL_HANDLE)
{
// Not checking actual VmaIsBufferImageGranularityConflict(allocType, suballoc.type).
if(suballoc.hAllocation->CanBecomeLost() &&
suballoc.hAllocation->GetLastUseFrameIndex() + frameInUseCount < currentFrameIndex)
{
++pAllocationRequest->itemsToMakeLostCount;
pAllocationRequest->sumItemSize += suballoc.size;
}
else
{
return false;
}
}
}
else
{
// Already on next page.
break;
}
++index1st;
}
}
}
// There is enough free space at the end after alignment.
if((index1st == suballocations1st.size() && resultOffset + allocSize + VMA_DEBUG_MARGIN < size) ||
(index1st < suballocations1st.size() && resultOffset + allocSize + VMA_DEBUG_MARGIN <= suballocations1st[index1st].offset))
{
// Check next suballocations for BufferImageGranularity conflicts.
// If conflict exists, allocation cannot be made here.
if(bufferImageGranularity > 1)
{
for(size_t nextSuballocIndex = index1st;
nextSuballocIndex < suballocations1st.size();
nextSuballocIndex++)
{
const VmaSuballocation& nextSuballoc = suballocations1st[nextSuballocIndex];
if(VmaBlocksOnSamePage(resultOffset, allocSize, nextSuballoc.offset, bufferImageGranularity))
{
if(VmaIsBufferImageGranularityConflict(allocType, nextSuballoc.type))
{
return false;
}
}
else
{
// Already on next page.
break;
}
}
}
// All tests passed: Success.
pAllocationRequest->offset = resultOffset;
pAllocationRequest->sumFreeSize =
(index1st < suballocations1st.size() ? suballocations1st[index1st].offset : size)
- resultBaseOffset
- pAllocationRequest->sumItemSize;
// pAllocationRequest->item unused.
return true;
}
}
}
return false;
}
bool VmaBlockMetadata_Linear::MakeRequestedAllocationsLost(
uint32_t currentFrameIndex,
uint32_t frameInUseCount,
VmaAllocationRequest* pAllocationRequest)
{
if(pAllocationRequest->itemsToMakeLostCount == 0)
{
return true;
}
VMA_ASSERT(m_2ndVectorMode == SECOND_VECTOR_EMPTY || m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER);
SuballocationVectorType& suballocations1st = AccessSuballocations1st();
size_t index1st = m_1stNullItemsBeginCount;
size_t madeLostCount = 0;
while(madeLostCount < pAllocationRequest->itemsToMakeLostCount)
{
VMA_ASSERT(index1st < suballocations1st.size());
VmaSuballocation& suballoc = suballocations1st[index1st];
if(suballoc.type != VMA_SUBALLOCATION_TYPE_FREE)
{
VMA_ASSERT(suballoc.hAllocation != VK_NULL_HANDLE);
VMA_ASSERT(suballoc.hAllocation->CanBecomeLost());
if(suballoc.hAllocation->MakeLost(currentFrameIndex, frameInUseCount))
{
suballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
suballoc.hAllocation = VK_NULL_HANDLE;
m_SumFreeSize += suballoc.size;
++m_1stNullItemsMiddleCount;
++madeLostCount;
}
else
{
return false;
}
}
++index1st;
}
CleanupAfterFree();
//VMA_HEAVY_ASSERT(Validate()); // Already called by ClanupAfterFree().
return true;
}
uint32_t VmaBlockMetadata_Linear::MakeAllocationsLost(uint32_t currentFrameIndex, uint32_t frameInUseCount)
{
uint32_t lostAllocationCount = 0;
SuballocationVectorType& suballocations1st = AccessSuballocations1st();
for(size_t i = m_1stNullItemsBeginCount, count = suballocations1st.size(); i < count; ++i)
{
VmaSuballocation& suballoc = suballocations1st[i];
if(suballoc.type != VMA_SUBALLOCATION_TYPE_FREE &&
suballoc.hAllocation->CanBecomeLost() &&
suballoc.hAllocation->MakeLost(currentFrameIndex, frameInUseCount))
{
suballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
suballoc.hAllocation = VK_NULL_HANDLE;
++m_1stNullItemsMiddleCount;
m_SumFreeSize += suballoc.size;
++lostAllocationCount;
}
}
SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
for(size_t i = 0, count = suballocations2nd.size(); i < count; ++i)
{
VmaSuballocation& suballoc = suballocations2nd[i];
if(suballoc.type != VMA_SUBALLOCATION_TYPE_FREE &&
suballoc.hAllocation->CanBecomeLost() &&
suballoc.hAllocation->MakeLost(currentFrameIndex, frameInUseCount))
{
suballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
suballoc.hAllocation = VK_NULL_HANDLE;
++m_2ndNullItemsCount;
++lostAllocationCount;
}
}
if(lostAllocationCount)
{
CleanupAfterFree();
}
return lostAllocationCount;
}
VkResult VmaBlockMetadata_Linear::CheckCorruption(const void* pBlockData)
{
SuballocationVectorType& suballocations1st = AccessSuballocations1st();
for(size_t i = m_1stNullItemsBeginCount, count = suballocations1st.size(); i < count; ++i)
{
const VmaSuballocation& suballoc = suballocations1st[i];
if(suballoc.type != VMA_SUBALLOCATION_TYPE_FREE)
{
if(!VmaValidateMagicValue(pBlockData, suballoc.offset - VMA_DEBUG_MARGIN))
{
VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED BEFORE VALIDATED ALLOCATION!");
return VK_ERROR_VALIDATION_FAILED_EXT;
}
if(!VmaValidateMagicValue(pBlockData, suballoc.offset + suballoc.size))
{
VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER VALIDATED ALLOCATION!");
return VK_ERROR_VALIDATION_FAILED_EXT;
}
}
}
SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
for(size_t i = 0, count = suballocations2nd.size(); i < count; ++i)
{
const VmaSuballocation& suballoc = suballocations2nd[i];
if(suballoc.type != VMA_SUBALLOCATION_TYPE_FREE)
{
if(!VmaValidateMagicValue(pBlockData, suballoc.offset - VMA_DEBUG_MARGIN))
{
VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED BEFORE VALIDATED ALLOCATION!");
return VK_ERROR_VALIDATION_FAILED_EXT;
}
if(!VmaValidateMagicValue(pBlockData, suballoc.offset + suballoc.size))
{
VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER VALIDATED ALLOCATION!");
return VK_ERROR_VALIDATION_FAILED_EXT;
}
}
}
return VK_SUCCESS;
}
void VmaBlockMetadata_Linear::Alloc(
const VmaAllocationRequest& request,
VmaSuballocationType type,
VkDeviceSize allocSize,
bool upperAddress,
VmaAllocation hAllocation)
{
const VmaSuballocation newSuballoc = { request.offset, allocSize, hAllocation, type };
if(upperAddress)
{
VMA_ASSERT(m_2ndVectorMode != SECOND_VECTOR_RING_BUFFER &&
"CRITICAL ERROR: Trying to use linear allocator as double stack while it was already used as ring buffer.");
SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
suballocations2nd.push_back(newSuballoc);
m_2ndVectorMode = SECOND_VECTOR_DOUBLE_STACK;
}
else
{
SuballocationVectorType& suballocations1st = AccessSuballocations1st();
// First allocation.
if(suballocations1st.empty())
{
suballocations1st.push_back(newSuballoc);
}
else
{
// New allocation at the end of 1st vector.
if(request.offset >= suballocations1st.back().offset + suballocations1st.back().size)
{
// Check if it fits before the end of the block.
VMA_ASSERT(request.offset + allocSize <= GetSize());
suballocations1st.push_back(newSuballoc);
}
// New allocation at the end of 2-part ring buffer, so before first allocation from 1st vector.
else if(request.offset + allocSize <= suballocations1st[m_1stNullItemsBeginCount].offset)
{
SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
switch(m_2ndVectorMode)
{
case SECOND_VECTOR_EMPTY:
// First allocation from second part ring buffer.
VMA_ASSERT(suballocations2nd.empty());
m_2ndVectorMode = SECOND_VECTOR_RING_BUFFER;
break;
case SECOND_VECTOR_RING_BUFFER:
// 2-part ring buffer is already started.
VMA_ASSERT(!suballocations2nd.empty());
break;
case SECOND_VECTOR_DOUBLE_STACK:
VMA_ASSERT(0 && "CRITICAL ERROR: Trying to use linear allocator as ring buffer while it was already used as double stack.");
break;
default:
VMA_ASSERT(0);
}
suballocations2nd.push_back(newSuballoc);
}
else
{
VMA_ASSERT(0 && "CRITICAL INTERNAL ERROR.");
}
}
}
m_SumFreeSize -= newSuballoc.size;
}
void VmaBlockMetadata_Linear::Free(const VmaAllocation allocation)
{
FreeAtOffset(allocation->GetOffset());
}
void VmaBlockMetadata_Linear::FreeAtOffset(VkDeviceSize offset)
{
SuballocationVectorType& suballocations1st = AccessSuballocations1st();
SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
if(!suballocations1st.empty())
{
// First allocation: Mark it as next empty at the beginning.
VmaSuballocation& firstSuballoc = suballocations1st[m_1stNullItemsBeginCount];
if(firstSuballoc.offset == offset)
{
firstSuballoc.type = VMA_SUBALLOCATION_TYPE_FREE;
firstSuballoc.hAllocation = VK_NULL_HANDLE;
m_SumFreeSize += firstSuballoc.size;
++m_1stNullItemsBeginCount;
CleanupAfterFree();
return;
}
}
// Last allocation in 2-part ring buffer or top of upper stack (same logic).
if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER ||
m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK)
{
VmaSuballocation& lastSuballoc = suballocations2nd.back();
if(lastSuballoc.offset == offset)
{
m_SumFreeSize += lastSuballoc.size;
suballocations2nd.pop_back();
CleanupAfterFree();
return;
}
}
// Last allocation in 1st vector.
else if(m_2ndVectorMode == SECOND_VECTOR_EMPTY)
{
VmaSuballocation& lastSuballoc = suballocations1st.back();
if(lastSuballoc.offset == offset)
{
m_SumFreeSize += lastSuballoc.size;
suballocations1st.pop_back();
CleanupAfterFree();
return;
}
}
// Item from the middle of 1st vector.
{
VmaSuballocation refSuballoc;
refSuballoc.offset = offset;
// Rest of members stays uninitialized intentionally for better performance.
SuballocationVectorType::iterator it = VmaVectorFindSorted<VmaSuballocationOffsetLess>(
suballocations1st.begin() + m_1stNullItemsBeginCount,
suballocations1st.end(),
refSuballoc);
if(it != suballocations1st.end())
{
it->type = VMA_SUBALLOCATION_TYPE_FREE;
it->hAllocation = VK_NULL_HANDLE;
++m_1stNullItemsMiddleCount;
m_SumFreeSize += it->size;
CleanupAfterFree();
return;
}
}
if(m_2ndVectorMode != SECOND_VECTOR_EMPTY)
{
// Item from the middle of 2nd vector.
VmaSuballocation refSuballoc;
refSuballoc.offset = offset;
// Rest of members stays uninitialized intentionally for better performance.
SuballocationVectorType::iterator it = m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER ?
VmaVectorFindSorted<VmaSuballocationOffsetLess>(suballocations2nd.begin(), suballocations2nd.end(), refSuballoc) :
VmaVectorFindSorted<VmaSuballocationOffsetGreater>(suballocations2nd.begin(), suballocations2nd.end(), refSuballoc);
if(it != suballocations2nd.end())
{
it->type = VMA_SUBALLOCATION_TYPE_FREE;
it->hAllocation = VK_NULL_HANDLE;
++m_2ndNullItemsCount;
m_SumFreeSize += it->size;
CleanupAfterFree();
return;
}
}
VMA_ASSERT(0 && "Allocation to free not found in linear allocator!");
}
bool VmaBlockMetadata_Linear::ShouldCompact1st() const
{
const size_t nullItemCount = m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount;
const size_t suballocCount = AccessSuballocations1st().size();
return suballocCount > 32 && nullItemCount * 2 >= (suballocCount - nullItemCount) * 3;
}
void VmaBlockMetadata_Linear::CleanupAfterFree()
{
SuballocationVectorType& suballocations1st = AccessSuballocations1st();
SuballocationVectorType& suballocations2nd = AccessSuballocations2nd();
if(IsEmpty())
{
suballocations1st.clear();
suballocations2nd.clear();
m_1stNullItemsBeginCount = 0;
m_1stNullItemsMiddleCount = 0;
m_2ndNullItemsCount = 0;
m_2ndVectorMode = SECOND_VECTOR_EMPTY;
}
else
{
const size_t suballoc1stCount = suballocations1st.size();
const size_t nullItem1stCount = m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount;
VMA_ASSERT(nullItem1stCount <= suballoc1stCount);
// Find more null items at the beginning of 1st vector.
while(m_1stNullItemsBeginCount < suballoc1stCount &&
suballocations1st[m_1stNullItemsBeginCount].hAllocation == VK_NULL_HANDLE)
{
++m_1stNullItemsBeginCount;
--m_1stNullItemsMiddleCount;
}
// Find more null items at the end of 1st vector.
while(m_1stNullItemsMiddleCount > 0 &&
suballocations1st.back().hAllocation == VK_NULL_HANDLE)
{
--m_1stNullItemsMiddleCount;
suballocations1st.pop_back();
}
// Find more null items at the end of 2nd vector.
while(m_2ndNullItemsCount > 0 &&
suballocations2nd.back().hAllocation == VK_NULL_HANDLE)
{
--m_2ndNullItemsCount;
suballocations2nd.pop_back();
}
if(ShouldCompact1st())
{
const size_t nonNullItemCount = suballoc1stCount - nullItem1stCount;
size_t srcIndex = m_1stNullItemsBeginCount;
for(size_t dstIndex = 0; dstIndex < nonNullItemCount; ++dstIndex)
{
while(suballocations1st[srcIndex].hAllocation == VK_NULL_HANDLE)
{
++srcIndex;
}
if(dstIndex != srcIndex)
{
suballocations1st[dstIndex] = suballocations1st[srcIndex];
}
++srcIndex;
}
suballocations1st.resize(nonNullItemCount);
m_1stNullItemsBeginCount = 0;
m_1stNullItemsMiddleCount = 0;
}
// 2nd vector became empty.
if(suballocations2nd.empty())
{
m_2ndVectorMode = SECOND_VECTOR_EMPTY;
}
// 1st vector became empty.
if(suballocations1st.size() - m_1stNullItemsBeginCount == 0)
{
suballocations1st.clear();
m_1stNullItemsBeginCount = 0;
if(!suballocations2nd.empty() && m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER)
{
// Swap 1st with 2nd. Now 2nd is empty.
m_2ndVectorMode = SECOND_VECTOR_EMPTY;
m_1stNullItemsMiddleCount = m_2ndNullItemsCount;
while(m_1stNullItemsBeginCount < suballocations2nd.size() &&
suballocations2nd[m_1stNullItemsBeginCount].hAllocation == VK_NULL_HANDLE)
{
++m_1stNullItemsBeginCount;
--m_1stNullItemsMiddleCount;
}
m_2ndNullItemsCount = 0;
m_1stVectorIndex ^= 1;
}
}
}
VMA_HEAVY_ASSERT(Validate());
}
////////////////////////////////////////////////////////////////////////////////
// class VmaDeviceMemoryBlock
VmaDeviceMemoryBlock::VmaDeviceMemoryBlock(VmaAllocator hAllocator) :
m_pMetadata(VMA_NULL),
m_MemoryTypeIndex(UINT32_MAX),
m_Id(0),
m_hMemory(VK_NULL_HANDLE),
m_MapCount(0),
m_pMappedData(VMA_NULL)
{
}
void VmaDeviceMemoryBlock::Init(
VmaAllocator hAllocator,
uint32_t newMemoryTypeIndex,
VkDeviceMemory newMemory,
VkDeviceSize newSize,
uint32_t id,
bool linearAlgorithm)
{
VMA_ASSERT(m_hMemory == VK_NULL_HANDLE);
m_MemoryTypeIndex = newMemoryTypeIndex;
m_Id = id;
m_hMemory = newMemory;
if(linearAlgorithm)
{
m_pMetadata = vma_new(hAllocator, VmaBlockMetadata_Linear)(hAllocator);
}
else
{
m_pMetadata = vma_new(hAllocator, VmaBlockMetadata_Generic)(hAllocator);
}
m_pMetadata->Init(newSize);
}
void VmaDeviceMemoryBlock::Destroy(VmaAllocator allocator)
{
// This is the most important assert in the entire library.
// Hitting it means you have some memory leak - unreleased VmaAllocation objects.
VMA_ASSERT(m_pMetadata->IsEmpty() && "Some allocations were not freed before destruction of this memory block!");
VMA_ASSERT(m_hMemory != VK_NULL_HANDLE);
allocator->FreeVulkanMemory(m_MemoryTypeIndex, m_pMetadata->GetSize(), m_hMemory);
m_hMemory = VK_NULL_HANDLE;
vma_delete(allocator, m_pMetadata);
m_pMetadata = VMA_NULL;
}
bool VmaDeviceMemoryBlock::Validate() const
{
if((m_hMemory == VK_NULL_HANDLE) ||
(m_pMetadata->GetSize() == 0))
{
return false;
}
return m_pMetadata->Validate();
}
VkResult VmaDeviceMemoryBlock::CheckCorruption(VmaAllocator hAllocator)
{
void* pData = nullptr;
VkResult res = Map(hAllocator, 1, &pData);
if(res != VK_SUCCESS)
{
return res;
}
res = m_pMetadata->CheckCorruption(pData);
Unmap(hAllocator, 1);
return res;
}
VkResult VmaDeviceMemoryBlock::Map(VmaAllocator hAllocator, uint32_t count, void** ppData)
{
if(count == 0)
{
return VK_SUCCESS;
}
VmaMutexLock lock(m_Mutex, hAllocator->m_UseMutex);
if(m_MapCount != 0)
{
m_MapCount += count;
VMA_ASSERT(m_pMappedData != VMA_NULL);
if(ppData != VMA_NULL)
{
*ppData = m_pMappedData;
}
return VK_SUCCESS;
}
else
{
VkResult result = (*hAllocator->GetVulkanFunctions().vkMapMemory)(
hAllocator->m_hDevice,
m_hMemory,
0, // offset
VK_WHOLE_SIZE,
0, // flags
&m_pMappedData);
if(result == VK_SUCCESS)
{
if(ppData != VMA_NULL)
{
*ppData = m_pMappedData;
}
m_MapCount = count;
}
return result;
}
}
void VmaDeviceMemoryBlock::Unmap(VmaAllocator hAllocator, uint32_t count)
{
if(count == 0)
{
return;
}
VmaMutexLock lock(m_Mutex, hAllocator->m_UseMutex);
if(m_MapCount >= count)
{
m_MapCount -= count;
if(m_MapCount == 0)
{
m_pMappedData = VMA_NULL;
(*hAllocator->GetVulkanFunctions().vkUnmapMemory)(hAllocator->m_hDevice, m_hMemory);
}
}
else
{
VMA_ASSERT(0 && "VkDeviceMemory block is being unmapped while it was not previously mapped.");
}
}
VkResult VmaDeviceMemoryBlock::WriteMagicValueAroundAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize)
{
VMA_ASSERT(VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_MARGIN % 4 == 0 && VMA_DEBUG_DETECT_CORRUPTION);
VMA_ASSERT(allocOffset >= VMA_DEBUG_MARGIN);
void* pData;
VkResult res = Map(hAllocator, 1, &pData);
if(res != VK_SUCCESS)
{
return res;
}
VmaWriteMagicValue(pData, allocOffset - VMA_DEBUG_MARGIN);
VmaWriteMagicValue(pData, allocOffset + allocSize);
Unmap(hAllocator, 1);
return VK_SUCCESS;
}
VkResult VmaDeviceMemoryBlock::ValidateMagicValueAroundAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize)
{
VMA_ASSERT(VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_MARGIN % 4 == 0 && VMA_DEBUG_DETECT_CORRUPTION);
VMA_ASSERT(allocOffset >= VMA_DEBUG_MARGIN);
void* pData;
VkResult res = Map(hAllocator, 1, &pData);
if(res != VK_SUCCESS)
{
return res;
}
if(!VmaValidateMagicValue(pData, allocOffset - VMA_DEBUG_MARGIN))
{
VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED BEFORE FREED ALLOCATION!");
}
else if(!VmaValidateMagicValue(pData, allocOffset + allocSize))
{
VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER FREED ALLOCATION!");
}
Unmap(hAllocator, 1);
return VK_SUCCESS;
}
VkResult VmaDeviceMemoryBlock::BindBufferMemory(
const VmaAllocator hAllocator,
const VmaAllocation hAllocation,
VkBuffer hBuffer)
{
VMA_ASSERT(hAllocation->GetType() == VmaAllocation_T::ALLOCATION_TYPE_BLOCK &&
hAllocation->GetBlock() == this);
// This lock is important so that we don't call vkBind... and/or vkMap... simultaneously on the same VkDeviceMemory from multiple threads.
VmaMutexLock lock(m_Mutex, hAllocator->m_UseMutex);
return hAllocator->GetVulkanFunctions().vkBindBufferMemory(
hAllocator->m_hDevice,
hBuffer,
m_hMemory,
hAllocation->GetOffset());
}
VkResult VmaDeviceMemoryBlock::BindImageMemory(
const VmaAllocator hAllocator,
const VmaAllocation hAllocation,
VkImage hImage)
{
VMA_ASSERT(hAllocation->GetType() == VmaAllocation_T::ALLOCATION_TYPE_BLOCK &&
hAllocation->GetBlock() == this);
// This lock is important so that we don't call vkBind... and/or vkMap... simultaneously on the same VkDeviceMemory from multiple threads.
VmaMutexLock lock(m_Mutex, hAllocator->m_UseMutex);
return hAllocator->GetVulkanFunctions().vkBindImageMemory(
hAllocator->m_hDevice,
hImage,
m_hMemory,
hAllocation->GetOffset());
}
static void InitStatInfo(VmaStatInfo& outInfo)
{
memset(&outInfo, 0, sizeof(outInfo));
outInfo.allocationSizeMin = UINT64_MAX;
outInfo.unusedRangeSizeMin = UINT64_MAX;
}
// Adds statistics srcInfo into inoutInfo, like: inoutInfo += srcInfo.
static void VmaAddStatInfo(VmaStatInfo& inoutInfo, const VmaStatInfo& srcInfo)
{
inoutInfo.blockCount += srcInfo.blockCount;
inoutInfo.allocationCount += srcInfo.allocationCount;
inoutInfo.unusedRangeCount += srcInfo.unusedRangeCount;
inoutInfo.usedBytes += srcInfo.usedBytes;
inoutInfo.unusedBytes += srcInfo.unusedBytes;
inoutInfo.allocationSizeMin = VMA_MIN(inoutInfo.allocationSizeMin, srcInfo.allocationSizeMin);
inoutInfo.allocationSizeMax = VMA_MAX(inoutInfo.allocationSizeMax, srcInfo.allocationSizeMax);
inoutInfo.unusedRangeSizeMin = VMA_MIN(inoutInfo.unusedRangeSizeMin, srcInfo.unusedRangeSizeMin);
inoutInfo.unusedRangeSizeMax = VMA_MAX(inoutInfo.unusedRangeSizeMax, srcInfo.unusedRangeSizeMax);
}
static void VmaPostprocessCalcStatInfo(VmaStatInfo& inoutInfo)
{
inoutInfo.allocationSizeAvg = (inoutInfo.allocationCount > 0) ?
VmaRoundDiv<VkDeviceSize>(inoutInfo.usedBytes, inoutInfo.allocationCount) : 0;
inoutInfo.unusedRangeSizeAvg = (inoutInfo.unusedRangeCount > 0) ?
VmaRoundDiv<VkDeviceSize>(inoutInfo.unusedBytes, inoutInfo.unusedRangeCount) : 0;
}
VmaPool_T::VmaPool_T(
VmaAllocator hAllocator,
const VmaPoolCreateInfo& createInfo,
VkDeviceSize preferredBlockSize) :
m_BlockVector(
hAllocator,
createInfo.memoryTypeIndex,
createInfo.blockSize != 0 ? createInfo.blockSize : preferredBlockSize,
createInfo.minBlockCount,
createInfo.maxBlockCount,
(createInfo.flags & VMA_POOL_CREATE_IGNORE_BUFFER_IMAGE_GRANULARITY_BIT) != 0 ? 1 : hAllocator->GetBufferImageGranularity(),
createInfo.frameInUseCount,
true, // isCustomPool
createInfo.blockSize != 0, // explicitBlockSize
(createInfo.flags & VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT) != 0), // linearAlgorithm
m_Id(0)
{
}
VmaPool_T::~VmaPool_T()
{
}
#if VMA_STATS_STRING_ENABLED
#endif // #if VMA_STATS_STRING_ENABLED
VmaBlockVector::VmaBlockVector(
VmaAllocator hAllocator,
uint32_t memoryTypeIndex,
VkDeviceSize preferredBlockSize,
size_t minBlockCount,
size_t maxBlockCount,
VkDeviceSize bufferImageGranularity,
uint32_t frameInUseCount,
bool isCustomPool,
bool explicitBlockSize,
bool linearAlgorithm) :
m_hAllocator(hAllocator),
m_MemoryTypeIndex(memoryTypeIndex),
m_PreferredBlockSize(preferredBlockSize),
m_MinBlockCount(minBlockCount),
m_MaxBlockCount(maxBlockCount),
m_BufferImageGranularity(bufferImageGranularity),
m_FrameInUseCount(frameInUseCount),
m_IsCustomPool(isCustomPool),
m_ExplicitBlockSize(explicitBlockSize),
m_LinearAlgorithm(linearAlgorithm),
m_HasEmptyBlock(false),
m_Blocks(VmaStlAllocator<VmaDeviceMemoryBlock*>(hAllocator->GetAllocationCallbacks())),
m_pDefragmentator(VMA_NULL),
m_NextBlockId(0)
{
}
VmaBlockVector::~VmaBlockVector()
{
VMA_ASSERT(m_pDefragmentator == VMA_NULL);
for(size_t i = m_Blocks.size(); i--; )
{
m_Blocks[i]->Destroy(m_hAllocator);
vma_delete(m_hAllocator, m_Blocks[i]);
}
}
VkResult VmaBlockVector::CreateMinBlocks()
{
for(size_t i = 0; i < m_MinBlockCount; ++i)
{
VkResult res = CreateBlock(m_PreferredBlockSize, VMA_NULL);
if(res != VK_SUCCESS)
{
return res;
}
}
return VK_SUCCESS;
}
void VmaBlockVector::GetPoolStats(VmaPoolStats* pStats)
{
VmaMutexLock lock(m_Mutex, m_hAllocator->m_UseMutex);
const size_t blockCount = m_Blocks.size();
pStats->size = 0;
pStats->unusedSize = 0;
pStats->allocationCount = 0;
pStats->unusedRangeCount = 0;
pStats->unusedRangeSizeMax = 0;
pStats->blockCount = blockCount;
for(uint32_t blockIndex = 0; blockIndex < blockCount; ++blockIndex)
{
const VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex];
VMA_ASSERT(pBlock);
VMA_HEAVY_ASSERT(pBlock->Validate());
pBlock->m_pMetadata->AddPoolStats(*pStats);
}
}
bool VmaBlockVector::IsCorruptionDetectionEnabled() const
{
const uint32_t requiredMemFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
return (VMA_DEBUG_DETECT_CORRUPTION != 0) &&
(VMA_DEBUG_MARGIN > 0) &&
(m_hAllocator->m_MemProps.memoryTypes[m_MemoryTypeIndex].propertyFlags & requiredMemFlags) == requiredMemFlags;
}
static const uint32_t VMA_ALLOCATION_TRY_COUNT = 32;
VkResult VmaBlockVector::Allocate(
VmaPool hCurrentPool,
uint32_t currentFrameIndex,
VkDeviceSize size,
VkDeviceSize alignment,
const VmaAllocationCreateInfo& createInfo,
VmaSuballocationType suballocType,
VmaAllocation* pAllocation)
{
const bool isUpperAddress = (createInfo.flags & VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT) != 0;
bool canMakeOtherLost = (createInfo.flags & VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT) != 0;
const bool mapped = (createInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0;
const bool isUserDataString = (createInfo.flags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0;
const bool canCreateNewBlock =
((createInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) == 0) &&
(m_Blocks.size() < m_MaxBlockCount);
// If linearAlgorithm is used, canMakeOtherLost is available only when used as ring buffer.
// Which in turn is available only when maxBlockCount = 1.
if(m_LinearAlgorithm && m_MaxBlockCount > 1)
{
canMakeOtherLost = false;
}
// Upper address can only be used with linear allocator and within single memory block.
if(isUpperAddress &&
(!m_LinearAlgorithm || m_MaxBlockCount > 1))
{
return VK_ERROR_FEATURE_NOT_PRESENT;
}
// Early reject: requested allocation size is larger that maximum block size for this block vector.
if(size + 2 * VMA_DEBUG_MARGIN > m_PreferredBlockSize)
{
return VK_ERROR_OUT_OF_DEVICE_MEMORY;
}
VmaMutexLock lock(m_Mutex, m_hAllocator->m_UseMutex);
/*
Under certain condition, this whole section can be skipped for optimization, so
we move on directly to trying to allocate with canMakeOtherLost. That's the case
e.g. for custom pools with linear algorithm.
*/
if(!canMakeOtherLost || canCreateNewBlock)
{
// 1. Search existing allocations. Try to allocate without making other allocations lost.
VmaAllocationCreateFlags allocFlagsCopy = createInfo.flags;
allocFlagsCopy &= ~VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT;
if(m_LinearAlgorithm)
{
// Use only last block.
if(!m_Blocks.empty())
{
VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks.back();
VMA_ASSERT(pCurrBlock);
VkResult res = AllocateFromBlock(
pCurrBlock,
hCurrentPool,
currentFrameIndex,
size,
alignment,
allocFlagsCopy,
createInfo.pUserData,
suballocType,
pAllocation);
if(res == VK_SUCCESS)
{
VMA_DEBUG_LOG(" Returned from last block #%u", (uint32_t)(m_Blocks.size() - 1));
return VK_SUCCESS;
}
}
}
else
{
// Forward order in m_Blocks - prefer blocks with smallest amount of free space.
for(size_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex )
{
VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks[blockIndex];
VMA_ASSERT(pCurrBlock);
VkResult res = AllocateFromBlock(
pCurrBlock,
hCurrentPool,
currentFrameIndex,
size,
alignment,
allocFlagsCopy,
createInfo.pUserData,
suballocType,
pAllocation);
if(res == VK_SUCCESS)
{
VMA_DEBUG_LOG(" Returned from existing block #%u", (uint32_t)blockIndex);
return VK_SUCCESS;
}
}
}
// 2. Try to create new block.
if(canCreateNewBlock)
{
// Calculate optimal size for new block.
VkDeviceSize newBlockSize = m_PreferredBlockSize;
uint32_t newBlockSizeShift = 0;
const uint32_t NEW_BLOCK_SIZE_SHIFT_MAX = 3;
if(!m_ExplicitBlockSize)
{
// Allocate 1/8, 1/4, 1/2 as first blocks.
const VkDeviceSize maxExistingBlockSize = CalcMaxBlockSize();
for(uint32_t i = 0; i < NEW_BLOCK_SIZE_SHIFT_MAX; ++i)
{
const VkDeviceSize smallerNewBlockSize = newBlockSize / 2;
if(smallerNewBlockSize > maxExistingBlockSize && smallerNewBlockSize >= size * 2)
{
newBlockSize = smallerNewBlockSize;
++newBlockSizeShift;
}
else
{
break;
}
}
}
size_t newBlockIndex = 0;
VkResult res = CreateBlock(newBlockSize, &newBlockIndex);
// Allocation of this size failed? Try 1/2, 1/4, 1/8 of m_PreferredBlockSize.
if(!m_ExplicitBlockSize)
{
while(res < 0 && newBlockSizeShift < NEW_BLOCK_SIZE_SHIFT_MAX)
{
const VkDeviceSize smallerNewBlockSize = newBlockSize / 2;
if(smallerNewBlockSize >= size)
{
newBlockSize = smallerNewBlockSize;
++newBlockSizeShift;
res = CreateBlock(newBlockSize, &newBlockIndex);
}
else
{
break;
}
}
}
if(res == VK_SUCCESS)
{
VmaDeviceMemoryBlock* const pBlock = m_Blocks[newBlockIndex];
VMA_ASSERT(pBlock->m_pMetadata->GetSize() >= size);
res = AllocateFromBlock(
pBlock,
hCurrentPool,
currentFrameIndex,
size,
alignment,
allocFlagsCopy,
createInfo.pUserData,
suballocType,
pAllocation);
if(res == VK_SUCCESS)
{
VMA_DEBUG_LOG(" Created new block Size=%llu", newBlockSize);
return VK_SUCCESS;
}
else
{
// Allocation from new block failed, possibly due to VMA_DEBUG_MARGIN or alignment.
return VK_ERROR_OUT_OF_DEVICE_MEMORY;
}
}
}
}
// 3. Try to allocate from existing blocks with making other allocations lost.
if(canMakeOtherLost)
{
uint32_t tryIndex = 0;
for(; tryIndex < VMA_ALLOCATION_TRY_COUNT; ++tryIndex)
{
VmaDeviceMemoryBlock* pBestRequestBlock = VMA_NULL;
VmaAllocationRequest bestRequest = {};
VkDeviceSize bestRequestCost = VK_WHOLE_SIZE;
// 1. Search existing allocations.
// Forward order in m_Blocks - prefer blocks with smallest amount of free space.
for(size_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex )
{
VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks[blockIndex];
VMA_ASSERT(pCurrBlock);
VmaAllocationRequest currRequest = {};
if(pCurrBlock->m_pMetadata->CreateAllocationRequest(
currentFrameIndex,
m_FrameInUseCount,
m_BufferImageGranularity,
size,
alignment,
(createInfo.flags & VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT) != 0,
suballocType,
canMakeOtherLost,
&currRequest))
{
const VkDeviceSize currRequestCost = currRequest.CalcCost();
if(pBestRequestBlock == VMA_NULL ||
currRequestCost < bestRequestCost)
{
pBestRequestBlock = pCurrBlock;
bestRequest = currRequest;
bestRequestCost = currRequestCost;
if(bestRequestCost == 0)
{
break;
}
}
}
}
if(pBestRequestBlock != VMA_NULL)
{
if(mapped)
{
VkResult res = pBestRequestBlock->Map(m_hAllocator, 1, VMA_NULL);
if(res != VK_SUCCESS)
{
return res;
}
}
if(pBestRequestBlock->m_pMetadata->MakeRequestedAllocationsLost(
currentFrameIndex,
m_FrameInUseCount,
&bestRequest))
{
// We no longer have an empty Allocation.
if(pBestRequestBlock->m_pMetadata->IsEmpty())
{
m_HasEmptyBlock = false;
}
// Allocate from this pBlock.
*pAllocation = vma_new(m_hAllocator, VmaAllocation_T)(currentFrameIndex, isUserDataString);
pBestRequestBlock->m_pMetadata->Alloc(bestRequest, suballocType, size, isUpperAddress, *pAllocation);
(*pAllocation)->InitBlockAllocation(
hCurrentPool,
pBestRequestBlock,
bestRequest.offset,
alignment,
size,
suballocType,
mapped,
(createInfo.flags & VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT) != 0);
VMA_HEAVY_ASSERT(pBestRequestBlock->Validate());
VMA_DEBUG_LOG(" Returned from existing allocation #%u", (uint32_t)blockIndex);
(*pAllocation)->SetUserData(m_hAllocator, createInfo.pUserData);
if(VMA_DEBUG_INITIALIZE_ALLOCATIONS)
{
m_hAllocator->FillAllocation(*pAllocation, VMA_ALLOCATION_FILL_PATTERN_CREATED);
}
if(IsCorruptionDetectionEnabled())
{
VkResult res = pBestRequestBlock->WriteMagicValueAroundAllocation(m_hAllocator, bestRequest.offset, size);
VMA_ASSERT(res == VK_SUCCESS && "Couldn't map block memory to write magic value.");
}
return VK_SUCCESS;
}
// else: Some allocations must have been touched while we are here. Next try.
}
else
{
// Could not find place in any of the blocks - break outer loop.
break;
}
}
/* Maximum number of tries exceeded - a very unlike event when many other
threads are simultaneously touching allocations making it impossible to make
lost at the same time as we try to allocate. */
if(tryIndex == VMA_ALLOCATION_TRY_COUNT)
{
return VK_ERROR_TOO_MANY_OBJECTS;
}
}
return VK_ERROR_OUT_OF_DEVICE_MEMORY;
}
void VmaBlockVector::Free(
VmaAllocation hAllocation)
{
VmaDeviceMemoryBlock* pBlockToDelete = VMA_NULL;
// Scope for lock.
{
VmaMutexLock lock(m_Mutex, m_hAllocator->m_UseMutex);
VmaDeviceMemoryBlock* pBlock = hAllocation->GetBlock();
if(IsCorruptionDetectionEnabled())
{
VkResult res = pBlock->ValidateMagicValueAroundAllocation(m_hAllocator, hAllocation->GetOffset(), hAllocation->GetSize());
VMA_ASSERT(res == VK_SUCCESS && "Couldn't map block memory to validate magic value.");
}
if(hAllocation->IsPersistentMap())
{
pBlock->Unmap(m_hAllocator, 1);
}
pBlock->m_pMetadata->Free(hAllocation);
VMA_HEAVY_ASSERT(pBlock->Validate());
VMA_DEBUG_LOG(" Freed from MemoryTypeIndex=%u", memTypeIndex);
// pBlock became empty after this deallocation.
if(pBlock->m_pMetadata->IsEmpty())
{
// Already has empty Allocation. We don't want to have two, so delete this one.
if(m_HasEmptyBlock && m_Blocks.size() > m_MinBlockCount)
{
pBlockToDelete = pBlock;
Remove(pBlock);
}
// We now have first empty block.
else
{
m_HasEmptyBlock = true;
}
}
// pBlock didn't become empty, but we have another empty block - find and free that one.
// (This is optional, heuristics.)
else if(m_HasEmptyBlock)
{
VmaDeviceMemoryBlock* pLastBlock = m_Blocks.back();
if(pLastBlock->m_pMetadata->IsEmpty() && m_Blocks.size() > m_MinBlockCount)
{
pBlockToDelete = pLastBlock;
m_Blocks.pop_back();
m_HasEmptyBlock = false;
}
}
IncrementallySortBlocks();
}
// Destruction of a free Allocation. Deferred until this point, outside of mutex
// lock, for performance reason.
if(pBlockToDelete != VMA_NULL)
{
VMA_DEBUG_LOG(" Deleted empty allocation");
pBlockToDelete->Destroy(m_hAllocator);
vma_delete(m_hAllocator, pBlockToDelete);
}
}
VkDeviceSize VmaBlockVector::CalcMaxBlockSize() const
{
VkDeviceSize result = 0;
for(size_t i = m_Blocks.size(); i--; )
{
result = VMA_MAX(result, m_Blocks[i]->m_pMetadata->GetSize());
if(result >= m_PreferredBlockSize)
{
break;
}
}
return result;
}
void VmaBlockVector::Remove(VmaDeviceMemoryBlock* pBlock)
{
for(uint32_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex)
{
if(m_Blocks[blockIndex] == pBlock)
{
VmaVectorRemove(m_Blocks, blockIndex);
return;
}
}
VMA_ASSERT(0);
}
void VmaBlockVector::IncrementallySortBlocks()
{
if(!m_LinearAlgorithm)
{
// Bubble sort only until first swap.
for(size_t i = 1; i < m_Blocks.size(); ++i)
{
if(m_Blocks[i - 1]->m_pMetadata->GetSumFreeSize() > m_Blocks[i]->m_pMetadata->GetSumFreeSize())
{
VMA_SWAP(m_Blocks[i - 1], m_Blocks[i]);
return;
}
}
}
}
VkResult VmaBlockVector::AllocateFromBlock(
VmaDeviceMemoryBlock* pBlock,
VmaPool hCurrentPool,
uint32_t currentFrameIndex,
VkDeviceSize size,
VkDeviceSize alignment,
VmaAllocationCreateFlags allocFlags,
void* pUserData,
VmaSuballocationType suballocType,
VmaAllocation* pAllocation)
{
VMA_ASSERT((allocFlags & VMA_ALLOCATION_CREATE_CAN_MAKE_OTHER_LOST_BIT) == 0);
const bool isUpperAddress = (allocFlags & VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT) != 0;
const bool mapped = (allocFlags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0;
const bool isUserDataString = (allocFlags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0;
VmaAllocationRequest currRequest = {};
if(pBlock->m_pMetadata->CreateAllocationRequest(
currentFrameIndex,
m_FrameInUseCount,
m_BufferImageGranularity,
size,
alignment,
isUpperAddress,
suballocType,
false, // canMakeOtherLost
&currRequest))
{
// Allocate from pCurrBlock.
VMA_ASSERT(currRequest.itemsToMakeLostCount == 0);
if(mapped)
{
VkResult res = pBlock->Map(m_hAllocator, 1, VMA_NULL);
if(res != VK_SUCCESS)
{
return res;
}
}
// We no longer have an empty Allocation.
if(pBlock->m_pMetadata->IsEmpty())
{
m_HasEmptyBlock = false;
}
*pAllocation = vma_new(m_hAllocator, VmaAllocation_T)(currentFrameIndex, isUserDataString);
pBlock->m_pMetadata->Alloc(currRequest, suballocType, size, isUpperAddress, *pAllocation);
(*pAllocation)->InitBlockAllocation(
hCurrentPool,
pBlock,
currRequest.offset,
alignment,
size,
suballocType,
mapped,
(allocFlags & VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT) != 0);
VMA_HEAVY_ASSERT(pBlock->Validate());
(*pAllocation)->SetUserData(m_hAllocator, pUserData);
if(VMA_DEBUG_INITIALIZE_ALLOCATIONS)
{
m_hAllocator->FillAllocation(*pAllocation, VMA_ALLOCATION_FILL_PATTERN_CREATED);
}
if(IsCorruptionDetectionEnabled())
{
VkResult res = pBlock->WriteMagicValueAroundAllocation(m_hAllocator, currRequest.offset, size);
VMA_ASSERT(res == VK_SUCCESS && "Couldn't map block memory to write magic value.");
}
return VK_SUCCESS;
}
return VK_ERROR_OUT_OF_DEVICE_MEMORY;
}
VkResult VmaBlockVector::CreateBlock(VkDeviceSize blockSize, size_t* pNewBlockIndex)
{
VkMemoryAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO };
allocInfo.memoryTypeIndex = m_MemoryTypeIndex;
allocInfo.allocationSize = blockSize;
VkDeviceMemory mem = VK_NULL_HANDLE;
VkResult res = m_hAllocator->AllocateVulkanMemory(&allocInfo, &mem);
if(res < 0)
{
return res;
}
// New VkDeviceMemory successfully created.
// Create new Allocation for it.
VmaDeviceMemoryBlock* const pBlock = vma_new(m_hAllocator, VmaDeviceMemoryBlock)(m_hAllocator);
pBlock->Init(
m_hAllocator,
m_MemoryTypeIndex,
mem,
allocInfo.allocationSize,
m_NextBlockId++,
m_LinearAlgorithm);
m_Blocks.push_back(pBlock);
if(pNewBlockIndex != VMA_NULL)
{
*pNewBlockIndex = m_Blocks.size() - 1;
}
return VK_SUCCESS;
}
#if VMA_STATS_STRING_ENABLED
void VmaBlockVector::PrintDetailedMap(class VmaJsonWriter& json)
{
VmaMutexLock lock(m_Mutex, m_hAllocator->m_UseMutex);
json.BeginObject();
if(m_IsCustomPool)
{
json.WriteString("MemoryTypeIndex");
json.WriteNumber(m_MemoryTypeIndex);
json.WriteString("BlockSize");
json.WriteNumber(m_PreferredBlockSize);
json.WriteString("BlockCount");
json.BeginObject(true);
if(m_MinBlockCount > 0)
{
json.WriteString("Min");
json.WriteNumber((uint64_t)m_MinBlockCount);
}
if(m_MaxBlockCount < SIZE_MAX)
{
json.WriteString("Max");
json.WriteNumber((uint64_t)m_MaxBlockCount);
}
json.WriteString("Cur");
json.WriteNumber((uint64_t)m_Blocks.size());
json.EndObject();
if(m_FrameInUseCount > 0)
{
json.WriteString("FrameInUseCount");
json.WriteNumber(m_FrameInUseCount);
}
if(m_LinearAlgorithm)
{
json.WriteString("LinearAlgorithm");
json.WriteBool(true);
}
}
else
{
json.WriteString("PreferredBlockSize");
json.WriteNumber(m_PreferredBlockSize);
}
json.WriteString("Blocks");
json.BeginObject();
for(size_t i = 0; i < m_Blocks.size(); ++i)
{
json.BeginString();
json.ContinueString(m_Blocks[i]->GetId());
json.EndString();
m_Blocks[i]->m_pMetadata->PrintDetailedMap(json);
}
json.EndObject();
json.EndObject();
}
#endif // #if VMA_STATS_STRING_ENABLED
VmaDefragmentator* VmaBlockVector::EnsureDefragmentator(
VmaAllocator hAllocator,
uint32_t currentFrameIndex)
{
if(m_pDefragmentator == VMA_NULL)
{
m_pDefragmentator = vma_new(m_hAllocator, VmaDefragmentator)(
hAllocator,
this,
currentFrameIndex);
}
return m_pDefragmentator;
}
VkResult VmaBlockVector::Defragment(
VmaDefragmentationStats* pDefragmentationStats,
VkDeviceSize& maxBytesToMove,
uint32_t& maxAllocationsToMove)
{
if(m_pDefragmentator == VMA_NULL)
{
return VK_SUCCESS;
}
VmaMutexLock lock(m_Mutex, m_hAllocator->m_UseMutex);
// Defragment.
VkResult result = m_pDefragmentator->Defragment(maxBytesToMove, maxAllocationsToMove);
// Accumulate statistics.
if(pDefragmentationStats != VMA_NULL)
{
const VkDeviceSize bytesMoved = m_pDefragmentator->GetBytesMoved();
const uint32_t allocationsMoved = m_pDefragmentator->GetAllocationsMoved();
pDefragmentationStats->bytesMoved += bytesMoved;
pDefragmentationStats->allocationsMoved += allocationsMoved;
VMA_ASSERT(bytesMoved <= maxBytesToMove);
VMA_ASSERT(allocationsMoved <= maxAllocationsToMove);
maxBytesToMove -= bytesMoved;
maxAllocationsToMove -= allocationsMoved;
}
// Free empty blocks.
m_HasEmptyBlock = false;
for(size_t blockIndex = m_Blocks.size(); blockIndex--; )
{
VmaDeviceMemoryBlock* pBlock = m_Blocks[blockIndex];
if(pBlock->m_pMetadata->IsEmpty())
{
if(m_Blocks.size() > m_MinBlockCount)
{
if(pDefragmentationStats != VMA_NULL)
{
++pDefragmentationStats->deviceMemoryBlocksFreed;
pDefragmentationStats->bytesFreed += pBlock->m_pMetadata->GetSize();
}
VmaVectorRemove(m_Blocks, blockIndex);
pBlock->Destroy(m_hAllocator);
vma_delete(m_hAllocator, pBlock);
}
else
{
m_HasEmptyBlock = true;
}
}
}
return result;
}
void VmaBlockVector::DestroyDefragmentator()
{
if(m_pDefragmentator != VMA_NULL)
{
vma_delete(m_hAllocator, m_pDefragmentator);
m_pDefragmentator = VMA_NULL;
}
}
void VmaBlockVector::MakePoolAllocationsLost(
uint32_t currentFrameIndex,
size_t* pLostAllocationCount)
{
VmaMutexLock lock(m_Mutex, m_hAllocator->m_UseMutex);
size_t lostAllocationCount = 0;
for(uint32_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex)
{
VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex];
VMA_ASSERT(pBlock);
lostAllocationCount += pBlock->m_pMetadata->MakeAllocationsLost(currentFrameIndex, m_FrameInUseCount);
}
if(pLostAllocationCount != VMA_NULL)
{
*pLostAllocationCount = lostAllocationCount;
}
}
VkResult VmaBlockVector::CheckCorruption()
{
if(!IsCorruptionDetectionEnabled())
{
return VK_ERROR_FEATURE_NOT_PRESENT;
}
VmaMutexLock lock(m_Mutex, m_hAllocator->m_UseMutex);
for(uint32_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex)
{
VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex];
VMA_ASSERT(pBlock);
VkResult res = pBlock->CheckCorruption(m_hAllocator);
if(res != VK_SUCCESS)
{
return res;
}
}
return VK_SUCCESS;
}
void VmaBlockVector::AddStats(VmaStats* pStats)
{
const uint32_t memTypeIndex = m_MemoryTypeIndex;
const uint32_t memHeapIndex = m_hAllocator->MemoryTypeIndexToHeapIndex(memTypeIndex);
VmaMutexLock lock(m_Mutex, m_hAllocator->m_UseMutex);
for(uint32_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex)
{
const VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex];
VMA_ASSERT(pBlock);
VMA_HEAVY_ASSERT(pBlock->Validate());
VmaStatInfo allocationStatInfo;
pBlock->m_pMetadata->CalcAllocationStatInfo(allocationStatInfo);
VmaAddStatInfo(pStats->total, allocationStatInfo);
VmaAddStatInfo(pStats->memoryType[memTypeIndex], allocationStatInfo);
VmaAddStatInfo(pStats->memoryHeap[memHeapIndex], allocationStatInfo);
}
}
////////////////////////////////////////////////////////////////////////////////
// VmaDefragmentator members definition
VmaDefragmentator::VmaDefragmentator(
VmaAllocator hAllocator,
VmaBlockVector* pBlockVector,
uint32_t currentFrameIndex) :
m_hAllocator(hAllocator),
m_pBlockVector(pBlockVector),
m_CurrentFrameIndex(currentFrameIndex),
m_BytesMoved(0),
m_AllocationsMoved(0),
m_Allocations(VmaStlAllocator<AllocationInfo>(hAllocator->GetAllocationCallbacks())),
m_Blocks(VmaStlAllocator<BlockInfo*>(hAllocator->GetAllocationCallbacks()))
{
VMA_ASSERT(!pBlockVector->UsesLinearAlgorithm());
}
VmaDefragmentator::~VmaDefragmentator()
{
for(size_t i = m_Blocks.size(); i--; )
{
vma_delete(m_hAllocator, m_Blocks[i]);
}
}
void VmaDefragmentator::AddAllocation(VmaAllocation hAlloc, VkBool32* pChanged)
{
AllocationInfo allocInfo;
allocInfo.m_hAllocation = hAlloc;
allocInfo.m_pChanged = pChanged;
m_Allocations.push_back(allocInfo);
}
VkResult VmaDefragmentator::BlockInfo::EnsureMapping(VmaAllocator hAllocator, void** ppMappedData)
{
// It has already been mapped for defragmentation.
if(m_pMappedDataForDefragmentation)
{
*ppMappedData = m_pMappedDataForDefragmentation;
return VK_SUCCESS;
}
// It is originally mapped.
if(m_pBlock->GetMappedData())
{
*ppMappedData = m_pBlock->GetMappedData();
return VK_SUCCESS;
}
// Map on first usage.
VkResult res = m_pBlock->Map(hAllocator, 1, &m_pMappedDataForDefragmentation);
*ppMappedData = m_pMappedDataForDefragmentation;
return res;
}
void VmaDefragmentator::BlockInfo::Unmap(VmaAllocator hAllocator)
{
if(m_pMappedDataForDefragmentation != VMA_NULL)
{
m_pBlock->Unmap(hAllocator, 1);
}
}
VkResult VmaDefragmentator::DefragmentRound(
VkDeviceSize maxBytesToMove,
uint32_t maxAllocationsToMove)
{
if(m_Blocks.empty())
{
return VK_SUCCESS;
}
size_t srcBlockIndex = m_Blocks.size() - 1;
size_t srcAllocIndex = SIZE_MAX;
for(;;)
{
// 1. Find next allocation to move.
// 1.1. Start from last to first m_Blocks - they are sorted from most "destination" to most "source".
// 1.2. Then start from last to first m_Allocations - they are sorted from largest to smallest.
while(srcAllocIndex >= m_Blocks[srcBlockIndex]->m_Allocations.size())
{
if(m_Blocks[srcBlockIndex]->m_Allocations.empty())
{
// Finished: no more allocations to process.
if(srcBlockIndex == 0)
{
return VK_SUCCESS;
}
else
{
--srcBlockIndex;
srcAllocIndex = SIZE_MAX;
}
}
else
{
srcAllocIndex = m_Blocks[srcBlockIndex]->m_Allocations.size() - 1;
}
}
BlockInfo* pSrcBlockInfo = m_Blocks[srcBlockIndex];
AllocationInfo& allocInfo = pSrcBlockInfo->m_Allocations[srcAllocIndex];
const VkDeviceSize size = allocInfo.m_hAllocation->GetSize();
const VkDeviceSize srcOffset = allocInfo.m_hAllocation->GetOffset();
const VkDeviceSize alignment = allocInfo.m_hAllocation->GetAlignment();
const VmaSuballocationType suballocType = allocInfo.m_hAllocation->GetSuballocationType();
// 2. Try to find new place for this allocation in preceding or current block.
for(size_t dstBlockIndex = 0; dstBlockIndex <= srcBlockIndex; ++dstBlockIndex)
{
BlockInfo* pDstBlockInfo = m_Blocks[dstBlockIndex];
VmaAllocationRequest dstAllocRequest;
if(pDstBlockInfo->m_pBlock->m_pMetadata->CreateAllocationRequest(
m_CurrentFrameIndex,
m_pBlockVector->GetFrameInUseCount(),
m_pBlockVector->GetBufferImageGranularity(),
size,
alignment,
false, // upperAddress
suballocType,
false, // canMakeOtherLost
&dstAllocRequest) &&
MoveMakesSense(
dstBlockIndex, dstAllocRequest.offset, srcBlockIndex, srcOffset))
{
VMA_ASSERT(dstAllocRequest.itemsToMakeLostCount == 0);
// Reached limit on number of allocations or bytes to move.
if((m_AllocationsMoved + 1 > maxAllocationsToMove) ||
(m_BytesMoved + size > maxBytesToMove))
{
return VK_INCOMPLETE;
}
void* pDstMappedData = VMA_NULL;
VkResult res = pDstBlockInfo->EnsureMapping(m_hAllocator, &pDstMappedData);
if(res != VK_SUCCESS)
{
return res;
}
void* pSrcMappedData = VMA_NULL;
res = pSrcBlockInfo->EnsureMapping(m_hAllocator, &pSrcMappedData);
if(res != VK_SUCCESS)
{
return res;
}
// THE PLACE WHERE ACTUAL DATA COPY HAPPENS.
memcpy(
reinterpret_cast<char*>(pDstMappedData) + dstAllocRequest.offset,
reinterpret_cast<char*>(pSrcMappedData) + srcOffset,
static_cast<size_t>(size));
if(VMA_DEBUG_MARGIN > 0)
{
VmaWriteMagicValue(pDstMappedData, dstAllocRequest.offset - VMA_DEBUG_MARGIN);
VmaWriteMagicValue(pDstMappedData, dstAllocRequest.offset + size);
}
pDstBlockInfo->m_pBlock->m_pMetadata->Alloc(
dstAllocRequest,
suballocType,
size,
false, // upperAddress
allocInfo.m_hAllocation);
pSrcBlockInfo->m_pBlock->m_pMetadata->FreeAtOffset(srcOffset);
allocInfo.m_hAllocation->ChangeBlockAllocation(m_hAllocator, pDstBlockInfo->m_pBlock, dstAllocRequest.offset);
if(allocInfo.m_pChanged != VMA_NULL)
{
*allocInfo.m_pChanged = VK_TRUE;
}
++m_AllocationsMoved;
m_BytesMoved += size;
VmaVectorRemove(pSrcBlockInfo->m_Allocations, srcAllocIndex);
break;
}
}
// If not processed, this allocInfo remains in pBlockInfo->m_Allocations for next round.
if(srcAllocIndex > 0)
{
--srcAllocIndex;
}
else
{
if(srcBlockIndex > 0)
{
--srcBlockIndex;
srcAllocIndex = SIZE_MAX;
}
else
{
return VK_SUCCESS;
}
}
}
}
VkResult VmaDefragmentator::Defragment(
VkDeviceSize maxBytesToMove,
uint32_t maxAllocationsToMove)
{
if(m_Allocations.empty())
{
return VK_SUCCESS;
}
// Create block info for each block.
const size_t blockCount = m_pBlockVector->m_Blocks.size();
for(size_t blockIndex = 0; blockIndex < blockCount; ++blockIndex)
{
BlockInfo* pBlockInfo = vma_new(m_hAllocator, BlockInfo)(m_hAllocator->GetAllocationCallbacks());
pBlockInfo->m_pBlock = m_pBlockVector->m_Blocks[blockIndex];
m_Blocks.push_back(pBlockInfo);
}
// Sort them by m_pBlock pointer value.
VMA_SORT(m_Blocks.begin(), m_Blocks.end(), BlockPointerLess());
// Move allocation infos from m_Allocations to appropriate m_Blocks[memTypeIndex].m_Allocations.
for(size_t blockIndex = 0, allocCount = m_Allocations.size(); blockIndex < allocCount; ++blockIndex)
{
AllocationInfo& allocInfo = m_Allocations[blockIndex];
// Now as we are inside VmaBlockVector::m_Mutex, we can make final check if this allocation was not lost.
if(allocInfo.m_hAllocation->GetLastUseFrameIndex() != VMA_FRAME_INDEX_LOST)
{
VmaDeviceMemoryBlock* pBlock = allocInfo.m_hAllocation->GetBlock();
BlockInfoVector::iterator it = VmaBinaryFindFirstNotLess(m_Blocks.begin(), m_Blocks.end(), pBlock, BlockPointerLess());
if(it != m_Blocks.end() && (*it)->m_pBlock == pBlock)
{
(*it)->m_Allocations.push_back(allocInfo);
}
else
{
VMA_ASSERT(0);
}
}
}
m_Allocations.clear();
for(size_t blockIndex = 0; blockIndex < blockCount; ++blockIndex)
{
BlockInfo* pBlockInfo = m_Blocks[blockIndex];
pBlockInfo->CalcHasNonMovableAllocations();
pBlockInfo->SortAllocationsBySizeDescecnding();
}
// Sort m_Blocks this time by the main criterium, from most "destination" to most "source" blocks.
VMA_SORT(m_Blocks.begin(), m_Blocks.end(), BlockInfoCompareMoveDestination());
// Execute defragmentation rounds (the main part).
VkResult result = VK_SUCCESS;
for(size_t round = 0; (round < 2) && (result == VK_SUCCESS); ++round)
{
result = DefragmentRound(maxBytesToMove, maxAllocationsToMove);
}
// Unmap blocks that were mapped for defragmentation.
for(size_t blockIndex = 0; blockIndex < blockCount; ++blockIndex)
{
m_Blocks[blockIndex]->Unmap(m_hAllocator);
}
return result;
}
bool VmaDefragmentator::MoveMakesSense(
size_t dstBlockIndex, VkDeviceSize dstOffset,
size_t srcBlockIndex, VkDeviceSize srcOffset)
{
if(dstBlockIndex < srcBlockIndex)
{
return true;
}
if(dstBlockIndex > srcBlockIndex)
{
return false;
}
if(dstOffset < srcOffset)
{
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
// VmaRecorder
#if VMA_RECORDING_ENABLED
VmaRecorder::VmaRecorder() :
m_UseMutex(true),
m_Flags(0),
m_File(VMA_NULL),
m_Freq(INT64_MAX),
m_StartCounter(INT64_MAX)
{
}
VkResult VmaRecorder::Init(const VmaRecordSettings& settings, bool useMutex)
{
m_UseMutex = useMutex;
m_Flags = settings.flags;
QueryPerformanceFrequency((LARGE_INTEGER*)&m_Freq);
QueryPerformanceCounter((LARGE_INTEGER*)&m_StartCounter);
// Open file for writing.
errno_t err = fopen_s(&m_File, settings.pFilePath, "wb");
if(err != 0)
{
return VK_ERROR_INITIALIZATION_FAILED;
}
// Write header.
fprintf(m_File, "%s\n", "Vulkan Memory Allocator,Calls recording");
fprintf(m_File, "%s\n", "1,3");
return VK_SUCCESS;
}
VmaRecorder::~VmaRecorder()
{
if(m_File != VMA_NULL)
{
fclose(m_File);
}
}
void VmaRecorder::RecordCreateAllocator(uint32_t frameIndex)
{
CallParams callParams;
GetBasicParams(callParams);
VmaMutexLock lock(m_FileMutex, m_UseMutex);
fprintf(m_File, "%u,%.3f,%u,vmaCreateAllocator\n", callParams.threadId, callParams.time, frameIndex);
Flush();
}
void VmaRecorder::RecordDestroyAllocator(uint32_t frameIndex)
{
CallParams callParams;
GetBasicParams(callParams);
VmaMutexLock lock(m_FileMutex, m_UseMutex);
fprintf(m_File, "%u,%.3f,%u,vmaDestroyAllocator\n", callParams.threadId, callParams.time, frameIndex);
Flush();
}
void VmaRecorder::RecordCreatePool(uint32_t frameIndex, const VmaPoolCreateInfo& createInfo, VmaPool pool)
{
CallParams callParams;
GetBasicParams(callParams);
VmaMutexLock lock(m_FileMutex, m_UseMutex);
fprintf(m_File, "%u,%.3f,%u,vmaCreatePool,%u,%u,%llu,%llu,%llu,%u,%p\n", callParams.threadId, callParams.time, frameIndex,
createInfo.memoryTypeIndex,
createInfo.flags,
createInfo.blockSize,
createInfo.minBlockCount,
createInfo.maxBlockCount,
createInfo.frameInUseCount,
pool);
Flush();
}
void VmaRecorder::RecordDestroyPool(uint32_t frameIndex, VmaPool pool)
{
CallParams callParams;
GetBasicParams(callParams);
VmaMutexLock lock(m_FileMutex, m_UseMutex);
fprintf(m_File, "%u,%.3f,%u,vmaDestroyPool,%p\n", callParams.threadId, callParams.time, frameIndex,
pool);
Flush();
}
void VmaRecorder::RecordAllocateMemory(uint32_t frameIndex,
const VkMemoryRequirements& vkMemReq,
const VmaAllocationCreateInfo& createInfo,
VmaAllocation allocation)
{
CallParams callParams;
GetBasicParams(callParams);
VmaMutexLock lock(m_FileMutex, m_UseMutex);
UserDataString userDataStr(createInfo.flags, createInfo.pUserData);
fprintf(m_File, "%u,%.3f,%u,vmaAllocateMemory,%llu,%llu,%u,%u,%u,%u,%u,%u,%p,%p,%s\n", callParams.threadId, callParams.time, frameIndex,
vkMemReq.size,
vkMemReq.alignment,
vkMemReq.memoryTypeBits,
createInfo.flags,
createInfo.usage,
createInfo.requiredFlags,
createInfo.preferredFlags,
createInfo.memoryTypeBits,
createInfo.pool,
allocation,
userDataStr.GetString());
Flush();
}
void VmaRecorder::RecordAllocateMemoryForBuffer(uint32_t frameIndex,
const VkMemoryRequirements& vkMemReq,
bool requiresDedicatedAllocation,
bool prefersDedicatedAllocation,
const VmaAllocationCreateInfo& createInfo,
VmaAllocation allocation)
{
CallParams callParams;
GetBasicParams(callParams);
VmaMutexLock lock(m_FileMutex, m_UseMutex);
UserDataString userDataStr(createInfo.flags, createInfo.pUserData);
fprintf(m_File, "%u,%.3f,%u,vmaAllocateMemoryForBuffer,%llu,%llu,%u,%u,%u,%u,%u,%u,%u,%u,%p,%p,%s\n", callParams.threadId, callParams.time, frameIndex,
vkMemReq.size,
vkMemReq.alignment,
vkMemReq.memoryTypeBits,
requiresDedicatedAllocation ? 1 : 0,
prefersDedicatedAllocation ? 1 : 0,
createInfo.flags,
createInfo.usage,
createInfo.requiredFlags,
createInfo.preferredFlags,
createInfo.memoryTypeBits,
createInfo.pool,
allocation,
userDataStr.GetString());
Flush();
}
void VmaRecorder::RecordAllocateMemoryForImage(uint32_t frameIndex,
const VkMemoryRequirements& vkMemReq,
bool requiresDedicatedAllocation,
bool prefersDedicatedAllocation,
const VmaAllocationCreateInfo& createInfo,
VmaAllocation allocation)
{
CallParams callParams;
GetBasicParams(callParams);
VmaMutexLock lock(m_FileMutex, m_UseMutex);
UserDataString userDataStr(createInfo.flags, createInfo.pUserData);
fprintf(m_File, "%u,%.3f,%u,vmaAllocateMemoryForImage,%llu,%llu,%u,%u,%u,%u,%u,%u,%u,%u,%p,%p,%s\n", callParams.threadId, callParams.time, frameIndex,
vkMemReq.size,
vkMemReq.alignment,
vkMemReq.memoryTypeBits,
requiresDedicatedAllocation ? 1 : 0,
prefersDedicatedAllocation ? 1 : 0,
createInfo.flags,
createInfo.usage,
createInfo.requiredFlags,
createInfo.preferredFlags,
createInfo.memoryTypeBits,
createInfo.pool,
allocation,
userDataStr.GetString());
Flush();
}
void VmaRecorder::RecordFreeMemory(uint32_t frameIndex,
VmaAllocation allocation)
{
CallParams callParams;
GetBasicParams(callParams);
VmaMutexLock lock(m_FileMutex, m_UseMutex);
fprintf(m_File, "%u,%.3f,%u,vmaFreeMemory,%p\n", callParams.threadId, callParams.time, frameIndex,
allocation);
Flush();
}
void VmaRecorder::RecordSetAllocationUserData(uint32_t frameIndex,
VmaAllocation allocation,
const void* pUserData)
{
CallParams callParams;
GetBasicParams(callParams);
VmaMutexLock lock(m_FileMutex, m_UseMutex);
UserDataString userDataStr(
allocation->IsUserDataString() ? VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT : 0,
pUserData);
fprintf(m_File, "%u,%.3f,%u,vmaSetAllocationUserData,%p,%s\n", callParams.threadId, callParams.time, frameIndex,
allocation,
userDataStr.GetString());
Flush();
}
void VmaRecorder::RecordCreateLostAllocation(uint32_t frameIndex,
VmaAllocation allocation)
{
CallParams callParams;
GetBasicParams(callParams);
VmaMutexLock lock(m_FileMutex, m_UseMutex);
fprintf(m_File, "%u,%.3f,%u,vmaCreateLostAllocation,%p\n", callParams.threadId, callParams.time, frameIndex,
allocation);
Flush();
}
void VmaRecorder::RecordMapMemory(uint32_t frameIndex,
VmaAllocation allocation)
{
CallParams callParams;
GetBasicParams(callParams);
VmaMutexLock lock(m_FileMutex, m_UseMutex);
fprintf(m_File, "%u,%.3f,%u,vmaMapMemory,%p\n", callParams.threadId, callParams.time, frameIndex,
allocation);
Flush();
}
void VmaRecorder::RecordUnmapMemory(uint32_t frameIndex,
VmaAllocation allocation)
{
CallParams callParams;
GetBasicParams(callParams);
VmaMutexLock lock(m_FileMutex, m_UseMutex);
fprintf(m_File, "%u,%.3f,%u,vmaUnmapMemory,%p\n", callParams.threadId, callParams.time, frameIndex,
allocation);
Flush();
}
void VmaRecorder::RecordFlushAllocation(uint32_t frameIndex,
VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size)
{
CallParams callParams;
GetBasicParams(callParams);
VmaMutexLock lock(m_FileMutex, m_UseMutex);
fprintf(m_File, "%u,%.3f,%u,vmaFlushAllocation,%p,%llu,%llu\n", callParams.threadId, callParams.time, frameIndex,
allocation,
offset,
size);
Flush();
}
void VmaRecorder::RecordInvalidateAllocation(uint32_t frameIndex,
VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size)
{
CallParams callParams;
GetBasicParams(callParams);
VmaMutexLock lock(m_FileMutex, m_UseMutex);
fprintf(m_File, "%u,%.3f,%u,vmaInvalidateAllocation,%p,%llu,%llu\n", callParams.threadId, callParams.time, frameIndex,
allocation,
offset,
size);
Flush();
}
void VmaRecorder::RecordCreateBuffer(uint32_t frameIndex,
const VkBufferCreateInfo& bufCreateInfo,
const VmaAllocationCreateInfo& allocCreateInfo,
VmaAllocation allocation)
{
CallParams callParams;
GetBasicParams(callParams);
VmaMutexLock lock(m_FileMutex, m_UseMutex);
UserDataString userDataStr(allocCreateInfo.flags, allocCreateInfo.pUserData);
fprintf(m_File, "%u,%.3f,%u,vmaCreateBuffer,%u,%llu,%u,%u,%u,%u,%u,%u,%u,%p,%p,%s\n", callParams.threadId, callParams.time, frameIndex,
bufCreateInfo.flags,
bufCreateInfo.size,
bufCreateInfo.usage,
bufCreateInfo.sharingMode,
allocCreateInfo.flags,
allocCreateInfo.usage,
allocCreateInfo.requiredFlags,
allocCreateInfo.preferredFlags,
allocCreateInfo.memoryTypeBits,
allocCreateInfo.pool,
allocation,
userDataStr.GetString());
Flush();
}
void VmaRecorder::RecordCreateImage(uint32_t frameIndex,
const VkImageCreateInfo& imageCreateInfo,
const VmaAllocationCreateInfo& allocCreateInfo,
VmaAllocation allocation)
{
CallParams callParams;
GetBasicParams(callParams);
VmaMutexLock lock(m_FileMutex, m_UseMutex);
UserDataString userDataStr(allocCreateInfo.flags, allocCreateInfo.pUserData);
fprintf(m_File, "%u,%.3f,%u,vmaCreateImage,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%p,%p,%s\n", callParams.threadId, callParams.time, frameIndex,
imageCreateInfo.flags,
imageCreateInfo.imageType,
imageCreateInfo.format,
imageCreateInfo.extent.width,
imageCreateInfo.extent.height,
imageCreateInfo.extent.depth,
imageCreateInfo.mipLevels,
imageCreateInfo.arrayLayers,
imageCreateInfo.samples,
imageCreateInfo.tiling,
imageCreateInfo.usage,
imageCreateInfo.sharingMode,
imageCreateInfo.initialLayout,
allocCreateInfo.flags,
allocCreateInfo.usage,
allocCreateInfo.requiredFlags,
allocCreateInfo.preferredFlags,
allocCreateInfo.memoryTypeBits,
allocCreateInfo.pool,
allocation,
userDataStr.GetString());
Flush();
}
void VmaRecorder::RecordDestroyBuffer(uint32_t frameIndex,
VmaAllocation allocation)
{
CallParams callParams;
GetBasicParams(callParams);
VmaMutexLock lock(m_FileMutex, m_UseMutex);
fprintf(m_File, "%u,%.3f,%u,vmaDestroyBuffer,%p\n", callParams.threadId, callParams.time, frameIndex,
allocation);
Flush();
}
void VmaRecorder::RecordDestroyImage(uint32_t frameIndex,
VmaAllocation allocation)
{
CallParams callParams;
GetBasicParams(callParams);
VmaMutexLock lock(m_FileMutex, m_UseMutex);
fprintf(m_File, "%u,%.3f,%u,vmaDestroyImage,%p\n", callParams.threadId, callParams.time, frameIndex,
allocation);
Flush();
}
void VmaRecorder::RecordTouchAllocation(uint32_t frameIndex,
VmaAllocation allocation)
{
CallParams callParams;
GetBasicParams(callParams);
VmaMutexLock lock(m_FileMutex, m_UseMutex);
fprintf(m_File, "%u,%.3f,%u,vmaTouchAllocation,%p\n", callParams.threadId, callParams.time, frameIndex,
allocation);
Flush();
}
void VmaRecorder::RecordGetAllocationInfo(uint32_t frameIndex,
VmaAllocation allocation)
{
CallParams callParams;
GetBasicParams(callParams);
VmaMutexLock lock(m_FileMutex, m_UseMutex);
fprintf(m_File, "%u,%.3f,%u,vmaGetAllocationInfo,%p\n", callParams.threadId, callParams.time, frameIndex,
allocation);
Flush();
}
void VmaRecorder::RecordMakePoolAllocationsLost(uint32_t frameIndex,
VmaPool pool)
{
CallParams callParams;
GetBasicParams(callParams);
VmaMutexLock lock(m_FileMutex, m_UseMutex);
fprintf(m_File, "%u,%.3f,%u,vmaMakePoolAllocationsLost,%p\n", callParams.threadId, callParams.time, frameIndex,
pool);
Flush();
}
VmaRecorder::UserDataString::UserDataString(VmaAllocationCreateFlags allocFlags, const void* pUserData)
{
if(pUserData != VMA_NULL)
{
if((allocFlags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0)
{
m_Str = (const char*)pUserData;
}
else
{
sprintf_s(m_PtrStr, "%p", pUserData);
m_Str = m_PtrStr;
}
}
else
{
m_Str = "";
}
}
void VmaRecorder::WriteConfiguration(
const VkPhysicalDeviceProperties& devProps,
const VkPhysicalDeviceMemoryProperties& memProps,
bool dedicatedAllocationExtensionEnabled)
{
fprintf(m_File, "Config,Begin\n");
fprintf(m_File, "PhysicalDevice,apiVersion,%u\n", devProps.apiVersion);
fprintf(m_File, "PhysicalDevice,driverVersion,%u\n", devProps.driverVersion);
fprintf(m_File, "PhysicalDevice,vendorID,%u\n", devProps.vendorID);
fprintf(m_File, "PhysicalDevice,deviceID,%u\n", devProps.deviceID);
fprintf(m_File, "PhysicalDevice,deviceType,%u\n", devProps.deviceType);
fprintf(m_File, "PhysicalDevice,deviceName,%s\n", devProps.deviceName);
fprintf(m_File, "PhysicalDeviceLimits,maxMemoryAllocationCount,%u\n", devProps.limits.maxMemoryAllocationCount);
fprintf(m_File, "PhysicalDeviceLimits,bufferImageGranularity,%llu\n", devProps.limits.bufferImageGranularity);
fprintf(m_File, "PhysicalDeviceLimits,nonCoherentAtomSize,%llu\n", devProps.limits.nonCoherentAtomSize);
fprintf(m_File, "PhysicalDeviceMemory,HeapCount,%u\n", memProps.memoryHeapCount);
for(uint32_t i = 0; i < memProps.memoryHeapCount; ++i)
{
fprintf(m_File, "PhysicalDeviceMemory,Heap,%u,size,%llu\n", i, memProps.memoryHeaps[i].size);
fprintf(m_File, "PhysicalDeviceMemory,Heap,%u,flags,%u\n", i, memProps.memoryHeaps[i].flags);
}
fprintf(m_File, "PhysicalDeviceMemory,TypeCount,%u\n", memProps.memoryTypeCount);
for(uint32_t i = 0; i < memProps.memoryTypeCount; ++i)
{
fprintf(m_File, "PhysicalDeviceMemory,Type,%u,heapIndex,%u\n", i, memProps.memoryTypes[i].heapIndex);
fprintf(m_File, "PhysicalDeviceMemory,Type,%u,propertyFlags,%u\n", i, memProps.memoryTypes[i].propertyFlags);
}
fprintf(m_File, "Extension,VK_KHR_dedicated_allocation,%u\n", dedicatedAllocationExtensionEnabled ? 1 : 0);
fprintf(m_File, "Macro,VMA_DEBUG_ALWAYS_DEDICATED_MEMORY,%u\n", VMA_DEBUG_ALWAYS_DEDICATED_MEMORY ? 1 : 0);
fprintf(m_File, "Macro,VMA_DEBUG_ALIGNMENT,%llu\n", (VkDeviceSize)VMA_DEBUG_ALIGNMENT);
fprintf(m_File, "Macro,VMA_DEBUG_MARGIN,%llu\n", (VkDeviceSize)VMA_DEBUG_MARGIN);
fprintf(m_File, "Macro,VMA_DEBUG_INITIALIZE_ALLOCATIONS,%u\n", VMA_DEBUG_INITIALIZE_ALLOCATIONS ? 1 : 0);
fprintf(m_File, "Macro,VMA_DEBUG_DETECT_CORRUPTION,%u\n", VMA_DEBUG_DETECT_CORRUPTION ? 1 : 0);
fprintf(m_File, "Macro,VMA_DEBUG_GLOBAL_MUTEX,%u\n", VMA_DEBUG_GLOBAL_MUTEX ? 1 : 0);
fprintf(m_File, "Macro,VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY,%llu\n", (VkDeviceSize)VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY);
fprintf(m_File, "Macro,VMA_SMALL_HEAP_MAX_SIZE,%llu\n", (VkDeviceSize)VMA_SMALL_HEAP_MAX_SIZE);
fprintf(m_File, "Macro,VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE,%llu\n", (VkDeviceSize)VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE);
fprintf(m_File, "Config,End\n");
}
void VmaRecorder::GetBasicParams(CallParams& outParams)
{
outParams.threadId = GetCurrentThreadId();
LARGE_INTEGER counter;
QueryPerformanceCounter(&counter);
outParams.time = (double)(counter.QuadPart - m_StartCounter) / (double)m_Freq;
}
void VmaRecorder::Flush()
{
if((m_Flags & VMA_RECORD_FLUSH_AFTER_CALL_BIT) != 0)
{
fflush(m_File);
}
}
#endif // #if VMA_RECORDING_ENABLED
////////////////////////////////////////////////////////////////////////////////
// VmaAllocator_T
VmaAllocator_T::VmaAllocator_T(const VmaAllocatorCreateInfo* pCreateInfo) :
m_UseMutex((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT) == 0),
m_UseKhrDedicatedAllocation((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT) != 0),
m_hDevice(pCreateInfo->device),
m_AllocationCallbacksSpecified(pCreateInfo->pAllocationCallbacks != VMA_NULL),
m_AllocationCallbacks(pCreateInfo->pAllocationCallbacks ?
*pCreateInfo->pAllocationCallbacks : VmaEmptyAllocationCallbacks),
m_PreferredLargeHeapBlockSize(0),
m_PhysicalDevice(pCreateInfo->physicalDevice),
m_CurrentFrameIndex(0),
m_Pools(VmaStlAllocator<VmaPool>(GetAllocationCallbacks())),
m_NextPoolId(0)
#if VMA_RECORDING_ENABLED
,m_pRecorder(VMA_NULL)
#endif
{
if(VMA_DEBUG_DETECT_CORRUPTION)
{
// Needs to be multiply of uint32_t size because we are going to write VMA_CORRUPTION_DETECTION_MAGIC_VALUE to it.
VMA_ASSERT(VMA_DEBUG_MARGIN % sizeof(uint32_t) == 0);
}
VMA_ASSERT(pCreateInfo->physicalDevice && pCreateInfo->device);
#if !(VMA_DEDICATED_ALLOCATION)
if((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT) != 0)
{
VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT set but required extensions are disabled by preprocessor macros.");
}
#endif
memset(&m_DeviceMemoryCallbacks, 0 ,sizeof(m_DeviceMemoryCallbacks));
memset(&m_PhysicalDeviceProperties, 0, sizeof(m_PhysicalDeviceProperties));
memset(&m_MemProps, 0, sizeof(m_MemProps));
memset(&m_pBlockVectors, 0, sizeof(m_pBlockVectors));
memset(&m_pDedicatedAllocations, 0, sizeof(m_pDedicatedAllocations));
for(uint32_t i = 0; i < VK_MAX_MEMORY_HEAPS; ++i)
{
m_HeapSizeLimit[i] = VK_WHOLE_SIZE;
}
if(pCreateInfo->pDeviceMemoryCallbacks != VMA_NULL)
{
m_DeviceMemoryCallbacks.pfnAllocate = pCreateInfo->pDeviceMemoryCallbacks->pfnAllocate;
m_DeviceMemoryCallbacks.pfnFree = pCreateInfo->pDeviceMemoryCallbacks->pfnFree;
}
ImportVulkanFunctions(pCreateInfo->pVulkanFunctions);
(*m_VulkanFunctions.vkGetPhysicalDeviceProperties)(m_PhysicalDevice, &m_PhysicalDeviceProperties);
(*m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties)(m_PhysicalDevice, &m_MemProps);
m_PreferredLargeHeapBlockSize = (pCreateInfo->preferredLargeHeapBlockSize != 0) ?
pCreateInfo->preferredLargeHeapBlockSize : static_cast<VkDeviceSize>(VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE);
if(pCreateInfo->pHeapSizeLimit != VMA_NULL)
{
for(uint32_t heapIndex = 0; heapIndex < GetMemoryHeapCount(); ++heapIndex)
{
const VkDeviceSize limit = pCreateInfo->pHeapSizeLimit[heapIndex];
if(limit != VK_WHOLE_SIZE)
{
m_HeapSizeLimit[heapIndex] = limit;
if(limit < m_MemProps.memoryHeaps[heapIndex].size)
{
m_MemProps.memoryHeaps[heapIndex].size = limit;
}
}
}
}
for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
{
const VkDeviceSize preferredBlockSize = CalcPreferredBlockSize(memTypeIndex);
m_pBlockVectors[memTypeIndex] = vma_new(this, VmaBlockVector)(
this,
memTypeIndex,
preferredBlockSize,
0,
SIZE_MAX,
GetBufferImageGranularity(),
pCreateInfo->frameInUseCount,
false, // isCustomPool
false, // explicitBlockSize
false); // linearAlgorithm
// No need to call m_pBlockVectors[memTypeIndex][blockVectorTypeIndex]->CreateMinBlocks here,
// becase minBlockCount is 0.
m_pDedicatedAllocations[memTypeIndex] = vma_new(this, AllocationVectorType)(VmaStlAllocator<VmaAllocation>(GetAllocationCallbacks()));
}
}
VkResult VmaAllocator_T::Init(const VmaAllocatorCreateInfo* pCreateInfo)
{
VkResult res = VK_SUCCESS;
if(pCreateInfo->pRecordSettings != VMA_NULL &&
!VmaStrIsEmpty(pCreateInfo->pRecordSettings->pFilePath))
{
#if VMA_RECORDING_ENABLED
m_pRecorder = vma_new(this, VmaRecorder)();
res = m_pRecorder->Init(*pCreateInfo->pRecordSettings, m_UseMutex);
if(res != VK_SUCCESS)
{
return res;
}
m_pRecorder->WriteConfiguration(
m_PhysicalDeviceProperties,
m_MemProps,
m_UseKhrDedicatedAllocation);
m_pRecorder->RecordCreateAllocator(GetCurrentFrameIndex());
#else
VMA_ASSERT(0 && "VmaAllocatorCreateInfo::pRecordSettings used, but not supported due to VMA_RECORDING_ENABLED not defined to 1.");
return VK_ERROR_FEATURE_NOT_PRESENT;
#endif
}
return res;
}
VmaAllocator_T::~VmaAllocator_T()
{
#if VMA_RECORDING_ENABLED
if(m_pRecorder != VMA_NULL)
{
m_pRecorder->RecordDestroyAllocator(GetCurrentFrameIndex());
vma_delete(this, m_pRecorder);
}
#endif
VMA_ASSERT(m_Pools.empty());
for(size_t i = GetMemoryTypeCount(); i--; )
{
vma_delete(this, m_pDedicatedAllocations[i]);
vma_delete(this, m_pBlockVectors[i]);
}
}
void VmaAllocator_T::ImportVulkanFunctions(const VmaVulkanFunctions* pVulkanFunctions)
{
#if VMA_STATIC_VULKAN_FUNCTIONS == 1
m_VulkanFunctions.vkGetPhysicalDeviceProperties = &vkGetPhysicalDeviceProperties;
m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties = &vkGetPhysicalDeviceMemoryProperties;
m_VulkanFunctions.vkAllocateMemory = &vkAllocateMemory;
m_VulkanFunctions.vkFreeMemory = &vkFreeMemory;
m_VulkanFunctions.vkMapMemory = &vkMapMemory;
m_VulkanFunctions.vkUnmapMemory = &vkUnmapMemory;
m_VulkanFunctions.vkFlushMappedMemoryRanges = &vkFlushMappedMemoryRanges;
m_VulkanFunctions.vkInvalidateMappedMemoryRanges = &vkInvalidateMappedMemoryRanges;
m_VulkanFunctions.vkBindBufferMemory = &vkBindBufferMemory;
m_VulkanFunctions.vkBindImageMemory = &vkBindImageMemory;
m_VulkanFunctions.vkGetBufferMemoryRequirements = &vkGetBufferMemoryRequirements;
m_VulkanFunctions.vkGetImageMemoryRequirements = &vkGetImageMemoryRequirements;
m_VulkanFunctions.vkCreateBuffer = &vkCreateBuffer;
m_VulkanFunctions.vkDestroyBuffer = &vkDestroyBuffer;
m_VulkanFunctions.vkCreateImage = &vkCreateImage;
m_VulkanFunctions.vkDestroyImage = &vkDestroyImage;
#if VMA_DEDICATED_ALLOCATION
if(m_UseKhrDedicatedAllocation)
{
m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR =
(PFN_vkGetBufferMemoryRequirements2KHR)vkGetDeviceProcAddr(m_hDevice, "vkGetBufferMemoryRequirements2KHR");
m_VulkanFunctions.vkGetImageMemoryRequirements2KHR =
(PFN_vkGetImageMemoryRequirements2KHR)vkGetDeviceProcAddr(m_hDevice, "vkGetImageMemoryRequirements2KHR");
}
#endif // #if VMA_DEDICATED_ALLOCATION
#endif // #if VMA_STATIC_VULKAN_FUNCTIONS == 1
#define VMA_COPY_IF_NOT_NULL(funcName) \
if(pVulkanFunctions->funcName != VMA_NULL) m_VulkanFunctions.funcName = pVulkanFunctions->funcName;
if(pVulkanFunctions != VMA_NULL)
{
VMA_COPY_IF_NOT_NULL(vkGetPhysicalDeviceProperties);
VMA_COPY_IF_NOT_NULL(vkGetPhysicalDeviceMemoryProperties);
VMA_COPY_IF_NOT_NULL(vkAllocateMemory);
VMA_COPY_IF_NOT_NULL(vkFreeMemory);
VMA_COPY_IF_NOT_NULL(vkMapMemory);
VMA_COPY_IF_NOT_NULL(vkUnmapMemory);
VMA_COPY_IF_NOT_NULL(vkFlushMappedMemoryRanges);
VMA_COPY_IF_NOT_NULL(vkInvalidateMappedMemoryRanges);
VMA_COPY_IF_NOT_NULL(vkBindBufferMemory);
VMA_COPY_IF_NOT_NULL(vkBindImageMemory);
VMA_COPY_IF_NOT_NULL(vkGetBufferMemoryRequirements);
VMA_COPY_IF_NOT_NULL(vkGetImageMemoryRequirements);
VMA_COPY_IF_NOT_NULL(vkCreateBuffer);
VMA_COPY_IF_NOT_NULL(vkDestroyBuffer);
VMA_COPY_IF_NOT_NULL(vkCreateImage);
VMA_COPY_IF_NOT_NULL(vkDestroyImage);
#if VMA_DEDICATED_ALLOCATION
VMA_COPY_IF_NOT_NULL(vkGetBufferMemoryRequirements2KHR);
VMA_COPY_IF_NOT_NULL(vkGetImageMemoryRequirements2KHR);
#endif
}
#undef VMA_COPY_IF_NOT_NULL
// If these asserts are hit, you must either #define VMA_STATIC_VULKAN_FUNCTIONS 1
// or pass valid pointers as VmaAllocatorCreateInfo::pVulkanFunctions.
VMA_ASSERT(m_VulkanFunctions.vkGetPhysicalDeviceProperties != VMA_NULL);
VMA_ASSERT(m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties != VMA_NULL);
VMA_ASSERT(m_VulkanFunctions.vkAllocateMemory != VMA_NULL);
VMA_ASSERT(m_VulkanFunctions.vkFreeMemory != VMA_NULL);
VMA_ASSERT(m_VulkanFunctions.vkMapMemory != VMA_NULL);
VMA_ASSERT(m_VulkanFunctions.vkUnmapMemory != VMA_NULL);
VMA_ASSERT(m_VulkanFunctions.vkFlushMappedMemoryRanges != VMA_NULL);
VMA_ASSERT(m_VulkanFunctions.vkInvalidateMappedMemoryRanges != VMA_NULL);
VMA_ASSERT(m_VulkanFunctions.vkBindBufferMemory != VMA_NULL);
VMA_ASSERT(m_VulkanFunctions.vkBindImageMemory != VMA_NULL);
VMA_ASSERT(m_VulkanFunctions.vkGetBufferMemoryRequirements != VMA_NULL);
VMA_ASSERT(m_VulkanFunctions.vkGetImageMemoryRequirements != VMA_NULL);
VMA_ASSERT(m_VulkanFunctions.vkCreateBuffer != VMA_NULL);
VMA_ASSERT(m_VulkanFunctions.vkDestroyBuffer != VMA_NULL);
VMA_ASSERT(m_VulkanFunctions.vkCreateImage != VMA_NULL);
VMA_ASSERT(m_VulkanFunctions.vkDestroyImage != VMA_NULL);
#if VMA_DEDICATED_ALLOCATION
if(m_UseKhrDedicatedAllocation)
{
VMA_ASSERT(m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR != VMA_NULL);
VMA_ASSERT(m_VulkanFunctions.vkGetImageMemoryRequirements2KHR != VMA_NULL);
}
#endif
}
VkDeviceSize VmaAllocator_T::CalcPreferredBlockSize(uint32_t memTypeIndex)
{
const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(memTypeIndex);
const VkDeviceSize heapSize = m_MemProps.memoryHeaps[heapIndex].size;
const bool isSmallHeap = heapSize <= VMA_SMALL_HEAP_MAX_SIZE;
return isSmallHeap ? (heapSize / 8) : m_PreferredLargeHeapBlockSize;
}
VkResult VmaAllocator_T::AllocateMemoryOfType(
VkDeviceSize size,
VkDeviceSize alignment,
bool dedicatedAllocation,
VkBuffer dedicatedBuffer,
VkImage dedicatedImage,
const VmaAllocationCreateInfo& createInfo,
uint32_t memTypeIndex,
VmaSuballocationType suballocType,
VmaAllocation* pAllocation)
{
VMA_ASSERT(pAllocation != VMA_NULL);
VMA_DEBUG_LOG(" AllocateMemory: MemoryTypeIndex=%u, Size=%llu", memTypeIndex, vkMemReq.size);
VmaAllocationCreateInfo finalCreateInfo = createInfo;
// If memory type is not HOST_VISIBLE, disable MAPPED.
if((finalCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0 &&
(m_MemProps.memoryTypes[memTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0)
{
finalCreateInfo.flags &= ~VMA_ALLOCATION_CREATE_MAPPED_BIT;
}
VmaBlockVector* const blockVector = m_pBlockVectors[memTypeIndex];
VMA_ASSERT(blockVector);
const VkDeviceSize preferredBlockSize = blockVector->GetPreferredBlockSize();
bool preferDedicatedMemory =
VMA_DEBUG_ALWAYS_DEDICATED_MEMORY ||
dedicatedAllocation ||
// Heuristics: Allocate dedicated memory if requested size if greater than half of preferred block size.
size > preferredBlockSize / 2;
if(preferDedicatedMemory &&
(finalCreateInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) == 0 &&
finalCreateInfo.pool == VK_NULL_HANDLE)
{
finalCreateInfo.flags |= VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT;
}
if((finalCreateInfo.flags & VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT) != 0)
{
if((finalCreateInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) != 0)
{
return VK_ERROR_OUT_OF_DEVICE_MEMORY;
}
else
{
return AllocateDedicatedMemory(
size,
suballocType,
memTypeIndex,
(finalCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0,
(finalCreateInfo.flags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0,
finalCreateInfo.pUserData,
dedicatedBuffer,
dedicatedImage,
pAllocation);
}
}
else
{
VkResult res = blockVector->Allocate(
VK_NULL_HANDLE, // hCurrentPool
m_CurrentFrameIndex.load(),
size,
alignment,
finalCreateInfo,
suballocType,
pAllocation);
if(res == VK_SUCCESS)
{
return res;
}
// 5. Try dedicated memory.
if((finalCreateInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) != 0)
{
return VK_ERROR_OUT_OF_DEVICE_MEMORY;
}
else
{
res = AllocateDedicatedMemory(
size,
suballocType,
memTypeIndex,
(finalCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0,
(finalCreateInfo.flags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0,
finalCreateInfo.pUserData,
dedicatedBuffer,
dedicatedImage,
pAllocation);
if(res == VK_SUCCESS)
{
// Succeeded: AllocateDedicatedMemory function already filld pMemory, nothing more to do here.
VMA_DEBUG_LOG(" Allocated as DedicatedMemory");
return VK_SUCCESS;
}
else
{
// Everything failed: Return error code.
VMA_DEBUG_LOG(" vkAllocateMemory FAILED");
return res;
}
}
}
}
VkResult VmaAllocator_T::AllocateDedicatedMemory(
VkDeviceSize size,
VmaSuballocationType suballocType,
uint32_t memTypeIndex,
bool map,
bool isUserDataString,
void* pUserData,
VkBuffer dedicatedBuffer,
VkImage dedicatedImage,
VmaAllocation* pAllocation)
{
VMA_ASSERT(pAllocation);
VkMemoryAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO };
allocInfo.memoryTypeIndex = memTypeIndex;
allocInfo.allocationSize = size;
#if VMA_DEDICATED_ALLOCATION
VkMemoryDedicatedAllocateInfoKHR dedicatedAllocInfo = { VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO_KHR };
if(m_UseKhrDedicatedAllocation)
{
if(dedicatedBuffer != VK_NULL_HANDLE)
{
VMA_ASSERT(dedicatedImage == VK_NULL_HANDLE);
dedicatedAllocInfo.buffer = dedicatedBuffer;
allocInfo.pNext = &dedicatedAllocInfo;
}
else if(dedicatedImage != VK_NULL_HANDLE)
{
dedicatedAllocInfo.image = dedicatedImage;
allocInfo.pNext = &dedicatedAllocInfo;
}
}
#endif // #if VMA_DEDICATED_ALLOCATION
// Allocate VkDeviceMemory.
VkDeviceMemory hMemory = VK_NULL_HANDLE;
VkResult res = AllocateVulkanMemory(&allocInfo, &hMemory);
if(res < 0)
{
VMA_DEBUG_LOG(" vkAllocateMemory FAILED");
return res;
}
void* pMappedData = VMA_NULL;
if(map)
{
res = (*m_VulkanFunctions.vkMapMemory)(
m_hDevice,
hMemory,
0,
VK_WHOLE_SIZE,
0,
&pMappedData);
if(res < 0)
{
VMA_DEBUG_LOG(" vkMapMemory FAILED");
FreeVulkanMemory(memTypeIndex, size, hMemory);
return res;
}
}
*pAllocation = vma_new(this, VmaAllocation_T)(m_CurrentFrameIndex.load(), isUserDataString);
(*pAllocation)->InitDedicatedAllocation(memTypeIndex, hMemory, suballocType, pMappedData, size);
(*pAllocation)->SetUserData(this, pUserData);
if(VMA_DEBUG_INITIALIZE_ALLOCATIONS)
{
FillAllocation(*pAllocation, VMA_ALLOCATION_FILL_PATTERN_CREATED);
}
// Register it in m_pDedicatedAllocations.
{
VmaMutexLock lock(m_DedicatedAllocationsMutex[memTypeIndex], m_UseMutex);
AllocationVectorType* pDedicatedAllocations = m_pDedicatedAllocations[memTypeIndex];
VMA_ASSERT(pDedicatedAllocations);
VmaVectorInsertSorted<VmaPointerLess>(*pDedicatedAllocations, *pAllocation);
}
VMA_DEBUG_LOG(" Allocated DedicatedMemory MemoryTypeIndex=#%u", memTypeIndex);
return VK_SUCCESS;
}
void VmaAllocator_T::GetBufferMemoryRequirements(
VkBuffer hBuffer,
VkMemoryRequirements& memReq,
bool& requiresDedicatedAllocation,
bool& prefersDedicatedAllocation) const
{
#if VMA_DEDICATED_ALLOCATION
if(m_UseKhrDedicatedAllocation)
{
VkBufferMemoryRequirementsInfo2KHR memReqInfo = { VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2_KHR };
memReqInfo.buffer = hBuffer;
VkMemoryDedicatedRequirementsKHR memDedicatedReq = { VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR };
VkMemoryRequirements2KHR memReq2 = { VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2_KHR };
memReq2.pNext = &memDedicatedReq;
(*m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR)(m_hDevice, &memReqInfo, &memReq2);
memReq = memReq2.memoryRequirements;
requiresDedicatedAllocation = (memDedicatedReq.requiresDedicatedAllocation != VK_FALSE);
prefersDedicatedAllocation = (memDedicatedReq.prefersDedicatedAllocation != VK_FALSE);
}
else
#endif // #if VMA_DEDICATED_ALLOCATION
{
(*m_VulkanFunctions.vkGetBufferMemoryRequirements)(m_hDevice, hBuffer, &memReq);
requiresDedicatedAllocation = false;
prefersDedicatedAllocation = false;
}
}
void VmaAllocator_T::GetImageMemoryRequirements(
VkImage hImage,
VkMemoryRequirements& memReq,
bool& requiresDedicatedAllocation,
bool& prefersDedicatedAllocation) const
{
#if VMA_DEDICATED_ALLOCATION
if(m_UseKhrDedicatedAllocation)
{
VkImageMemoryRequirementsInfo2KHR memReqInfo = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2_KHR };
memReqInfo.image = hImage;
VkMemoryDedicatedRequirementsKHR memDedicatedReq = { VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR };
VkMemoryRequirements2KHR memReq2 = { VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2_KHR };
memReq2.pNext = &memDedicatedReq;
(*m_VulkanFunctions.vkGetImageMemoryRequirements2KHR)(m_hDevice, &memReqInfo, &memReq2);
memReq = memReq2.memoryRequirements;
requiresDedicatedAllocation = (memDedicatedReq.requiresDedicatedAllocation != VK_FALSE);
prefersDedicatedAllocation = (memDedicatedReq.prefersDedicatedAllocation != VK_FALSE);
}
else
#endif // #if VMA_DEDICATED_ALLOCATION
{
(*m_VulkanFunctions.vkGetImageMemoryRequirements)(m_hDevice, hImage, &memReq);
requiresDedicatedAllocation = false;
prefersDedicatedAllocation = false;
}
}
VkResult VmaAllocator_T::AllocateMemory(
const VkMemoryRequirements& vkMemReq,
bool requiresDedicatedAllocation,
bool prefersDedicatedAllocation,
VkBuffer dedicatedBuffer,
VkImage dedicatedImage,
const VmaAllocationCreateInfo& createInfo,
VmaSuballocationType suballocType,
VmaAllocation* pAllocation)
{
if((createInfo.flags & VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT) != 0 &&
(createInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) != 0)
{
VMA_ASSERT(0 && "Specifying VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT together with VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT makes no sense.");
return VK_ERROR_OUT_OF_DEVICE_MEMORY;
}
if((createInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0 &&
(createInfo.flags & VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT) != 0)
{
VMA_ASSERT(0 && "Specifying VMA_ALLOCATION_CREATE_MAPPED_BIT together with VMA_ALLOCATION_CREATE_CAN_BECOME_LOST_BIT is invalid.");
return VK_ERROR_OUT_OF_DEVICE_MEMORY;
}
if(requiresDedicatedAllocation)
{
if((createInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) != 0)
{
VMA_ASSERT(0 && "VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT specified while dedicated allocation is required.");
return VK_ERROR_OUT_OF_DEVICE_MEMORY;
}
if(createInfo.pool != VK_NULL_HANDLE)
{
VMA_ASSERT(0 && "Pool specified while dedicated allocation is required.");
return VK_ERROR_OUT_OF_DEVICE_MEMORY;
}
}
if((createInfo.pool != VK_NULL_HANDLE) &&
((createInfo.flags & (VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT)) != 0))
{
VMA_ASSERT(0 && "Specifying VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT when pool != null is invalid.");
return VK_ERROR_OUT_OF_DEVICE_MEMORY;
}
if(createInfo.pool != VK_NULL_HANDLE)
{
const VkDeviceSize alignmentForPool = VMA_MAX(
vkMemReq.alignment,
GetMemoryTypeMinAlignment(createInfo.pool->m_BlockVector.GetMemoryTypeIndex()));
return createInfo.pool->m_BlockVector.Allocate(
createInfo.pool,
m_CurrentFrameIndex.load(),
vkMemReq.size,
alignmentForPool,
createInfo,
suballocType,
pAllocation);
}
else
{
// Bit mask of memory Vulkan types acceptable for this allocation.
uint32_t memoryTypeBits = vkMemReq.memoryTypeBits;
uint32_t memTypeIndex = UINT32_MAX;
VkResult res = vmaFindMemoryTypeIndex(this, memoryTypeBits, &createInfo, &memTypeIndex);
if(res == VK_SUCCESS)
{
VkDeviceSize alignmentForMemType = VMA_MAX(
vkMemReq.alignment,
GetMemoryTypeMinAlignment(memTypeIndex));
res = AllocateMemoryOfType(
vkMemReq.size,
alignmentForMemType,
requiresDedicatedAllocation || prefersDedicatedAllocation,
dedicatedBuffer,
dedicatedImage,
createInfo,
memTypeIndex,
suballocType,
pAllocation);
// Succeeded on first try.
if(res == VK_SUCCESS)
{
return res;
}
// Allocation from this memory type failed. Try other compatible memory types.
else
{
for(;;)
{
// Remove old memTypeIndex from list of possibilities.
memoryTypeBits &= ~(1u << memTypeIndex);
// Find alternative memTypeIndex.
res = vmaFindMemoryTypeIndex(this, memoryTypeBits, &createInfo, &memTypeIndex);
if(res == VK_SUCCESS)
{
alignmentForMemType = VMA_MAX(
vkMemReq.alignment,
GetMemoryTypeMinAlignment(memTypeIndex));
res = AllocateMemoryOfType(
vkMemReq.size,
alignmentForMemType,
requiresDedicatedAllocation || prefersDedicatedAllocation,
dedicatedBuffer,
dedicatedImage,
createInfo,
memTypeIndex,
suballocType,
pAllocation);
// Allocation from this alternative memory type succeeded.
if(res == VK_SUCCESS)
{
return res;
}
// else: Allocation from this memory type failed. Try next one - next loop iteration.
}
// No other matching memory type index could be found.
else
{
// Not returning res, which is VK_ERROR_FEATURE_NOT_PRESENT, because we already failed to allocate once.
return VK_ERROR_OUT_OF_DEVICE_MEMORY;
}
}
}
}
// Can't find any single memory type maching requirements. res is VK_ERROR_FEATURE_NOT_PRESENT.
else
return res;
}
}
void VmaAllocator_T::FreeMemory(const VmaAllocation allocation)
{
VMA_ASSERT(allocation);
if(TouchAllocation(allocation))
{
if(VMA_DEBUG_INITIALIZE_ALLOCATIONS)
{
FillAllocation(allocation, VMA_ALLOCATION_FILL_PATTERN_DESTROYED);
}
switch(allocation->GetType())
{
case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
{
VmaBlockVector* pBlockVector = VMA_NULL;
VmaPool hPool = allocation->GetPool();
if(hPool != VK_NULL_HANDLE)
{
pBlockVector = &hPool->m_BlockVector;
}
else
{
const uint32_t memTypeIndex = allocation->GetMemoryTypeIndex();
pBlockVector = m_pBlockVectors[memTypeIndex];
}
pBlockVector->Free(allocation);
}
break;
case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
FreeDedicatedMemory(allocation);
break;
default:
VMA_ASSERT(0);
}
}
allocation->SetUserData(this, VMA_NULL);
vma_delete(this, allocation);
}
void VmaAllocator_T::CalculateStats(VmaStats* pStats)
{
// Initialize.
InitStatInfo(pStats->total);
for(size_t i = 0; i < VK_MAX_MEMORY_TYPES; ++i)
InitStatInfo(pStats->memoryType[i]);
for(size_t i = 0; i < VK_MAX_MEMORY_HEAPS; ++i)
InitStatInfo(pStats->memoryHeap[i]);
// Process default pools.
for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
{
VmaBlockVector* const pBlockVector = m_pBlockVectors[memTypeIndex];
VMA_ASSERT(pBlockVector);
pBlockVector->AddStats(pStats);
}
// Process custom pools.
{
VmaMutexLock lock(m_PoolsMutex, m_UseMutex);
for(size_t poolIndex = 0, poolCount = m_Pools.size(); poolIndex < poolCount; ++poolIndex)
{
m_Pools[poolIndex]->m_BlockVector.AddStats(pStats);
}
}
// Process dedicated allocations.
for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
{
const uint32_t memHeapIndex = MemoryTypeIndexToHeapIndex(memTypeIndex);
VmaMutexLock dedicatedAllocationsLock(m_DedicatedAllocationsMutex[memTypeIndex], m_UseMutex);
AllocationVectorType* const pDedicatedAllocVector = m_pDedicatedAllocations[memTypeIndex];
VMA_ASSERT(pDedicatedAllocVector);
for(size_t allocIndex = 0, allocCount = pDedicatedAllocVector->size(); allocIndex < allocCount; ++allocIndex)
{
VmaStatInfo allocationStatInfo;
(*pDedicatedAllocVector)[allocIndex]->DedicatedAllocCalcStatsInfo(allocationStatInfo);
VmaAddStatInfo(pStats->total, allocationStatInfo);
VmaAddStatInfo(pStats->memoryType[memTypeIndex], allocationStatInfo);
VmaAddStatInfo(pStats->memoryHeap[memHeapIndex], allocationStatInfo);
}
}
// Postprocess.
VmaPostprocessCalcStatInfo(pStats->total);
for(size_t i = 0; i < GetMemoryTypeCount(); ++i)
VmaPostprocessCalcStatInfo(pStats->memoryType[i]);
for(size_t i = 0; i < GetMemoryHeapCount(); ++i)
VmaPostprocessCalcStatInfo(pStats->memoryHeap[i]);
}
static const uint32_t VMA_VENDOR_ID_AMD = 4098;
VkResult VmaAllocator_T::Defragment(
VmaAllocation* pAllocations,
size_t allocationCount,
VkBool32* pAllocationsChanged,
const VmaDefragmentationInfo* pDefragmentationInfo,
VmaDefragmentationStats* pDefragmentationStats)
{
if(pAllocationsChanged != VMA_NULL)
{
memset(pAllocationsChanged, 0, sizeof(*pAllocationsChanged));
}
if(pDefragmentationStats != VMA_NULL)
{
memset(pDefragmentationStats, 0, sizeof(*pDefragmentationStats));
}
const uint32_t currentFrameIndex = m_CurrentFrameIndex.load();
VmaMutexLock poolsLock(m_PoolsMutex, m_UseMutex);
const size_t poolCount = m_Pools.size();
// Dispatch pAllocations among defragmentators. Create them in BlockVectors when necessary.
for(size_t allocIndex = 0; allocIndex < allocationCount; ++allocIndex)
{
VmaAllocation hAlloc = pAllocations[allocIndex];
VMA_ASSERT(hAlloc);
const uint32_t memTypeIndex = hAlloc->GetMemoryTypeIndex();
// DedicatedAlloc cannot be defragmented.
const VkMemoryPropertyFlags requiredMemFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
if((hAlloc->GetType() == VmaAllocation_T::ALLOCATION_TYPE_BLOCK) &&
// Only HOST_VISIBLE and HOST_COHERENT memory types can be defragmented.
((m_MemProps.memoryTypes[memTypeIndex].propertyFlags & requiredMemFlags) == requiredMemFlags) &&
// Lost allocation cannot be defragmented.
(hAlloc->GetLastUseFrameIndex() != VMA_FRAME_INDEX_LOST))
{
VmaBlockVector* pAllocBlockVector = VMA_NULL;
const VmaPool hAllocPool = hAlloc->GetPool();
// This allocation belongs to custom pool.
if(hAllocPool != VK_NULL_HANDLE)
{
// Pools with linear algorithm are not defragmented.
if(!hAllocPool->m_BlockVector.UsesLinearAlgorithm())
{
pAllocBlockVector = &hAllocPool->m_BlockVector;
}
}
// This allocation belongs to general pool.
else
{
pAllocBlockVector = m_pBlockVectors[memTypeIndex];
}
if(pAllocBlockVector != VMA_NULL)
{
VmaDefragmentator* const pDefragmentator =
pAllocBlockVector->EnsureDefragmentator(this, currentFrameIndex);
VkBool32* const pChanged = (pAllocationsChanged != VMA_NULL) ?
&pAllocationsChanged[allocIndex] : VMA_NULL;
pDefragmentator->AddAllocation(hAlloc, pChanged);
}
}
}
VkResult result = VK_SUCCESS;
// ======== Main processing.
VkDeviceSize maxBytesToMove = SIZE_MAX;
uint32_t maxAllocationsToMove = UINT32_MAX;
if(pDefragmentationInfo != VMA_NULL)
{
maxBytesToMove = pDefragmentationInfo->maxBytesToMove;
maxAllocationsToMove = pDefragmentationInfo->maxAllocationsToMove;
}
// Process standard memory.
for(uint32_t memTypeIndex = 0;
(memTypeIndex < GetMemoryTypeCount()) && (result == VK_SUCCESS);
++memTypeIndex)
{
// Only HOST_VISIBLE memory types can be defragmented.
if((m_MemProps.memoryTypes[memTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0)
{
result = m_pBlockVectors[memTypeIndex]->Defragment(
pDefragmentationStats,
maxBytesToMove,
maxAllocationsToMove);
}
}
// Process custom pools.
for(size_t poolIndex = 0; (poolIndex < poolCount) && (result == VK_SUCCESS); ++poolIndex)
{
result = m_Pools[poolIndex]->m_BlockVector.Defragment(
pDefragmentationStats,
maxBytesToMove,
maxAllocationsToMove);
}
// ======== Destroy defragmentators.
// Process custom pools.
for(size_t poolIndex = poolCount; poolIndex--; )
{
m_Pools[poolIndex]->m_BlockVector.DestroyDefragmentator();
}
// Process standard memory.
for(uint32_t memTypeIndex = GetMemoryTypeCount(); memTypeIndex--; )
{
if((m_MemProps.memoryTypes[memTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0)
{
m_pBlockVectors[memTypeIndex]->DestroyDefragmentator();
}
}
return result;
}
void VmaAllocator_T::GetAllocationInfo(VmaAllocation hAllocation, VmaAllocationInfo* pAllocationInfo)
{
if(hAllocation->CanBecomeLost())
{
/*
Warning: This is a carefully designed algorithm.
Do not modify unless you really know what you're doing :)
*/
const uint32_t localCurrFrameIndex = m_CurrentFrameIndex.load();
uint32_t localLastUseFrameIndex = hAllocation->GetLastUseFrameIndex();
for(;;)
{
if(localLastUseFrameIndex == VMA_FRAME_INDEX_LOST)
{
pAllocationInfo->memoryType = UINT32_MAX;
pAllocationInfo->deviceMemory = VK_NULL_HANDLE;
pAllocationInfo->offset = 0;
pAllocationInfo->size = hAllocation->GetSize();
pAllocationInfo->pMappedData = VMA_NULL;
pAllocationInfo->pUserData = hAllocation->GetUserData();
return;
}
else if(localLastUseFrameIndex == localCurrFrameIndex)
{
pAllocationInfo->memoryType = hAllocation->GetMemoryTypeIndex();
pAllocationInfo->deviceMemory = hAllocation->GetMemory();
pAllocationInfo->offset = hAllocation->GetOffset();
pAllocationInfo->size = hAllocation->GetSize();
pAllocationInfo->pMappedData = VMA_NULL;
pAllocationInfo->pUserData = hAllocation->GetUserData();
return;
}
else // Last use time earlier than current time.
{
if(hAllocation->CompareExchangeLastUseFrameIndex(localLastUseFrameIndex, localCurrFrameIndex))
{
localLastUseFrameIndex = localCurrFrameIndex;
}
}
}
}
else
{
#if VMA_STATS_STRING_ENABLED
uint32_t localCurrFrameIndex = m_CurrentFrameIndex.load();
uint32_t localLastUseFrameIndex = hAllocation->GetLastUseFrameIndex();
for(;;)
{
VMA_ASSERT(localLastUseFrameIndex != VMA_FRAME_INDEX_LOST);
if(localLastUseFrameIndex == localCurrFrameIndex)
{
break;
}
else // Last use time earlier than current time.
{
if(hAllocation->CompareExchangeLastUseFrameIndex(localLastUseFrameIndex, localCurrFrameIndex))
{
localLastUseFrameIndex = localCurrFrameIndex;
}
}
}
#endif
pAllocationInfo->memoryType = hAllocation->GetMemoryTypeIndex();
pAllocationInfo->deviceMemory = hAllocation->GetMemory();
pAllocationInfo->offset = hAllocation->GetOffset();
pAllocationInfo->size = hAllocation->GetSize();
pAllocationInfo->pMappedData = hAllocation->GetMappedData();
pAllocationInfo->pUserData = hAllocation->GetUserData();
}
}
bool VmaAllocator_T::TouchAllocation(VmaAllocation hAllocation)
{
// This is a stripped-down version of VmaAllocator_T::GetAllocationInfo.
if(hAllocation->CanBecomeLost())
{
uint32_t localCurrFrameIndex = m_CurrentFrameIndex.load();
uint32_t localLastUseFrameIndex = hAllocation->GetLastUseFrameIndex();
for(;;)
{
if(localLastUseFrameIndex == VMA_FRAME_INDEX_LOST)
{
return false;
}
else if(localLastUseFrameIndex == localCurrFrameIndex)
{
return true;
}
else // Last use time earlier than current time.
{
if(hAllocation->CompareExchangeLastUseFrameIndex(localLastUseFrameIndex, localCurrFrameIndex))
{
localLastUseFrameIndex = localCurrFrameIndex;
}
}
}
}
else
{
#if VMA_STATS_STRING_ENABLED
uint32_t localCurrFrameIndex = m_CurrentFrameIndex.load();
uint32_t localLastUseFrameIndex = hAllocation->GetLastUseFrameIndex();
for(;;)
{
VMA_ASSERT(localLastUseFrameIndex != VMA_FRAME_INDEX_LOST);
if(localLastUseFrameIndex == localCurrFrameIndex)
{
break;
}
else // Last use time earlier than current time.
{
if(hAllocation->CompareExchangeLastUseFrameIndex(localLastUseFrameIndex, localCurrFrameIndex))
{
localLastUseFrameIndex = localCurrFrameIndex;
}
}
}
#endif
return true;
}
}
VkResult VmaAllocator_T::CreatePool(const VmaPoolCreateInfo* pCreateInfo, VmaPool* pPool)
{
VMA_DEBUG_LOG(" CreatePool: MemoryTypeIndex=%u, flags=%u", pCreateInfo->memoryTypeIndex, pCreateInfo->flags);
const bool isLinearAlgorithm = (pCreateInfo->flags & VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT) != 0;
VmaPoolCreateInfo newCreateInfo = *pCreateInfo;
if(newCreateInfo.maxBlockCount == 0)
{
newCreateInfo.maxBlockCount = SIZE_MAX;
}
if(newCreateInfo.minBlockCount > newCreateInfo.maxBlockCount)
{
return VK_ERROR_INITIALIZATION_FAILED;
}
const VkDeviceSize preferredBlockSize = CalcPreferredBlockSize(newCreateInfo.memoryTypeIndex);
*pPool = vma_new(this, VmaPool_T)(this, newCreateInfo, preferredBlockSize);
VkResult res = (*pPool)->m_BlockVector.CreateMinBlocks();
if(res != VK_SUCCESS)
{
vma_delete(this, *pPool);
*pPool = VMA_NULL;
return res;
}
// Add to m_Pools.
{
VmaMutexLock lock(m_PoolsMutex, m_UseMutex);
(*pPool)->SetId(m_NextPoolId++);
VmaVectorInsertSorted<VmaPointerLess>(m_Pools, *pPool);
}
return VK_SUCCESS;
}
void VmaAllocator_T::DestroyPool(VmaPool pool)
{
// Remove from m_Pools.
{
VmaMutexLock lock(m_PoolsMutex, m_UseMutex);
bool success = VmaVectorRemoveSorted<VmaPointerLess>(m_Pools, pool);
VMA_ASSERT(success && "Pool not found in Allocator.");
}
vma_delete(this, pool);
}
void VmaAllocator_T::GetPoolStats(VmaPool pool, VmaPoolStats* pPoolStats)
{
pool->m_BlockVector.GetPoolStats(pPoolStats);
}
void VmaAllocator_T::SetCurrentFrameIndex(uint32_t frameIndex)
{
m_CurrentFrameIndex.store(frameIndex);
}
void VmaAllocator_T::MakePoolAllocationsLost(
VmaPool hPool,
size_t* pLostAllocationCount)
{
hPool->m_BlockVector.MakePoolAllocationsLost(
m_CurrentFrameIndex.load(),
pLostAllocationCount);
}
VkResult VmaAllocator_T::CheckPoolCorruption(VmaPool hPool)
{
return hPool->m_BlockVector.CheckCorruption();
}
VkResult VmaAllocator_T::CheckCorruption(uint32_t memoryTypeBits)
{
VkResult finalRes = VK_ERROR_FEATURE_NOT_PRESENT;
// Process default pools.
for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
{
if(((1u << memTypeIndex) & memoryTypeBits) != 0)
{
VmaBlockVector* const pBlockVector = m_pBlockVectors[memTypeIndex];
VMA_ASSERT(pBlockVector);
VkResult localRes = pBlockVector->CheckCorruption();
switch(localRes)
{
case VK_ERROR_FEATURE_NOT_PRESENT:
break;
case VK_SUCCESS:
finalRes = VK_SUCCESS;
break;
default:
return localRes;
}
}
}
// Process custom pools.
{
VmaMutexLock lock(m_PoolsMutex, m_UseMutex);
for(size_t poolIndex = 0, poolCount = m_Pools.size(); poolIndex < poolCount; ++poolIndex)
{
if(((1u << m_Pools[poolIndex]->m_BlockVector.GetMemoryTypeIndex()) & memoryTypeBits) != 0)
{
VkResult localRes = m_Pools[poolIndex]->m_BlockVector.CheckCorruption();
switch(localRes)
{
case VK_ERROR_FEATURE_NOT_PRESENT:
break;
case VK_SUCCESS:
finalRes = VK_SUCCESS;
break;
default:
return localRes;
}
}
}
}
return finalRes;
}
void VmaAllocator_T::CreateLostAllocation(VmaAllocation* pAllocation)
{
*pAllocation = vma_new(this, VmaAllocation_T)(VMA_FRAME_INDEX_LOST, false);
(*pAllocation)->InitLost();
}
VkResult VmaAllocator_T::AllocateVulkanMemory(const VkMemoryAllocateInfo* pAllocateInfo, VkDeviceMemory* pMemory)
{
const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(pAllocateInfo->memoryTypeIndex);
VkResult res;
if(m_HeapSizeLimit[heapIndex] != VK_WHOLE_SIZE)
{
VmaMutexLock lock(m_HeapSizeLimitMutex, m_UseMutex);
if(m_HeapSizeLimit[heapIndex] >= pAllocateInfo->allocationSize)
{
res = (*m_VulkanFunctions.vkAllocateMemory)(m_hDevice, pAllocateInfo, GetAllocationCallbacks(), pMemory);
if(res == VK_SUCCESS)
{
m_HeapSizeLimit[heapIndex] -= pAllocateInfo->allocationSize;
}
}
else
{
res = VK_ERROR_OUT_OF_DEVICE_MEMORY;
}
}
else
{
res = (*m_VulkanFunctions.vkAllocateMemory)(m_hDevice, pAllocateInfo, GetAllocationCallbacks(), pMemory);
}
if(res == VK_SUCCESS && m_DeviceMemoryCallbacks.pfnAllocate != VMA_NULL)
{
(*m_DeviceMemoryCallbacks.pfnAllocate)(this, pAllocateInfo->memoryTypeIndex, *pMemory, pAllocateInfo->allocationSize);
}
return res;
}
void VmaAllocator_T::FreeVulkanMemory(uint32_t memoryType, VkDeviceSize size, VkDeviceMemory hMemory)
{
if(m_DeviceMemoryCallbacks.pfnFree != VMA_NULL)
{
(*m_DeviceMemoryCallbacks.pfnFree)(this, memoryType, hMemory, size);
}
(*m_VulkanFunctions.vkFreeMemory)(m_hDevice, hMemory, GetAllocationCallbacks());
const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(memoryType);
if(m_HeapSizeLimit[heapIndex] != VK_WHOLE_SIZE)
{
VmaMutexLock lock(m_HeapSizeLimitMutex, m_UseMutex);
m_HeapSizeLimit[heapIndex] += size;
}
}
VkResult VmaAllocator_T::Map(VmaAllocation hAllocation, void** ppData)
{
if(hAllocation->CanBecomeLost())
{
return VK_ERROR_MEMORY_MAP_FAILED;
}
switch(hAllocation->GetType())
{
case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
{
VmaDeviceMemoryBlock* const pBlock = hAllocation->GetBlock();
char *pBytes = VMA_NULL;
VkResult res = pBlock->Map(this, 1, (void**)&pBytes);
if(res == VK_SUCCESS)
{
*ppData = pBytes + (ptrdiff_t)hAllocation->GetOffset();
hAllocation->BlockAllocMap();
}
return res;
}
case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
return hAllocation->DedicatedAllocMap(this, ppData);
default:
VMA_ASSERT(0);
return VK_ERROR_MEMORY_MAP_FAILED;
}
}
void VmaAllocator_T::Unmap(VmaAllocation hAllocation)
{
switch(hAllocation->GetType())
{
case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
{
VmaDeviceMemoryBlock* const pBlock = hAllocation->GetBlock();
hAllocation->BlockAllocUnmap();
pBlock->Unmap(this, 1);
}
break;
case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
hAllocation->DedicatedAllocUnmap(this);
break;
default:
VMA_ASSERT(0);
}
}
VkResult VmaAllocator_T::BindBufferMemory(VmaAllocation hAllocation, VkBuffer hBuffer)
{
VkResult res = VK_SUCCESS;
switch(hAllocation->GetType())
{
case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
res = GetVulkanFunctions().vkBindBufferMemory(
m_hDevice,
hBuffer,
hAllocation->GetMemory(),
0); //memoryOffset
break;
case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
{
VmaDeviceMemoryBlock* pBlock = hAllocation->GetBlock();
VMA_ASSERT(pBlock && "Binding buffer to allocation that doesn't belong to any block. Is the allocation lost?");
res = pBlock->BindBufferMemory(this, hAllocation, hBuffer);
break;
}
default:
VMA_ASSERT(0);
}
return res;
}
VkResult VmaAllocator_T::BindImageMemory(VmaAllocation hAllocation, VkImage hImage)
{
VkResult res = VK_SUCCESS;
switch(hAllocation->GetType())
{
case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
res = GetVulkanFunctions().vkBindImageMemory(
m_hDevice,
hImage,
hAllocation->GetMemory(),
0); //memoryOffset
break;
case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
{
VmaDeviceMemoryBlock* pBlock = hAllocation->GetBlock();
VMA_ASSERT(pBlock && "Binding image to allocation that doesn't belong to any block. Is the allocation lost?");
res = pBlock->BindImageMemory(this, hAllocation, hImage);
break;
}
default:
VMA_ASSERT(0);
}
return res;
}
void VmaAllocator_T::FlushOrInvalidateAllocation(
VmaAllocation hAllocation,
VkDeviceSize offset, VkDeviceSize size,
VMA_CACHE_OPERATION op)
{
const uint32_t memTypeIndex = hAllocation->GetMemoryTypeIndex();
if(size > 0 && IsMemoryTypeNonCoherent(memTypeIndex))
{
const VkDeviceSize allocationSize = hAllocation->GetSize();
VMA_ASSERT(offset <= allocationSize);
const VkDeviceSize nonCoherentAtomSize = m_PhysicalDeviceProperties.limits.nonCoherentAtomSize;
VkMappedMemoryRange memRange = { VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE };
memRange.memory = hAllocation->GetMemory();
switch(hAllocation->GetType())
{
case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED:
memRange.offset = VmaAlignDown(offset, nonCoherentAtomSize);
if(size == VK_WHOLE_SIZE)
{
memRange.size = allocationSize - memRange.offset;
}
else
{
VMA_ASSERT(offset + size <= allocationSize);
memRange.size = VMA_MIN(
VmaAlignUp(size + (offset - memRange.offset), nonCoherentAtomSize),
allocationSize - memRange.offset);
}
break;
case VmaAllocation_T::ALLOCATION_TYPE_BLOCK:
{
// 1. Still within this allocation.
memRange.offset = VmaAlignDown(offset, nonCoherentAtomSize);
if(size == VK_WHOLE_SIZE)
{
size = allocationSize - offset;
}
else
{
VMA_ASSERT(offset + size <= allocationSize);
}
memRange.size = VmaAlignUp(size + (offset - memRange.offset), nonCoherentAtomSize);
// 2. Adjust to whole block.
const VkDeviceSize allocationOffset = hAllocation->GetOffset();
VMA_ASSERT(allocationOffset % nonCoherentAtomSize == 0);
const VkDeviceSize blockSize = hAllocation->GetBlock()->m_pMetadata->GetSize();
memRange.offset += allocationOffset;
memRange.size = VMA_MIN(memRange.size, blockSize - memRange.offset);
break;
}
default:
VMA_ASSERT(0);
}
switch(op)
{
case VMA_CACHE_FLUSH:
(*GetVulkanFunctions().vkFlushMappedMemoryRanges)(m_hDevice, 1, &memRange);
break;
case VMA_CACHE_INVALIDATE:
(*GetVulkanFunctions().vkInvalidateMappedMemoryRanges)(m_hDevice, 1, &memRange);
break;
default:
VMA_ASSERT(0);
}
}
// else: Just ignore this call.
}
void VmaAllocator_T::FreeDedicatedMemory(VmaAllocation allocation)
{
VMA_ASSERT(allocation && allocation->GetType() == VmaAllocation_T::ALLOCATION_TYPE_DEDICATED);
const uint32_t memTypeIndex = allocation->GetMemoryTypeIndex();
{
VmaMutexLock lock(m_DedicatedAllocationsMutex[memTypeIndex], m_UseMutex);
AllocationVectorType* const pDedicatedAllocations = m_pDedicatedAllocations[memTypeIndex];
VMA_ASSERT(pDedicatedAllocations);
bool success = VmaVectorRemoveSorted<VmaPointerLess>(*pDedicatedAllocations, allocation);
VMA_ASSERT(success);
}
VkDeviceMemory hMemory = allocation->GetMemory();
if(allocation->GetMappedData() != VMA_NULL)
{
(*m_VulkanFunctions.vkUnmapMemory)(m_hDevice, hMemory);
}
FreeVulkanMemory(memTypeIndex, allocation->GetSize(), hMemory);
VMA_DEBUG_LOG(" Freed DedicatedMemory MemoryTypeIndex=%u", memTypeIndex);
}
void VmaAllocator_T::FillAllocation(const VmaAllocation hAllocation, uint8_t pattern)
{
if(VMA_DEBUG_INITIALIZE_ALLOCATIONS &&
!hAllocation->CanBecomeLost() &&
(m_MemProps.memoryTypes[hAllocation->GetMemoryTypeIndex()].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0)
{
void* pData = VMA_NULL;
VkResult res = Map(hAllocation, &pData);
if(res == VK_SUCCESS)
{
memset(pData, (int)pattern, (size_t)hAllocation->GetSize());
FlushOrInvalidateAllocation(hAllocation, 0, VK_WHOLE_SIZE, VMA_CACHE_FLUSH);
Unmap(hAllocation);
}
else
{
VMA_ASSERT(0 && "VMA_DEBUG_INITIALIZE_ALLOCATIONS is enabled, but couldn't map memory to fill allocation.");
}
}
}
#if VMA_STATS_STRING_ENABLED
void VmaAllocator_T::PrintDetailedMap(VmaJsonWriter& json)
{
bool dedicatedAllocationsStarted = false;
for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
{
VmaMutexLock dedicatedAllocationsLock(m_DedicatedAllocationsMutex[memTypeIndex], m_UseMutex);
AllocationVectorType* const pDedicatedAllocVector = m_pDedicatedAllocations[memTypeIndex];
VMA_ASSERT(pDedicatedAllocVector);
if(pDedicatedAllocVector->empty() == false)
{
if(dedicatedAllocationsStarted == false)
{
dedicatedAllocationsStarted = true;
json.WriteString("DedicatedAllocations");
json.BeginObject();
}
json.BeginString("Type ");
json.ContinueString(memTypeIndex);
json.EndString();
json.BeginArray();
for(size_t i = 0; i < pDedicatedAllocVector->size(); ++i)
{
json.BeginObject(true);
const VmaAllocation hAlloc = (*pDedicatedAllocVector)[i];
hAlloc->PrintParameters(json);
json.EndObject();
}
json.EndArray();
}
}
if(dedicatedAllocationsStarted)
{
json.EndObject();
}
{
bool allocationsStarted = false;
for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex)
{
if(m_pBlockVectors[memTypeIndex]->IsEmpty() == false)
{
if(allocationsStarted == false)
{
allocationsStarted = true;
json.WriteString("DefaultPools");
json.BeginObject();
}
json.BeginString("Type ");
json.ContinueString(memTypeIndex);
json.EndString();
m_pBlockVectors[memTypeIndex]->PrintDetailedMap(json);
}
}
if(allocationsStarted)
{
json.EndObject();
}
}
// Custom pools
{
VmaMutexLock lock(m_PoolsMutex, m_UseMutex);
const size_t poolCount = m_Pools.size();
if(poolCount > 0)
{
json.WriteString("Pools");
json.BeginObject();
for(size_t poolIndex = 0; poolIndex < poolCount; ++poolIndex)
{
json.BeginString();
json.ContinueString(m_Pools[poolIndex]->GetId());
json.EndString();
m_Pools[poolIndex]->m_BlockVector.PrintDetailedMap(json);
}
json.EndObject();
}
}
}
#endif // #if VMA_STATS_STRING_ENABLED
////////////////////////////////////////////////////////////////////////////////
// Public interface
VkResult vmaCreateAllocator(
const VmaAllocatorCreateInfo* pCreateInfo,
VmaAllocator* pAllocator)
{
VMA_ASSERT(pCreateInfo && pAllocator);
VMA_DEBUG_LOG("vmaCreateAllocator");
*pAllocator = vma_new(pCreateInfo->pAllocationCallbacks, VmaAllocator_T)(pCreateInfo);
return (*pAllocator)->Init(pCreateInfo);
}
void vmaDestroyAllocator(
VmaAllocator allocator)
{
if(allocator != VK_NULL_HANDLE)
{
VMA_DEBUG_LOG("vmaDestroyAllocator");
VkAllocationCallbacks allocationCallbacks = allocator->m_AllocationCallbacks;
vma_delete(&allocationCallbacks, allocator);
}
}
void vmaGetPhysicalDeviceProperties(
VmaAllocator allocator,
const VkPhysicalDeviceProperties **ppPhysicalDeviceProperties)
{
VMA_ASSERT(allocator && ppPhysicalDeviceProperties);
*ppPhysicalDeviceProperties = &allocator->m_PhysicalDeviceProperties;
}
void vmaGetMemoryProperties(
VmaAllocator allocator,
const VkPhysicalDeviceMemoryProperties** ppPhysicalDeviceMemoryProperties)
{
VMA_ASSERT(allocator && ppPhysicalDeviceMemoryProperties);
*ppPhysicalDeviceMemoryProperties = &allocator->m_MemProps;
}
void vmaGetMemoryTypeProperties(
VmaAllocator allocator,
uint32_t memoryTypeIndex,
VkMemoryPropertyFlags* pFlags)
{
VMA_ASSERT(allocator && pFlags);
VMA_ASSERT(memoryTypeIndex < allocator->GetMemoryTypeCount());
*pFlags = allocator->m_MemProps.memoryTypes[memoryTypeIndex].propertyFlags;
}
void vmaSetCurrentFrameIndex(
VmaAllocator allocator,
uint32_t frameIndex)
{
VMA_ASSERT(allocator);
VMA_ASSERT(frameIndex != VMA_FRAME_INDEX_LOST);
VMA_DEBUG_GLOBAL_MUTEX_LOCK
allocator->SetCurrentFrameIndex(frameIndex);
}
void vmaCalculateStats(
VmaAllocator allocator,
VmaStats* pStats)
{
VMA_ASSERT(allocator && pStats);
VMA_DEBUG_GLOBAL_MUTEX_LOCK
allocator->CalculateStats(pStats);
}
#if VMA_STATS_STRING_ENABLED
void vmaBuildStatsString(
VmaAllocator allocator,
char** ppStatsString,
VkBool32 detailedMap)
{
VMA_ASSERT(allocator && ppStatsString);
VMA_DEBUG_GLOBAL_MUTEX_LOCK
VmaStringBuilder sb(allocator);
{
VmaJsonWriter json(allocator->GetAllocationCallbacks(), sb);
json.BeginObject();
VmaStats stats;
allocator->CalculateStats(&stats);
json.WriteString("Total");
VmaPrintStatInfo(json, stats.total);
for(uint32_t heapIndex = 0; heapIndex < allocator->GetMemoryHeapCount(); ++heapIndex)
{
json.BeginString("Heap ");
json.ContinueString(heapIndex);
json.EndString();
json.BeginObject();
json.WriteString("Size");
json.WriteNumber(allocator->m_MemProps.memoryHeaps[heapIndex].size);
json.WriteString("Flags");
json.BeginArray(true);
if((allocator->m_MemProps.memoryHeaps[heapIndex].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) != 0)
{
json.WriteString("DEVICE_LOCAL");
}
json.EndArray();
if(stats.memoryHeap[heapIndex].blockCount > 0)
{
json.WriteString("Stats");
VmaPrintStatInfo(json, stats.memoryHeap[heapIndex]);
}
for(uint32_t typeIndex = 0; typeIndex < allocator->GetMemoryTypeCount(); ++typeIndex)
{
if(allocator->MemoryTypeIndexToHeapIndex(typeIndex) == heapIndex)
{
json.BeginString("Type ");
json.ContinueString(typeIndex);
json.EndString();
json.BeginObject();
json.WriteString("Flags");
json.BeginArray(true);
VkMemoryPropertyFlags flags = allocator->m_MemProps.memoryTypes[typeIndex].propertyFlags;
if((flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0)
{
json.WriteString("DEVICE_LOCAL");
}
if((flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0)
{
json.WriteString("HOST_VISIBLE");
}
if((flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) != 0)
{
json.WriteString("HOST_COHERENT");
}
if((flags & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) != 0)
{
json.WriteString("HOST_CACHED");
}
if((flags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) != 0)
{
json.WriteString("LAZILY_ALLOCATED");
}
json.EndArray();
if(stats.memoryType[typeIndex].blockCount > 0)
{
json.WriteString("Stats");
VmaPrintStatInfo(json, stats.memoryType[typeIndex]);
}
json.EndObject();
}
}
json.EndObject();
}
if(detailedMap == VK_TRUE)
{
allocator->PrintDetailedMap(json);
}
json.EndObject();
}
const size_t len = sb.GetLength();
char* const pChars = vma_new_array(allocator, char, len + 1);
if(len > 0)
{
memcpy(pChars, sb.GetData(), len);
}
pChars[len] = '\0';
*ppStatsString = pChars;
}
void vmaFreeStatsString(
VmaAllocator allocator,
char* pStatsString)
{
if(pStatsString != VMA_NULL)
{
VMA_ASSERT(allocator);
size_t len = strlen(pStatsString);
vma_delete_array(allocator, pStatsString, len + 1);
}
}
#endif // #if VMA_STATS_STRING_ENABLED
/*
This function is not protected by any mutex because it just reads immutable data.
*/
VkResult vmaFindMemoryTypeIndex(
VmaAllocator allocator,
uint32_t memoryTypeBits,
const VmaAllocationCreateInfo* pAllocationCreateInfo,
uint32_t* pMemoryTypeIndex)
{
VMA_ASSERT(allocator != VK_NULL_HANDLE);
VMA_ASSERT(pAllocationCreateInfo != VMA_NULL);
VMA_ASSERT(pMemoryTypeIndex != VMA_NULL);
if(pAllocationCreateInfo->memoryTypeBits != 0)
{
memoryTypeBits &= pAllocationCreateInfo->memoryTypeBits;
}
uint32_t requiredFlags = pAllocationCreateInfo->requiredFlags;
uint32_t preferredFlags = pAllocationCreateInfo->preferredFlags;
const bool mapped = (pAllocationCreateInfo->flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0;
if(mapped)
{
preferredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
}
// Convert usage to requiredFlags and preferredFlags.
switch(pAllocationCreateInfo->usage)
{
case VMA_MEMORY_USAGE_UNKNOWN:
break;
case VMA_MEMORY_USAGE_GPU_ONLY:
if(!allocator->IsIntegratedGpu() || (preferredFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0)
{
preferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
}
break;
case VMA_MEMORY_USAGE_CPU_ONLY:
requiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
break;
case VMA_MEMORY_USAGE_CPU_TO_GPU:
requiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
if(!allocator->IsIntegratedGpu() || (preferredFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0)
{
preferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
}
break;
case VMA_MEMORY_USAGE_GPU_TO_CPU:
requiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
preferredFlags |= VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
break;
default:
break;
}
*pMemoryTypeIndex = UINT32_MAX;
uint32_t minCost = UINT32_MAX;
for(uint32_t memTypeIndex = 0, memTypeBit = 1;
memTypeIndex < allocator->GetMemoryTypeCount();
++memTypeIndex, memTypeBit <<= 1)
{
// This memory type is acceptable according to memoryTypeBits bitmask.
if((memTypeBit & memoryTypeBits) != 0)
{
const VkMemoryPropertyFlags currFlags =
allocator->m_MemProps.memoryTypes[memTypeIndex].propertyFlags;
// This memory type contains requiredFlags.
if((requiredFlags & ~currFlags) == 0)
{
// Calculate cost as number of bits from preferredFlags not present in this memory type.
uint32_t currCost = VmaCountBitsSet(preferredFlags & ~currFlags);
// Remember memory type with lowest cost.
if(currCost < minCost)
{
*pMemoryTypeIndex = memTypeIndex;
if(currCost == 0)
{
return VK_SUCCESS;
}
minCost = currCost;
}
}
}
}
return (*pMemoryTypeIndex != UINT32_MAX) ? VK_SUCCESS : VK_ERROR_FEATURE_NOT_PRESENT;
}
VkResult vmaFindMemoryTypeIndexForBufferInfo(
VmaAllocator allocator,
const VkBufferCreateInfo* pBufferCreateInfo,
const VmaAllocationCreateInfo* pAllocationCreateInfo,
uint32_t* pMemoryTypeIndex)
{
VMA_ASSERT(allocator != VK_NULL_HANDLE);
VMA_ASSERT(pBufferCreateInfo != VMA_NULL);
VMA_ASSERT(pAllocationCreateInfo != VMA_NULL);
VMA_ASSERT(pMemoryTypeIndex != VMA_NULL);
const VkDevice hDev = allocator->m_hDevice;
VkBuffer hBuffer = VK_NULL_HANDLE;
VkResult res = allocator->GetVulkanFunctions().vkCreateBuffer(
hDev, pBufferCreateInfo, allocator->GetAllocationCallbacks(), &hBuffer);
if(res == VK_SUCCESS)
{
VkMemoryRequirements memReq = {};
allocator->GetVulkanFunctions().vkGetBufferMemoryRequirements(
hDev, hBuffer, &memReq);
res = vmaFindMemoryTypeIndex(
allocator,
memReq.memoryTypeBits,
pAllocationCreateInfo,
pMemoryTypeIndex);
allocator->GetVulkanFunctions().vkDestroyBuffer(
hDev, hBuffer, allocator->GetAllocationCallbacks());
}
return res;
}
VkResult vmaFindMemoryTypeIndexForImageInfo(
VmaAllocator allocator,
const VkImageCreateInfo* pImageCreateInfo,
const VmaAllocationCreateInfo* pAllocationCreateInfo,
uint32_t* pMemoryTypeIndex)
{
VMA_ASSERT(allocator != VK_NULL_HANDLE);
VMA_ASSERT(pImageCreateInfo != VMA_NULL);
VMA_ASSERT(pAllocationCreateInfo != VMA_NULL);
VMA_ASSERT(pMemoryTypeIndex != VMA_NULL);
const VkDevice hDev = allocator->m_hDevice;
VkImage hImage = VK_NULL_HANDLE;
VkResult res = allocator->GetVulkanFunctions().vkCreateImage(
hDev, pImageCreateInfo, allocator->GetAllocationCallbacks(), &hImage);
if(res == VK_SUCCESS)
{
VkMemoryRequirements memReq = {};
allocator->GetVulkanFunctions().vkGetImageMemoryRequirements(
hDev, hImage, &memReq);
res = vmaFindMemoryTypeIndex(
allocator,
memReq.memoryTypeBits,
pAllocationCreateInfo,
pMemoryTypeIndex);
allocator->GetVulkanFunctions().vkDestroyImage(
hDev, hImage, allocator->GetAllocationCallbacks());
}
return res;
}
VkResult vmaCreatePool(
VmaAllocator allocator,
const VmaPoolCreateInfo* pCreateInfo,
VmaPool* pPool)
{
VMA_ASSERT(allocator && pCreateInfo && pPool);
VMA_DEBUG_LOG("vmaCreatePool");
VMA_DEBUG_GLOBAL_MUTEX_LOCK
VkResult res = allocator->CreatePool(pCreateInfo, pPool);
#if VMA_RECORDING_ENABLED
if(allocator->GetRecorder() != VMA_NULL)
{
allocator->GetRecorder()->RecordCreatePool(allocator->GetCurrentFrameIndex(), *pCreateInfo, *pPool);
}
#endif
return res;
}
void vmaDestroyPool(
VmaAllocator allocator,
VmaPool pool)
{
VMA_ASSERT(allocator);
if(pool == VK_NULL_HANDLE)
{
return;
}
VMA_DEBUG_LOG("vmaDestroyPool");
VMA_DEBUG_GLOBAL_MUTEX_LOCK
#if VMA_RECORDING_ENABLED
if(allocator->GetRecorder() != VMA_NULL)
{
allocator->GetRecorder()->RecordDestroyPool(allocator->GetCurrentFrameIndex(), pool);
}
#endif
allocator->DestroyPool(pool);
}
void vmaGetPoolStats(
VmaAllocator allocator,
VmaPool pool,
VmaPoolStats* pPoolStats)
{
VMA_ASSERT(allocator && pool && pPoolStats);
VMA_DEBUG_GLOBAL_MUTEX_LOCK
allocator->GetPoolStats(pool, pPoolStats);
}
void vmaMakePoolAllocationsLost(
VmaAllocator allocator,
VmaPool pool,
size_t* pLostAllocationCount)
{
VMA_ASSERT(allocator && pool);
VMA_DEBUG_GLOBAL_MUTEX_LOCK
#if VMA_RECORDING_ENABLED
if(allocator->GetRecorder() != VMA_NULL)
{
allocator->GetRecorder()->RecordMakePoolAllocationsLost(allocator->GetCurrentFrameIndex(), pool);
}
#endif
allocator->MakePoolAllocationsLost(pool, pLostAllocationCount);
}
VkResult vmaCheckPoolCorruption(VmaAllocator allocator, VmaPool pool)
{
VMA_ASSERT(allocator && pool);
VMA_DEBUG_GLOBAL_MUTEX_LOCK
VMA_DEBUG_LOG("vmaCheckPoolCorruption");
return allocator->CheckPoolCorruption(pool);
}
VkResult vmaAllocateMemory(
VmaAllocator allocator,
const VkMemoryRequirements* pVkMemoryRequirements,
const VmaAllocationCreateInfo* pCreateInfo,
VmaAllocation* pAllocation,
VmaAllocationInfo* pAllocationInfo)
{
VMA_ASSERT(allocator && pVkMemoryRequirements && pCreateInfo && pAllocation);
VMA_DEBUG_LOG("vmaAllocateMemory");
VMA_DEBUG_GLOBAL_MUTEX_LOCK
VkResult result = allocator->AllocateMemory(
*pVkMemoryRequirements,
false, // requiresDedicatedAllocation
false, // prefersDedicatedAllocation
VK_NULL_HANDLE, // dedicatedBuffer
VK_NULL_HANDLE, // dedicatedImage
*pCreateInfo,
VMA_SUBALLOCATION_TYPE_UNKNOWN,
pAllocation);
#if VMA_RECORDING_ENABLED
if(allocator->GetRecorder() != VMA_NULL)
{
allocator->GetRecorder()->RecordAllocateMemory(
allocator->GetCurrentFrameIndex(),
*pVkMemoryRequirements,
*pCreateInfo,
*pAllocation);
}
#endif
if(pAllocationInfo != VMA_NULL && result == VK_SUCCESS)
{
allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
}
return result;
}
VkResult vmaAllocateMemoryForBuffer(
VmaAllocator allocator,
VkBuffer buffer,
const VmaAllocationCreateInfo* pCreateInfo,
VmaAllocation* pAllocation,
VmaAllocationInfo* pAllocationInfo)
{
VMA_ASSERT(allocator && buffer != VK_NULL_HANDLE && pCreateInfo && pAllocation);
VMA_DEBUG_LOG("vmaAllocateMemoryForBuffer");
VMA_DEBUG_GLOBAL_MUTEX_LOCK
VkMemoryRequirements vkMemReq = {};
bool requiresDedicatedAllocation = false;
bool prefersDedicatedAllocation = false;
allocator->GetBufferMemoryRequirements(buffer, vkMemReq,
requiresDedicatedAllocation,
prefersDedicatedAllocation);
VkResult result = allocator->AllocateMemory(
vkMemReq,
requiresDedicatedAllocation,
prefersDedicatedAllocation,
buffer, // dedicatedBuffer
VK_NULL_HANDLE, // dedicatedImage
*pCreateInfo,
VMA_SUBALLOCATION_TYPE_BUFFER,
pAllocation);
#if VMA_RECORDING_ENABLED
if(allocator->GetRecorder() != VMA_NULL)
{
allocator->GetRecorder()->RecordAllocateMemoryForBuffer(
allocator->GetCurrentFrameIndex(),
vkMemReq,
requiresDedicatedAllocation,
prefersDedicatedAllocation,
*pCreateInfo,
*pAllocation);
}
#endif
if(pAllocationInfo && result == VK_SUCCESS)
{
allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
}
return result;
}
VkResult vmaAllocateMemoryForImage(
VmaAllocator allocator,
VkImage image,
const VmaAllocationCreateInfo* pCreateInfo,
VmaAllocation* pAllocation,
VmaAllocationInfo* pAllocationInfo)
{
VMA_ASSERT(allocator && image != VK_NULL_HANDLE && pCreateInfo && pAllocation);
VMA_DEBUG_LOG("vmaAllocateMemoryForImage");
VMA_DEBUG_GLOBAL_MUTEX_LOCK
VkMemoryRequirements vkMemReq = {};
bool requiresDedicatedAllocation = false;
bool prefersDedicatedAllocation = false;
allocator->GetImageMemoryRequirements(image, vkMemReq,
requiresDedicatedAllocation, prefersDedicatedAllocation);
VkResult result = allocator->AllocateMemory(
vkMemReq,
requiresDedicatedAllocation,
prefersDedicatedAllocation,
VK_NULL_HANDLE, // dedicatedBuffer
image, // dedicatedImage
*pCreateInfo,
VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN,
pAllocation);
#if VMA_RECORDING_ENABLED
if(allocator->GetRecorder() != VMA_NULL)
{
allocator->GetRecorder()->RecordAllocateMemoryForImage(
allocator->GetCurrentFrameIndex(),
vkMemReq,
requiresDedicatedAllocation,
prefersDedicatedAllocation,
*pCreateInfo,
*pAllocation);
}
#endif
if(pAllocationInfo && result == VK_SUCCESS)
{
allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
}
return result;
}
void vmaFreeMemory(
VmaAllocator allocator,
VmaAllocation allocation)
{
VMA_ASSERT(allocator);
if(allocation == VK_NULL_HANDLE)
{
return;
}
VMA_DEBUG_LOG("vmaFreeMemory");
VMA_DEBUG_GLOBAL_MUTEX_LOCK
#if VMA_RECORDING_ENABLED
if(allocator->GetRecorder() != VMA_NULL)
{
allocator->GetRecorder()->RecordFreeMemory(
allocator->GetCurrentFrameIndex(),
allocation);
}
#endif
allocator->FreeMemory(allocation);
}
void vmaGetAllocationInfo(
VmaAllocator allocator,
VmaAllocation allocation,
VmaAllocationInfo* pAllocationInfo)
{
VMA_ASSERT(allocator && allocation && pAllocationInfo);
VMA_DEBUG_GLOBAL_MUTEX_LOCK
#if VMA_RECORDING_ENABLED
if(allocator->GetRecorder() != VMA_NULL)
{
allocator->GetRecorder()->RecordGetAllocationInfo(
allocator->GetCurrentFrameIndex(),
allocation);
}
#endif
allocator->GetAllocationInfo(allocation, pAllocationInfo);
}
VkBool32 vmaTouchAllocation(
VmaAllocator allocator,
VmaAllocation allocation)
{
VMA_ASSERT(allocator && allocation);
VMA_DEBUG_GLOBAL_MUTEX_LOCK
#if VMA_RECORDING_ENABLED
if(allocator->GetRecorder() != VMA_NULL)
{
allocator->GetRecorder()->RecordTouchAllocation(
allocator->GetCurrentFrameIndex(),
allocation);
}
#endif
return allocator->TouchAllocation(allocation);
}
void vmaSetAllocationUserData(
VmaAllocator allocator,
VmaAllocation allocation,
void* pUserData)
{
VMA_ASSERT(allocator && allocation);
VMA_DEBUG_GLOBAL_MUTEX_LOCK
allocation->SetUserData(allocator, pUserData);
#if VMA_RECORDING_ENABLED
if(allocator->GetRecorder() != VMA_NULL)
{
allocator->GetRecorder()->RecordSetAllocationUserData(
allocator->GetCurrentFrameIndex(),
allocation,
pUserData);
}
#endif
}
void vmaCreateLostAllocation(
VmaAllocator allocator,
VmaAllocation* pAllocation)
{
VMA_ASSERT(allocator && pAllocation);
VMA_DEBUG_GLOBAL_MUTEX_LOCK;
allocator->CreateLostAllocation(pAllocation);
#if VMA_RECORDING_ENABLED
if(allocator->GetRecorder() != VMA_NULL)
{
allocator->GetRecorder()->RecordCreateLostAllocation(
allocator->GetCurrentFrameIndex(),
*pAllocation);
}
#endif
}
VkResult vmaMapMemory(
VmaAllocator allocator,
VmaAllocation allocation,
void** ppData)
{
VMA_ASSERT(allocator && allocation && ppData);
VMA_DEBUG_GLOBAL_MUTEX_LOCK
VkResult res = allocator->Map(allocation, ppData);
#if VMA_RECORDING_ENABLED
if(allocator->GetRecorder() != VMA_NULL)
{
allocator->GetRecorder()->RecordMapMemory(
allocator->GetCurrentFrameIndex(),
allocation);
}
#endif
return res;
}
void vmaUnmapMemory(
VmaAllocator allocator,
VmaAllocation allocation)
{
VMA_ASSERT(allocator && allocation);
VMA_DEBUG_GLOBAL_MUTEX_LOCK
#if VMA_RECORDING_ENABLED
if(allocator->GetRecorder() != VMA_NULL)
{
allocator->GetRecorder()->RecordUnmapMemory(
allocator->GetCurrentFrameIndex(),
allocation);
}
#endif
allocator->Unmap(allocation);
}
void vmaFlushAllocation(VmaAllocator allocator, VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size)
{
VMA_ASSERT(allocator && allocation);
VMA_DEBUG_LOG("vmaFlushAllocation");
VMA_DEBUG_GLOBAL_MUTEX_LOCK
allocator->FlushOrInvalidateAllocation(allocation, offset, size, VMA_CACHE_FLUSH);
#if VMA_RECORDING_ENABLED
if(allocator->GetRecorder() != VMA_NULL)
{
allocator->GetRecorder()->RecordFlushAllocation(
allocator->GetCurrentFrameIndex(),
allocation, offset, size);
}
#endif
}
void vmaInvalidateAllocation(VmaAllocator allocator, VmaAllocation allocation, VkDeviceSize offset, VkDeviceSize size)
{
VMA_ASSERT(allocator && allocation);
VMA_DEBUG_LOG("vmaInvalidateAllocation");
VMA_DEBUG_GLOBAL_MUTEX_LOCK
allocator->FlushOrInvalidateAllocation(allocation, offset, size, VMA_CACHE_INVALIDATE);
#if VMA_RECORDING_ENABLED
if(allocator->GetRecorder() != VMA_NULL)
{
allocator->GetRecorder()->RecordInvalidateAllocation(
allocator->GetCurrentFrameIndex(),
allocation, offset, size);
}
#endif
}
VkResult vmaCheckCorruption(VmaAllocator allocator, uint32_t memoryTypeBits)
{
VMA_ASSERT(allocator);
VMA_DEBUG_LOG("vmaCheckCorruption");
VMA_DEBUG_GLOBAL_MUTEX_LOCK
return allocator->CheckCorruption(memoryTypeBits);
}
VkResult vmaDefragment(
VmaAllocator allocator,
VmaAllocation* pAllocations,
size_t allocationCount,
VkBool32* pAllocationsChanged,
const VmaDefragmentationInfo *pDefragmentationInfo,
VmaDefragmentationStats* pDefragmentationStats)
{
VMA_ASSERT(allocator && pAllocations);
VMA_DEBUG_LOG("vmaDefragment");
VMA_DEBUG_GLOBAL_MUTEX_LOCK
return allocator->Defragment(pAllocations, allocationCount, pAllocationsChanged, pDefragmentationInfo, pDefragmentationStats);
}
VkResult vmaBindBufferMemory(
VmaAllocator allocator,
VmaAllocation allocation,
VkBuffer buffer)
{
VMA_ASSERT(allocator && allocation && buffer);
VMA_DEBUG_LOG("vmaBindBufferMemory");
VMA_DEBUG_GLOBAL_MUTEX_LOCK
return allocator->BindBufferMemory(allocation, buffer);
}
VkResult vmaBindImageMemory(
VmaAllocator allocator,
VmaAllocation allocation,
VkImage image)
{
VMA_ASSERT(allocator && allocation && image);
VMA_DEBUG_LOG("vmaBindImageMemory");
VMA_DEBUG_GLOBAL_MUTEX_LOCK
return allocator->BindImageMemory(allocation, image);
}
VkResult vmaCreateBuffer(
VmaAllocator allocator,
const VkBufferCreateInfo* pBufferCreateInfo,
const VmaAllocationCreateInfo* pAllocationCreateInfo,
VkBuffer* pBuffer,
VmaAllocation* pAllocation,
VmaAllocationInfo* pAllocationInfo)
{
VMA_ASSERT(allocator && pBufferCreateInfo && pAllocationCreateInfo && pBuffer && pAllocation);
VMA_DEBUG_LOG("vmaCreateBuffer");
VMA_DEBUG_GLOBAL_MUTEX_LOCK
*pBuffer = VK_NULL_HANDLE;
*pAllocation = VK_NULL_HANDLE;
// 1. Create VkBuffer.
VkResult res = (*allocator->GetVulkanFunctions().vkCreateBuffer)(
allocator->m_hDevice,
pBufferCreateInfo,
allocator->GetAllocationCallbacks(),
pBuffer);
if(res >= 0)
{
// 2. vkGetBufferMemoryRequirements.
VkMemoryRequirements vkMemReq = {};
bool requiresDedicatedAllocation = false;
bool prefersDedicatedAllocation = false;
allocator->GetBufferMemoryRequirements(*pBuffer, vkMemReq,
requiresDedicatedAllocation, prefersDedicatedAllocation);
// Make sure alignment requirements for specific buffer usages reported
// in Physical Device Properties are included in alignment reported by memory requirements.
if((pBufferCreateInfo->usage & VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT) != 0)
{
VMA_ASSERT(vkMemReq.alignment %
allocator->m_PhysicalDeviceProperties.limits.minTexelBufferOffsetAlignment == 0);
}
if((pBufferCreateInfo->usage & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT) != 0)
{
VMA_ASSERT(vkMemReq.alignment %
allocator->m_PhysicalDeviceProperties.limits.minUniformBufferOffsetAlignment == 0);
}
if((pBufferCreateInfo->usage & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT) != 0)
{
VMA_ASSERT(vkMemReq.alignment %
allocator->m_PhysicalDeviceProperties.limits.minStorageBufferOffsetAlignment == 0);
}
// 3. Allocate memory using allocator.
res = allocator->AllocateMemory(
vkMemReq,
requiresDedicatedAllocation,
prefersDedicatedAllocation,
*pBuffer, // dedicatedBuffer
VK_NULL_HANDLE, // dedicatedImage
*pAllocationCreateInfo,
VMA_SUBALLOCATION_TYPE_BUFFER,
pAllocation);
#if VMA_RECORDING_ENABLED
if(allocator->GetRecorder() != VMA_NULL)
{
allocator->GetRecorder()->RecordCreateBuffer(
allocator->GetCurrentFrameIndex(),
*pBufferCreateInfo,
*pAllocationCreateInfo,
*pAllocation);
}
#endif
if(res >= 0)
{
// 3. Bind buffer with memory.
res = allocator->BindBufferMemory(*pAllocation, *pBuffer);
if(res >= 0)
{
// All steps succeeded.
#if VMA_STATS_STRING_ENABLED
(*pAllocation)->InitBufferImageUsage(pBufferCreateInfo->usage);
#endif
if(pAllocationInfo != VMA_NULL)
{
allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
}
return VK_SUCCESS;
}
allocator->FreeMemory(*pAllocation);
*pAllocation = VK_NULL_HANDLE;
(*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, *pBuffer, allocator->GetAllocationCallbacks());
*pBuffer = VK_NULL_HANDLE;
return res;
}
(*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, *pBuffer, allocator->GetAllocationCallbacks());
*pBuffer = VK_NULL_HANDLE;
return res;
}
return res;
}
void vmaDestroyBuffer(
VmaAllocator allocator,
VkBuffer buffer,
VmaAllocation allocation)
{
VMA_ASSERT(allocator);
if(buffer == VK_NULL_HANDLE && allocation == VK_NULL_HANDLE)
{
return;
}
VMA_DEBUG_LOG("vmaDestroyBuffer");
VMA_DEBUG_GLOBAL_MUTEX_LOCK
#if VMA_RECORDING_ENABLED
if(allocator->GetRecorder() != VMA_NULL)
{
allocator->GetRecorder()->RecordDestroyBuffer(
allocator->GetCurrentFrameIndex(),
allocation);
}
#endif
if(buffer != VK_NULL_HANDLE)
{
(*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, buffer, allocator->GetAllocationCallbacks());
}
if(allocation != VK_NULL_HANDLE)
{
allocator->FreeMemory(allocation);
}
}
VkResult vmaCreateImage(
VmaAllocator allocator,
const VkImageCreateInfo* pImageCreateInfo,
const VmaAllocationCreateInfo* pAllocationCreateInfo,
VkImage* pImage,
VmaAllocation* pAllocation,
VmaAllocationInfo* pAllocationInfo)
{
VMA_ASSERT(allocator && pImageCreateInfo && pAllocationCreateInfo && pImage && pAllocation);
VMA_DEBUG_LOG("vmaCreateImage");
VMA_DEBUG_GLOBAL_MUTEX_LOCK
*pImage = VK_NULL_HANDLE;
*pAllocation = VK_NULL_HANDLE;
// 1. Create VkImage.
VkResult res = (*allocator->GetVulkanFunctions().vkCreateImage)(
allocator->m_hDevice,
pImageCreateInfo,
allocator->GetAllocationCallbacks(),
pImage);
if(res >= 0)
{
VmaSuballocationType suballocType = pImageCreateInfo->tiling == VK_IMAGE_TILING_OPTIMAL ?
VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL :
VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR;
// 2. Allocate memory using allocator.
VkMemoryRequirements vkMemReq = {};
bool requiresDedicatedAllocation = false;
bool prefersDedicatedAllocation = false;
allocator->GetImageMemoryRequirements(*pImage, vkMemReq,
requiresDedicatedAllocation, prefersDedicatedAllocation);
res = allocator->AllocateMemory(
vkMemReq,
requiresDedicatedAllocation,
prefersDedicatedAllocation,
VK_NULL_HANDLE, // dedicatedBuffer
*pImage, // dedicatedImage
*pAllocationCreateInfo,
suballocType,
pAllocation);
#if VMA_RECORDING_ENABLED
if(allocator->GetRecorder() != VMA_NULL)
{
allocator->GetRecorder()->RecordCreateImage(
allocator->GetCurrentFrameIndex(),
*pImageCreateInfo,
*pAllocationCreateInfo,
*pAllocation);
}
#endif
if(res >= 0)
{
// 3. Bind image with memory.
res = allocator->BindImageMemory(*pAllocation, *pImage);
if(res >= 0)
{
// All steps succeeded.
#if VMA_STATS_STRING_ENABLED
(*pAllocation)->InitBufferImageUsage(pImageCreateInfo->usage);
#endif
if(pAllocationInfo != VMA_NULL)
{
allocator->GetAllocationInfo(*pAllocation, pAllocationInfo);
}
return VK_SUCCESS;
}
allocator->FreeMemory(*pAllocation);
*pAllocation = VK_NULL_HANDLE;
(*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, *pImage, allocator->GetAllocationCallbacks());
*pImage = VK_NULL_HANDLE;
return res;
}
(*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, *pImage, allocator->GetAllocationCallbacks());
*pImage = VK_NULL_HANDLE;
return res;
}
return res;
}
void vmaDestroyImage(
VmaAllocator allocator,
VkImage image,
VmaAllocation allocation)
{
VMA_ASSERT(allocator);
if(image == VK_NULL_HANDLE && allocation == VK_NULL_HANDLE)
{
return;
}
VMA_DEBUG_LOG("vmaDestroyImage");
VMA_DEBUG_GLOBAL_MUTEX_LOCK
#if VMA_RECORDING_ENABLED
if(allocator->GetRecorder() != VMA_NULL)
{
allocator->GetRecorder()->RecordDestroyImage(
allocator->GetCurrentFrameIndex(),
allocation);
}
#endif
if(image != VK_NULL_HANDLE)
{
(*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, image, allocator->GetAllocationCallbacks());
}
if(allocation != VK_NULL_HANDLE)
{
allocator->FreeMemory(allocation);
}
}
#endif // #ifdef VMA_IMPLEMENTATION
|