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
|
/*
* Copyright (c) 2015-2019 The Khronos Group Inc.
* Copyright (c) 2015-2019 Valve Corporation
* Copyright (c) 2015-2019 LunarG, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: Chia-I Wu <olv@lunarg.com>
* Author: Courtney Goeltzenleuchter <courtney@LunarG.com>
* Author: Ian Elliott <ian@LunarG.com>
* Author: Ian Elliott <ianelliott@google.com>
* Author: Jon Ashburn <jon@lunarg.com>
* Author: Gwan-gyeong Mun <elongbug@gmail.com>
* Author: Tony Barbour <tony@LunarG.com>
* Author: Bill Hollings <bill.hollings@brenwill.com>
*/
#define _GNU_SOURCE
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include <signal.h>
#if defined(VK_USE_PLATFORM_SCREEN_QNX)
#include <errno.h>
#endif
#if defined(VK_USE_PLATFORM_XLIB_KHR)
#include "xlib_loader.h"
#endif
#if defined(VK_USE_PLATFORM_XCB_KHR)
#include "xcb_loader.h"
#endif
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
#include <linux/input.h>
#include "wayland_loader.h"
#endif
#ifdef _WIN32
#ifdef _MSC_VER
#pragma comment(linker, "/subsystem:windows")
#endif // MSVC
#define APP_NAME_STR_LEN 80
#endif // _WIN32
#include "cube_functions.h"
#include <vulkan/vulkan.h>
#include "linmath.h"
#include "object_type_string_helper.h"
#include "gettime.h"
#include "inttypes.h"
#define MILLION 1000000L
#define BILLION 1000000000L
#define DEMO_TEXTURE_COUNT 1
#define APP_SHORT_NAME "vkcube"
#define APP_LONG_NAME "Vulkan Cube"
// Allow a maximum of two outstanding presentation operations.
#define FRAME_LAG 2
// Need to know how big of a buffer of swapchain images, image views, and semaphores are needed
#define MAX_SWAPCHAIN_IMAGE_COUNT 8
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
#if defined(NDEBUG) && defined(__GNUC__)
#define U_ASSERT_ONLY __attribute__((unused))
#else
#define U_ASSERT_ONLY
#endif
#if defined(__GNUC__)
#define UNUSED __attribute__((unused))
#else
#define UNUSED
#endif
#ifdef _WIN32
bool in_callback = false;
#define ERR_EXIT(err_msg, err_class) \
do { \
if (!demo->suppress_popups) MessageBox(NULL, err_msg, err_class, MB_OK); \
exit(1); \
} while (0)
void DbgMsg(char *fmt, ...) {
va_list va;
va_start(va, fmt);
vprintf(fmt, va);
va_end(va);
fflush(stdout);
}
#elif defined __ANDROID__
#include <android/log.h>
#define ERR_EXIT(err_msg, err_class) \
do { \
((void)__android_log_print(ANDROID_LOG_INFO, "Vulkan Cube", err_msg)); \
exit(1); \
} while (0)
#ifdef VARARGS_WORKS_ON_ANDROID
void DbgMsg(const char *fmt, ...) {
va_list va;
va_start(va, fmt);
__android_log_print(ANDROID_LOG_INFO, "Vulkan Cube", fmt, va);
va_end(va);
}
#else // VARARGS_WORKS_ON_ANDROID
#define DbgMsg(fmt, ...) \
do { \
((void)__android_log_print(ANDROID_LOG_INFO, "Vulkan Cube", fmt, ##__VA_ARGS__)); \
} while (0)
#endif // VARARGS_WORKS_ON_ANDROID
#else
#define ERR_EXIT(err_msg, err_class) \
do { \
printf("%s\n", err_msg); \
fflush(stdout); \
exit(1); \
} while (0)
void DbgMsg(char *fmt, ...) {
va_list va;
va_start(va, fmt);
vprintf(fmt, va);
va_end(va);
fflush(stdout);
}
#endif
/*
* structure to track all objects related to a texture.
*/
struct texture_object {
VkSampler sampler;
VkImage image;
VkBuffer buffer;
VkImageLayout imageLayout;
VkMemoryAllocateInfo mem_alloc;
VkDeviceMemory mem;
VkImageView view;
int32_t tex_width, tex_height;
};
static char *tex_files[] = {"lunarg.ppm"};
static int validation_error = 0;
struct vktexcube_vs_uniform {
// Must start with MVP
float mvp[4][4];
float position[12 * 3][4];
float attr[12 * 3][4];
};
//--------------------------------------------------------------------------------------
// Mesh and VertexFormat Data
//--------------------------------------------------------------------------------------
// clang-format off
static const float g_vertex_buffer_data[] = {
-1.0f,-1.0f,-1.0f, // -X side
-1.0f,-1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, 1.0f,-1.0f,
-1.0f,-1.0f,-1.0f,
-1.0f,-1.0f,-1.0f, // -Z side
1.0f, 1.0f,-1.0f,
1.0f,-1.0f,-1.0f,
-1.0f,-1.0f,-1.0f,
-1.0f, 1.0f,-1.0f,
1.0f, 1.0f,-1.0f,
-1.0f,-1.0f,-1.0f, // -Y side
1.0f,-1.0f,-1.0f,
1.0f,-1.0f, 1.0f,
-1.0f,-1.0f,-1.0f,
1.0f,-1.0f, 1.0f,
-1.0f,-1.0f, 1.0f,
-1.0f, 1.0f,-1.0f, // +Y side
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f,-1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f,-1.0f,
1.0f, 1.0f,-1.0f, // +X side
1.0f, 1.0f, 1.0f,
1.0f,-1.0f, 1.0f,
1.0f,-1.0f, 1.0f,
1.0f,-1.0f,-1.0f,
1.0f, 1.0f,-1.0f,
-1.0f, 1.0f, 1.0f, // +Z side
-1.0f,-1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
-1.0f,-1.0f, 1.0f,
1.0f,-1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
};
static const float g_uv_buffer_data[] = {
0.0f, 1.0f, // -X side
1.0f, 1.0f,
1.0f, 0.0f,
1.0f, 0.0f,
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f, // -Z side
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f,
1.0f, 0.0f,
0.0f, 0.0f,
1.0f, 0.0f, // -Y side
1.0f, 1.0f,
0.0f, 1.0f,
1.0f, 0.0f,
0.0f, 1.0f,
0.0f, 0.0f,
1.0f, 0.0f, // +Y side
0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f,
1.0f, 0.0f, // +X side
0.0f, 0.0f,
0.0f, 1.0f,
0.0f, 1.0f,
1.0f, 1.0f,
1.0f, 0.0f,
0.0f, 0.0f, // +Z side
0.0f, 1.0f,
1.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f,
1.0f, 0.0f,
};
// clang-format on
void dumpMatrix(const char *note, mat4x4 MVP) {
int i;
printf("%s: \n", note);
for (i = 0; i < 4; i++) {
printf("%f, %f, %f, %f\n", MVP[i][0], MVP[i][1], MVP[i][2], MVP[i][3]);
}
printf("\n");
fflush(stdout);
}
void dumpVec4(const char *note, vec4 vector) {
printf("%s: \n", note);
printf("%f, %f, %f, %f\n", vector[0], vector[1], vector[2], vector[3]);
printf("\n");
fflush(stdout);
}
char const *to_string(VkPhysicalDeviceType const type) {
switch (type) {
case VK_PHYSICAL_DEVICE_TYPE_OTHER:
return "Other";
case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU:
return "IntegratedGpu";
case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU:
return "DiscreteGpu";
case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU:
return "VirtualGpu";
case VK_PHYSICAL_DEVICE_TYPE_CPU:
return "Cpu";
default:
return "Unknown";
}
}
typedef enum WSI_PLATFORM {
WSI_PLATFORM_AUTO = 0,
WSI_PLATFORM_WIN32,
WSI_PLATFORM_METAL,
WSI_PLATFORM_ANDROID,
WSI_PLATFORM_QNX,
WSI_PLATFORM_XCB,
WSI_PLATFORM_XLIB,
WSI_PLATFORM_WAYLAND,
WSI_PLATFORM_DIRECTFB,
WSI_PLATFORM_DISPLAY,
WSI_PLATFORM_INVALID, // Sentinel just to indicate invalid user input
} WSI_PLATFORM;
WSI_PLATFORM wsi_from_string(const char *str) {
if (strcmp(str, "auto") == 0) return WSI_PLATFORM_AUTO;
#if defined(VK_USE_PLATFORM_WIN32_KHR)
if (strcmp(str, "win32") == 0) return WSI_PLATFORM_WIN32;
#endif
#if defined(VK_USE_PLATFORM_METAL_EXT)
if (strcmp(str, "metal") == 0) return WSI_PLATFORM_METAL;
#endif
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
if (strcmp(str, "android") == 0) return WSI_PLATFORM_ANDROID;
#endif
#if defined(VK_USE_PLATFORM_SCREEN_QNX)
if (strcmp(str, "qnx") == 0) return WSI_PLATFORM_QNX;
#endif
#if defined(VK_USE_PLATFORM_XCB_KHR)
if (strcmp(str, "xcb") == 0) return WSI_PLATFORM_XCB;
#endif
#if defined(VK_USE_PLATFORM_XLIB_KHR)
if (strcmp(str, "xlib") == 0) return WSI_PLATFORM_XLIB;
#endif
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
if (strcmp(str, "wayland") == 0) return WSI_PLATFORM_WAYLAND;
#endif
#if defined(VK_USE_PLATFORM_DIRECTFB_EXT)
if (strcmp(str, "directfb") == 0) return WSI_PLATFORM_DIRECTFB;
#endif
#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
if (strcmp(str, "display") == 0) return WSI_PLATFORM_DISPLAY;
#endif
return WSI_PLATFORM_INVALID;
};
const char *wsi_to_string(WSI_PLATFORM wsi_platform) {
switch (wsi_platform) {
case (WSI_PLATFORM_AUTO):
return "auto";
#if defined(VK_USE_PLATFORM_WIN32_KHR)
case (WSI_PLATFORM_WIN32):
return "win32";
#endif
#if defined(VK_USE_PLATFORM_METAL_EXT)
case (WSI_PLATFORM_METAL):
return "metal";
#endif
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
case (WSI_PLATFORM_ANDROID):
return "android";
#endif
#if defined(VK_USE_PLATFORM_SCREEN_QNX)
case (WSI_PLATFORM_QNX):
return "qnx";
#endif
#if defined(VK_USE_PLATFORM_XCB_KHR)
case (WSI_PLATFORM_XCB):
return "xcb";
#endif
#if defined(VK_USE_PLATFORM_XLIB_KHR)
case (WSI_PLATFORM_XLIB):
return "xlib";
#endif
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
case (WSI_PLATFORM_WAYLAND):
return "wayland";
#endif
#if defined(VK_USE_PLATFORM_DIRECTFB_EXT)
case (WSI_PLATFORM_DIRECTFB):
return "directfb";
#endif
#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
case (WSI_PLATFORM_DISPLAY):
return "display";
#endif
default:
return "unknown";
}
};
typedef struct {
VkFence fence;
VkSemaphore image_acquired_semaphore;
VkCommandBuffer cmd;
VkCommandBuffer graphics_to_present_cmd;
VkBuffer uniform_buffer;
VkDeviceMemory uniform_memory;
void *uniform_memory_ptr;
VkDescriptorSet descriptor_set;
} SubmissionResources;
typedef struct {
VkImage image;
VkImageView view;
VkFramebuffer framebuffer;
VkSemaphore draw_complete_semaphore;
VkSemaphore image_ownership_semaphore;
} SwapchainImageResources;
struct demo {
#if defined(VK_USE_PLATFORM_WIN32_KHR)
#define APP_NAME_STR_LEN 80
HINSTANCE connection; // hInstance - Windows Instance
char name[APP_NAME_STR_LEN]; // Name to put on the window/icon
HWND window; // hWnd - window handle
POINT minsize; // minimum window size
#endif
#if defined(VK_USE_PLATFORM_XLIB_KHR)
void *xlib_library;
Display *xlib_display;
Window xlib_window;
Atom xlib_wm_delete_window;
#endif
#if defined(VK_USE_PLATFORM_XCB_KHR)
void *xcb_library;
Display *xcb_display;
xcb_connection_t *connection;
xcb_screen_t *screen;
xcb_window_t xcb_window;
xcb_intern_atom_reply_t *atom_wm_delete_window;
#endif
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
void *wayland_library; // Dynamic library for wayland
struct wl_display *wayland_display;
struct wl_registry *registry;
struct wl_compositor *compositor;
struct wl_surface *window;
struct xdg_wm_base *xdg_wm_base;
struct zxdg_decoration_manager_v1 *xdg_decoration_mgr;
struct zxdg_toplevel_decoration_v1 *toplevel_decoration;
struct xdg_surface *xdg_surface;
int xdg_surface_has_been_configured;
struct xdg_toplevel *xdg_toplevel;
struct wl_seat *seat;
struct wl_pointer *pointer;
struct wl_keyboard *keyboard;
int pending_width, pending_height;
#endif
#if defined(VK_USE_PLATFORM_DIRECTFB_EXT)
IDirectFB *dfb;
IDirectFBSurface *directfb_window;
IDirectFBEventBuffer *event_buffer;
#endif
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
struct ANativeWindow *window;
#endif
#if defined(VK_USE_PLATFORM_METAL_EXT)
void *caMetalLayer;
#endif
#if defined(VK_USE_PLATFORM_SCREEN_QNX)
screen_context_t screen_context;
screen_window_t screen_window;
screen_event_t screen_event;
#endif
WSI_PLATFORM wsi_platform;
VkSurfaceKHR surface;
bool initialized;
bool swapchain_ready;
bool is_minimized;
bool use_staging_buffer;
bool separate_present_queue;
bool invalid_gpu_selection;
int32_t gpu_number;
bool VK_KHR_incremental_present_enabled;
bool VK_GOOGLE_display_timing_enabled;
bool syncd_with_actual_presents;
uint64_t refresh_duration;
uint64_t refresh_duration_multiplier;
uint64_t target_IPD; // image present duration (inverse of frame rate)
uint64_t prev_desired_present_time;
uint32_t next_present_id;
uint32_t last_early_id; // 0 if no early images
uint32_t last_late_id; // 0 if no late images
VkInstance inst;
VkPhysicalDevice gpu;
VkDevice device;
VkQueue graphics_queue;
VkQueue present_queue;
uint32_t graphics_queue_family_index;
uint32_t present_queue_family_index;
VkPhysicalDeviceProperties gpu_props;
VkQueueFamilyProperties *queue_props;
VkPhysicalDeviceMemoryProperties memory_properties;
SubmissionResources submission_resources[FRAME_LAG];
uint32_t current_submission_index;
uint32_t enabled_extension_count;
uint32_t enabled_layer_count;
char *extension_names[64];
char *enabled_layers[64];
int width, height;
VkFormat format;
VkColorSpaceKHR color_space;
uint32_t swapchainImageCount;
VkSwapchainKHR swapchain;
SwapchainImageResources swapchain_resources[MAX_SWAPCHAIN_IMAGE_COUNT];
VkPresentModeKHR presentMode;
bool first_swapchain_frame;
VkCommandPool cmd_pool;
VkCommandPool present_cmd_pool;
struct {
VkFormat format;
VkImage image;
VkMemoryAllocateInfo mem_alloc;
VkDeviceMemory mem;
VkImageView view;
} depth;
struct texture_object textures[DEMO_TEXTURE_COUNT];
struct texture_object staging_texture;
VkCommandBuffer cmd; // Buffer for initialization commands
VkPipelineLayout pipeline_layout;
VkDescriptorSetLayout desc_layout;
VkPipelineCache pipelineCache;
VkRenderPass render_pass;
VkPipeline pipeline;
mat4x4 projection_matrix;
mat4x4 view_matrix;
mat4x4 model_matrix;
float spin_angle;
float spin_increment;
bool pause;
VkShaderModule vert_shader_module;
VkShaderModule frag_shader_module;
VkDescriptorPool desc_pool;
bool quit;
int32_t curFrame;
int32_t frameCount;
bool validate;
bool use_break;
bool suppress_popups;
bool force_errors;
VkDebugUtilsMessengerEXT dbg_messenger;
uint32_t queue_family_count;
};
VKAPI_ATTR VkBool32 VKAPI_CALL debug_messenger_callback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT messageType,
const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData,
void *pUserData) {
char prefix[64] = "";
char *message = (char *)malloc(strlen(pCallbackData->pMessage) + 5000);
assert(message);
struct demo *demo = (struct demo *)pUserData;
if (demo->use_break) {
#ifndef WIN32
raise(SIGTRAP);
#else
DebugBreak();
#endif
}
if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT) {
strcat(prefix, "VERBOSE : ");
} else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) {
strcat(prefix, "INFO : ");
} else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) {
strcat(prefix, "WARNING : ");
} else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) {
strcat(prefix, "ERROR : ");
}
if (messageType & VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT) {
strcat(prefix, "GENERAL");
} else {
if (messageType & VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT) {
strcat(prefix, "VALIDATION");
validation_error = 1;
}
if (messageType & VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT) {
if (messageType & VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT) {
strcat(prefix, "|");
}
strcat(prefix, "PERFORMANCE");
}
}
sprintf(message, "%s - Message Id Number: %d | Message Id Name: %s\n\t%s\n", prefix, pCallbackData->messageIdNumber,
pCallbackData->pMessageIdName == NULL ? "" : pCallbackData->pMessageIdName, pCallbackData->pMessage);
if (pCallbackData->objectCount > 0) {
char tmp_message[500];
sprintf(tmp_message, "\n\tObjects - %d\n", pCallbackData->objectCount);
strcat(message, tmp_message);
for (uint32_t object = 0; object < pCallbackData->objectCount; ++object) {
sprintf(tmp_message, "\t\tObject[%d] - %s", object, string_VkObjectType(pCallbackData->pObjects[object].objectType));
strcat(message, tmp_message);
VkObjectType t = pCallbackData->pObjects[object].objectType;
if (t == VK_OBJECT_TYPE_INSTANCE || t == VK_OBJECT_TYPE_PHYSICAL_DEVICE || t == VK_OBJECT_TYPE_DEVICE ||
t == VK_OBJECT_TYPE_COMMAND_BUFFER || t == VK_OBJECT_TYPE_QUEUE) {
sprintf(tmp_message, ", Handle %p", (void *)(uintptr_t)(pCallbackData->pObjects[object].objectHandle));
strcat(message, tmp_message);
} else {
sprintf(tmp_message, ", Handle Ox%" PRIx64, (pCallbackData->pObjects[object].objectHandle));
strcat(message, tmp_message);
}
if (NULL != pCallbackData->pObjects[object].pObjectName && strlen(pCallbackData->pObjects[object].pObjectName) > 0) {
sprintf(tmp_message, ", Name \"%s\"", pCallbackData->pObjects[object].pObjectName);
strcat(message, tmp_message);
}
sprintf(tmp_message, "\n");
strcat(message, tmp_message);
}
}
if (pCallbackData->cmdBufLabelCount > 0) {
char tmp_message[500];
sprintf(tmp_message, "\n\tCommand Buffer Labels - %d\n", pCallbackData->cmdBufLabelCount);
strcat(message, tmp_message);
for (uint32_t cmd_buf_label = 0; cmd_buf_label < pCallbackData->cmdBufLabelCount; ++cmd_buf_label) {
sprintf(tmp_message, "\t\tLabel[%d] - %s { %f, %f, %f, %f}\n", cmd_buf_label,
pCallbackData->pCmdBufLabels[cmd_buf_label].pLabelName, pCallbackData->pCmdBufLabels[cmd_buf_label].color[0],
pCallbackData->pCmdBufLabels[cmd_buf_label].color[1], pCallbackData->pCmdBufLabels[cmd_buf_label].color[2],
pCallbackData->pCmdBufLabels[cmd_buf_label].color[3]);
strcat(message, tmp_message);
}
}
#ifdef _WIN32
in_callback = true;
if (!demo->suppress_popups) MessageBox(NULL, message, "Alert", MB_OK);
in_callback = false;
#elif defined(ANDROID)
if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) {
__android_log_print(ANDROID_LOG_INFO, APP_SHORT_NAME, "%s", message);
} else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) {
__android_log_print(ANDROID_LOG_WARN, APP_SHORT_NAME, "%s", message);
} else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) {
__android_log_print(ANDROID_LOG_ERROR, APP_SHORT_NAME, "%s", message);
} else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT) {
__android_log_print(ANDROID_LOG_VERBOSE, APP_SHORT_NAME, "%s", message);
} else {
__android_log_print(ANDROID_LOG_INFO, APP_SHORT_NAME, "%s", message);
}
#else
printf("%s\n", message);
fflush(stdout);
#endif
free(message);
// Don't bail out, but keep going.
return false;
}
bool ActualTimeLate(uint64_t desired, uint64_t actual, uint64_t rdur) {
// The desired time was the earliest time that the present should have
// occured. In almost every case, the actual time should be later than the
// desired time. We should only consider the actual time "late" if it is
// after "desired + rdur".
if (actual <= desired) {
// The actual time was before or equal to the desired time. This will
// probably never happen, but in case it does, return false since the
// present was obviously NOT late.
return false;
}
uint64_t deadline = desired + rdur;
if (actual > deadline) {
return true;
} else {
return false;
}
}
bool CanPresentEarlier(uint64_t earliest, uint64_t actual, uint64_t margin, uint64_t rdur) {
if (earliest < actual) {
// Consider whether this present could have occured earlier. Make sure
// that earliest time was at least 2msec earlier than actual time, and
// that the margin was at least 2msec:
uint64_t diff = actual - earliest;
if ((diff >= (2 * MILLION)) && (margin >= (2 * MILLION))) {
// This present could have occured earlier because both: 1) the
// earliest time was at least 2 msec before actual time, and 2) the
// margin was at least 2msec.
return true;
}
}
return false;
}
// Forward declarations:
static void demo_resize(struct demo *demo);
static void demo_create_surface(struct demo *demo);
#if defined(__GNUC__) || defined(__clang__)
#define DECORATE_PRINTF(_fmt_argnum, _first_param_num) __attribute__((format(printf, _fmt_argnum, _first_param_num)))
#else
#define DECORATE_PRINTF(_fmt_num, _first_param_num)
#endif
DECORATE_PRINTF(4, 5)
static void demo_name_object(struct demo *demo, VkObjectType object_type, uint64_t vulkan_handle, const char *format, ...) {
if (!demo->validate) {
return;
}
VkResult U_ASSERT_ONLY err;
char name[1024];
va_list argptr;
va_start(argptr, format);
vsnprintf(name, sizeof(name), format, argptr);
va_end(argptr);
name[sizeof(name) - 1] = '\0';
VkDebugUtilsObjectNameInfoEXT obj_name = {
.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT,
.pNext = NULL,
.objectType = object_type,
.objectHandle = vulkan_handle,
.pObjectName = name,
};
err = vkSetDebugUtilsObjectNameEXT(demo->device, &obj_name);
assert(!err);
}
DECORATE_PRINTF(4, 5)
static void demo_push_cb_label(struct demo *demo, VkCommandBuffer cb, const float *color, const char *format, ...) {
if (!demo->validate) {
return;
}
char name[1024];
va_list argptr;
va_start(argptr, format);
vsnprintf(name, sizeof(name), format, argptr);
va_end(argptr);
name[sizeof(name) - 1] = '\0';
VkDebugUtilsLabelEXT label = {
.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT,
.pNext = NULL,
.pLabelName = name,
};
if (color) {
memcpy(label.color, color, sizeof(label.color));
}
vkCmdBeginDebugUtilsLabelEXT(cb, &label);
}
static void demo_pop_cb_label(struct demo *demo, VkCommandBuffer cb) {
if (!demo->validate) {
return;
}
vkCmdEndDebugUtilsLabelEXT(cb);
}
static bool memory_type_from_properties(struct demo *demo, uint32_t typeBits, VkFlags requirements_mask, uint32_t *typeIndex) {
// Search memtypes to find first index with those properties
for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
if ((typeBits & 1) == 1) {
// Type is available, does it match user properties?
if ((demo->memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
*typeIndex = i;
return true;
}
}
typeBits >>= 1;
}
// No memory types matched, return failure
return false;
}
static void demo_flush_init_cmd(struct demo *demo) {
VkResult U_ASSERT_ONLY err;
// This function could get called twice if the texture uses a staging buffer
// In that case the second call should be ignored
if (demo->cmd == VK_NULL_HANDLE) return;
err = vkEndCommandBuffer(demo->cmd);
assert(!err);
VkFence fence;
VkFenceCreateInfo fence_ci = {.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, .pNext = NULL, .flags = 0};
if (demo->force_errors) {
// Remove sType to intentionally force validation layer errors.
fence_ci.sType = 0;
}
err = vkCreateFence(demo->device, &fence_ci, NULL, &fence);
assert(!err);
demo_name_object(demo, VK_OBJECT_TYPE_FENCE, (uint64_t)fence, "InitFence");
const VkCommandBuffer cmd_bufs[] = {demo->cmd};
VkSubmitInfo submit_info = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
.pNext = NULL,
.waitSemaphoreCount = 0,
.pWaitSemaphores = NULL,
.pWaitDstStageMask = NULL,
.commandBufferCount = 1,
.pCommandBuffers = cmd_bufs,
.signalSemaphoreCount = 0,
.pSignalSemaphores = NULL};
err = vkQueueSubmit(demo->graphics_queue, 1, &submit_info, fence);
assert(!err);
err = vkWaitForFences(demo->device, 1, &fence, VK_TRUE, UINT64_MAX);
assert(!err);
vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, cmd_bufs);
vkDestroyFence(demo->device, fence, NULL);
demo->cmd = VK_NULL_HANDLE;
}
static void demo_set_image_layout(struct demo *demo, VkImage image, VkImageAspectFlags aspectMask, VkImageLayout old_image_layout,
VkImageLayout new_image_layout, VkAccessFlagBits srcAccessMask, VkPipelineStageFlags src_stages,
VkPipelineStageFlags dest_stages) {
assert(demo->cmd);
VkImageMemoryBarrier image_memory_barrier = {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.pNext = NULL,
.srcAccessMask = srcAccessMask,
.dstAccessMask = 0,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.oldLayout = old_image_layout,
.newLayout = new_image_layout,
.image = image,
.subresourceRange = {aspectMask, 0, 1, 0, 1}};
switch (new_image_layout) {
case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
/* Make sure anything that was copying from this image has completed */
image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
image_memory_barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
image_memory_barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
break;
case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_INPUT_ATTACHMENT_READ_BIT;
break;
case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
break;
case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR:
image_memory_barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
break;
default:
image_memory_barrier.dstAccessMask = 0;
break;
}
VkImageMemoryBarrier *pmemory_barrier = &image_memory_barrier;
vkCmdPipelineBarrier(demo->cmd, src_stages, dest_stages, 0, 0, NULL, 0, NULL, 1, pmemory_barrier);
}
static void demo_draw_build_cmd(struct demo *demo, SubmissionResources *submission_resource,
SwapchainImageResources *swapchain_resource) {
const VkCommandBufferBeginInfo cmd_buf_info = {
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.pNext = NULL,
.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT,
.pInheritanceInfo = NULL,
};
const VkClearValue clear_values[2] = {
[0] = {.color.float32 = {0.2f, 0.2f, 0.2f, 0.2f}},
[1] = {.depthStencil = {1.0f, 0}},
};
const VkRenderPassBeginInfo rp_begin = {
.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,
.pNext = NULL,
.renderPass = demo->render_pass,
.framebuffer = swapchain_resource->framebuffer,
.renderArea.offset.x = 0,
.renderArea.offset.y = 0,
.renderArea.extent.width = demo->width,
.renderArea.extent.height = demo->height,
.clearValueCount = 2,
.pClearValues = clear_values,
};
VkResult U_ASSERT_ONLY err;
err = vkResetCommandBuffer(submission_resource->cmd, 0 /* VK_COMMAND_BUFFER_RESET_FLAGS */);
err = vkBeginCommandBuffer(submission_resource->cmd, &cmd_buf_info);
demo_name_object(demo, VK_OBJECT_TYPE_COMMAND_BUFFER, (uint64_t)submission_resource->cmd, "CubeDrawCommandBuf");
const float begin_color[4] = {0.4f, 0.3f, 0.2f, 0.1f};
demo_push_cb_label(demo, submission_resource->cmd, begin_color, "DrawBegin");
assert(!err);
vkCmdBeginRenderPass(submission_resource->cmd, &rp_begin, VK_SUBPASS_CONTENTS_INLINE);
const float renderpass_color[4] = {8.4f, 7.3f, 6.2f, 7.1f};
demo_push_cb_label(demo, submission_resource->cmd, renderpass_color, "InsideRenderPass");
vkCmdBindPipeline(submission_resource->cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, demo->pipeline);
vkCmdBindDescriptorSets(submission_resource->cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, demo->pipeline_layout, 0, 1,
&submission_resource->descriptor_set, 0, NULL);
VkViewport viewport;
memset(&viewport, 0, sizeof(viewport));
float viewport_dimension;
if (demo->width < demo->height) {
viewport_dimension = (float)demo->width;
viewport.y = (demo->height - demo->width) / 2.0f;
} else {
viewport_dimension = (float)demo->height;
viewport.x = (demo->width - demo->height) / 2.0f;
}
viewport.height = viewport_dimension;
viewport.width = viewport_dimension;
viewport.minDepth = (float)0.0f;
viewport.maxDepth = (float)1.0f;
vkCmdSetViewport(submission_resource->cmd, 0, 1, &viewport);
VkRect2D scissor;
memset(&scissor, 0, sizeof(scissor));
scissor.extent.width = demo->width;
scissor.extent.height = demo->height;
scissor.offset.x = 0;
scissor.offset.y = 0;
vkCmdSetScissor(submission_resource->cmd, 0, 1, &scissor);
const float draw_color[4] = {-0.4f, -0.3f, -0.2f, -0.1f};
demo_push_cb_label(demo, submission_resource->cmd, draw_color, "ActualDraw");
vkCmdDraw(submission_resource->cmd, 12 * 3, 1, 0, 0);
demo_pop_cb_label(demo, submission_resource->cmd);
// Note that ending the renderpass changes the image's layout from
// COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
vkCmdEndRenderPass(submission_resource->cmd);
demo_pop_cb_label(demo, submission_resource->cmd);
if (demo->separate_present_queue) {
// We have to transfer ownership from the graphics queue family to the
// present queue family to be able to present. Note that we don't have
// to transfer from present queue family back to graphics queue family at
// the start of the next frame because we don't care about the image's
// contents at that point.
VkImageMemoryBarrier image_ownership_barrier = {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.pNext = NULL,
.srcAccessMask = 0,
.dstAccessMask = 0,
.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
.srcQueueFamilyIndex = demo->graphics_queue_family_index,
.dstQueueFamilyIndex = demo->present_queue_family_index,
.image = swapchain_resource->image,
.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}};
vkCmdPipelineBarrier(submission_resource->cmd, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
0, 0, NULL, 0, NULL, 1, &image_ownership_barrier);
}
demo_pop_cb_label(demo, submission_resource->cmd);
err = vkEndCommandBuffer(submission_resource->cmd);
assert(!err);
}
void demo_build_image_ownership_cmd(struct demo *demo, SubmissionResources *submission_resource,
SwapchainImageResources *swapchain_resource) {
VkResult U_ASSERT_ONLY err;
err = vkResetCommandBuffer(submission_resource->graphics_to_present_cmd, 0 /* VK_COMMAND_BUFFER_RESET_FLAGS */);
assert(!err);
const VkCommandBufferBeginInfo cmd_buf_info = {
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.pNext = NULL,
.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT,
.pInheritanceInfo = NULL,
};
err = vkBeginCommandBuffer(submission_resource->graphics_to_present_cmd, &cmd_buf_info);
assert(!err);
VkImageMemoryBarrier image_ownership_barrier = {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.pNext = NULL,
.srcAccessMask = 0,
.dstAccessMask = 0,
.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
.srcQueueFamilyIndex = demo->graphics_queue_family_index,
.dstQueueFamilyIndex = demo->present_queue_family_index,
.image = swapchain_resource->image,
.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}};
vkCmdPipelineBarrier(submission_resource->graphics_to_present_cmd, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, NULL, 1, &image_ownership_barrier);
err = vkEndCommandBuffer(submission_resource->graphics_to_present_cmd);
assert(!err);
}
void demo_update_data_buffer(struct demo *demo, void *uniform_memory_ptr) {
mat4x4 MVP, Model, VP;
int matrixSize = sizeof(MVP);
mat4x4_mul(VP, demo->projection_matrix, demo->view_matrix);
// Rotate around the Y axis
mat4x4_dup(Model, demo->model_matrix);
mat4x4_rotate_Y(demo->model_matrix, Model, (float)degreesToRadians(demo->spin_angle));
mat4x4_orthonormalize(demo->model_matrix, demo->model_matrix);
mat4x4_mul(MVP, VP, demo->model_matrix);
memcpy(uniform_memory_ptr, (const void *)&MVP[0][0], matrixSize);
}
void DemoUpdateTargetIPD(struct demo *demo) {
// Look at what happened to previous presents, and make appropriate
// adjustments in timing:
VkResult U_ASSERT_ONLY err;
VkPastPresentationTimingGOOGLE *past = NULL;
uint32_t count = 0;
err = vkGetPastPresentationTimingGOOGLE(demo->device, demo->swapchain, &count, NULL);
assert(!err);
if (count) {
past = (VkPastPresentationTimingGOOGLE *)malloc(sizeof(VkPastPresentationTimingGOOGLE) * count);
assert(past);
err = vkGetPastPresentationTimingGOOGLE(demo->device, demo->swapchain, &count, past);
assert(!err);
bool early = false;
bool late = false;
bool calibrate_next = false;
for (uint32_t i = 0; i < count; i++) {
if (!demo->syncd_with_actual_presents) {
// This is the first time that we've received an
// actualPresentTime for this swapchain. In order to not
// perceive these early frames as "late", we need to sync-up
// our future desiredPresentTime's with the
// actualPresentTime(s) that we're receiving now.
calibrate_next = true;
// So that we don't suspect any pending presents as late,
// record them all as suspected-late presents:
demo->last_late_id = demo->next_present_id - 1;
demo->last_early_id = 0;
demo->syncd_with_actual_presents = true;
break;
} else if (CanPresentEarlier(past[i].earliestPresentTime, past[i].actualPresentTime, past[i].presentMargin,
demo->refresh_duration)) {
// This image could have been presented earlier. We don't want
// to decrease the target_IPD until we've seen early presents
// for at least two seconds.
if (demo->last_early_id == past[i].presentID) {
// We've now seen two seconds worth of early presents.
// Flag it as such, and reset the counter:
early = true;
demo->last_early_id = 0;
} else if (demo->last_early_id == 0) {
// This is the first early present we've seen.
// Calculate the presentID for two seconds from now.
uint64_t lastEarlyTime = past[i].actualPresentTime + (2 * BILLION);
uint32_t howManyPresents = (uint32_t)((lastEarlyTime - past[i].actualPresentTime) / demo->target_IPD);
demo->last_early_id = past[i].presentID + howManyPresents;
} else {
// We are in the midst of a set of early images,
// and so we won't do anything.
}
late = false;
demo->last_late_id = 0;
} else if (ActualTimeLate(past[i].desiredPresentTime, past[i].actualPresentTime, demo->refresh_duration)) {
// This image was presented after its desired time. Since
// there's a delay between calling vkQueuePresentKHR and when
// we get the timing data, several presents may have been late.
// Thus, we need to threat all of the outstanding presents as
// being likely late, so that we only increase the target_IPD
// once for all of those presents.
if ((demo->last_late_id == 0) || (demo->last_late_id < past[i].presentID)) {
late = true;
// Record the last suspected-late present:
demo->last_late_id = demo->next_present_id - 1;
} else {
// We are in the midst of a set of likely-late images,
// and so we won't do anything.
}
early = false;
demo->last_early_id = 0;
} else {
// Since this image was not presented early or late, reset
// any sets of early or late presentIDs:
early = false;
late = false;
calibrate_next = true;
demo->last_early_id = 0;
demo->last_late_id = 0;
}
}
if (early) {
// Since we've seen at least two-seconds worth of presnts that
// could have occured earlier than desired, let's decrease the
// target_IPD (i.e. increase the frame rate):
//
// TODO(ianelliott): Try to calculate a better target_IPD based
// on the most recently-seen present (this is overly-simplistic).
demo->refresh_duration_multiplier--;
if (demo->refresh_duration_multiplier == 0) {
// This should never happen, but in case it does, don't
// try to go faster.
demo->refresh_duration_multiplier = 1;
}
demo->target_IPD = demo->refresh_duration * demo->refresh_duration_multiplier;
}
if (late) {
// Since we found a new instance of a late present, we want to
// increase the target_IPD (i.e. decrease the frame rate):
//
// TODO(ianelliott): Try to calculate a better target_IPD based
// on the most recently-seen present (this is overly-simplistic).
demo->refresh_duration_multiplier++;
demo->target_IPD = demo->refresh_duration * demo->refresh_duration_multiplier;
}
if (calibrate_next) {
int64_t multiple = demo->next_present_id - past[count - 1].presentID;
demo->prev_desired_present_time = (past[count - 1].actualPresentTime + (multiple * demo->target_IPD));
}
free(past);
}
}
static void demo_draw(struct demo *demo) {
// Don't draw if initialization isn't complete, if the swapchain became outdated, or if the window is minimized
if (!demo->initialized || !demo->swapchain_ready || demo->is_minimized) {
return;
}
VkResult U_ASSERT_ONLY err;
SubmissionResources current_submission = demo->submission_resources[demo->current_submission_index];
// Ensure no more than FRAME_LAG renderings are outstanding
vkWaitForFences(demo->device, 1, ¤t_submission.fence, VK_TRUE, UINT64_MAX);
uint32_t current_swapchain_image_index;
do {
// Get the index of the next available swapchain image:
err = vkAcquireNextImageKHR(demo->device, demo->swapchain, UINT64_MAX, current_submission.image_acquired_semaphore,
VK_NULL_HANDLE, ¤t_swapchain_image_index);
if (err == VK_ERROR_OUT_OF_DATE_KHR) {
// demo->swapchain is out of date (e.g. the window was resized) and
// must be recreated:
demo_resize(demo);
} else if (err == VK_SUBOPTIMAL_KHR) {
// demo->swapchain is not as optimal as it could be, but the platform's
// presentation engine will still present the image correctly.
break;
} else if (err == VK_ERROR_SURFACE_LOST_KHR) {
vkDestroySurfaceKHR(demo->inst, demo->surface, NULL);
demo_create_surface(demo);
demo_resize(demo);
} else {
assert(!err);
}
// Stop drawing if we resized but didn't successfully create a new swapchain.
if (!demo->swapchain_ready) {
return;
}
} while (err != VK_SUCCESS);
SwapchainImageResources current_swapchain_resource = demo->swapchain_resources[current_swapchain_image_index];
demo_update_data_buffer(demo, current_submission.uniform_memory_ptr);
if (demo->VK_GOOGLE_display_timing_enabled) {
// Look at what happened to previous presents, and make appropriate
// adjustments in timing:
DemoUpdateTargetIPD(demo);
// Note: a real application would position its geometry to that it's in
// the correct locatoin for when the next image is presented. It might
// also wait, so that there's less latency between any input and when
// the next image is rendered/presented. This demo program is so
// simple that it doesn't do either of those.
}
demo_draw_build_cmd(demo, ¤t_submission, ¤t_swapchain_resource);
if (demo->separate_present_queue) {
demo_build_image_ownership_cmd(demo, ¤t_submission, ¤t_swapchain_resource);
}
// Only reset right before submitting so we can't deadlock on an un-signalled fence that has nothing submitted to it
vkResetFences(demo->device, 1, ¤t_submission.fence);
// Wait for the image acquired semaphore to be signaled to ensure
// that the image won't be rendered to until the presentation
// engine has fully released ownership to the application, and it is
// okay to render to the image.
VkPipelineStageFlags pipe_stage_flags;
VkSubmitInfo submit_info;
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.pNext = NULL;
pipe_stage_flags = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
submit_info.pWaitDstStageMask = &pipe_stage_flags;
submit_info.waitSemaphoreCount = 1;
submit_info.pWaitSemaphores = ¤t_submission.image_acquired_semaphore;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = ¤t_submission.cmd;
submit_info.signalSemaphoreCount = 1;
submit_info.pSignalSemaphores = ¤t_swapchain_resource.draw_complete_semaphore;
err = vkQueueSubmit(demo->graphics_queue, 1, &submit_info, current_submission.fence);
assert(!err);
if (demo->separate_present_queue) {
// If we are using separate queues, change image ownership to the
// present queue before presenting, waiting for the draw complete
// semaphore and signalling the ownership released semaphore when finished
VkFence nullFence = VK_NULL_HANDLE;
pipe_stage_flags = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
submit_info.waitSemaphoreCount = 1;
submit_info.pWaitSemaphores = ¤t_swapchain_resource.draw_complete_semaphore;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = ¤t_submission.graphics_to_present_cmd;
submit_info.signalSemaphoreCount = 1;
submit_info.pSignalSemaphores = ¤t_swapchain_resource.image_ownership_semaphore;
err = vkQueueSubmit(demo->present_queue, 1, &submit_info, nullFence);
assert(!err);
}
// If we are using separate queues we have to wait for image ownership,
// otherwise wait for draw complete
VkPresentInfoKHR present = {
.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
.pNext = NULL,
.waitSemaphoreCount = 1,
.pWaitSemaphores = (demo->separate_present_queue) ? ¤t_swapchain_resource.image_ownership_semaphore
: ¤t_swapchain_resource.draw_complete_semaphore,
.swapchainCount = 1,
.pSwapchains = &demo->swapchain,
.pImageIndices = ¤t_swapchain_image_index,
};
VkRectLayerKHR rect;
VkPresentRegionKHR region;
VkPresentRegionsKHR regions;
if (demo->VK_KHR_incremental_present_enabled) {
// If using VK_KHR_incremental_present, we provide a hint of the region
// that contains changed content relative to the previously-presented
// image. The implementation can use this hint in order to save
// work/power (by only copying the region in the hint). The
// implementation is free to ignore the hint though, and so we must
// ensure that the entire image has the correctly-drawn content.
uint32_t eighthOfWidth = demo->width / 8;
uint32_t eighthOfHeight = demo->height / 8;
if (demo->first_swapchain_frame) {
rect.offset.x = 0;
rect.offset.y = 0;
rect.extent.width = demo->width;
rect.extent.height = demo->height;
} else {
rect.offset.x = eighthOfWidth;
rect.offset.y = eighthOfHeight;
rect.extent.width = eighthOfWidth * 6;
rect.extent.height = eighthOfHeight * 6;
}
rect.layer = 0;
region.rectangleCount = 1;
region.pRectangles = ▭
regions.sType = VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR;
regions.pNext = present.pNext;
regions.swapchainCount = present.swapchainCount;
regions.pRegions = ®ion;
present.pNext = ®ions;
}
if (demo->VK_GOOGLE_display_timing_enabled) {
VkPresentTimeGOOGLE ptime;
if (demo->prev_desired_present_time == 0) {
// This must be the first present for this swapchain.
//
// We don't know where we are relative to the presentation engine's
// display's refresh cycle. We also don't know how long rendering
// takes. Let's make a grossly-simplified assumption that the
// desiredPresentTime should be half way between now and
// now+target_IPD. We will adjust over time.
uint64_t curtime = getTimeInNanoseconds();
if (curtime == 0) {
// Since we didn't find out the current time, don't give a
// desiredPresentTime:
ptime.desiredPresentTime = 0;
} else {
ptime.desiredPresentTime = curtime + (demo->target_IPD >> 1);
}
} else {
ptime.desiredPresentTime = (demo->prev_desired_present_time + demo->target_IPD);
}
ptime.presentID = demo->next_present_id++;
demo->prev_desired_present_time = ptime.desiredPresentTime;
VkPresentTimesInfoGOOGLE present_time = {
.sType = VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE,
.pNext = present.pNext,
.swapchainCount = present.swapchainCount,
.pTimes = &ptime,
};
if (demo->VK_GOOGLE_display_timing_enabled) {
present.pNext = &present_time;
}
}
err = vkQueuePresentKHR(demo->present_queue, &present);
demo->current_submission_index += 1;
demo->current_submission_index %= FRAME_LAG;
demo->first_swapchain_frame = false;
if (err == VK_ERROR_OUT_OF_DATE_KHR) {
// demo->swapchain is out of date (e.g. the window was resized) and
// must be recreated:
demo_resize(demo);
} else if (err == VK_SUBOPTIMAL_KHR) {
// SUBOPTIMAL could be due to a resize
VkSurfaceCapabilitiesKHR surfCapabilities;
err = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(demo->gpu, demo->surface, &surfCapabilities);
assert(!err);
if (surfCapabilities.currentExtent.width != (uint32_t)demo->width ||
surfCapabilities.currentExtent.height != (uint32_t)demo->height) {
demo_resize(demo);
}
} else if (err == VK_ERROR_SURFACE_LOST_KHR) {
vkDestroySurfaceKHR(demo->inst, demo->surface, NULL);
demo_create_surface(demo);
demo_resize(demo);
} else {
assert(!err);
}
}
// Forward decls for that demo_prepare_swapchain needs
static void demo_prepare_depth(struct demo *demo);
static void demo_prepare_framebuffers(struct demo *demo);
// Creates the swapchain, swapchain image views, depth buffer, framebuffers, and sempahores.
// This function returns early if it fails to create a swapchain, setting swapchain_ready to false.
static void demo_prepare_swapchain(struct demo *demo) {
VkResult U_ASSERT_ONLY err;
VkSwapchainKHR oldSwapchain = demo->swapchain;
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
if (demo->wsi_platform == WSI_PLATFORM_WAYLAND && !demo->xdg_surface_has_been_configured) {
return;
}
#endif
// Check the surface capabilities and formats
VkSurfaceCapabilitiesKHR surfCapabilities;
err = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(demo->gpu, demo->surface, &surfCapabilities);
assert(!err);
uint32_t presentModeCount;
err = vkGetPhysicalDeviceSurfacePresentModesKHR(demo->gpu, demo->surface, &presentModeCount, NULL);
assert(!err);
VkPresentModeKHR *presentModes = (VkPresentModeKHR *)malloc(presentModeCount * sizeof(VkPresentModeKHR));
assert(presentModes);
err = vkGetPhysicalDeviceSurfacePresentModesKHR(demo->gpu, demo->surface, &presentModeCount, presentModes);
assert(!err);
VkExtent2D swapchainExtent;
// width and height are either both 0xFFFFFFFF, or both not 0xFFFFFFFF.
if (surfCapabilities.currentExtent.width == 0xFFFFFFFF) {
// If the surface size is undefined, the size is set to the size
// of the images requested, which must fit within the minimum and
// maximum values.
swapchainExtent.width = demo->width;
swapchainExtent.height = demo->height;
if (swapchainExtent.width < surfCapabilities.minImageExtent.width) {
swapchainExtent.width = surfCapabilities.minImageExtent.width;
} else if (swapchainExtent.width > surfCapabilities.maxImageExtent.width) {
swapchainExtent.width = surfCapabilities.maxImageExtent.width;
}
if (swapchainExtent.height < surfCapabilities.minImageExtent.height) {
swapchainExtent.height = surfCapabilities.minImageExtent.height;
} else if (swapchainExtent.height > surfCapabilities.maxImageExtent.height) {
swapchainExtent.height = surfCapabilities.maxImageExtent.height;
}
} else {
// If the surface size is defined, the swap chain size must match
swapchainExtent = surfCapabilities.currentExtent;
demo->width = surfCapabilities.currentExtent.width;
demo->height = surfCapabilities.currentExtent.height;
}
if (surfCapabilities.maxImageExtent.width == 0 || surfCapabilities.maxImageExtent.height == 0) {
demo->is_minimized = true;
return;
} else {
demo->is_minimized = false;
}
// The FIFO present mode is guaranteed by the spec to be supported
// and to have no tearing. It's a great default present mode to use.
VkPresentModeKHR swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR;
// There are times when you may wish to use another present mode. The
// following code shows how to select them, and the comments provide some
// reasons you may wish to use them.
//
// It should be noted that Vulkan 1.0 doesn't provide a method for
// synchronizing rendering with the presentation engine's display. There
// is a method provided for throttling rendering with the display, but
// there are some presentation engines for which this method will not work.
// If an application doesn't throttle its rendering, and if it renders much
// faster than the refresh rate of the display, this can waste power on
// mobile devices. That is because power is being spent rendering images
// that may never be seen.
// VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care about
// tearing, or have some way of synchronizing their rendering with the
// display.
// VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
// generally render a new presentable image every refresh cycle, but are
// occasionally early. In this case, the application wants the new image
// to be displayed instead of the previously-queued-for-presentation image
// that has not yet been displayed.
// VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
// render a new presentable image every refresh cycle, but are occasionally
// late. In this case (perhaps because of stuttering/latency concerns),
// the application wants the late image to be immediately displayed, even
// though that may mean some tearing.
if (demo->presentMode != swapchainPresentMode) {
for (size_t i = 0; i < presentModeCount; ++i) {
if (presentModes[i] == demo->presentMode) {
swapchainPresentMode = demo->presentMode;
break;
}
}
}
if (swapchainPresentMode != demo->presentMode) {
ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
}
// Determine the number of VkImages to use in the swap chain.
// Application desires to acquire 3 images at a time for triple
// buffering
uint32_t desiredNumOfSwapchainImages = 3;
if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
}
// If maxImageCount is 0, we can ask for as many images as we want;
// otherwise we're limited to maxImageCount
if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
// Application must settle for fewer images than desired:
desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
}
VkSurfaceTransformFlagsKHR preTransform;
if (surfCapabilities.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) {
preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
} else {
preTransform = surfCapabilities.currentTransform;
}
// Find a supported composite alpha mode - one of these is guaranteed to be set
VkCompositeAlphaFlagBitsKHR compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
VkCompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR,
VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR,
VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR,
};
for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
compositeAlpha = compositeAlphaFlags[i];
break;
}
}
VkSwapchainCreateInfoKHR swapchain_ci = {
.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
.pNext = NULL,
.surface = demo->surface,
.minImageCount = desiredNumOfSwapchainImages,
.imageFormat = demo->format,
.imageColorSpace = demo->color_space,
.imageExtent =
{
.width = swapchainExtent.width,
.height = swapchainExtent.height,
},
.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
.preTransform = preTransform,
.compositeAlpha = compositeAlpha,
.imageArrayLayers = 1,
.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE,
.queueFamilyIndexCount = 0,
.pQueueFamilyIndices = NULL,
.presentMode = swapchainPresentMode,
.oldSwapchain = oldSwapchain,
.clipped = true,
};
uint32_t i;
err = vkCreateSwapchainKHR(demo->device, &swapchain_ci, NULL, &demo->swapchain);
assert(!err);
// If we just re-created an existing swapchain, we should destroy the old
// swapchain at this point.
// Note: destroying the swapchain also cleans up all its associated
// presentable images once the platform is done with them.
if (oldSwapchain != VK_NULL_HANDLE) {
vkDestroySwapchainKHR(demo->device, oldSwapchain, NULL);
}
err = vkGetSwapchainImagesKHR(demo->device, demo->swapchain, &demo->swapchainImageCount, NULL);
assert(!err);
VkImage *swapchainImages = (VkImage *)malloc(demo->swapchainImageCount * sizeof(VkImage));
assert(swapchainImages);
err = vkGetSwapchainImagesKHR(demo->device, demo->swapchain, &demo->swapchainImageCount, swapchainImages);
assert(!err);
for (i = 0; i < demo->swapchainImageCount; i++) {
demo_name_object(demo, VK_OBJECT_TYPE_IMAGE, (uint64_t)swapchainImages[i], "SwapchainImage(%u)", i);
}
for (i = 0; i < demo->swapchainImageCount; i++) {
VkImageViewCreateInfo color_image_view = {
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
.pNext = NULL,
.format = demo->format,
.components =
{
.r = VK_COMPONENT_SWIZZLE_IDENTITY,
.g = VK_COMPONENT_SWIZZLE_IDENTITY,
.b = VK_COMPONENT_SWIZZLE_IDENTITY,
.a = VK_COMPONENT_SWIZZLE_IDENTITY,
},
.subresourceRange =
{.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1},
.viewType = VK_IMAGE_VIEW_TYPE_2D,
.flags = 0,
};
demo->swapchain_resources[i].image = swapchainImages[i];
color_image_view.image = demo->swapchain_resources[i].image;
err = vkCreateImageView(demo->device, &color_image_view, NULL, &demo->swapchain_resources[i].view);
assert(!err);
demo_name_object(demo, VK_OBJECT_TYPE_IMAGE_VIEW, (uint64_t)demo->swapchain_resources[i].view, "SwapchainView(%u)", i);
}
// Create semaphores to synchronize acquiring presentable buffers before
// rendering and waiting for drawing to be complete before presenting
VkSemaphoreCreateInfo semaphoreCreateInfo = {
.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
.pNext = NULL,
.flags = 0,
};
for (i = 0; i < demo->swapchainImageCount; i++) {
err = vkCreateSemaphore(demo->device, &semaphoreCreateInfo, NULL, &demo->swapchain_resources[i].draw_complete_semaphore);
assert(!err);
demo_name_object(demo, VK_OBJECT_TYPE_SEMAPHORE, (uint64_t)demo->swapchain_resources[i].draw_complete_semaphore,
"DrawCompleteSem(%u)", i);
if (demo->separate_present_queue) {
err = vkCreateSemaphore(demo->device, &semaphoreCreateInfo, NULL,
&demo->swapchain_resources[i].image_ownership_semaphore);
assert(!err);
demo_name_object(demo, VK_OBJECT_TYPE_SEMAPHORE, (uint64_t)demo->swapchain_resources[i].image_ownership_semaphore,
"ImageOwnerSem(%u)", i);
}
}
if (demo->VK_GOOGLE_display_timing_enabled) {
VkRefreshCycleDurationGOOGLE rc_dur;
err = vkGetRefreshCycleDurationGOOGLE(demo->device, demo->swapchain, &rc_dur);
assert(!err);
demo->refresh_duration = rc_dur.refreshDuration;
demo->syncd_with_actual_presents = false;
// Initially target 1X the refresh duration:
demo->target_IPD = demo->refresh_duration;
demo->refresh_duration_multiplier = 1;
demo->prev_desired_present_time = 0;
demo->next_present_id = 1;
}
if (NULL != swapchainImages) {
free(swapchainImages);
}
if (NULL != presentModes) {
free(presentModes);
}
demo_prepare_depth(demo);
demo_prepare_framebuffers(demo);
demo->swapchain_ready = true;
demo->first_swapchain_frame = true;
}
static void demo_prepare_depth(struct demo *demo) {
demo->depth.format = VK_FORMAT_D16_UNORM;
const VkImageCreateInfo image = {
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
.pNext = NULL,
.imageType = VK_IMAGE_TYPE_2D,
.format = demo->depth.format,
.extent = {demo->width, demo->height, 1},
.mipLevels = 1,
.arrayLayers = 1,
.samples = VK_SAMPLE_COUNT_1_BIT,
.tiling = VK_IMAGE_TILING_OPTIMAL,
.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
.flags = 0,
};
VkImageViewCreateInfo view = {
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
.pNext = NULL,
.image = VK_NULL_HANDLE,
.format = demo->depth.format,
.subresourceRange =
{.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1},
.flags = 0,
.viewType = VK_IMAGE_VIEW_TYPE_2D,
};
if (demo->force_errors) {
// Intentionally force a bad pNext value to generate a validation layer error
view.pNext = ℑ
}
VkMemoryRequirements mem_reqs;
VkResult U_ASSERT_ONLY err;
bool U_ASSERT_ONLY pass;
/* create image */
err = vkCreateImage(demo->device, &image, NULL, &demo->depth.image);
assert(!err);
demo_name_object(demo, VK_OBJECT_TYPE_IMAGE, (uint64_t)demo->depth.image, "DepthImage");
vkGetImageMemoryRequirements(demo->device, demo->depth.image, &mem_reqs);
assert(!err);
demo->depth.mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
demo->depth.mem_alloc.pNext = NULL;
demo->depth.mem_alloc.allocationSize = mem_reqs.size;
demo->depth.mem_alloc.memoryTypeIndex = 0;
pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
&demo->depth.mem_alloc.memoryTypeIndex);
assert(pass);
/* allocate memory */
err = vkAllocateMemory(demo->device, &demo->depth.mem_alloc, NULL, &demo->depth.mem);
assert(!err);
demo_name_object(demo, VK_OBJECT_TYPE_DEVICE_MEMORY, (uint64_t)demo->depth.mem, "DepthMem");
/* bind memory */
err = vkBindImageMemory(demo->device, demo->depth.image, demo->depth.mem, 0);
assert(!err);
/* create image view */
view.image = demo->depth.image;
err = vkCreateImageView(demo->device, &view, NULL, &demo->depth.view);
assert(!err);
demo_name_object(demo, VK_OBJECT_TYPE_IMAGE_VIEW, (uint64_t)demo->depth.view, "DepthView");
}
/* Convert ppm image data from header file into RGBA texture image */
#include "lunarg.ppm.h"
bool loadTexture(const char *filename, uint8_t *rgba_data, VkSubresourceLayout *layout, int32_t *width, int32_t *height) {
(void)filename;
char *cPtr;
cPtr = (char *)lunarg_ppm;
if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
return false;
}
while (strncmp(cPtr++, "\n", 1));
sscanf(cPtr, "%u %u", width, height);
if (rgba_data == NULL) {
return true;
}
while (strncmp(cPtr++, "\n", 1));
if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
return false;
}
while (strncmp(cPtr++, "\n", 1));
for (int y = 0; y < *height; y++) {
uint8_t *rowPtr = rgba_data;
for (int x = 0; x < *width; x++) {
memcpy(rowPtr, cPtr, 3);
rowPtr[3] = 255; /* Alpha of 1 */
rowPtr += 4;
cPtr += 3;
}
rgba_data += layout->rowPitch;
}
return true;
}
static void demo_prepare_texture_buffer(struct demo *demo, const char *filename, struct texture_object *tex_obj) {
int32_t tex_width;
int32_t tex_height;
VkResult U_ASSERT_ONLY err;
bool U_ASSERT_ONLY pass;
if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
ERR_EXIT("Failed to load textures", "Load Texture Failure");
}
tex_obj->tex_width = tex_width;
tex_obj->tex_height = tex_height;
const VkBufferCreateInfo buffer_create_info = {.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
.pNext = NULL,
.flags = 0,
.size = tex_width * tex_height * 4,
.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
.queueFamilyIndexCount = 0,
.pQueueFamilyIndices = NULL};
err = vkCreateBuffer(demo->device, &buffer_create_info, NULL, &tex_obj->buffer);
assert(!err);
demo_name_object(demo, VK_OBJECT_TYPE_BUFFER, (uint64_t)tex_obj->buffer, "TexBuffer(%s)", filename);
VkMemoryRequirements mem_reqs;
vkGetBufferMemoryRequirements(demo->device, tex_obj->buffer, &mem_reqs);
tex_obj->mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
tex_obj->mem_alloc.pNext = NULL;
tex_obj->mem_alloc.allocationSize = mem_reqs.size;
tex_obj->mem_alloc.memoryTypeIndex = 0;
VkFlags requirements = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, requirements, &tex_obj->mem_alloc.memoryTypeIndex);
assert(pass);
err = vkAllocateMemory(demo->device, &tex_obj->mem_alloc, NULL, &(tex_obj->mem));
assert(!err);
demo_name_object(demo, VK_OBJECT_TYPE_DEVICE_MEMORY, (uint64_t)tex_obj->mem, "TexBufMemory(%s)", filename);
/* bind memory */
err = vkBindBufferMemory(demo->device, tex_obj->buffer, tex_obj->mem, 0);
assert(!err);
VkSubresourceLayout layout;
memset(&layout, 0, sizeof(layout));
layout.rowPitch = tex_width * 4;
void *data;
err = vkMapMemory(demo->device, tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize, 0, &data);
assert(!err);
if (!loadTexture(filename, data, &layout, &tex_width, &tex_height)) {
fprintf(stderr, "Error loading texture: %s\n", filename);
}
vkUnmapMemory(demo->device, tex_obj->mem);
}
static void demo_prepare_texture_image(struct demo *demo, const char *filename, struct texture_object *tex_obj,
VkImageTiling tiling, VkImageUsageFlags usage, VkFlags required_props) {
const VkFormat tex_format = VK_FORMAT_R8G8B8A8_SRGB;
int32_t tex_width;
int32_t tex_height;
VkResult U_ASSERT_ONLY err;
bool U_ASSERT_ONLY pass;
if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
ERR_EXIT("Failed to load textures", "Load Texture Failure");
}
tex_obj->tex_width = tex_width;
tex_obj->tex_height = tex_height;
const VkImageCreateInfo image_create_info = {
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
.pNext = NULL,
.imageType = VK_IMAGE_TYPE_2D,
.format = tex_format,
.extent = {tex_width, tex_height, 1},
.mipLevels = 1,
.arrayLayers = 1,
.samples = VK_SAMPLE_COUNT_1_BIT,
.tiling = tiling,
.usage = usage,
.flags = 0,
.initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED,
};
VkMemoryRequirements mem_reqs;
err = vkCreateImage(demo->device, &image_create_info, NULL, &tex_obj->image);
assert(!err);
demo_name_object(demo, VK_OBJECT_TYPE_IMAGE, (uint64_t)tex_obj->image, "TexImage(%s)", filename);
vkGetImageMemoryRequirements(demo->device, tex_obj->image, &mem_reqs);
tex_obj->mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
tex_obj->mem_alloc.pNext = NULL;
tex_obj->mem_alloc.allocationSize = mem_reqs.size;
tex_obj->mem_alloc.memoryTypeIndex = 0;
pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex);
assert(pass);
/* allocate memory */
err = vkAllocateMemory(demo->device, &tex_obj->mem_alloc, NULL, &(tex_obj->mem));
assert(!err);
demo_name_object(demo, VK_OBJECT_TYPE_DEVICE_MEMORY, (uint64_t)tex_obj->mem, "TexImageMem(%s)", filename);
/* bind memory */
err = vkBindImageMemory(demo->device, tex_obj->image, tex_obj->mem, 0);
assert(!err);
if (required_props & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
const VkImageSubresource subres = {
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.mipLevel = 0,
.arrayLayer = 0,
};
VkSubresourceLayout layout;
void *data;
vkGetImageSubresourceLayout(demo->device, tex_obj->image, &subres, &layout);
err = vkMapMemory(demo->device, tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize, 0, &data);
assert(!err);
if (!loadTexture(filename, data, &layout, &tex_width, &tex_height)) {
fprintf(stderr, "Error loading texture: %s\n", filename);
}
vkUnmapMemory(demo->device, tex_obj->mem);
}
tex_obj->imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
}
static void demo_destroy_texture(struct demo *demo, struct texture_object *tex_objs) {
/* clean up staging resources */
vkFreeMemory(demo->device, tex_objs->mem, NULL);
if (tex_objs->image) vkDestroyImage(demo->device, tex_objs->image, NULL);
if (tex_objs->buffer) vkDestroyBuffer(demo->device, tex_objs->buffer, NULL);
}
static void demo_prepare_textures(struct demo *demo) {
const VkFormat tex_format = VK_FORMAT_R8G8B8A8_SRGB;
VkFormatProperties props;
uint32_t i;
vkGetPhysicalDeviceFormatProperties(demo->gpu, tex_format, &props);
for (i = 0; i < DEMO_TEXTURE_COUNT; i++) {
VkResult U_ASSERT_ONLY err;
if ((props.linearTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) && !demo->use_staging_buffer) {
demo_push_cb_label(demo, demo->cmd, NULL, "DirectTexture(%u)", i);
/* Device can texture using linear textures */
demo_prepare_texture_image(demo, tex_files[i], &demo->textures[i], VK_IMAGE_TILING_LINEAR, VK_IMAGE_USAGE_SAMPLED_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
// Nothing in the pipeline needs to be complete to start, and don't allow fragment
// shader to run until layout transition completes
demo_set_image_layout(demo, demo->textures[i].image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_PREINITIALIZED,
demo->textures[i].imageLayout, 0, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
demo->staging_texture.image = 0;
demo_pop_cb_label(demo, demo->cmd); // "DirectTexture"
} else if (props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) {
/* Must use staging buffer to copy linear texture to optimized */
demo_push_cb_label(demo, demo->cmd, NULL, "StagingTexture(%u)", i);
memset(&demo->staging_texture, 0, sizeof(demo->staging_texture));
demo_prepare_texture_buffer(demo, tex_files[i], &demo->staging_texture);
demo_prepare_texture_image(demo, tex_files[i], &demo->textures[i], VK_IMAGE_TILING_OPTIMAL,
(VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT),
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
demo_set_image_layout(demo, demo->textures[i].image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_PREINITIALIZED,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 0, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT);
demo_push_cb_label(demo, demo->cmd, NULL, "StagingBufferCopy(%u)", i);
VkBufferImageCopy copy_region = {
.bufferOffset = 0,
.bufferRowLength = demo->staging_texture.tex_width,
.bufferImageHeight = demo->staging_texture.tex_height,
.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.imageOffset = {0, 0, 0},
.imageExtent = {demo->staging_texture.tex_width, demo->staging_texture.tex_height, 1},
};
vkCmdCopyBufferToImage(demo->cmd, demo->staging_texture.buffer, demo->textures[i].image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region);
demo_pop_cb_label(demo, demo->cmd); // "StagingBufferCopy"
demo_set_image_layout(demo, demo->textures[i].image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
demo->textures[i].imageLayout, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
demo_pop_cb_label(demo, demo->cmd); // "StagingTexture"
} else {
/* Can't support VK_FORMAT_R8G8B8A8_SRGB !? */
assert(!"No support for R8G8B8A8_SRGB as texture image format");
}
const VkSamplerCreateInfo sampler = {
.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
.pNext = NULL,
.magFilter = VK_FILTER_NEAREST,
.minFilter = VK_FILTER_NEAREST,
.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST,
.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
.mipLodBias = 0.0f,
.anisotropyEnable = VK_FALSE,
.maxAnisotropy = 1,
.compareOp = VK_COMPARE_OP_NEVER,
.minLod = 0.0f,
.maxLod = 0.0f,
.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE,
.unnormalizedCoordinates = VK_FALSE,
};
VkImageViewCreateInfo view = {
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
.pNext = NULL,
.image = VK_NULL_HANDLE,
.viewType = VK_IMAGE_VIEW_TYPE_2D,
.format = tex_format,
.components =
{
VK_COMPONENT_SWIZZLE_IDENTITY,
VK_COMPONENT_SWIZZLE_IDENTITY,
VK_COMPONENT_SWIZZLE_IDENTITY,
VK_COMPONENT_SWIZZLE_IDENTITY,
},
.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1},
.flags = 0,
};
/* create sampler */
err = vkCreateSampler(demo->device, &sampler, NULL, &demo->textures[i].sampler);
assert(!err);
demo_name_object(demo, VK_OBJECT_TYPE_SAMPLER, (uint64_t)demo->textures[i].sampler, "Sampler(%u)", i);
/* create image view */
view.image = demo->textures[i].image;
err = vkCreateImageView(demo->device, &view, NULL, &demo->textures[i].view);
demo_name_object(demo, VK_OBJECT_TYPE_IMAGE_VIEW, (uint64_t)demo->textures[i].view, "TexImageView(%u)", i);
assert(!err);
}
}
void demo_prepare_cube_data_buffers(struct demo *demo) {
VkBufferCreateInfo buf_info;
VkMemoryRequirements mem_reqs;
VkMemoryAllocateInfo mem_alloc;
mat4x4 MVP, VP;
VkResult U_ASSERT_ONLY err;
bool U_ASSERT_ONLY pass;
struct vktexcube_vs_uniform data;
mat4x4_mul(VP, demo->projection_matrix, demo->view_matrix);
mat4x4_mul(MVP, VP, demo->model_matrix);
memcpy(data.mvp, MVP, sizeof(MVP));
// dumpMatrix("MVP", MVP);
for (unsigned int i = 0; i < 12 * 3; i++) {
data.position[i][0] = g_vertex_buffer_data[i * 3];
data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
data.position[i][3] = 1.0f;
data.attr[i][0] = g_uv_buffer_data[2 * i];
data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
data.attr[i][2] = 0;
data.attr[i][3] = 0;
}
memset(&buf_info, 0, sizeof(buf_info));
buf_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buf_info.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
buf_info.size = sizeof(data);
for (unsigned int i = 0; i < FRAME_LAG; i++) {
err = vkCreateBuffer(demo->device, &buf_info, NULL, &demo->submission_resources[i].uniform_buffer);
assert(!err);
demo_name_object(demo, VK_OBJECT_TYPE_BUFFER, (uint64_t)demo->submission_resources[i].uniform_buffer, "UniformBuf(%u)", i);
vkGetBufferMemoryRequirements(demo->device, demo->submission_resources[i].uniform_buffer, &mem_reqs);
mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
mem_alloc.pNext = NULL;
mem_alloc.allocationSize = mem_reqs.size;
mem_alloc.memoryTypeIndex = 0;
pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
&mem_alloc.memoryTypeIndex);
assert(pass);
err = vkAllocateMemory(demo->device, &mem_alloc, NULL, &demo->submission_resources[i].uniform_memory);
assert(!err);
demo_name_object(demo, VK_OBJECT_TYPE_DEVICE_MEMORY, (uint64_t)demo->submission_resources[i].uniform_memory,
"UniformMem(%u)", i);
err = vkMapMemory(demo->device, demo->submission_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, 0,
&demo->submission_resources[i].uniform_memory_ptr);
assert(!err);
memcpy(demo->submission_resources[i].uniform_memory_ptr, &data, sizeof data);
err = vkBindBufferMemory(demo->device, demo->submission_resources[i].uniform_buffer,
demo->submission_resources[i].uniform_memory, 0);
assert(!err);
}
}
static void demo_prepare_descriptor_layout(struct demo *demo) {
const VkDescriptorSetLayoutBinding layout_bindings[2] = {
[0] =
{
.binding = 0,
.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
.descriptorCount = 1,
.stageFlags = VK_SHADER_STAGE_VERTEX_BIT,
.pImmutableSamplers = NULL,
},
[1] =
{
.binding = 1,
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
.descriptorCount = DEMO_TEXTURE_COUNT,
.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT,
.pImmutableSamplers = NULL,
},
};
const VkDescriptorSetLayoutCreateInfo descriptor_layout = {
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
.pNext = NULL,
.bindingCount = 2,
.pBindings = layout_bindings,
};
VkResult U_ASSERT_ONLY err;
err = vkCreateDescriptorSetLayout(demo->device, &descriptor_layout, NULL, &demo->desc_layout);
assert(!err);
const VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
.pNext = NULL,
.setLayoutCount = 1,
.pSetLayouts = &demo->desc_layout,
};
err = vkCreatePipelineLayout(demo->device, &pPipelineLayoutCreateInfo, NULL, &demo->pipeline_layout);
assert(!err);
}
static void demo_prepare_render_pass(struct demo *demo) {
// The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED
// because at the start of the renderpass, we don't care about their contents.
// At the start of the subpass, the color attachment's layout will be transitioned
// to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout
// will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL. At the end of
// the renderpass, the color attachment's layout will be transitioned to
// LAYOUT_PRESENT_SRC_KHR to be ready to present. This is all done as part of
// the renderpass, no barriers are necessary.
const VkAttachmentDescription attachments[2] = {
[0] =
{
.format = demo->format,
.flags = 0,
.samples = VK_SAMPLE_COUNT_1_BIT,
.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
.storeOp = VK_ATTACHMENT_STORE_OP_STORE,
.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
},
[1] =
{
.format = demo->depth.format,
.flags = 0,
.samples = VK_SAMPLE_COUNT_1_BIT,
.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
},
};
const VkAttachmentReference color_reference = {
.attachment = 0,
.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
};
const VkAttachmentReference depth_reference = {
.attachment = 1,
.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
};
const VkSubpassDescription subpass = {
.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS,
.flags = 0,
.inputAttachmentCount = 0,
.pInputAttachments = NULL,
.colorAttachmentCount = 1,
.pColorAttachments = &color_reference,
.pResolveAttachments = NULL,
.pDepthStencilAttachment = &depth_reference,
.preserveAttachmentCount = 0,
.pPreserveAttachments = NULL,
};
VkSubpassDependency attachmentDependencies[2] = {
[0] =
{
// Depth buffer is shared between swapchain images
.srcSubpass = VK_SUBPASS_EXTERNAL,
.dstSubpass = 0,
.srcStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
.dstStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
.srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
.dependencyFlags = 0,
},
[1] =
{
// Image Layout Transition
.srcSubpass = VK_SUBPASS_EXTERNAL,
.dstSubpass = 0,
.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
.srcAccessMask = 0,
.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT,
.dependencyFlags = 0,
},
};
const VkRenderPassCreateInfo rp_info = {
.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO,
.pNext = NULL,
.flags = 0,
.attachmentCount = 2,
.pAttachments = attachments,
.subpassCount = 1,
.pSubpasses = &subpass,
.dependencyCount = 2,
.pDependencies = attachmentDependencies,
};
VkResult U_ASSERT_ONLY err;
err = vkCreateRenderPass(demo->device, &rp_info, NULL, &demo->render_pass);
assert(!err);
}
static VkShaderModule demo_prepare_shader_module(const char *name, struct demo *demo, const uint32_t *code, size_t size) {
VkShaderModule module;
VkShaderModuleCreateInfo moduleCreateInfo;
VkResult U_ASSERT_ONLY err;
moduleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
moduleCreateInfo.pNext = NULL;
moduleCreateInfo.flags = 0;
moduleCreateInfo.codeSize = size;
moduleCreateInfo.pCode = code;
err = vkCreateShaderModule(demo->device, &moduleCreateInfo, NULL, &module);
assert(!err);
demo_name_object(demo, VK_OBJECT_TYPE_SHADER_MODULE, (uint64_t)module, "%s", name);
return module;
}
static void demo_prepare_vs(struct demo *demo) {
const uint32_t vs_code[] = {
#include "cube.vert.inc"
};
demo->vert_shader_module = demo_prepare_shader_module("cube.vert", demo, vs_code, sizeof(vs_code));
}
static void demo_prepare_fs(struct demo *demo) {
const uint32_t fs_code[] = {
#include "cube.frag.inc"
};
demo->frag_shader_module = demo_prepare_shader_module("cube.frag", demo, fs_code, sizeof(fs_code));
}
static void demo_prepare_pipeline(struct demo *demo) {
#define NUM_DYNAMIC_STATES 2 /*Viewport + Scissor*/
VkGraphicsPipelineCreateInfo pipeline;
VkPipelineCacheCreateInfo pipelineCache;
VkPipelineVertexInputStateCreateInfo vi;
VkPipelineInputAssemblyStateCreateInfo ia;
VkPipelineRasterizationStateCreateInfo rs;
VkPipelineColorBlendStateCreateInfo cb;
VkPipelineDepthStencilStateCreateInfo ds;
VkPipelineViewportStateCreateInfo vp;
VkPipelineMultisampleStateCreateInfo ms;
VkDynamicState dynamicStateEnables[NUM_DYNAMIC_STATES];
VkPipelineDynamicStateCreateInfo dynamicState;
VkResult U_ASSERT_ONLY err;
memset(dynamicStateEnables, 0, sizeof dynamicStateEnables);
memset(&dynamicState, 0, sizeof dynamicState);
dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
dynamicState.pDynamicStates = dynamicStateEnables;
memset(&pipeline, 0, sizeof(pipeline));
pipeline.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipeline.layout = demo->pipeline_layout;
memset(&vi, 0, sizeof(vi));
vi.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
memset(&ia, 0, sizeof(ia));
ia.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
memset(&rs, 0, sizeof(rs));
rs.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rs.polygonMode = VK_POLYGON_MODE_FILL;
rs.cullMode = VK_CULL_MODE_BACK_BIT;
rs.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
rs.depthClampEnable = VK_FALSE;
rs.rasterizerDiscardEnable = VK_FALSE;
rs.depthBiasEnable = VK_FALSE;
rs.lineWidth = 1.0f;
memset(&cb, 0, sizeof(cb));
cb.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
VkPipelineColorBlendAttachmentState att_state[1];
memset(att_state, 0, sizeof(att_state));
att_state[0].colorWriteMask = 0xf;
att_state[0].blendEnable = VK_FALSE;
cb.attachmentCount = 1;
cb.pAttachments = att_state;
memset(&vp, 0, sizeof(vp));
vp.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
vp.viewportCount = 1;
dynamicStateEnables[dynamicState.dynamicStateCount++] = VK_DYNAMIC_STATE_VIEWPORT;
vp.scissorCount = 1;
dynamicStateEnables[dynamicState.dynamicStateCount++] = VK_DYNAMIC_STATE_SCISSOR;
memset(&ds, 0, sizeof(ds));
ds.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
ds.depthTestEnable = VK_TRUE;
ds.depthWriteEnable = VK_TRUE;
ds.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL;
ds.depthBoundsTestEnable = VK_FALSE;
ds.back.failOp = VK_STENCIL_OP_KEEP;
ds.back.passOp = VK_STENCIL_OP_KEEP;
ds.back.compareOp = VK_COMPARE_OP_ALWAYS;
ds.stencilTestEnable = VK_FALSE;
ds.front = ds.back;
memset(&ms, 0, sizeof(ms));
ms.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
ms.pSampleMask = NULL;
ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
demo_prepare_vs(demo);
demo_prepare_fs(demo);
// Two stages: vs and fs
VkPipelineShaderStageCreateInfo shaderStages[2];
memset(&shaderStages, 0, 2 * sizeof(VkPipelineShaderStageCreateInfo));
shaderStages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
shaderStages[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
shaderStages[0].module = demo->vert_shader_module;
shaderStages[0].pName = "main";
shaderStages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
shaderStages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
shaderStages[1].module = demo->frag_shader_module;
shaderStages[1].pName = "main";
memset(&pipelineCache, 0, sizeof(pipelineCache));
pipelineCache.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
err = vkCreatePipelineCache(demo->device, &pipelineCache, NULL, &demo->pipelineCache);
assert(!err);
pipeline.pVertexInputState = &vi;
pipeline.pInputAssemblyState = &ia;
pipeline.pRasterizationState = &rs;
pipeline.pColorBlendState = &cb;
pipeline.pMultisampleState = &ms;
pipeline.pViewportState = &vp;
pipeline.pDepthStencilState = &ds;
pipeline.stageCount = ARRAY_SIZE(shaderStages);
pipeline.pStages = shaderStages;
pipeline.renderPass = demo->render_pass;
pipeline.pDynamicState = &dynamicState;
err = vkCreateGraphicsPipelines(demo->device, demo->pipelineCache, 1, &pipeline, NULL, &demo->pipeline);
assert(!err);
vkDestroyShaderModule(demo->device, demo->frag_shader_module, NULL);
vkDestroyShaderModule(demo->device, demo->vert_shader_module, NULL);
}
static void demo_prepare_descriptor_pool(struct demo *demo) {
const VkDescriptorPoolSize type_counts[2] = {
[0] =
{
.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
.descriptorCount = FRAME_LAG,
},
[1] =
{
.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
.descriptorCount = FRAME_LAG * DEMO_TEXTURE_COUNT,
},
};
const VkDescriptorPoolCreateInfo descriptor_pool = {
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
.pNext = NULL,
.maxSets = FRAME_LAG,
.poolSizeCount = 2,
.pPoolSizes = type_counts,
};
VkResult U_ASSERT_ONLY err;
err = vkCreateDescriptorPool(demo->device, &descriptor_pool, NULL, &demo->desc_pool);
assert(!err);
}
static void demo_prepare_descriptor_set(struct demo *demo) {
VkDescriptorImageInfo tex_descs[DEMO_TEXTURE_COUNT];
VkWriteDescriptorSet writes[2];
VkResult U_ASSERT_ONLY err;
VkDescriptorSetAllocateInfo alloc_info = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
.pNext = NULL,
.descriptorPool = demo->desc_pool,
.descriptorSetCount = 1,
.pSetLayouts = &demo->desc_layout};
VkDescriptorBufferInfo buffer_info;
buffer_info.offset = 0;
buffer_info.range = sizeof(struct vktexcube_vs_uniform);
memset(&tex_descs, 0, sizeof(tex_descs));
for (unsigned int i = 0; i < DEMO_TEXTURE_COUNT; i++) {
tex_descs[i].sampler = demo->textures[i].sampler;
tex_descs[i].imageView = demo->textures[i].view;
tex_descs[i].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
}
memset(&writes, 0, sizeof(writes));
writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
writes[0].descriptorCount = 1;
writes[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
writes[0].pBufferInfo = &buffer_info;
writes[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
writes[1].dstBinding = 1;
writes[1].descriptorCount = DEMO_TEXTURE_COUNT;
writes[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
writes[1].pImageInfo = tex_descs;
for (unsigned int i = 0; i < FRAME_LAG; i++) {
err = vkAllocateDescriptorSets(demo->device, &alloc_info, &demo->submission_resources[i].descriptor_set);
assert(!err);
buffer_info.buffer = demo->submission_resources[i].uniform_buffer;
writes[0].dstSet = demo->submission_resources[i].descriptor_set;
writes[1].dstSet = demo->submission_resources[i].descriptor_set;
vkUpdateDescriptorSets(demo->device, 2, writes, 0, NULL);
}
}
static void demo_prepare_framebuffers(struct demo *demo) {
VkImageView attachments[2];
attachments[1] = demo->depth.view;
const VkFramebufferCreateInfo fb_info = {
.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
.pNext = NULL,
.renderPass = demo->render_pass,
.attachmentCount = 2,
.pAttachments = attachments,
.width = demo->width,
.height = demo->height,
.layers = 1,
};
VkResult U_ASSERT_ONLY err;
uint32_t i;
for (i = 0; i < demo->swapchainImageCount; i++) {
attachments[0] = demo->swapchain_resources[i].view;
err = vkCreateFramebuffer(demo->device, &fb_info, NULL, &demo->swapchain_resources[i].framebuffer);
assert(!err);
demo_name_object(demo, VK_OBJECT_TYPE_FRAMEBUFFER, (uint64_t)demo->swapchain_resources[i].framebuffer, "Framebuffer(%u)",
i);
}
}
static void demo_prepare_submission_sync_objects(struct demo *demo) {
VkSemaphoreCreateInfo semaphoreCreateInfo = {
.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
.pNext = NULL,
.flags = 0,
};
// Create fences that we can use to throttle if we get too far
// ahead of the image presents
VkFenceCreateInfo fence_ci = {
.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, .pNext = NULL, .flags = VK_FENCE_CREATE_SIGNALED_BIT};
VkResult U_ASSERT_ONLY err;
for (uint32_t i = 0; i < FRAME_LAG; i++) {
err = vkCreateFence(demo->device, &fence_ci, NULL, &demo->submission_resources[i].fence);
assert(!err);
err = vkCreateSemaphore(demo->device, &semaphoreCreateInfo, NULL, &demo->submission_resources[i].image_acquired_semaphore);
assert(!err);
demo_name_object(demo, VK_OBJECT_TYPE_SEMAPHORE, (uint64_t)demo->submission_resources[i].image_acquired_semaphore,
"AcquireSem(%u)", i);
}
}
static void demo_prepare(struct demo *demo) {
VkResult U_ASSERT_ONLY err;
if (demo->cmd_pool == VK_NULL_HANDLE) {
const VkCommandPoolCreateInfo cmd_pool_info = {
.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
.pNext = NULL,
.queueFamilyIndex = demo->graphics_queue_family_index,
.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
};
err = vkCreateCommandPool(demo->device, &cmd_pool_info, NULL, &demo->cmd_pool);
assert(!err);
}
const VkCommandBufferAllocateInfo cmd = {
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
.pNext = NULL,
.commandPool = demo->cmd_pool,
.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
.commandBufferCount = 1,
};
err = vkAllocateCommandBuffers(demo->device, &cmd, &demo->cmd);
assert(!err);
demo_name_object(demo, VK_OBJECT_TYPE_COMMAND_BUFFER, (uint64_t)demo->cmd, "PrepareCB");
VkCommandBufferBeginInfo cmd_buf_info = {
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.pNext = NULL,
.flags = 0,
.pInheritanceInfo = NULL,
};
err = vkBeginCommandBuffer(demo->cmd, &cmd_buf_info);
demo_push_cb_label(demo, demo->cmd, NULL, "Prepare");
assert(!err);
demo_prepare_textures(demo);
demo_prepare_cube_data_buffers(demo);
demo_prepare_descriptor_layout(demo);
// Only need to know the format of the depth buffer before we create the renderpass
demo->depth.format = VK_FORMAT_D16_UNORM;
demo_prepare_render_pass(demo);
demo_prepare_pipeline(demo);
for (uint32_t i = 0; i < FRAME_LAG; i++) {
err = vkAllocateCommandBuffers(demo->device, &cmd, &demo->submission_resources[i].cmd);
assert(!err);
demo_name_object(demo, VK_OBJECT_TYPE_COMMAND_BUFFER, (uint64_t)demo->submission_resources[i].cmd, "MainCommandBuffer(%u)",
i);
}
if (demo->separate_present_queue) {
const VkCommandPoolCreateInfo present_cmd_pool_info = {
.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
.pNext = NULL,
.queueFamilyIndex = demo->present_queue_family_index,
.flags = 0,
};
err = vkCreateCommandPool(demo->device, &present_cmd_pool_info, NULL, &demo->present_cmd_pool);
assert(!err);
const VkCommandBufferAllocateInfo present_cmd_info = {
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
.pNext = NULL,
.commandPool = demo->present_cmd_pool,
.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
.commandBufferCount = 1,
};
for (uint32_t i = 0; i < FRAME_LAG; i++) {
err = vkAllocateCommandBuffers(demo->device, &present_cmd_info, &demo->submission_resources[i].graphics_to_present_cmd);
assert(!err);
demo_name_object(demo, VK_OBJECT_TYPE_COMMAND_BUFFER, (uint64_t)demo->submission_resources[i].graphics_to_present_cmd,
"GfxToPresent(%u)", i);
}
}
demo_prepare_descriptor_pool(demo);
demo_prepare_descriptor_set(demo);
demo_prepare_submission_sync_objects(demo);
/*
* Prepare functions above may generate pipeline commands
* that need to be flushed before beginning the render loop.
*/
demo_pop_cb_label(demo, demo->cmd); // "Prepare"
demo_flush_init_cmd(demo);
if (demo->staging_texture.buffer) {
demo_destroy_texture(demo, &demo->staging_texture);
}
demo->current_submission_index = 0;
demo->initialized = true;
demo_prepare_swapchain(demo);
}
static void demo_cleanup(struct demo *demo) {
uint32_t i;
demo->initialized = false;
vkDeviceWaitIdle(demo->device);
// Wait for fences from present operations
for (i = 0; i < FRAME_LAG; i++) {
vkWaitForFences(demo->device, 1, &demo->submission_resources[i].fence, VK_TRUE, UINT64_MAX);
}
// If the window is currently minimized, demo_resize has already done some cleanup for us.
if (!demo->is_minimized) {
vkDestroyDescriptorPool(demo->device, demo->desc_pool, NULL);
vkDestroyPipeline(demo->device, demo->pipeline, NULL);
vkDestroyPipelineCache(demo->device, demo->pipelineCache, NULL);
vkDestroyRenderPass(demo->device, demo->render_pass, NULL);
vkDestroyPipelineLayout(demo->device, demo->pipeline_layout, NULL);
vkDestroyDescriptorSetLayout(demo->device, demo->desc_layout, NULL);
for (i = 0; i < DEMO_TEXTURE_COUNT; i++) {
vkDestroyImageView(demo->device, demo->textures[i].view, NULL);
vkDestroyImage(demo->device, demo->textures[i].image, NULL);
vkFreeMemory(demo->device, demo->textures[i].mem, NULL);
vkDestroySampler(demo->device, demo->textures[i].sampler, NULL);
}
vkDestroySwapchainKHR(demo->device, demo->swapchain, NULL);
vkDestroyImageView(demo->device, demo->depth.view, NULL);
vkDestroyImage(demo->device, demo->depth.image, NULL);
vkFreeMemory(demo->device, demo->depth.mem, NULL);
for (i = 0; i < demo->swapchainImageCount; i++) {
vkDestroyImageView(demo->device, demo->swapchain_resources[i].view, NULL);
vkDestroyFramebuffer(demo->device, demo->swapchain_resources[i].framebuffer, NULL);
vkDestroySemaphore(demo->device, demo->swapchain_resources[i].draw_complete_semaphore, NULL);
if (demo->separate_present_queue) {
vkDestroySemaphore(demo->device, demo->swapchain_resources[i].image_ownership_semaphore, NULL);
}
}
for (i = 0; i < FRAME_LAG; i++) {
vkDestroyFence(demo->device, demo->submission_resources[i].fence, NULL);
vkDestroySemaphore(demo->device, demo->submission_resources[i].image_acquired_semaphore, NULL);
vkDestroyBuffer(demo->device, demo->submission_resources[i].uniform_buffer, NULL);
vkUnmapMemory(demo->device, demo->submission_resources[i].uniform_memory);
vkFreeMemory(demo->device, demo->submission_resources[i].uniform_memory, NULL);
}
free(demo->queue_props);
vkDestroyCommandPool(demo->device, demo->cmd_pool, NULL);
if (demo->separate_present_queue) {
vkDestroyCommandPool(demo->device, demo->present_cmd_pool, NULL);
}
}
vkDeviceWaitIdle(demo->device);
vkDestroyDevice(demo->device, NULL);
if (demo->validate) {
vkDestroyDebugUtilsMessengerEXT(demo->inst, demo->dbg_messenger, NULL);
}
vkDestroySurfaceKHR(demo->inst, demo->surface, NULL);
#if defined(VK_USE_PLATFORM_XLIB_KHR)
if (demo->wsi_platform == WSI_PLATFORM_XLIB) {
XDestroyWindow(demo->xlib_display, demo->xlib_window);
XCloseDisplay(demo->xlib_display);
}
#endif
#if defined(VK_USE_PLATFORM_XCB_KHR)
if (demo->wsi_platform == WSI_PLATFORM_XCB) {
xcb_destroy_window(demo->connection, demo->xcb_window);
xcb_disconnect(demo->connection);
free(demo->atom_wm_delete_window);
}
#endif
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
if (demo->wsi_platform == WSI_PLATFORM_WAYLAND) {
if (demo->keyboard) wl_keyboard_destroy(demo->keyboard);
if (demo->pointer) wl_pointer_destroy(demo->pointer);
if (demo->seat) wl_seat_destroy(demo->seat);
xdg_toplevel_destroy(demo->xdg_toplevel);
xdg_surface_destroy(demo->xdg_surface);
wl_surface_destroy(demo->window);
xdg_wm_base_destroy(demo->xdg_wm_base);
if (demo->xdg_decoration_mgr) {
zxdg_toplevel_decoration_v1_destroy(demo->toplevel_decoration);
zxdg_decoration_manager_v1_destroy(demo->xdg_decoration_mgr);
}
wl_compositor_destroy(demo->compositor);
wl_registry_destroy(demo->registry);
wl_display_disconnect(demo->wayland_display);
}
#endif
#if defined(VK_USE_PLATFORM_DIRECTFB_EXT)
if (demo->wsi_platform == WSI_PLATFORM_DIRECTFB) {
demo->event_buffer->Release(demo->event_buffer);
demo->directfb_window->Release(demo->directfb_window);
demo->dfb->Release(demo->dfb);
}
#endif
#if defined(VK_USE_PLATFORM_SCREEN_QNX)
if (demo->wsi_platform == WSI_PLATFORM_QNX) {
screen_destroy_event(demo->screen_event);
screen_destroy_window(demo->screen_window);
screen_destroy_context(demo->screen_context);
}
#endif
vkDestroyInstance(demo->inst, NULL);
unload_vulkan_library();
}
static void demo_resize(struct demo *demo) {
uint32_t i;
// Don't react to resize until after first initialization.
if (!demo->initialized) {
return;
}
// Don't do anything if the surface has zero size, as vulkan disallows creating swapchains with zero area
// We use is_minimized to track this because zero size window usually occurs from minimizing
if (demo->width == 0 || demo->height == 0) {
demo->is_minimized = true;
return;
} else {
demo->is_minimized = false;
}
// In order to properly resize the window, we must re-create the
// swapchain
//
// First, destroy the old swapchain and its associated resources, setting swapchain_ready to false to prevent draw from running
if (demo->swapchain_ready) {
demo->swapchain_ready = false;
vkDeviceWaitIdle(demo->device);
vkDestroyImageView(demo->device, demo->depth.view, NULL);
vkDestroyImage(demo->device, demo->depth.image, NULL);
vkFreeMemory(demo->device, demo->depth.mem, NULL);
memset(&(demo->depth), 0, sizeof(demo->depth));
for (i = 0; i < demo->swapchainImageCount; i++) {
vkDestroyImageView(demo->device, demo->swapchain_resources[i].view, NULL);
vkDestroyFramebuffer(demo->device, demo->swapchain_resources[i].framebuffer, NULL);
vkDestroySemaphore(demo->device, demo->swapchain_resources[i].draw_complete_semaphore, NULL);
if (demo->separate_present_queue) {
vkDestroySemaphore(demo->device, demo->swapchain_resources[i].image_ownership_semaphore, NULL);
}
}
memset(&(demo->swapchain_resources), 0, sizeof(SwapchainImageResources) * MAX_SWAPCHAIN_IMAGE_COUNT);
}
// Second, recreate the swapchain, depth buffer, and framebuffers.
demo_prepare_swapchain(demo);
}
// On MS-Windows, make this a global, so it's available to WndProc()
struct demo demo;
#if defined(VK_USE_PLATFORM_WIN32_KHR)
static void demo_run(struct demo *demo) {
if (!demo->initialized || !demo->swapchain_ready) return;
demo_draw(demo);
if (!demo->is_minimized) {
demo->curFrame++;
}
if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) {
PostQuitMessage(validation_error);
}
}
// MS-Windows event handling function:
LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
switch (uMsg) {
case WM_CLOSE:
PostQuitMessage(validation_error);
break;
case WM_PAINT:
// The validation callback calls MessageBox which can generate paint
// events - don't make more Vulkan calls if we got here from the
// callback
if (!in_callback) {
demo_run(&demo);
}
break;
case WM_GETMINMAXINFO: // set window's minimum size
((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
return 0;
case WM_ERASEBKGND:
return 1;
case WM_SIZE:
// Resize the application to the new window size, except when
// it was minimized. Vulkan doesn't support images or swapchains
// with width=0 and height=0.
if (wParam != SIZE_MINIMIZED) {
demo.width = lParam & 0xffff;
demo.height = (lParam & 0xffff0000) >> 16;
demo_resize(&demo);
}
break;
case WM_KEYDOWN:
switch (wParam) {
case VK_ESCAPE:
PostQuitMessage(validation_error);
break;
case VK_LEFT:
demo.spin_angle -= demo.spin_increment;
break;
case VK_RIGHT:
demo.spin_angle += demo.spin_increment;
break;
case VK_SPACE:
demo.pause = !demo.pause;
break;
}
return 0;
default:
break;
}
return (DefWindowProc(hWnd, uMsg, wParam, lParam));
}
static void demo_create_window(struct demo *demo) {
WNDCLASSEX win_class;
// Initialize the window class structure:
win_class.cbSize = sizeof(WNDCLASSEX);
win_class.style = CS_HREDRAW | CS_VREDRAW;
win_class.lpfnWndProc = WndProc;
win_class.cbClsExtra = 0;
win_class.cbWndExtra = 0;
win_class.hInstance = demo->connection; // hInstance
win_class.hIcon = LoadIcon(NULL, IDI_APPLICATION);
win_class.hCursor = LoadCursor(NULL, IDC_ARROW);
win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
win_class.lpszMenuName = NULL;
win_class.lpszClassName = demo->name;
win_class.hIconSm = LoadIcon(NULL, IDI_WINLOGO);
// Register window class:
if (!RegisterClassEx(&win_class)) {
// It didn't work, so try to give a useful error:
printf("Unexpected error trying to start the application!\n");
fflush(stdout);
exit(1);
}
// Create window with the registered class:
RECT wr = {0, 0, demo->width, demo->height};
AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
demo->window = CreateWindowEx(0,
demo->name, // class name
demo->name, // app name
WS_OVERLAPPEDWINDOW | // window style
WS_VISIBLE | WS_SYSMENU,
100, 100, // x/y coords
wr.right - wr.left, // width
wr.bottom - wr.top, // height
NULL, // handle to parent
NULL, // handle to menu
demo->connection, // hInstance
NULL); // no extra parameters
if (!demo->window) {
// It didn't work, so try to give a useful error:
printf("Cannot create a window in which to draw!\n");
fflush(stdout);
exit(1);
}
// Window client area size must be at least 1 pixel high, to prevent crash.
demo->minsize.x = GetSystemMetrics(SM_CXMINTRACK);
demo->minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
}
#endif
#if defined(VK_USE_PLATFORM_XLIB_KHR)
static void demo_create_xlib_window(struct demo *demo) {
const char *display_envar = getenv("DISPLAY");
if (display_envar == NULL || display_envar[0] == '\0') {
printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
fflush(stdout);
exit(1);
}
XInitThreads();
demo->xlib_display = XOpenDisplay(NULL);
long visualMask = VisualScreenMask;
int numberOfVisuals;
XVisualInfo vInfoTemplate = {};
vInfoTemplate.screen = DefaultScreen(demo->xlib_display);
XVisualInfo *visualInfo = XGetVisualInfo(demo->xlib_display, visualMask, &vInfoTemplate, &numberOfVisuals);
Colormap colormap =
XCreateColormap(demo->xlib_display, RootWindow(demo->xlib_display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
XSetWindowAttributes windowAttributes = {};
windowAttributes.colormap = colormap;
windowAttributes.background_pixel = 0xFFFFFFFF;
windowAttributes.border_pixel = 0;
windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
demo->xlib_window = XCreateWindow(demo->xlib_display, RootWindow(demo->xlib_display, vInfoTemplate.screen), 0, 0, demo->width,
demo->height, 0, visualInfo->depth, InputOutput, visualInfo->visual,
CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
XSelectInput(demo->xlib_display, demo->xlib_window, ExposureMask | KeyPressMask);
XMapWindow(demo->xlib_display, demo->xlib_window);
XFlush(demo->xlib_display);
demo->xlib_wm_delete_window = XInternAtom(demo->xlib_display, "WM_DELETE_WINDOW", False);
XSetWMProtocols(demo->xlib_display, demo->xlib_window, &demo->xlib_wm_delete_window, 1);
}
static void demo_handle_xlib_event(struct demo *demo, const XEvent *event) {
switch (event->type) {
case ClientMessage:
if ((Atom)event->xclient.data.l[0] == demo->xlib_wm_delete_window) demo->quit = true;
break;
case KeyPress:
switch (event->xkey.keycode) {
case 0x9: // Escape
demo->quit = true;
break;
case 0x71: // left arrow key
demo->spin_angle -= demo->spin_increment;
break;
case 0x72: // right arrow key
demo->spin_angle += demo->spin_increment;
break;
case 0x41: // space bar
demo->pause = !demo->pause;
break;
}
break;
case ConfigureNotify:
if ((demo->width != event->xconfigure.width) || (demo->height != event->xconfigure.height)) {
demo->width = event->xconfigure.width;
demo->height = event->xconfigure.height;
demo_resize(demo);
}
break;
default:
break;
}
}
static void demo_run_xlib(struct demo *demo) {
while (!demo->quit) {
XEvent event;
if (demo->pause) {
XNextEvent(demo->xlib_display, &event);
demo_handle_xlib_event(demo, &event);
}
while (XPending(demo->xlib_display) > 0) {
XNextEvent(demo->xlib_display, &event);
demo_handle_xlib_event(demo, &event);
}
if (demo->initialized && demo->swapchain_ready) {
demo_draw(demo);
if (!demo->is_minimized) {
demo->curFrame++;
}
if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) demo->quit = true;
}
}
}
#endif
#if defined(VK_USE_PLATFORM_XCB_KHR)
static void demo_handle_xcb_event(struct demo *demo, const xcb_generic_event_t *event) {
uint8_t event_code = event->response_type & 0x7f;
switch (event_code) {
case XCB_EXPOSE:
// TODO: Resize window
break;
case XCB_CLIENT_MESSAGE:
if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*demo->atom_wm_delete_window).atom) {
demo->quit = true;
}
break;
case XCB_KEY_RELEASE: {
const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
switch (key->detail) {
case 0x9: // Escape
demo->quit = true;
break;
case 0x71: // left arrow key
demo->spin_angle -= demo->spin_increment;
break;
case 0x72: // right arrow key
demo->spin_angle += demo->spin_increment;
break;
case 0x41: // space bar
demo->pause = !demo->pause;
break;
}
} break;
case XCB_CONFIGURE_NOTIFY: {
const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
if ((demo->width != cfg->width) || (demo->height != cfg->height)) {
demo->width = cfg->width;
demo->height = cfg->height;
demo_resize(demo);
}
} break;
default:
break;
}
}
static void demo_run_xcb(struct demo *demo) {
xcb_flush(demo->connection);
while (!demo->quit) {
xcb_generic_event_t *event;
if (demo->pause) {
event = xcb_wait_for_event(demo->connection);
} else {
event = xcb_poll_for_event(demo->connection);
}
while (event) {
demo_handle_xcb_event(demo, event);
free(event);
event = xcb_poll_for_event(demo->connection);
}
if (demo->initialized && demo->swapchain_ready) {
demo_draw(demo);
if (!demo->is_minimized) {
demo->curFrame++;
}
if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) demo->quit = true;
}
}
}
static void demo_create_xcb_window(struct demo *demo) {
uint32_t value_mask, value_list[32];
demo->xcb_window = xcb_generate_id(demo->connection);
value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
value_list[0] = demo->screen->black_pixel;
value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
xcb_create_window(demo->connection, XCB_COPY_FROM_PARENT, demo->xcb_window, demo->screen->root, 0, 0, demo->width, demo->height,
0, XCB_WINDOW_CLASS_INPUT_OUTPUT, demo->screen->root_visual, value_mask, value_list);
char *name = "Vkcube X11";
xcb_intern_atom_cookie_t net_wm_name_cookie = xcb_intern_atom(demo->connection, 0, strlen("_NET_WM_NAME"), "_NET_WM_NAME");
xcb_intern_atom_cookie_t utf8_string_cookie = xcb_intern_atom(demo->connection, 0, strlen("UTF8_STRING"), "UTF8_STRING");
xcb_intern_atom_reply_t *net_wm_name_reply = xcb_intern_atom_reply(demo->connection, net_wm_name_cookie, NULL);
xcb_intern_atom_reply_t *utf8_string_reply = xcb_intern_atom_reply(demo->connection, utf8_string_cookie, NULL);
xcb_change_property(demo->connection, XCB_PROP_MODE_REPLACE,
demo->xcb_window, net_wm_name_reply->atom,
utf8_string_reply->atom, 8, strlen(name), name);
/* Magic code that will send notification when window is destroyed */
xcb_intern_atom_cookie_t cookie = xcb_intern_atom(demo->connection, 1, 12, "WM_PROTOCOLS");
xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(demo->connection, cookie, 0);
xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(demo->connection, 0, 16, "WM_DELETE_WINDOW");
demo->atom_wm_delete_window = xcb_intern_atom_reply(demo->connection, cookie2, 0);
xcb_change_property(demo->connection, XCB_PROP_MODE_REPLACE, demo->xcb_window, (*reply).atom, 4, 32, 1,
&(*demo->atom_wm_delete_window).atom);
free(reply);
xcb_map_window(demo->connection, demo->xcb_window);
// Force the x/y coordinates to 100,100 results are identical in consecutive
// runs
const uint32_t coords[] = {100, 100};
xcb_configure_window(demo->connection, demo->xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
}
// VK_USE_PLATFORM_XCB_KHR
#endif
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
static void demo_run(struct demo *demo) {
while (!demo->quit) {
// Flush any commands to the server
wl_display_flush(demo->wayland_display);
if (demo->pause) {
// block and wait for input
wl_display_dispatch(demo->wayland_display);
} else {
// Lock the display event queue in case the driver is doing something on another thread
// while we wait, keep pumping events
while (wl_display_prepare_read(demo->wayland_display) != 0) {
wl_display_dispatch_pending(demo->wayland_display);
}
// Actually do the read from the socket
wl_display_read_events(demo->wayland_display);
// Pump events
wl_display_dispatch_pending(demo->wayland_display);
if (demo->initialized && demo->swapchain_ready) {
demo_draw(demo);
if (!demo->is_minimized) {
demo->curFrame++;
}
if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) demo->quit = true;
}
}
}
}
static void handle_surface_configure(void *data, struct xdg_surface *xdg_surface, uint32_t serial) {
struct demo *demo = (struct demo *)data;
xdg_surface_ack_configure(xdg_surface, serial);
demo->xdg_surface_has_been_configured = 1;
if (demo->pending_width > 0) {
demo->width = demo->pending_width;
}
if (demo->pending_height > 0) {
demo->height = demo->pending_height;
}
demo_resize(demo);
}
static const struct xdg_surface_listener xdg_surface_listener = {handle_surface_configure};
static void handle_toplevel_configure(void *data, struct xdg_toplevel *xdg_toplevel UNUSED, int32_t width, int32_t height,
struct wl_array *states UNUSED) {
struct demo *demo = (struct demo *)data;
/* zero values imply the program may choose its own size, so in that case
* stay with the existing value (which on startup is the default) */
if (width > 0) {
demo->pending_width = width;
}
if (height > 0) {
demo->pending_height = height;
}
/* This should be followed by a surface configure */
}
static void handle_toplevel_close(void *data, struct xdg_toplevel *xdg_toplevel UNUSED) {
struct demo *demo = (struct demo *)data;
demo->quit = true;
}
static const struct xdg_toplevel_listener xdg_toplevel_listener = {handle_toplevel_configure, handle_toplevel_close};
static void demo_create_wayland_window(struct demo *demo) {
if (!demo->xdg_wm_base) {
printf("Compositor did not provide the standard protocol xdg-wm-base\n");
fflush(stdout);
exit(1);
}
demo->window = wl_compositor_create_surface(demo->compositor);
if (!demo->window) {
printf("Can not create wayland_surface from compositor!\n");
fflush(stdout);
exit(1);
}
demo->xdg_surface = xdg_wm_base_get_xdg_surface(demo->xdg_wm_base, demo->window);
if (!demo->xdg_surface) {
printf("Can not get xdg_surface from wayland_surface!\n");
fflush(stdout);
exit(1);
}
demo->xdg_toplevel = xdg_surface_get_toplevel(demo->xdg_surface);
if (!demo->xdg_toplevel) {
printf("Can not allocate xdg_toplevel for xdg_surface!\n");
fflush(stdout);
exit(1);
}
xdg_surface_add_listener(demo->xdg_surface, &xdg_surface_listener, demo);
xdg_toplevel_add_listener(demo->xdg_toplevel, &xdg_toplevel_listener, demo);
xdg_toplevel_set_title(demo->xdg_toplevel, APP_SHORT_NAME);
if (demo->xdg_decoration_mgr) {
// if supported, let the compositor render titlebars for us
demo->toplevel_decoration =
zxdg_decoration_manager_v1_get_toplevel_decoration(demo->xdg_decoration_mgr, demo->xdg_toplevel);
zxdg_toplevel_decoration_v1_set_mode(demo->toplevel_decoration, ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
}
wl_surface_commit(demo->window);
}
#endif
#if defined(VK_USE_PLATFORM_DIRECTFB_EXT)
static void demo_create_directfb_window(struct demo *demo) {
DFBResult ret;
ret = DirectFBInit(NULL, NULL);
if (ret) {
printf("DirectFBInit failed to initialize DirectFB!\n");
fflush(stdout);
exit(1);
}
ret = DirectFBCreate(&demo->dfb);
if (ret) {
printf("DirectFBCreate failed to create main interface of DirectFB!\n");
fflush(stdout);
exit(1);
}
DFBSurfaceDescription desc;
desc.flags = DSDESC_CAPS | DSDESC_WIDTH | DSDESC_HEIGHT;
desc.caps = DSCAPS_PRIMARY;
desc.width = demo->width;
desc.height = demo->height;
ret = demo->dfb->CreateSurface(demo->dfb, &desc, &demo->directfb_window);
if (ret) {
printf("CreateSurface failed to create DirectFB surface interface!\n");
fflush(stdout);
exit(1);
}
ret = demo->dfb->CreateInputEventBuffer(demo->dfb, DICAPS_KEYS, DFB_FALSE, &demo->event_buffer);
if (ret) {
printf("CreateInputEventBuffer failed to create DirectFB event buffer interface!\n");
fflush(stdout);
exit(1);
}
}
static void demo_handle_directfb_event(struct demo *demo, const DFBInputEvent *event) {
if (event->type != DIET_KEYPRESS) return;
switch (event->key_symbol) {
case DIKS_ESCAPE: // Escape
demo->quit = true;
break;
case DIKS_CURSOR_LEFT: // left arrow key
demo->spin_angle -= demo->spin_increment;
break;
case DIKS_CURSOR_RIGHT: // right arrow key
demo->spin_angle += demo->spin_increment;
break;
case DIKS_SPACE: // space bar
demo->pause = !demo->pause;
break;
default:
break;
}
}
static void demo_run_directfb(struct demo *demo) {
while (!demo->quit) {
DFBInputEvent event;
if (demo->pause) {
demo->event_buffer->WaitForEvent(demo->event_buffer);
if (!demo->event_buffer->GetEvent(demo->event_buffer, DFB_EVENT(&event))) demo_handle_directfb_event(demo, &event);
} else {
if (!demo->event_buffer->GetEvent(demo->event_buffer, DFB_EVENT(&event))) demo_handle_directfb_event(demo, &event);
if (demo->initialized && demo->swapchain_ready) {
demo_draw(demo);
if (!demo->is_minimized) {
demo->curFrame++;
}
if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) demo->quit = true;
}
}
}
}
#endif
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
static void demo_run(struct demo *demo) {
if (!demo->initialized || !demo->swapchain_ready) return;
demo_draw(demo);
if (!demo->is_minimized) {
demo->curFrame++;
}
}
#endif
#if defined(VK_USE_PLATFORM_METAL_EXT)
static void demo_run(struct demo *demo) {
if (!demo->initialized || !demo->swapchain_ready) return;
demo_draw(demo);
if (!demo->is_minimized) {
demo->curFrame++;
}
if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) {
demo->quit = TRUE;
}
}
#endif
#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
static VkResult demo_create_display_surface(struct demo *demo) {
VkResult U_ASSERT_ONLY err;
uint32_t display_count;
uint32_t mode_count;
uint32_t plane_count;
VkDisplayPropertiesKHR display_props;
VkDisplayKHR display;
VkDisplayModePropertiesKHR mode_props;
VkDisplayPlanePropertiesKHR *plane_props;
VkBool32 found_plane = VK_FALSE;
uint32_t plane_index;
VkExtent2D image_extent;
VkDisplaySurfaceCreateInfoKHR create_info;
// Get the first display
display_count = 1;
err = vkGetPhysicalDeviceDisplayPropertiesKHR(demo->gpu, &display_count, &display_props);
assert(!err || (err == VK_INCOMPLETE));
display = display_props.display;
// Get the first mode of the display
err = vkGetDisplayModePropertiesKHR(demo->gpu, display, &mode_count, NULL);
assert(!err);
if (mode_count == 0) {
printf("Cannot find any mode for the display!\n");
fflush(stdout);
exit(1);
}
mode_count = 1;
err = vkGetDisplayModePropertiesKHR(demo->gpu, display, &mode_count, &mode_props);
assert(!err || (err == VK_INCOMPLETE));
// Get the list of planes
err = vkGetPhysicalDeviceDisplayPlanePropertiesKHR(demo->gpu, &plane_count, NULL);
assert(!err);
if (plane_count == 0) {
printf("Cannot find any plane!\n");
fflush(stdout);
exit(1);
}
plane_props = malloc(sizeof(VkDisplayPlanePropertiesKHR) * plane_count);
assert(plane_props);
err = vkGetPhysicalDeviceDisplayPlanePropertiesKHR(demo->gpu, &plane_count, plane_props);
assert(!err);
// Find a plane compatible with the display
for (plane_index = 0; plane_index < plane_count; plane_index++) {
uint32_t supported_count;
VkDisplayKHR *supported_displays;
// Disqualify planes that are bound to a different display
if ((plane_props[plane_index].currentDisplay != VK_NULL_HANDLE) && (plane_props[plane_index].currentDisplay != display)) {
continue;
}
err = vkGetDisplayPlaneSupportedDisplaysKHR(demo->gpu, plane_index, &supported_count, NULL);
assert(!err);
if (supported_count == 0) {
continue;
}
supported_displays = malloc(sizeof(VkDisplayKHR) * supported_count);
assert(supported_displays);
err = vkGetDisplayPlaneSupportedDisplaysKHR(demo->gpu, plane_index, &supported_count, supported_displays);
assert(!err);
for (uint32_t i = 0; i < supported_count; i++) {
if (supported_displays[i] == display) {
found_plane = VK_TRUE;
break;
}
}
free(supported_displays);
if (found_plane) {
break;
}
}
if (!found_plane) {
printf("Cannot find a plane compatible with the display!\n");
fflush(stdout);
exit(1);
}
VkDisplayPlaneCapabilitiesKHR planeCaps;
vkGetDisplayPlaneCapabilitiesKHR(demo->gpu, mode_props.displayMode, plane_index, &planeCaps);
// Find a supported alpha mode
VkDisplayPlaneAlphaFlagBitsKHR alphaMode = VK_DISPLAY_PLANE_ALPHA_OPAQUE_BIT_KHR;
VkDisplayPlaneAlphaFlagBitsKHR alphaModes[4] = {
VK_DISPLAY_PLANE_ALPHA_OPAQUE_BIT_KHR,
VK_DISPLAY_PLANE_ALPHA_GLOBAL_BIT_KHR,
VK_DISPLAY_PLANE_ALPHA_PER_PIXEL_BIT_KHR,
VK_DISPLAY_PLANE_ALPHA_PER_PIXEL_PREMULTIPLIED_BIT_KHR,
};
for (uint32_t i = 0; i < sizeof(alphaModes); i++) {
if (planeCaps.supportedAlpha & alphaModes[i]) {
alphaMode = alphaModes[i];
break;
}
}
image_extent.width = mode_props.parameters.visibleRegion.width;
image_extent.height = mode_props.parameters.visibleRegion.height;
create_info.sType = VK_STRUCTURE_TYPE_DISPLAY_SURFACE_CREATE_INFO_KHR;
create_info.pNext = NULL;
create_info.flags = 0;
create_info.displayMode = mode_props.displayMode;
create_info.planeIndex = plane_index;
create_info.planeStackIndex = plane_props[plane_index].currentStackIndex;
create_info.transform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
create_info.alphaMode = alphaMode;
create_info.globalAlpha = 1.0f;
create_info.imageExtent = image_extent;
free(plane_props);
return vkCreateDisplayPlaneSurfaceKHR(demo->inst, &create_info, NULL, &demo->surface);
}
static void demo_run_display(struct demo *demo) {
while (!demo->quit) {
demo_draw(demo);
demo->curFrame++;
if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) {
demo->quit = true;
}
}
}
#endif
#if defined(VK_USE_PLATFORM_SCREEN_QNX)
#include <sys/keycodes.h>
static void demo_run(struct demo *demo) {
int size[2] = {0, 0};
screen_window_t win;
int val;
int rc;
while (!demo->quit) {
while (!screen_get_event(demo->screen_context, demo->screen_event, demo->pause ? ~0 : 0)) {
rc = screen_get_event_property_iv(demo->screen_event, SCREEN_PROPERTY_TYPE, &val);
if (rc) {
printf("Cannot get SCREEN_PROPERTY_TYPE of the event! (%s)\n", strerror(errno));
fflush(stdout);
demo->quit = true;
break;
}
if (val == SCREEN_EVENT_NONE) {
break;
}
switch (val) {
case SCREEN_EVENT_KEYBOARD:
rc = screen_get_event_property_iv(demo->screen_event, SCREEN_PROPERTY_FLAGS, &val);
if (rc) {
printf("Cannot get SCREEN_PROPERTY_FLAGS of the event! (%s)\n", strerror(errno));
fflush(stdout);
demo->quit = true;
break;
}
if (val & KEY_DOWN) {
rc = screen_get_event_property_iv(demo->screen_event, SCREEN_PROPERTY_SYM, &val);
if (rc) {
printf("Cannot get SCREEN_PROPERTY_SYM of the event! (%s)\n", strerror(errno));
fflush(stdout);
demo->quit = true;
break;
}
switch (val) {
case KEYCODE_ESCAPE:
demo->quit = true;
break;
case KEYCODE_SPACE:
demo->pause = !demo->pause;
break;
case KEYCODE_LEFT:
demo->spin_angle -= demo->spin_increment;
break;
case KEYCODE_RIGHT:
demo->spin_angle += demo->spin_increment;
break;
default:
break;
}
}
break;
case SCREEN_EVENT_PROPERTY:
rc = screen_get_event_property_pv(demo->screen_event, SCREEN_PROPERTY_WINDOW, (void **)&win);
if (rc) {
printf("Cannot get SCREEN_PROPERTY_WINDOW of the event! (%s)\n", strerror(errno));
fflush(stdout);
demo->quit = true;
break;
}
rc = screen_get_event_property_iv(demo->screen_event, SCREEN_PROPERTY_NAME, &val);
if (rc) {
printf("Cannot get SCREEN_PROPERTY_NAME of the event! (%s)\n", strerror(errno));
fflush(stdout);
demo->quit = true;
break;
}
if (win == demo->screen_window) {
switch (val) {
case SCREEN_PROPERTY_SIZE:
rc = screen_get_window_property_iv(win, SCREEN_PROPERTY_SIZE, size);
if (rc) {
printf("Cannot get SCREEN_PROPERTY_SIZE of the window in the event! (%s)\n", strerror(errno));
fflush(stdout);
demo->quit = true;
break;
}
demo->width = size[0];
demo->height = size[1];
demo_resize(demo);
break;
default:
/* We are not interested in any other events for now */
break;
}
}
break;
}
}
if (demo->pause || !demo->initialized || !demo->swapchain_ready) {
} else {
demo_draw(demo);
if (!demo->is_minimized) {
demo->curFrame++;
}
if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) {
demo->quit = true;
}
}
}
}
static void demo_create_screen_window(struct demo *demo) {
const char *idstr = APP_SHORT_NAME;
int size[2];
int usage = SCREEN_USAGE_VULKAN;
int rc;
rc = screen_create_context(&demo->screen_context, 0);
if (rc) {
printf("Cannot create QNX Screen context!\n");
fflush(stdout);
exit(EXIT_FAILURE);
}
rc = screen_create_window(&demo->screen_window, demo->screen_context);
if (rc) {
printf("Cannot create QNX Screen window!\n");
fflush(stdout);
exit(EXIT_FAILURE);
}
rc = screen_create_event(&demo->screen_event);
if (rc) {
printf("Cannot create QNX Screen event!\n");
fflush(stdout);
exit(EXIT_FAILURE);
}
/* Set window caption */
screen_set_window_property_cv(demo->screen_window, SCREEN_PROPERTY_ID_STRING, strlen(idstr), idstr);
/* Setup VULKAN usage flags */
rc = screen_set_window_property_iv(demo->screen_window, SCREEN_PROPERTY_USAGE, &usage);
if (rc) {
printf("Cannot set SCREEN_USAGE_VULKAN flag!\n");
fflush(stdout);
exit(EXIT_FAILURE);
}
/* Setup window size */
if ((demo->width == 0) || (demo->height == 0)) {
/* Obtain automatically set window size provided by WM */
rc = screen_get_window_property_iv(demo->screen_window, SCREEN_PROPERTY_SIZE, size);
if (rc) {
printf("Cannot obtain current window size!\n");
fflush(stdout);
exit(EXIT_FAILURE);
}
demo->width = size[0];
demo->height = size[1];
} else {
size[0] = demo->width;
size[1] = demo->height;
rc = screen_set_window_property_iv(demo->screen_window, SCREEN_PROPERTY_SIZE, size);
if (rc) {
printf("Cannot set window size!\n");
fflush(stdout);
exit(EXIT_FAILURE);
}
}
}
#endif
/*
* Return 1 (true) if all layer names specified in check_names
* can be found in given layer properties.
*/
static VkBool32 demo_check_layers(uint32_t check_count, char **check_names, uint32_t layer_count, VkLayerProperties *layers) {
for (uint32_t i = 0; i < check_count; i++) {
VkBool32 found = 0;
for (uint32_t j = 0; j < layer_count; j++) {
if (!strcmp(check_names[i], layers[j].layerName)) {
found = 1;
break;
}
}
if (!found) {
fprintf(stderr, "Cannot find layer: %s\n", check_names[i]);
return 0;
}
}
return 1;
}
#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
int find_display_gpu(int gpu_number, uint32_t gpu_count, VkPhysicalDevice *physical_devices) {
uint32_t display_count = 0;
VkResult U_ASSERT_ONLY result;
int gpu_return = gpu_number;
if (gpu_number >= 0) {
result = vkGetPhysicalDeviceDisplayPropertiesKHR(physical_devices[gpu_number], &display_count, NULL);
assert(!result);
} else {
for (uint32_t i = 0; i < gpu_count; i++) {
result = vkGetPhysicalDeviceDisplayPropertiesKHR(physical_devices[i], &display_count, NULL);
assert(!result);
if (display_count) {
gpu_return = i;
break;
}
}
}
if (display_count > 0)
return gpu_return;
else
return -1;
}
#endif
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
static void pointer_handle_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx,
wl_fixed_t sy) {}
static void pointer_handle_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) {}
static void pointer_handle_motion(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy) {}
static void pointer_handle_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button,
uint32_t state) {
struct demo *demo = data;
if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED) {
xdg_toplevel_move(demo->xdg_toplevel, demo->seat, serial);
}
}
static void pointer_handle_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {}
static const struct wl_pointer_listener pointer_listener = {
pointer_handle_enter, pointer_handle_leave, pointer_handle_motion, pointer_handle_button, pointer_handle_axis,
};
static void keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {}
static void keyboard_handle_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface,
struct wl_array *keys) {}
static void keyboard_handle_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) {}
static void keyboard_handle_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key,
uint32_t state) {
if (state != WL_KEYBOARD_KEY_STATE_RELEASED) return;
struct demo *demo = data;
switch (key) {
case KEY_ESC: // Escape
demo->quit = true;
break;
case KEY_LEFT: // left arrow key
demo->spin_angle -= demo->spin_increment;
break;
case KEY_RIGHT: // right arrow key
demo->spin_angle += demo->spin_increment;
break;
case KEY_SPACE: // space bar
demo->pause = !demo->pause;
break;
}
}
static void keyboard_handle_modifiers(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed,
uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {}
static const struct wl_keyboard_listener keyboard_listener = {
keyboard_handle_keymap, keyboard_handle_enter, keyboard_handle_leave, keyboard_handle_key, keyboard_handle_modifiers,
};
static void seat_handle_capabilities(void *data, struct wl_seat *seat, enum wl_seat_capability caps) {
// Subscribe to pointer events
struct demo *demo = data;
if ((caps & WL_SEAT_CAPABILITY_POINTER) && !demo->pointer) {
demo->pointer = wl_seat_get_pointer(seat);
wl_pointer_add_listener(demo->pointer, &pointer_listener, demo);
} else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && demo->pointer) {
wl_pointer_destroy(demo->pointer);
demo->pointer = NULL;
}
// Subscribe to keyboard events
if (caps & WL_SEAT_CAPABILITY_KEYBOARD) {
demo->keyboard = wl_seat_get_keyboard(seat);
wl_keyboard_add_listener(demo->keyboard, &keyboard_listener, demo);
} else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD) && demo->keyboard) {
wl_keyboard_destroy(demo->keyboard);
demo->keyboard = NULL;
}
}
static const struct wl_seat_listener seat_listener = {
seat_handle_capabilities,
};
static void wm_base_ping(void *data UNUSED, struct xdg_wm_base *xdg_wm_base, uint32_t serial) {
xdg_wm_base_pong(xdg_wm_base, serial);
}
static const struct xdg_wm_base_listener wm_base_listener = {wm_base_ping};
static void registry_handle_global(void *data, struct wl_registry *registry, uint32_t id, const char *interface,
uint32_t version UNUSED) {
struct demo *demo = data;
// pickup wayland objects when they appear
if (strcmp(interface, wl_compositor_interface.name) == 0) {
uint32_t minVersion = version < 4 ? version : 4;
demo->compositor = wl_registry_bind(registry, id, &wl_compositor_interface, minVersion);
if (demo->VK_KHR_incremental_present_enabled && minVersion < 4) {
fprintf(stderr, "Wayland compositor doesn't support VK_KHR_incremental_present, disabling.\n");
demo->VK_KHR_incremental_present_enabled = false;
}
} else if (strcmp(interface, xdg_wm_base_interface.name) == 0) {
demo->xdg_wm_base = wl_registry_bind(registry, id, &xdg_wm_base_interface, 1);
xdg_wm_base_add_listener(demo->xdg_wm_base, &wm_base_listener, NULL);
} else if (strcmp(interface, wl_seat_interface.name) == 0) {
demo->seat = wl_registry_bind(registry, id, &wl_seat_interface, 1);
wl_seat_add_listener(demo->seat, &seat_listener, demo);
} else if (strcmp(interface, zxdg_decoration_manager_v1_interface.name) == 0) {
demo->xdg_decoration_mgr = wl_registry_bind(registry, id, &zxdg_decoration_manager_v1_interface, 1);
}
}
static void registry_handle_global_remove(void *data UNUSED, struct wl_registry *registry UNUSED, uint32_t name UNUSED) {}
static const struct wl_registry_listener registry_listener = {registry_handle_global, registry_handle_global_remove};
#endif
#if defined(VK_USE_PLATFORM_XCB_KHR)
static const char *demo_init_xcb_connection(struct demo *demo) {
demo->xcb_library = initialize_xcb();
if (NULL == demo->xcb_library) {
return "Cannot load XCB dynamic library.";
}
const xcb_setup_t *setup;
xcb_screen_iterator_t iter;
int scr;
const char *display_envar = getenv("DISPLAY");
if (display_envar == NULL || display_envar[0] == '\0') {
return "Environment variable DISPLAY requires a valid value.n";
}
demo->connection = xcb_connect(NULL, &scr);
if (xcb_connection_has_error(demo->connection) > 0) {
return "Cannot connect to XCB.";
}
setup = xcb_get_setup(demo->connection);
iter = xcb_setup_roots_iterator(setup);
while (scr-- > 0) xcb_screen_next(&iter);
demo->screen = iter.data;
return NULL;
}
#endif
#if defined(VK_USE_PLATFORM_XLIB_KHR)
static const char *demo_init_xlib_connection(struct demo *demo) {
demo->xlib_library = initialize_xlib();
if (NULL == demo->xlib_library) {
return "Cannot load XLIB dynamic library.";
}
return NULL;
}
#endif
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
static const char *demo_init_wayland_connection(struct demo *demo) {
demo->wayland_library = initialize_wayland();
if (NULL == demo->wayland_library) {
return "Cannot load wayland dynamic library.";
}
demo->wayland_display = wl_display_connect(NULL);
if (demo->wayland_display == NULL) {
return "Cannot connect to wayland.";
}
demo->registry = wl_display_get_registry(demo->wayland_display);
wl_registry_add_listener(demo->registry, ®istry_listener, demo);
wl_display_roundtrip(demo->wayland_display);
return NULL;
}
#endif
// Check that WSI platforms are available - only necessary when multiple WSI platforms exist, like on linux
// If the wsi_platform is AUTO, this function also sets wsi_platform to the first available WSI platform
// Otherwise, it errors out if the specified wsi_platform isn't available
static void demo_check_and_set_wsi_platform(struct demo *demo) {
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
if (demo->wsi_platform == WSI_PLATFORM_WAYLAND || demo->wsi_platform == WSI_PLATFORM_AUTO) {
bool wayland_extension_available = false;
for (uint32_t i = 0; i < demo->enabled_extension_count; i++) {
if (strcmp(demo->extension_names[i], VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME) == 0) {
wayland_extension_available = true;
break;
}
}
if (wayland_extension_available) {
const char *error_msg = demo_init_wayland_connection(demo);
if (error_msg != NULL) {
if (demo->wsi_platform == WSI_PLATFORM_WAYLAND) {
fprintf(stderr, "%s\nExiting ...\n", error_msg);
fflush(stdout);
exit(1);
}
} else {
demo->wsi_platform = WSI_PLATFORM_WAYLAND;
return;
}
}
}
#endif
#if defined(VK_USE_PLATFORM_XCB_KHR)
if (demo->wsi_platform == WSI_PLATFORM_XCB || demo->wsi_platform == WSI_PLATFORM_AUTO) {
bool xcb_extension_available = false;
for (uint32_t i = 0; i < demo->enabled_extension_count; i++) {
if (strcmp(demo->extension_names[i], VK_KHR_XCB_SURFACE_EXTENSION_NAME) == 0) {
xcb_extension_available = true;
break;
}
}
if (xcb_extension_available) {
const char *error_msg = demo_init_xcb_connection(demo);
if (error_msg != NULL) {
if (demo->wsi_platform == WSI_PLATFORM_XCB) {
fprintf(stderr, "%s\nExiting ...\n", error_msg);
fflush(stdout);
exit(1);
}
} else {
demo->wsi_platform = WSI_PLATFORM_XCB;
return;
}
}
}
#endif
#if defined(VK_USE_PLATFORM_XLIB_KHR)
if (demo->wsi_platform == WSI_PLATFORM_XLIB || demo->wsi_platform == WSI_PLATFORM_AUTO) {
bool xlib_extension_available = false;
for (uint32_t i = 0; i < demo->enabled_extension_count; i++) {
if (strcmp(demo->extension_names[i], VK_KHR_XLIB_SURFACE_EXTENSION_NAME) == 0) {
xlib_extension_available = true;
break;
}
}
if (xlib_extension_available) {
const char *error_msg = demo_init_xlib_connection(demo);
if (error_msg != NULL) {
if (demo->wsi_platform == WSI_PLATFORM_XLIB) {
fprintf(stderr, "%s\nExiting ...\n", error_msg);
fflush(stdout);
exit(1);
}
} else {
demo->wsi_platform = WSI_PLATFORM_XLIB;
return;
}
}
}
#endif
#if defined(VK_USE_PLATFORM_DIRECTFB_EXT)
if (demo->wsi_platform == WSI_PLATFORM_DIRECTFB || demo->wsi_platform == WSI_PLATFORM_AUTO) {
bool direftfb_extension_available = false;
for (uint32_t i = 0; i < demo->enabled_extension_count; i++) {
if (strcmp(demo->extension_names[i], VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME) == 0) {
direftfb_extension_available = true;
break;
}
}
if (direftfb_extension_available) {
// Because DirectFB is still linked in, we can assume that it works if we got here
demo->wsi_platform = WSI_PLATFORM_DIRECTFB;
return;
}
}
#endif
#if defined(VK_USE_PLATFORM_WIN32_KHR)
if (demo->wsi_platform == WSI_PLATFORM_WIN32 || demo->wsi_platform == WSI_PLATFORM_AUTO) {
bool win32_extension_available = false;
for (uint32_t i = 0; i < demo->enabled_extension_count; i++) {
if (strcmp(demo->extension_names[i], VK_KHR_WIN32_SURFACE_EXTENSION_NAME) == 0) {
win32_extension_available = true;
break;
}
}
if (win32_extension_available) {
demo->wsi_platform = WSI_PLATFORM_WIN32;
return;
}
}
#endif
#if defined(VK_USE_PLATFORM_METAL_EXT)
if (demo->wsi_platform == WSI_PLATFORM_METAL || demo->wsi_platform == WSI_PLATFORM_AUTO) {
bool metal_extension_available = false;
for (uint32_t i = 0; i < demo->enabled_extension_count; i++) {
if (strcmp(demo->extension_names[i], VK_EXT_METAL_SURFACE_EXTENSION_NAME) == 0) {
metal_extension_available = true;
break;
}
}
if (metal_extension_available) {
demo->wsi_platform = WSI_PLATFORM_METAL;
return;
}
}
#endif
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
if (demo->wsi_platform == WSI_PLATFORM_ANDROID || demo->wsi_platform == WSI_PLATFORM_AUTO) {
bool android_extension_available = false;
for (uint32_t i = 0; i < demo->enabled_extension_count; i++) {
if (strcmp(demo->extension_names[i], VK_KHR_ANDROID_SURFACE_EXTENSION_NAME) == 0) {
android_extension_available = true;
break;
}
}
if (android_extension_available) {
demo->wsi_platform = WSI_PLATFORM_ANDROID;
return;
}
}
#endif
#if defined(VK_USE_PLATFORM_SCREEN_QNX)
if (demo->wsi_platform == WSI_PLATFORM_QNX || demo->wsi_platform == WSI_PLATFORM_AUTO) {
bool qnx_extension_available = false;
for (uint32_t i = 0; i < demo->enabled_extension_count; i++) {
if (strcmp(demo->extension_names[i], VK_QNX_SCREEN_SURFACE_EXTENSION_NAME) == 0) {
qnx_extension_available = true;
break;
}
}
if (qnx_extension_available) {
demo->wsi_platform = WSI_PLATFORM_QNX;
return;
}
}
#endif
#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
if (demo->wsi_platform == WSI_PLATFORM_DISPLAY || demo->wsi_platform == WSI_PLATFORM_AUTO) {
bool display_extension_available = false;
for (uint32_t i = 0; i < demo->enabled_extension_count; i++) {
if (strcmp(demo->extension_names[i], VK_KHR_DISPLAY_EXTENSION_NAME) == 0) {
display_extension_available = true;
break;
}
}
if (display_extension_available) {
// Because DISPLAY doesn't require additional libraries, we can assume that it works if we got here
demo->wsi_platform = WSI_PLATFORM_DISPLAY;
return;
}
}
#endif
}
static void demo_init_vk(struct demo *demo) {
VkResult err;
uint32_t instance_extension_count = 0;
uint32_t instance_layer_count = 0;
char *instance_validation_layers[] = {"VK_LAYER_KHRONOS_validation"};
demo->enabled_extension_count = 0;
demo->enabled_layer_count = 0;
demo->is_minimized = false;
demo->cmd_pool = VK_NULL_HANDLE;
err = load_vulkan_library();
if (err != VK_SUCCESS) {
ERR_EXIT(
"Unable to find the Vulkan runtime on the system.\n\n"
"This likely indicates that no Vulkan capable drivers are installed.",
"Installation Failure");
}
// Look for validation layers
VkBool32 validation_found = 0;
if (demo->validate) {
err = vkEnumerateInstanceLayerProperties(&instance_layer_count, NULL);
assert(!err);
if (instance_layer_count > 0) {
VkLayerProperties *instance_layers = malloc(sizeof(VkLayerProperties) * instance_layer_count);
err = vkEnumerateInstanceLayerProperties(&instance_layer_count, instance_layers);
assert(!err);
validation_found = demo_check_layers(ARRAY_SIZE(instance_validation_layers), instance_validation_layers,
instance_layer_count, instance_layers);
if (validation_found) {
demo->enabled_layer_count = ARRAY_SIZE(instance_validation_layers);
demo->enabled_layers[0] = "VK_LAYER_KHRONOS_validation";
}
free(instance_layers);
}
if (!validation_found) {
ERR_EXIT(
"vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
"Please look at the Getting Started guide for additional information.\n",
"vkCreateInstance Failure");
}
}
/* Look for instance extensions */
VkBool32 surfaceExtFound = false;
VkBool32 platformSurfaceExtFound = false;
bool portabilityEnumerationActive = false;
memset(demo->extension_names, 0, sizeof(demo->extension_names));
err = vkEnumerateInstanceExtensionProperties(NULL, &instance_extension_count, NULL);
assert(!err);
if (instance_extension_count > 0) {
VkExtensionProperties *instance_extensions = malloc(sizeof(VkExtensionProperties) * instance_extension_count);
err = vkEnumerateInstanceExtensionProperties(NULL, &instance_extension_count, instance_extensions);
assert(!err);
for (uint32_t i = 0; i < instance_extension_count; i++) {
if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
surfaceExtFound = true;
demo->extension_names[demo->enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
}
#if defined(VK_USE_PLATFORM_WIN32_KHR)
if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName) &&
(demo->wsi_platform == WSI_PLATFORM_AUTO || demo->wsi_platform == WSI_PLATFORM_WIN32)) {
platformSurfaceExtFound = true;
demo->extension_names[demo->enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
}
#endif
#if defined(VK_USE_PLATFORM_XLIB_KHR)
if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName) &&
(demo->wsi_platform == WSI_PLATFORM_AUTO || demo->wsi_platform == WSI_PLATFORM_XLIB)) {
platformSurfaceExtFound = true;
demo->extension_names[demo->enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
}
#endif
#if defined(VK_USE_PLATFORM_XCB_KHR)
if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName) &&
(demo->wsi_platform == WSI_PLATFORM_AUTO || demo->wsi_platform == WSI_PLATFORM_XCB)) {
platformSurfaceExtFound = true;
demo->extension_names[demo->enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME;
}
#endif
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName) &&
(demo->wsi_platform == WSI_PLATFORM_AUTO || demo->wsi_platform == WSI_PLATFORM_WAYLAND)) {
platformSurfaceExtFound = true;
demo->extension_names[demo->enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME;
}
#endif
#if defined(VK_USE_PLATFORM_DIRECTFB_EXT)
if (!strcmp(VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName) &&
(demo->wsi_platform == WSI_PLATFORM_AUTO || demo->wsi_platform == WSI_PLATFORM_DIRECTFB)) {
platformSurfaceExtFound = true;
demo->extension_names[demo->enabled_extension_count++] = VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME;
}
#endif
#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName) &&
(demo->wsi_platform == WSI_PLATFORM_AUTO || demo->wsi_platform == WSI_PLATFORM_DISPLAY)) {
platformSurfaceExtFound = true;
demo->extension_names[demo->enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME;
}
#endif
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
if (!strcmp(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName) &&
(demo->wsi_platform == WSI_PLATFORM_AUTO || demo->wsi_platform == WSI_PLATFORM_ANDROID)) {
platformSurfaceExtFound = true;
demo->extension_names[demo->enabled_extension_count++] = VK_KHR_ANDROID_SURFACE_EXTENSION_NAME;
}
#endif
#if defined(VK_USE_PLATFORM_METAL_EXT)
if (!strcmp(VK_EXT_METAL_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName) &&
(demo->wsi_platform == WSI_PLATFORM_AUTO || demo->wsi_platform == WSI_PLATFORM_METAL)) {
platformSurfaceExtFound = true;
demo->extension_names[demo->enabled_extension_count++] = VK_EXT_METAL_SURFACE_EXTENSION_NAME;
}
#endif
#if defined(VK_USE_PLATFORM_SCREEN_QNX)
if (!strcmp(VK_QNX_SCREEN_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName) &&
(demo->wsi_platform == WSI_PLATFORM_AUTO || demo->wsi_platform == WSI_PLATFORM_QNX)) {
platformSurfaceExtFound = true;
demo->extension_names[demo->enabled_extension_count++] = VK_QNX_SCREEN_SURFACE_EXTENSION_NAME;
}
#endif
if (!strcmp(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME, instance_extensions[i].extensionName)) {
demo->extension_names[demo->enabled_extension_count++] = VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME;
}
if (!strcmp(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, instance_extensions[i].extensionName)) {
if (demo->validate) {
demo->extension_names[demo->enabled_extension_count++] = VK_EXT_DEBUG_UTILS_EXTENSION_NAME;
}
}
// We want cube to be able to enumerate drivers that support the portability_subset extension, so we have to enable
// the portability enumeration extension.
if (!strcmp(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME, instance_extensions[i].extensionName)) {
portabilityEnumerationActive = true;
demo->extension_names[demo->enabled_extension_count++] = VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME;
}
assert(demo->enabled_extension_count < 64);
}
free(instance_extensions);
}
if (!surfaceExtFound) {
ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME
" instance extension.\n\n"
"This indicates that no compatible Vulkan installable client driver (ICD) is present or that the system is not "
"configured to present to the screen. \n",
"vkCreateInstance Failure");
}
if (!platformSurfaceExtFound) {
switch (demo->wsi_platform) {
#if defined(VK_USE_PLATFORM_WIN32_KHR)
case (WSI_PLATFORM_WIN32):
ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
" instance extension.\n\n"
"The selected WSI platform win32 is not available, please choose a different WSI platform\n",
"vkCreateInstance Failure");
break;
#endif
#if defined(VK_USE_PLATFORM_METAL_EXT)
case (WSI_PLATFORM_METAL):
ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_METAL_SURFACE_EXTENSION_NAME
" instance extension.\n\n"
"The selected WSI platform metal is not available, please choose a different WSI platform\n",
"vkCreateInstance Failure");
break;
#endif
#if defined(VK_USE_PLATFORM_XCB_KHR)
case (WSI_PLATFORM_XCB):
ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
" instance extension.\n\n"
"The selected WSI platform xcb is not available, please choose a different WSI platform\n",
"vkCreateInstance Failure");
break;
#endif
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
case (WSI_PLATFORM_WAYLAND):
ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
" instance extension.\n\n"
"The selected WSI platform wayland is not available, please choose a different WSI platform\n",
"vkCreateInstance Failure");
break;
#endif
#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
case (WSI_PLATFORM_DISPLAY):
ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME
" instance extension.\n\n"
"The selected WSI platform display is not available, please choose a different WSI platform\n",
"vkCreateInstance Failure");
break;
#endif
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
case (WSI_PLATFORM_ANDROID):
ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_ANDROID_SURFACE_EXTENSION_NAME
" instance extension.\n\n"
"The selected WSI platform android is not available, please choose a different WSI platform\n",
"vkCreateInstance Failure");
break;
#endif
#if defined(VK_USE_PLATFORM_XLIB_KHR)
case (WSI_PLATFORM_XLIB):
ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
" instance extension.\n\n"
"The selected WSI platform xlib is not available, please choose a different WSI platform\n",
"vkCreateInstance Failure");
break;
#endif
#if defined(VK_USE_PLATFORM_DIRECTFB_EXT)
case (WSI_PLATFORM_DIRECTFB):
ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME
" instance extension.\n\n"
"The selected WSI platform directfb is not available, please choose a different WSI platform\n",
"vkCreateInstance Failure");
break;
#endif
#if defined(VK_USE_PLATFORM_SCREEN_QNX)
case (WSI_PLATFORM_QNX):
ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_QNX_SCREEN_SURFACE_EXTENSION_NAME
" instance extension.\n\n"
"The selected WSI platform qnx is not available, please choose a different WSI platform\n",
"vkCreateInstance Failure");
break;
#endif
default:
case (WSI_PLATFORM_AUTO):
// Getting here indicates we are using the WSI extension that is default on this platform
ERR_EXIT(
"vkEnumerateInstanceExtensionProperties failed to find any supported WSI surface instance extensions.\n\n"
"This indicates that no compatible Vulkan installable client driver (ICD) is present or that the system is not "
"configured to present to the screen. \n",
"vkCreateInstance Failure");
break;
}
}
bool auto_wsi_platform = demo->wsi_platform == WSI_PLATFORM_AUTO;
demo_check_and_set_wsi_platform(demo);
// Print a message to indicate the automatically set WSI platform
if (auto_wsi_platform && demo->wsi_platform != WSI_PLATFORM_AUTO) {
fprintf(stderr, "Selected WSI platform: %s\n", wsi_to_string(demo->wsi_platform));
}
const VkApplicationInfo app = {
.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
.pNext = NULL,
.pApplicationName = APP_SHORT_NAME,
.applicationVersion = 0,
.pEngineName = APP_SHORT_NAME,
.engineVersion = 0,
.apiVersion = VK_API_VERSION_1_0,
};
VkInstanceCreateInfo inst_info = {
.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
.pNext = NULL,
.flags = (portabilityEnumerationActive ? VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR : 0),
.pApplicationInfo = &app,
.enabledLayerCount = demo->enabled_layer_count,
.ppEnabledLayerNames = (const char *const *)instance_validation_layers,
.enabledExtensionCount = demo->enabled_extension_count,
.ppEnabledExtensionNames = (const char *const *)demo->extension_names,
};
/*
* This is info for a temp callback to use during CreateInstance.
* After the instance is created, we use the instance-based
* function to register the final callback.
*/
VkDebugUtilsMessengerCreateInfoEXT dbg_messenger_create_info;
if (demo->validate) {
// VK_EXT_debug_utils style
dbg_messenger_create_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
dbg_messenger_create_info.pNext = NULL;
dbg_messenger_create_info.flags = 0;
dbg_messenger_create_info.messageSeverity =
VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
dbg_messenger_create_info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
dbg_messenger_create_info.pfnUserCallback = debug_messenger_callback;
dbg_messenger_create_info.pUserData = demo;
inst_info.pNext = &dbg_messenger_create_info;
}
err = vkCreateInstance(&inst_info, NULL, &demo->inst);
if (err == VK_ERROR_INCOMPATIBLE_DRIVER) {
ERR_EXIT(
"Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
"Please look at the Getting Started guide for additional information.\n",
"vkCreateInstance Failure");
} else if (err == VK_ERROR_EXTENSION_NOT_PRESENT) {
ERR_EXIT(
"Cannot find a specified extension library.\n"
"Make sure your layers path is set appropriately.\n",
"vkCreateInstance Failure");
} else if (err) {
ERR_EXIT(
"vkCreateInstance failed.\n\n"
"Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
"Please look at the Getting Started guide for additional information.\n",
"vkCreateInstance Failure");
}
load_vulkan_instance_functions(demo->inst);
}
static void demo_select_physical_device(struct demo *demo) {
VkResult err;
/* Make initial call to query gpu_count, then second call for gpu info */
uint32_t gpu_count = 0;
err = vkEnumeratePhysicalDevices(demo->inst, &gpu_count, NULL);
assert(!err);
if (gpu_count <= 0) {
ERR_EXIT(
"vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
"Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
"Please look at the Getting Started guide for additional information.\n",
"vkEnumeratePhysicalDevices Failure");
}
VkPhysicalDevice *physical_devices = malloc(sizeof(VkPhysicalDevice) * gpu_count);
err = vkEnumeratePhysicalDevices(demo->inst, &gpu_count, physical_devices);
assert(!err);
if (demo->invalid_gpu_selection || (demo->gpu_number >= 0 && !((uint32_t)demo->gpu_number < gpu_count))) {
fprintf(stderr, "GPU %d specified is not present, GPU count = %u\n", demo->gpu_number, gpu_count);
ERR_EXIT("Specified GPU number is not present", "User Error");
}
if (demo->wsi_platform == WSI_PLATFORM_DISPLAY) {
#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
demo->gpu_number = find_display_gpu(demo->gpu_number, gpu_count, physical_devices);
if (demo->gpu_number < 0) {
printf("Cannot find any display!\n");
fflush(stdout);
exit(1);
}
#else
printf("WSI selection was set to DISPLAY but vkcube was not compiled with support for the DISPLAY platform, exiting \n");
fflush(stdout);
exit(1);
#endif
} else {
/* Try to auto select most suitable device */
if (demo->gpu_number == -1) {
VkPhysicalDeviceProperties physicalDeviceProperties;
int prev_priority = 0;
for (uint32_t i = 0; i < gpu_count; i++) {
vkGetPhysicalDeviceProperties(physical_devices[i], &physicalDeviceProperties);
assert(physicalDeviceProperties.deviceType <= VK_PHYSICAL_DEVICE_TYPE_CPU);
// Continue next gpu if this gpu does not support the surface.
VkBool32 supported = VK_FALSE;
VkResult result = vkGetPhysicalDeviceSurfaceSupportKHR(physical_devices[i], 0, demo->surface, &supported);
if (result != VK_SUCCESS || !supported) continue;
int priority = 0;
switch (physicalDeviceProperties.deviceType) {
case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU:
priority = 5;
break;
case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU:
priority = 4;
break;
case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU:
priority = 3;
break;
case VK_PHYSICAL_DEVICE_TYPE_CPU:
priority = 2;
break;
case VK_PHYSICAL_DEVICE_TYPE_OTHER:
priority = 1;
break;
default:
priority = -1;
break;
}
if (priority > prev_priority) {
demo->gpu_number = i;
prev_priority = priority;
}
}
}
}
assert(demo->gpu_number >= 0);
demo->gpu = physical_devices[demo->gpu_number];
{
VkPhysicalDeviceProperties physicalDeviceProperties;
vkGetPhysicalDeviceProperties(demo->gpu, &physicalDeviceProperties);
fprintf(stderr, "Selected GPU %d: %s, type: %s\n", demo->gpu_number, physicalDeviceProperties.deviceName,
to_string(physicalDeviceProperties.deviceType));
}
free(physical_devices);
/* Look for device extensions */
uint32_t device_extension_count = 0;
VkBool32 swapchainExtFound = 0;
demo->enabled_extension_count = 0;
memset(demo->extension_names, 0, sizeof(demo->extension_names));
err = vkEnumerateDeviceExtensionProperties(demo->gpu, NULL, &device_extension_count, NULL);
assert(!err);
if (device_extension_count > 0) {
VkExtensionProperties *device_extensions = malloc(sizeof(VkExtensionProperties) * device_extension_count);
err = vkEnumerateDeviceExtensionProperties(demo->gpu, NULL, &device_extension_count, device_extensions);
assert(!err);
for (uint32_t i = 0; i < device_extension_count; i++) {
if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) {
swapchainExtFound = 1;
demo->extension_names[demo->enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
}
if (!strcmp("VK_KHR_portability_subset", device_extensions[i].extensionName)) {
demo->extension_names[demo->enabled_extension_count++] = "VK_KHR_portability_subset";
}
assert(demo->enabled_extension_count < 64);
}
if (demo->VK_KHR_incremental_present_enabled) {
// Even though the user "enabled" the extension via the command
// line, we must make sure that it's enumerated for use with the
// device. Therefore, disable it here, and re-enable it again if
// enumerated.
demo->VK_KHR_incremental_present_enabled = false;
for (uint32_t i = 0; i < device_extension_count; i++) {
if (!strcmp(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME, device_extensions[i].extensionName)) {
demo->extension_names[demo->enabled_extension_count++] = VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME;
demo->VK_KHR_incremental_present_enabled = true;
DbgMsg("VK_KHR_incremental_present extension enabled\n");
}
assert(demo->enabled_extension_count < 64);
}
if (!demo->VK_KHR_incremental_present_enabled) {
DbgMsg("VK_KHR_incremental_present extension NOT AVAILABLE\n");
}
}
if (demo->VK_GOOGLE_display_timing_enabled) {
// Even though the user "enabled" the extension via the command
// line, we must make sure that it's enumerated for use with the
// device. Therefore, disable it here, and re-enable it again if
// enumerated.
demo->VK_GOOGLE_display_timing_enabled = false;
for (uint32_t i = 0; i < device_extension_count; i++) {
if (!strcmp(VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME, device_extensions[i].extensionName)) {
demo->extension_names[demo->enabled_extension_count++] = VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME;
demo->VK_GOOGLE_display_timing_enabled = true;
DbgMsg("VK_GOOGLE_display_timing extension enabled\n");
}
assert(demo->enabled_extension_count < 64);
}
if (!demo->VK_GOOGLE_display_timing_enabled) {
DbgMsg("VK_GOOGLE_display_timing extension NOT AVAILABLE\n");
}
}
free(device_extensions);
}
if (!swapchainExtFound) {
ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
" extension.\n\nDo you have a compatible Vulkan installable client driver (ICD) installed?\n"
"Please look at the Getting Started guide for additional information.\n",
"vkCreateInstance Failure");
}
if (demo->validate) {
/*
* This is info for a temp callback to use during CreateInstance.
* After the instance is created, we use the instance-based
* function to register the final callback.
*/
VkDebugUtilsMessengerCreateInfoEXT dbg_messenger_create_info;
// VK_EXT_debug_utils style
dbg_messenger_create_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
dbg_messenger_create_info.pNext = NULL;
dbg_messenger_create_info.flags = 0;
dbg_messenger_create_info.messageSeverity =
VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
dbg_messenger_create_info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
dbg_messenger_create_info.pfnUserCallback = debug_messenger_callback;
dbg_messenger_create_info.pUserData = demo;
err = vkCreateDebugUtilsMessengerEXT(demo->inst, &dbg_messenger_create_info, NULL, &demo->dbg_messenger);
switch (err) {
case VK_SUCCESS:
break;
case VK_ERROR_OUT_OF_HOST_MEMORY:
ERR_EXIT("CreateDebugUtilsMessengerEXT: out of host memory\n", "CreateDebugUtilsMessengerEXT Failure");
break;
default:
ERR_EXIT("CreateDebugUtilsMessengerEXT: unknown failure\n", "CreateDebugUtilsMessengerEXT Failure");
break;
}
}
vkGetPhysicalDeviceProperties(demo->gpu, &demo->gpu_props);
/* Call with NULL data to get count */
vkGetPhysicalDeviceQueueFamilyProperties(demo->gpu, &demo->queue_family_count, NULL);
assert(demo->queue_family_count >= 1);
demo->queue_props = (VkQueueFamilyProperties *)malloc(demo->queue_family_count * sizeof(VkQueueFamilyProperties));
vkGetPhysicalDeviceQueueFamilyProperties(demo->gpu, &demo->queue_family_count, demo->queue_props);
// Query fine-grained feature support for this device.
// If app has specific feature requirements it should check supported
// features based on this query
VkPhysicalDeviceFeatures physDevFeatures;
vkGetPhysicalDeviceFeatures(demo->gpu, &physDevFeatures);
}
static void demo_create_device(struct demo *demo) {
VkResult U_ASSERT_ONLY err;
float queue_priorities[1] = {0.0};
VkDeviceQueueCreateInfo queues[2];
queues[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queues[0].pNext = NULL;
queues[0].queueFamilyIndex = demo->graphics_queue_family_index;
queues[0].queueCount = 1;
queues[0].pQueuePriorities = queue_priorities;
queues[0].flags = 0;
VkDeviceCreateInfo device = {
.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
.pNext = NULL,
.queueCreateInfoCount = 1,
.pQueueCreateInfos = queues,
.enabledLayerCount = 0,
.ppEnabledLayerNames = NULL,
.enabledExtensionCount = demo->enabled_extension_count,
.ppEnabledExtensionNames = (const char *const *)demo->extension_names,
.pEnabledFeatures = NULL, // If specific features are required, pass them in here
};
if (demo->separate_present_queue) {
queues[1].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queues[1].pNext = NULL;
queues[1].queueFamilyIndex = demo->present_queue_family_index;
queues[1].queueCount = 1;
queues[1].pQueuePriorities = queue_priorities;
queues[1].flags = 0;
device.queueCreateInfoCount = 2;
}
err = vkCreateDevice(demo->gpu, &device, NULL, &demo->device);
assert(!err);
load_vulkan_device_functions(demo->device);
}
static void demo_create_surface(struct demo *demo) {
VkResult U_ASSERT_ONLY err = VK_SUCCESS;
// Create a WSI surface for the window:
#if defined(VK_USE_PLATFORM_WIN32_KHR)
if (demo->wsi_platform == WSI_PLATFORM_WIN32) {
VkWin32SurfaceCreateInfoKHR win32_createInfo;
win32_createInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
win32_createInfo.pNext = NULL;
win32_createInfo.flags = 0;
win32_createInfo.hinstance = demo->connection;
win32_createInfo.hwnd = demo->window;
err = vkCreateWin32SurfaceKHR(demo->inst, &win32_createInfo, NULL, &demo->surface);
}
#endif
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
if (demo->wsi_platform == WSI_PLATFORM_WAYLAND) {
VkWaylandSurfaceCreateInfoKHR wayland_createInfo;
wayland_createInfo.sType = VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR;
wayland_createInfo.pNext = NULL;
wayland_createInfo.flags = 0;
wayland_createInfo.display = demo->wayland_display;
wayland_createInfo.surface = demo->window;
err = vkCreateWaylandSurfaceKHR(demo->inst, &wayland_createInfo, NULL, &demo->surface);
}
#endif
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
if (demo->wsi_platform == WSI_PLATFORM_ANDROID) {
VkAndroidSurfaceCreateInfoKHR android_createInfo;
android_createInfo.sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR;
android_createInfo.pNext = NULL;
android_createInfo.flags = 0;
android_createInfo.window = (struct ANativeWindow *)(demo->window);
err = vkCreateAndroidSurfaceKHR(demo->inst, &android_createInfo, NULL, &demo->surface);
}
#endif
#if defined(VK_USE_PLATFORM_XLIB_KHR)
if (demo->wsi_platform == WSI_PLATFORM_XLIB) {
VkXlibSurfaceCreateInfoKHR xlib_createInfo;
xlib_createInfo.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR;
xlib_createInfo.pNext = NULL;
xlib_createInfo.flags = 0;
xlib_createInfo.dpy = demo->xlib_display;
xlib_createInfo.window = demo->xlib_window;
err = vkCreateXlibSurfaceKHR(demo->inst, &xlib_createInfo, NULL, &demo->surface);
}
#endif
#if defined(VK_USE_PLATFORM_XCB_KHR)
if (demo->wsi_platform == WSI_PLATFORM_XCB) {
VkXcbSurfaceCreateInfoKHR xcb_createInfo;
xcb_createInfo.sType = VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR;
xcb_createInfo.pNext = NULL;
xcb_createInfo.flags = 0;
xcb_createInfo.connection = demo->connection;
xcb_createInfo.window = demo->xcb_window;
err = vkCreateXcbSurfaceKHR(demo->inst, &xcb_createInfo, NULL, &demo->surface);
}
#endif
#if defined(VK_USE_PLATFORM_DIRECTFB_EXT)
if (demo->wsi_platform == WSI_PLATFORM_DIRECTFB) {
VkDirectFBSurfaceCreateInfoEXT directfb_createInfo;
directfb_createInfo.sType = VK_STRUCTURE_TYPE_DIRECTFB_SURFACE_CREATE_INFO_EXT;
directfb_createInfo.pNext = NULL;
directfb_createInfo.flags = 0;
directfb_createInfo.dfb = demo->dfb;
directfb_createInfo.surface = demo->directfb_window;
err = vkCreateDirectFBSurfaceEXT(demo->inst, &directfb_createInfo, NULL, &demo->surface);
}
#endif
#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
if (demo->wsi_platform == WSI_PLATFORM_DISPLAY) {
err = demo_create_display_surface(demo);
}
#endif
#if defined(VK_USE_PLATFORM_METAL_EXT)
if (demo->wsi_platform == WSI_PLATFORM_METAL) {
VkMetalSurfaceCreateInfoEXT metal_createInfo;
metal_createInfo.sType = VK_STRUCTURE_TYPE_METAL_SURFACE_CREATE_INFO_EXT;
metal_createInfo.pNext = NULL;
metal_createInfo.flags = 0;
metal_createInfo.pLayer = demo->caMetalLayer;
err = vkCreateMetalSurfaceEXT(demo->inst, &metal_createInfo, NULL, &demo->surface);
}
#endif
#if defined(VK_USE_PLATFORM_SCREEN_QNX)
if (demo->wsi_platform == WSI_PLATFORM_QNX) {
VkScreenSurfaceCreateInfoQNX qnx_createInfo;
qnx_createInfo.sType = VK_STRUCTURE_TYPE_SCREEN_SURFACE_CREATE_INFO_QNX;
qnx_createInfo.pNext = NULL;
qnx_createInfo.flags = 0;
qnx_createInfo.context = demo->screen_context;
qnx_createInfo.window = demo->screen_window;
err = vkCreateScreenSurfaceQNX(demo->inst, &qnx_createInfo, NULL, &demo->surface);
}
#endif
assert(!err);
}
static VkSurfaceFormatKHR pick_surface_format(const VkSurfaceFormatKHR *surfaceFormats, uint32_t count) {
// Prefer non-SRGB formats...
for (uint32_t i = 0; i < count; i++) {
const VkFormat format = surfaceFormats[i].format;
if (format == VK_FORMAT_R8G8B8A8_UNORM || format == VK_FORMAT_B8G8R8A8_UNORM ||
format == VK_FORMAT_A2B10G10R10_UNORM_PACK32 || format == VK_FORMAT_A2R10G10B10_UNORM_PACK32 ||
format == VK_FORMAT_A1R5G5B5_UNORM_PACK16 || format == VK_FORMAT_R5G6B5_UNORM_PACK16 ||
format == VK_FORMAT_R16G16B16A16_SFLOAT) {
return surfaceFormats[i];
}
}
printf("Can't find our preferred formats... Falling back to first exposed format. Rendering may be incorrect.\n");
assert(count >= 1);
return surfaceFormats[0];
}
static void demo_init_vk_swapchain(struct demo *demo) {
VkResult U_ASSERT_ONLY err;
// Iterate over each queue to learn whether it supports presenting:
VkBool32 *supportsPresent = (VkBool32 *)malloc(demo->queue_family_count * sizeof(VkBool32));
for (uint32_t i = 0; i < demo->queue_family_count; i++) {
vkGetPhysicalDeviceSurfaceSupportKHR(demo->gpu, i, demo->surface, &supportsPresent[i]);
}
// Search for a graphics and a present queue in the array of queue
// families, try to find one that supports both
uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
uint32_t presentQueueFamilyIndex = UINT32_MAX;
for (uint32_t i = 0; i < demo->queue_family_count; i++) {
if ((demo->queue_props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0) {
if (graphicsQueueFamilyIndex == UINT32_MAX) {
graphicsQueueFamilyIndex = i;
}
if (supportsPresent[i] == VK_TRUE) {
graphicsQueueFamilyIndex = i;
presentQueueFamilyIndex = i;
break;
}
}
}
if (presentQueueFamilyIndex == UINT32_MAX) {
// If didn't find a queue that supports both graphics and present, then
// find a separate present queue.
for (uint32_t i = 0; i < demo->queue_family_count; ++i) {
if (supportsPresent[i] == VK_TRUE) {
presentQueueFamilyIndex = i;
break;
}
}
}
// Generate error if could not find both a graphics and a present queue
if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
}
demo->graphics_queue_family_index = graphicsQueueFamilyIndex;
demo->present_queue_family_index = presentQueueFamilyIndex;
demo->separate_present_queue = (demo->graphics_queue_family_index != demo->present_queue_family_index);
free(supportsPresent);
demo_create_device(demo);
vkGetDeviceQueue(demo->device, demo->graphics_queue_family_index, 0, &demo->graphics_queue);
if (!demo->separate_present_queue) {
demo->present_queue = demo->graphics_queue;
} else {
vkGetDeviceQueue(demo->device, demo->present_queue_family_index, 0, &demo->present_queue);
}
// Get the list of VkFormat's that are supported:
uint32_t formatCount;
err = vkGetPhysicalDeviceSurfaceFormatsKHR(demo->gpu, demo->surface, &formatCount, NULL);
assert(!err);
VkSurfaceFormatKHR *surfFormats = (VkSurfaceFormatKHR *)malloc(formatCount * sizeof(VkSurfaceFormatKHR));
err = vkGetPhysicalDeviceSurfaceFormatsKHR(demo->gpu, demo->surface, &formatCount, surfFormats);
assert(!err);
VkSurfaceFormatKHR surfaceFormat = pick_surface_format(surfFormats, formatCount);
demo->format = surfaceFormat.format;
demo->color_space = surfaceFormat.colorSpace;
free(surfFormats);
demo->quit = false;
demo->curFrame = 0;
demo->first_swapchain_frame = true;
// Get Memory information and properties
vkGetPhysicalDeviceMemoryProperties(demo->gpu, &demo->memory_properties);
}
static void demo_init(struct demo *demo, int argc, char **argv) {
vec3 eye = {0.0f, 3.0f, 5.0f};
vec3 origin = {0, 0, 0};
vec3 up = {0.0f, 1.0f, 0.0};
memset(demo, 0, sizeof(*demo));
demo->presentMode = VK_PRESENT_MODE_FIFO_KHR;
demo->frameCount = INT32_MAX;
/* Autodetect suitable / best GPU by default */
demo->gpu_number = -1;
demo->width = 500;
demo->height = 500;
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "--use_staging") == 0) {
demo->use_staging_buffer = true;
continue;
}
if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {
demo->presentMode = atoi(argv[i + 1]);
i++;
continue;
}
if (strcmp(argv[i], "--break") == 0) {
demo->use_break = true;
continue;
}
if (strcmp(argv[i], "--validate") == 0) {
demo->validate = true;
continue;
}
if (strcmp(argv[i], "--xlib") == 0) {
fprintf(stderr, "--xlib is deprecated and no longer does anything\n");
continue;
}
if (strcmp(argv[i], "--c") == 0 && demo->frameCount == INT32_MAX && i < argc - 1 &&
sscanf(argv[i + 1], "%d", &demo->frameCount) == 1 && demo->frameCount >= 0) {
i++;
continue;
}
if (strcmp(argv[i], "--width") == 0) {
if (i < argc - 1 && sscanf(argv[i + 1], "%d", &demo->width) == 1) {
if (demo->width > 0) {
i++;
continue;
} else {
ERR_EXIT("The --width parameter must be greater than 0", "User Error");
}
}
ERR_EXIT("The --width parameter must be followed by a number", "User Error");
}
if (strcmp(argv[i], "--height") == 0) {
if (i < argc - 1 && sscanf(argv[i + 1], "%d", &demo->height) == 1) {
if (demo->height > 0) {
i++;
continue;
} else {
ERR_EXIT("The --height parameter must be greater than 0", "User Error");
}
}
ERR_EXIT("The --height parameter must be followed by a number", "User Error");
}
if (strcmp(argv[i], "--suppress_popups") == 0) {
demo->suppress_popups = true;
continue;
}
if (strcmp(argv[i], "--display_timing") == 0) {
demo->VK_GOOGLE_display_timing_enabled = true;
continue;
}
if (strcmp(argv[i], "--incremental_present") == 0) {
demo->VK_KHR_incremental_present_enabled = true;
continue;
}
if ((strcmp(argv[i], "--gpu_number") == 0) && (i < argc - 1)) {
demo->gpu_number = atoi(argv[i + 1]);
if (demo->gpu_number < 0) demo->invalid_gpu_selection = true;
i++;
continue;
}
if (strcmp(argv[i], "--force_errors") == 0) {
demo->force_errors = true;
continue;
}
if ((strcmp(argv[i], "--wsi") == 0) && (i < argc - 1)) {
size_t argc_len = strlen(argv[i + 1]);
for (size_t argc_i = 0; argc_i < argc_len; argc_i++) {
argv[i + 1][argc_i] = tolower(argv[i + 1][argc_i]);
}
WSI_PLATFORM selection = wsi_from_string(argv[i + 1]);
if (selection == WSI_PLATFORM_INVALID) {
printf(
"The --wsi parameter %s is not a supported WSI platform. The list of available platforms is available from "
"--help\n",
(const char *)&(argv[i + 1][0]));
fflush(stdout);
exit(1);
}
demo->wsi_platform = selection;
i++;
continue;
}
#if defined(ANDROID)
ERR_EXIT("Usage: vkcube [--validate]\n", "Usage");
#else
// Making the help for --wsi nice requires a little extra work since the list depends on what is available at
// compile time
size_t max_str_len = 100;
char *available_wsi_platforms = (char *)malloc(max_str_len);
memset(available_wsi_platforms, 0, max_str_len);
#if defined(VK_USE_PLATFORM_XCB_KHR)
strncat(available_wsi_platforms, "xcb", max_str_len);
#endif
#if defined(VK_USE_PLATFORM_XLIB_KHR)
if (strlen(available_wsi_platforms) > 0) {
strncat(available_wsi_platforms, "|", max_str_len);
}
strncat(available_wsi_platforms, "xlib", max_str_len);
#endif
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
if (strlen(available_wsi_platforms) > 0) {
strncat(available_wsi_platforms, "|", max_str_len);
}
strncat(available_wsi_platforms, "wayland", max_str_len);
#endif
#if defined(VK_USE_PLATFORM_DIRECTFB_EXT)
if (strlen(available_wsi_platforms) > 0) {
strncat(available_wsi_platforms, "|", max_str_len);
}
strncat(available_wsi_platforms, "directfb", max_str_len);
#endif
#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
if (strlen(available_wsi_platforms) > 0) {
strncat(available_wsi_platforms, "|", max_str_len);
}
strncat(available_wsi_platforms, "display", max_str_len);
#endif
#if defined(VK_USE_PLATFORM_WIN32_KHR)
if (strlen(available_wsi_platforms) > 0) {
strncat(available_wsi_platforms, "|", max_str_len);
}
strncat(available_wsi_platforms, "win32", max_str_len);
#endif
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
if (strlen(available_wsi_platforms) > 0) {
strncat(available_wsi_platforms, "|", max_str_len);
}
strncat(available_wsi_platforms, "android", max_str_len);
#endif
#if defined(VK_USE_PLATFORM_METAL_EXT)
if (strlen(available_wsi_platforms) > 0) {
strncat(available_wsi_platforms, "|", max_str_len);
}
strncat(available_wsi_platforms, "metal", max_str_len);
#endif
#if defined(VK_USE_PLATFORM_SCREEN_QNX)
if (strlen(available_wsi_platforms) > 0) {
strncat(available_wsi_platforms, "|", max_str_len);
}
strncat(available_wsi_platforms, "qnx", max_str_len);
#endif
char *message =
"Usage:\n %s\t[--use_staging] [--validate]\n"
"\t[--break] [--c <framecount>] [--suppress_popups]\n"
"\t[--incremental_present] [--display_timing]\n"
"\t[--gpu_number <index of physical device>]\n"
"\t[--present_mode <present mode enum>]\n"
"\t[--width <width>] [--height <height>]\n"
"\t[--force_errors]\n"
"\t[--wsi <%s>]\n"
"\t<present_mode_enum>\n"
"\t\tVK_PRESENT_MODE_IMMEDIATE_KHR = %d\n"
"\t\tVK_PRESENT_MODE_MAILBOX_KHR = %d\n"
"\t\tVK_PRESENT_MODE_FIFO_KHR = %d\n"
"\t\tVK_PRESENT_MODE_FIFO_RELAXED_KHR = %d\n";
int length = snprintf(NULL, 0, message, APP_SHORT_NAME, available_wsi_platforms, VK_PRESENT_MODE_IMMEDIATE_KHR,
VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR, VK_PRESENT_MODE_FIFO_RELAXED_KHR);
char *usage = (char *)malloc(length + 1);
if (!usage) {
exit(1);
}
snprintf(usage, length + 1, message, APP_SHORT_NAME, available_wsi_platforms, VK_PRESENT_MODE_IMMEDIATE_KHR,
VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR, VK_PRESENT_MODE_FIFO_RELAXED_KHR);
#if defined(_WIN32)
if (!demo->suppress_popups) MessageBox(NULL, usage, "Usage Error", MB_OK);
#else
fprintf(stderr, "%s", usage);
fflush(stderr);
#endif
free(usage);
exit(1);
#endif
}
demo->initialized = false;
demo_init_vk(demo);
demo->spin_angle = 4.0f;
demo->spin_increment = 0.2f;
demo->pause = false;
mat4x4_perspective(demo->projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f);
mat4x4_look_at(demo->view_matrix, eye, origin, up);
mat4x4_identity(demo->model_matrix);
demo->projection_matrix[1][1] *= -1; // Flip projection matrix from GL to Vulkan orientation.
}
#if defined(VK_USE_PLATFORM_WIN32_KHR)
// Include header required for parsing the command line options.
#include <shellapi.h>
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
MSG msg; // message
bool done; // flag saying when app is complete
int argc;
char **argv;
// Ensure wParam is initialized.
msg.wParam = 0;
// Use the CommandLine functions to get the command line arguments.
// Unfortunately, Microsoft outputs
// this information as wide characters for Unicode, and we simply want the
// Ascii version to be compatible
// with the non-Windows side. So, we have to convert the information to
// Ascii character strings.
LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
if (NULL == commandLineArgs) {
argc = 0;
}
if (argc > 0) {
argv = (char **)malloc(sizeof(char *) * argc);
if (argv == NULL) {
argc = 0;
} else {
for (int iii = 0; iii < argc; iii++) {
size_t wideCharLen = wcslen(commandLineArgs[iii]);
size_t numConverted = 0;
argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
if (argv[iii] != NULL) {
wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
}
}
}
} else {
argv = NULL;
}
demo_init(&demo, argc, argv);
// Free up the items we had to allocate for the command line arguments.
if (argc > 0 && argv != NULL) {
for (int iii = 0; iii < argc; iii++) {
if (argv[iii] != NULL) {
free(argv[iii]);
}
}
free(argv);
}
demo.connection = hInstance;
strncpy(demo.name, "Vulkan Cube", APP_NAME_STR_LEN);
demo_create_window(&demo);
demo_create_surface(&demo);
demo_select_physical_device(&demo);
demo_init_vk_swapchain(&demo);
demo_prepare(&demo);
done = false; // initialize loop condition variable
// main message loop
while (!done) {
if (demo.pause) {
const BOOL succ = WaitMessage();
if (!succ) {
struct demo *tmp = &demo;
struct demo *demo = tmp;
ERR_EXIT("WaitMessage() failed on paused demo", "event loop error");
}
}
PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
if (msg.message == WM_QUIT) // check for a quit message
{
done = true; // if found, quit app
} else {
/* Translate and dispatch to event queue*/
TranslateMessage(&msg);
DispatchMessage(&msg);
}
RedrawWindow(demo.window, NULL, NULL, RDW_INTERNALPAINT);
}
demo_cleanup(&demo);
return (int)msg.wParam;
}
#endif
#if defined(VK_USE_PLATFORM_METAL_EXT)
static void demo_main(struct demo *demo, void *caMetalLayer, int argc, const char *argv[]) {
demo_init(demo, argc, (char **)argv);
demo->caMetalLayer = caMetalLayer;
demo_create_surface(demo);
demo_select_physical_device(demo);
demo_init_vk_swapchain(demo);
demo_prepare(demo);
demo->spin_angle = 0.4f;
}
#endif
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
#include <android/log.h>
#include <android_native_app_glue.h>
#include "android_util.h"
static bool active = false;
struct demo demo;
static int32_t processInput(struct android_app *app, AInputEvent *event) { return 0; }
static void processCommand(struct android_app *app, int32_t cmd) {
switch (cmd) {
case APP_CMD_INIT_WINDOW: {
if (app->window) {
// We're getting a new window. If the app is starting up, we
// need to initialize. If the app has already been
// initialized, that means that we lost our previous window,
// which means that we have a lot of work to do. At a minimum,
// we need to destroy the swapchain and surface associated with
// the old window, and create a new surface and swapchain.
// However, since there are a lot of other objects/state that
// is tied to the swapchain, it's easiest to simply cleanup and
// start over (i.e. use a brute-force approach of re-starting
// the app)
if (demo.initialized) {
demo_cleanup(&demo);
}
// Parse Intents into argc, argv
// Use the following key to send arguments, i.e.
// --es args "--validate"
const char key[] = "args";
char *appTag = (char *)APP_SHORT_NAME;
int argc = 0;
char **argv = get_args(app, key, appTag, &argc);
__android_log_print(ANDROID_LOG_INFO, appTag, "argc = %i", argc);
for (int i = 0; i < argc; i++) __android_log_print(ANDROID_LOG_INFO, appTag, "argv[%i] = %s", i, argv[i]);
demo_init(&demo, argc, argv);
// Free the argv malloc'd by get_args
for (int i = 0; i < argc; i++) free(argv[i]);
demo.window = (void *)app->window;
demo_create_surface(&demo);
demo_select_physical_device(&demo);
demo_init_vk_swapchain(&demo);
demo_prepare(&demo);
}
break;
}
case APP_CMD_GAINED_FOCUS: {
active = true;
break;
}
case APP_CMD_LOST_FOCUS: {
active = false;
break;
}
}
}
void android_main(struct android_app *app) {
demo.initialized = false;
app->onAppCmd = processCommand;
app->onInputEvent = processInput;
while (1) {
int events;
struct android_poll_source *source;
while (ALooper_pollOnce(active ? 0 : -1, NULL, &events, (void **)&source) >= 0) {
if (source) {
source->process(app, source);
}
if (app->destroyRequested != 0) {
demo_cleanup(&demo);
return;
}
}
if (demo.initialized && demo.swapchain_ready && active) {
demo_run(&demo);
}
}
}
#elif defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__QNX__) || defined(__GNU__)
int main(int argc, char **argv) {
struct demo demo;
demo_init(&demo, argc, argv);
switch (demo.wsi_platform) {
default:
case (WSI_PLATFORM_AUTO):
fprintf(stderr,
"WSI platform should have already been set, indicating a bug. Please set a WSI platform manually with "
"--wsi\n");
exit(1);
break;
#if defined(VK_USE_PLATFORM_XCB_KHR)
case (WSI_PLATFORM_XCB):
demo_create_xcb_window(&demo);
break;
#endif
#if defined(VK_USE_PLATFORM_XLIB_KHR)
case (WSI_PLATFORM_XLIB):
demo_create_xlib_window(&demo);
break;
#endif
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
case (WSI_PLATFORM_WAYLAND):
demo_create_wayland_window(&demo);
break;
#endif
#if defined(VK_USE_PLATFORM_DIRECTFB_EXT)
case (WSI_PLATFORM_DIRECTFB):
demo_create_directfb_window(&demo);
break;
#endif
#if defined(VK_USE_PLATFORM_SCREEN_QNX)
case (WSI_PLATFORM_QNX):
demo_create_screen_window(&demo);
break;
#endif
#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
case (WSI_PLATFORM_DISPLAY):
// select physical device because display surface creation needs a gpu to be selected.
demo_select_physical_device(&demo);
break;
#endif
}
demo_create_surface(&demo);
if (demo.wsi_platform != WSI_PLATFORM_DISPLAY) {
demo_select_physical_device(&demo);
}
demo_init_vk_swapchain(&demo);
demo_prepare(&demo);
switch (demo.wsi_platform) {
default:
case (WSI_PLATFORM_AUTO):
fprintf(stderr,
"WSI platform should have already been set, indicating a bug. Please set a WSI platform manually with "
"--wsi\n");
exit(1);
break;
#if defined(VK_USE_PLATFORM_XCB_KHR)
case (WSI_PLATFORM_XCB):
demo_run_xcb(&demo);
break;
#endif
#if defined(VK_USE_PLATFORM_XLIB_KHR)
case (WSI_PLATFORM_XLIB):
demo_run_xlib(&demo);
break;
#endif
#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
case (WSI_PLATFORM_WAYLAND):
demo_run(&demo);
break;
#endif
#if defined(VK_USE_PLATFORM_DIRECTFB_EXT)
case (WSI_PLATFORM_DIRECTFB):
demo_run_directfb(&demo);
break;
#endif
#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
case (WSI_PLATFORM_DISPLAY):
demo_run_display(&demo);
break;
#endif
#if defined(VK_USE_PLATFORM_SCREEN_QNX)
case (WSI_PLATFORM_QNX):
demo_run(&demo);
break;
#endif
}
demo_cleanup(&demo);
return validation_error;
}
#endif
|