1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548
|
/*
PsychToolbox3/Source/Common/Screen/PsychImagingPipelineSupport.c
PLATFORMS:
All. Well, all with sufficiently advanced graphics hardware...
AUTHORS:
Mario Kleiner mk mario.kleiner.de@gmail.com
HISTORY:
12/05/06 mk Wrote it.
DESCRIPTION:
Infrastructure for all Screen imaging pipeline functions, i.e., hook callback functions and chains
and GLSL based internal image processing pipeline.
The level of support for PTB's imaging pipe strongly depends on the capabilities of the gfx-hardware,
especially GLSL support, shader support and Framebuffer object support.
NOTES:
TO DO:
*/
#include "Screen.h"
static char texturePlanar1FragmentShaderSrc[] =
"\n"
"\n"
"#extension GL_ARB_texture_rectangle : enable \n"
"\n"
"uniform sampler2DRect Image; \n"
"varying vec4 unclampedFragColor; \n"
"varying vec2 texNominalSize; \n"
"\n"
"void main() \n"
"{ \n"
" vec4 texcolor; \n"
" texcolor.rgb = vec3(texture2DRect(Image, gl_TexCoord[0].st).r); \n"
" texcolor.a = 1.0; \n"
"\n"
" /* Multiply texcolor with incoming fragment color (GL_MODULATE emulation): */ \n"
" /* Assign result as output fragment color: */ \n"
" gl_FragColor = texcolor * unclampedFragColor; \n"
"} \n";
static char texturePlanar2FragmentShaderSrc[] =
"\n"
" \n"
"#extension GL_ARB_texture_rectangle : enable \n"
" \n"
"uniform sampler2DRect Image; \n"
"varying vec4 unclampedFragColor; \n"
"varying vec2 texNominalSize; \n"
" \n"
"void main() \n"
"{ \n"
" vec4 texcolor; \n"
" texcolor.rgb = vec3(texture2DRect(Image, gl_TexCoord[0].st).r); \n"
" texcolor.a = texture2DRect(Image, gl_TexCoord[0].st + vec2(0.0, 1.0 * texNominalSize.y)).r; \n"
"\n"
" /* Multiply texcolor with incoming fragment color (GL_MODULATE emulation): */ \n"
" /* Assign result as output fragment color: */ \n"
" gl_FragColor = texcolor * unclampedFragColor; \n"
"} \n";
static char texturePlanar3FragmentShaderSrc[] =
"\n"
" \n"
"#extension GL_ARB_texture_rectangle : enable \n"
" \n"
"uniform sampler2DRect Image; \n"
"varying vec4 unclampedFragColor; \n"
"varying vec2 texNominalSize; \n"
" \n"
"void main() \n"
"{ \n"
" vec4 texcolor; \n"
" texcolor.r = texture2DRect(Image, gl_TexCoord[0].st).r; \n"
" texcolor.g = texture2DRect(Image, gl_TexCoord[0].st + vec2(0.0, 1.0 * texNominalSize.y)).r; \n"
" texcolor.b = texture2DRect(Image, gl_TexCoord[0].st + vec2(0.0, 2.0 * texNominalSize.y)).r; \n"
" texcolor.a = 1.0; \n"
"\n"
" /* Multiply texcolor with incoming fragment color (GL_MODULATE emulation): */ \n"
" /* Assign result as output fragment color: */ \n"
" gl_FragColor = texcolor * unclampedFragColor; \n"
"} \n";
static char texturePlanar4FragmentShaderSrc[] =
"\n"
" \n"
"#extension GL_ARB_texture_rectangle : enable \n"
" \n"
"uniform sampler2DRect Image; \n"
"varying vec4 unclampedFragColor; \n"
"varying vec2 texNominalSize; \n"
" \n"
"void main() \n"
"{ \n"
" vec4 texcolor; \n"
" texcolor.r = texture2DRect(Image, gl_TexCoord[0].st).r; \n"
" texcolor.g = texture2DRect(Image, gl_TexCoord[0].st + vec2(0.0, 1.0 * texNominalSize.y)).r; \n"
" texcolor.b = texture2DRect(Image, gl_TexCoord[0].st + vec2(0.0, 2.0 * texNominalSize.y)).r; \n"
" texcolor.a = texture2DRect(Image, gl_TexCoord[0].st + vec2(0.0, 3.0 * texNominalSize.y)).r; \n"
"\n"
" /* Multiply texcolor with incoming fragment color (GL_MODULATE emulation): */ \n"
" /* Assign result as output fragment color: */ \n"
" gl_FragColor = texcolor * unclampedFragColor; \n"
"} \n";
/* Sampling and conversion shader from YUV-I420 planar format to standard RGBA8
* format. Samples our YUV I420 planar luminance texture, builds yuv sample, then
* performs color space conversion from yuv to rgb.
*
* This shader is based on BSD licensed example code from Peter Bengtsson, from
* http://www.fourcc.org/source/YUV420P-OpenGL-GLSLang.c
*/
static char texturePlanarI420FragmentShaderSrc[] =
"/* YUV-I420 planar texture sampling fragment shader. */ \n"
"/* Retrieves YUV sample from proper locations in planes. */ \n"
"/* Converts YUV sample to RGB color triplet and applies */ \n"
"/* GL_MODULATE texture function emulation before fragment output. */ \n"
"\n"
"#extension GL_ARB_texture_rectangle : enable \n"
" \n"
"uniform sampler2DRect Image; \n"
"varying vec4 unclampedFragColor; \n"
"varying vec2 texNominalSize; \n"
" \n"
"void main() \n"
"{ \n"
" float r, g, b, y, u, v;\n"
" float nx, ny;\n"
"\n"
" nx = gl_TexCoord[0].x;\n"
" ny = gl_TexCoord[0].y;\n"
"\n"
" y = texture2DRect(Image, vec2(nx, ny)).r;\n"
" ny = floor(ny * 0.5);\n"
" nx = floor(nx * 0.5);\n"
" if (mod(ny, 2.0) >= 0.5) {\n"
" nx += texNominalSize.x * 0.5;\n"
" }\n"
"\n"
" ny = (ny - mod(ny, 2.0)) * 0.5;\n"
" u = texture2DRect(Image, vec2(nx, ny + texNominalSize.y)).r; \n"
" v = texture2DRect(Image, vec2(nx, ny + (1.25 * texNominalSize.y))).r; \n"
"\n"
" y = 1.1643 * (y - 0.0625);\n"
" u = u - 0.5;\n"
" v = v - 0.5;\n"
"\n"
" r = y + 1.5958 * v;\n"
" g = y - 0.39173 * u - 0.81290 * v;\n"
" b = y + 2.017 * u;\n"
"\n"
" /* Multiply texcolor with incoming fragment color (GL_MODULATE emulation): */ \n"
" /* Assign result as output fragment color: */ \n"
" gl_FragColor = vec4(r, g, b, 1.0) * unclampedFragColor; \n"
"} \n";
/* Sampling and conversion shader from Y8-I800 planar format to standard RGBA8
* format. Samples our Y8 I800 planar luminance texture, then performs color
* space conversion from y to rgb.
*/
static char texturePlanarI800FragmentShaderSrc[] =
"/* Y8-I800 planar texture sampling fragment shader. */ \n"
"/* Retrieves Y8 sample from proper location. */ \n"
"/* Converts Y8 sample to RGB color triplet and applies */ \n"
"/* GL_MODULATE texture function emulation before fragment output. */ \n"
"\n"
"#extension GL_ARB_texture_rectangle : enable \n"
" \n"
"uniform sampler2DRect Image; \n"
"varying vec4 unclampedFragColor; \n"
" \n"
"void main() \n"
"{ \n"
" float y = texture2DRect(Image, gl_TexCoord[0].xy).r;\n"
" y = 1.1643 * (y - 0.0625);\n"
"\n"
" /* Multiply texcolor with incoming fragment color (GL_MODULATE emulation): */ \n"
" /* Assign result as output fragment color: */ \n"
" gl_FragColor = vec4(y, y, y, 1.0) * unclampedFragColor; \n"
"} \n";
char texturePlanarVertexShaderSrc[] =
"/* Simple pass-through vertex shader: Emulates fixed function pipeline, but passes */ \n"
"/* modulateColor as varying unclampedFragColor to circumvent vertex color */ \n"
"/* clamping on gfx-hardware / OS combos that don't support unclamped operation: */ \n"
"/* PTBs color handling is expected to pass the vertex color in modulateColor */ \n"
"/* for unclamped drawing for this reason. */ \n"
"\n"
"varying vec4 unclampedFragColor;\n"
"varying vec2 texNominalSize;\n"
"attribute vec4 modulateColor;\n"
"attribute vec4 sizeAngleFilterMode;\n"
"\n"
"void main()\n"
"{\n"
" /* Simply copy input unclamped RGBA pixel color into output varying color: */\n"
" unclampedFragColor = modulateColor;\n"
" texNominalSize = sizeAngleFilterMode.xy;\n"
"\n"
" gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0;\n"
"\n"
" /* Output position is the same as fixed function pipeline: */\n"
" gl_Position = ftransform();\n"
"}\n\0";
// Source code for a fragment shader that performs texture lookup and
// modulation, but taking the modulatecolor from 'unclampedFragColor'
// instead of standard interpolated fragment color. This is used when
// high-precision and unclamped fragment input colors are needed and
// the hw doesn't support that. It's a drop in replacement for fixed
// function pipe otherwise:
static char textureLookupFragmentShaderSrc[] =
"\n"
" \n"
"#extension GL_ARB_texture_rectangle : enable \n"
" \n"
"uniform sampler2DRect Image; \n"
"varying vec4 unclampedFragColor; \n"
" \n"
"void main() \n"
"{ \n"
" vec4 texcolor = texture2DRect(Image, gl_TexCoord[0].st); \n"
" /* Multiply texcolor with incoming fragment color (GL_MODULATE emulation): */ \n"
" /* Assign result as output fragment color: */ \n"
" gl_FragColor = texcolor * unclampedFragColor; \n"
"} \n";
// Source code for a fragment shader that performs bilinear texture filtering.
// This shader is used as a drop-in replacement for GL's GL_LINEAR built-in
// texture filter, whenever that filter is not available: All pre ATI Radeon HD
// hardware and all pre GF6000 NVidia hardware can't filter float textures,
// GF6/7 series NVidia hardware can only filter 16bpc floats, not 32bpc floats.
static char textureBilinearFilterFragmentShaderSrc[] =
"\n"
" \n"
" \n"
"#extension GL_ARB_texture_rectangle : enable \n"
" \n"
"uniform sampler2DRect Image; \n"
"varying vec4 unclampedFragColor; \n"
" \n"
"void main() \n"
"{ \n"
" /* Get wanted texture coordinate for which we should filter: */ \n"
" vec2 texinpos = (gl_TexCoord[0].st) - vec2(0.5, 0.5); \n"
" /* Retrieve texel colors for 4 nearest neighbours: */ \n"
" vec4 tl=texture2DRect(Image, floor(texinpos)); \n"
" vec4 tr=texture2DRect(Image, floor(texinpos) + vec2(1.0, 0.0)); \n"
" vec4 bl=texture2DRect(Image, floor(texinpos) + vec2(0.0, 1.0)); \n"
" vec4 br=texture2DRect(Image, floor(texinpos) + vec2(1.0, 1.0)); \n"
" /* Perform weighted linear interpolation -- bilinear interpolation of the 4: */ \n"
" tl=mix(tl,tr,fract(texinpos.x)); \n"
" bl=mix(bl,br,fract(texinpos.x)); \n"
" vec4 texcolor = mix(tl, bl, fract(texinpos.y)); \n"
" /* Multiply filtered texcolor with incoming fragment color (GL_MODULATE emulation): */ \n"
" /* Assign result as output fragment color: */ \n"
" gl_FragColor = texcolor * unclampedFragColor; \n"
"} \n";
char textureBilinearFilterVertexShaderSrc[] =
"/* Simple pass-through vertex shader: Emulates fixed function pipeline, but passes */ \n"
"/* modulateColor as varying unclampedFragColor to circumvent vertex color */ \n"
"/* clamping on gfx-hardware / OS combos that don't support unclamped operation: */ \n"
"/* PTBs color handling is expected to pass the vertex color in modulateColor */ \n"
"/* for unclamped drawing for this reason. */ \n"
"\n"
"varying vec4 unclampedFragColor;\n"
"attribute vec4 modulateColor;\n"
"\n"
"void main()\n"
"{\n"
" /* Simply copy input unclamped RGBA pixel color into output varying color: */\n"
" unclampedFragColor = modulateColor;\n"
"\n"
" gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0;\n"
"\n"
" /* Output position is the same as fixed function pipeline: */\n"
" gl_Position = ftransform();\n"
"}\n\0";
// Source code for our GLSL anaglyph stereo shader:
char anaglyphshadersrc[] =
"/* Weight vector for conversion from RGB to Luminance, according to NTSC spec. */ \n"
" \n"
"#extension GL_ARB_texture_rectangle : enable \n"
" \n"
"uniform vec3 ColorToGrayWeights; \n"
"/* Bias to add to final product - The background color (normally (0,0,0)). */ \n"
"uniform vec3 ChannelBias; \n"
"/* Left image channel and right image channel: */ \n"
"uniform sampler2DRect Image1; \n"
"uniform sampler2DRect Image2; \n"
"uniform vec3 Gains1;\n"
"uniform vec3 Gains2;\n"
"\n"
"void main()\n"
"{\n"
" /* Lookup RGBA pixel colors in left- and right buffer and convert to Luminance */\n"
" vec3 incolor1 = texture2DRect(Image1, gl_TexCoord[0].st).rgb;\n"
" float luminance1 = dot(incolor1, ColorToGrayWeights);\n"
" vec3 incolor2 = texture2DRect(Image2, gl_TexCoord[0].st).rgb;\n"
" float luminance2 = dot(incolor2, ColorToGrayWeights);\n"
" /* Replicate in own RGBA tupel */\n"
" vec3 channel1 = vec3(luminance1);\n"
" vec3 channel2 = vec3(luminance2);\n"
" /* Mask with per channel weights: */\n"
" channel1 = channel1 * Gains1;\n"
" channel2 = channel2 * Gains2;\n"
" /* Add them up to form final output fragment: */\n"
" gl_FragColor.rgb = channel1 + channel2 + ChannelBias;\n"
" /* Alpha is forced to 1 - It does not matter anymore: */\n"
" gl_FragColor.a = 1.0;\n"
"}\n\0";
char passthroughshadersrc[] =
" \n"
"#extension GL_ARB_texture_rectangle : enable \n"
" \n"
"uniform sampler2DRect Image1; \n"
"\n"
"void main()\n"
"{\n"
" gl_FragColor.rgb = texture2DRect(Image1, gl_TexCoord[0].st).rgb;\n"
" gl_FragColor.a = 1.0;\n"
"}\n\0";
char multisampletexfetchshadersrc[] =
" \n"
"#extension GL_ARB_texture_multisample : enable \n"
" \n"
"uniform sampler2DMS Image1; \n"
"uniform int nrsamples;\n"
"\n"
"void main()\n"
"{\n"
" vec4 color = vec4(0.0);\n"
" for (int i = 0; i < nrsamples; i++) {\n"
" color += texelFetch(Image1, ivec2(gl_TexCoord[0].st), i);\n"
" }\n"
" gl_FragColor = color / vec4(nrsamples);\n"
"}\n\0";
// This array maps hook point name strings to indices. The symbolic constants in
// PsychImagingPipelineSupport.h define symbolic names for the indices for fast
// lookup by name:
#define MAX_HOOKNAME_LENGTH 40
#define MAX_HOOKSYNOPSIS_LENGTH 1024
char PsychHookPointNames[MAX_SCREEN_HOOKS][MAX_HOOKNAME_LENGTH] = {
"CloseOnscreenWindowPreGLShutdown",
"CloseOnscreenWindowPostGLShutdown",
"UserspaceBufferDrawingFinished",
"StereoLeftCompositingBlit",
"StereoRightCompositingBlit",
"StereoCompositingBlit",
"MirrorWindowBlit",
"FinalOutputFormattingBlit",
"UserspaceBufferDrawingPrepare",
"IdentityBlitChain",
"LeftFinalizerBlitChain",
"RightFinalizerBlitChain",
"UserDefinedBlit",
"FinalOutputFormattingBlit0",
"FinalOutputFormattingBlit1",
"ScreenFlipImpliedOperations",
"PreSwapbuffersOperations"
};
char PsychHookPointSynopsis[MAX_SCREEN_HOOKS][MAX_HOOKSYNOPSIS_LENGTH] = {
"OpenGL based actions to be performed when an onscreen window is closed, e.g., teardown for special output devices.",
"Non-graphics actions to be performed when an onscreen window is closed, e.g., teardown for special output devices.",
"Operations to be performed after last drawing command, i.e. in Screen('Flip') or Screen('DrawingFinshed').",
"Perform generic user-defined image processing on image content of left-eye (or mono) buffer.",
"Perform generic user-defined image processing on image content of right-eye buffer.",
"Internal(preinitialized): Compose left- and right-eye view into one combined image for all stereo modes except quad-buffered flip-frame stereo.",
"Perform blit operations to aid implementation of mirror / clone modes, e.g., for master window -> slave window blits.",
"Perform post-processing indifferent of stereo mode, e.g., special data formatting for devices like BrightSideHDR, Bits++, Video attenuators...",
"Operations to be performed immediately after Screen('Flip') in order to prepare drawing commands of users script.",
"Internal(preinitialized): Only for internal use. Only modify for debugging and testing of pipeline itself!",
"Internal(preinitialized): Perform last time operation on left (or mono) channel, e.g., draw blue-sync lines.",
"Internal(preinitialized): Perform last time operation on right channel, e.g., draw blue-sync lines.",
"Defines a user defined image processing operation for the Screen('TransformTexture') command.",
"Perform post-processing on 1st (left) output channel, e.g., special data formatting for devices like BrightSideHDR, Bits++, Video attenuators...",
"Perform post-processing on 2nd (right) output channel, e.g., special data formatting for devices like BrightSideHDR, Bits++, Video attenuators...",
"This is called after a bufferswap has truly completed by Screen('Flip'), Screen('AsyncFlipCheckEnd') or Screen('AsyncFlipEnd'). Use of OpenGL commands and Matlab commands is allowed here.",
"Called before emitting the PsychOSFlipWindowBuffers() call, ie., less than 1 video refresh from flipdeadline away. No OpenGL ops allowed!"
};
/* PsychInitImagingPipelineDefaultsForWindowRecord()
* Set "all-off" defaults in windowRecord. This is called during creation of a windowRecord.
* It sets all imaging related fields to safe defaults.
*/
void PsychInitImagingPipelineDefaultsForWindowRecord(PsychWindowRecordType *windowRecord)
{
int i;
// Initialize everything to "all-off" default:
for (i=0; i<MAX_SCREEN_HOOKS; i++) {
windowRecord->HookChainEnabled[i]=FALSE;
windowRecord->HookChain[i]=NULL;
}
// Disable all special framebuffer objects by default:
windowRecord->drawBufferFBO[0]=-1;
windowRecord->drawBufferFBO[1]=-1;
windowRecord->inputBufferFBO[0]=-1;
windowRecord->inputBufferFBO[1]=-1;
windowRecord->processedDrawBufferFBO[0]=-1;
windowRecord->processedDrawBufferFBO[1]=-1;
windowRecord->processedDrawBufferFBO[2]=-1;
windowRecord->preConversionFBO[0]=-1;
windowRecord->preConversionFBO[1]=-1;
windowRecord->preConversionFBO[2]=-1;
windowRecord->finalizedFBO[0]=-1;
windowRecord->finalizedFBO[1]=-1;
windowRecord->fboCount = 0;
// NULL-out fboTable:
for (i=0; i<MAX_FBOTABLE_SLOTS; i++) windowRecord->fboTable[i] = NULL;
// Setup mode switch in record to "all off":
windowRecord->imagingMode = 0;
return;
}
/* PsychInitializeImagingPipeline()
*
* Initialize imaging pipeline for windowRecord, applying the imagingmode flags. Called by Screen('OpenWindow').
*
* This routine performs initial setup of an imaging pipeline for an onscreen window. It sets up reasonable
* default values in the windowRecord (imaging pipe is disabled by default if imagingmode is zero), based on
* the imagingmode flags and all the windowRecord and OpenGL settings.
*
* 1. FBO's are setup according to the requested imagingmode, stereomode and color depth of a window.
* 2. Depending on stereo mode and imagingmode, some default GLSL shaders may get created and attached to
* some hook-chains for advanced stereo processing.
*/
void PsychInitializeImagingPipeline(PsychWindowRecordType *windowRecord, int imagingmode, int multiSample)
{
GLenum fboInternalFormat, finalizedFBOFormat;
int newimagingmode = 0;
int fbocount = 0;
int winwidth, winheight;
int clientwidth, clientheight;
psych_bool needzbuffer, needoutputconversion, needimageprocessing, needseparatestreams, needfastbackingstore, targetisfinalFB;
GLuint glsl;
GLint redbits;
float rg, gg, bg; // Gains for color channels and color masking for anaglyph shader setup.
char blittercfg[1000];
// Processing ends here after minimal "all off" setup, if pipeline is disabled:
if (imagingmode<=0) {
imagingmode=0;
return;
}
// Activate rendering context of this window:
PsychSetGLContext(windowRecord);
// Check if this system does support OpenGL framebuffer objects and rectangle textures:
if (!(windowRecord->gfxcaps & kPsychGfxCapFBO)) {
// Unsupported! This is a complete no-go :(
printf("PTB-ERROR: Initialization of the built-in image processing pipeline failed. Your graphics hardware or graphics driver does not support\n");
printf("PTB-ERROR: the required OpenGL framebuffer object extension. You may want to upgrade to the latest drivers or if that doesn't help, to a\n");
printf("PTB-ERROR: more recent graphics card. You'll need at minimum a NVidia GeforceFX-5000 or a ATI Radeon 9600 or Intel GMA 950 for this to work.\n");
printf("PTB-ERROR: See the www.psychtoolbox.org Wiki for recommendations. You can still use basic stereo support (with restricted performance and features)\n");
printf("PTB-ERROR: by disabling the imaging pipeline (imagingmode = 0) but still selecting a stereomode in the 'OpenWindow' subfunction.\n");
PsychErrorExitMsg(PsychError_user, "Imaging Pipeline setup: Sorry, your graphics card does not meet the minimum requirements for use of the imaging pipeline.");
}
// Another child protection:
if ((windowRecord->windowType != kPsychDoubleBufferOnscreen) || PsychPrefStateGet_EmulateOldPTB()>0) {
PsychErrorExitMsg(PsychError_user, "Imaging Pipeline setup: Sorry, imaging pipeline only supported on double buffered onscreen windows and if not in emulation mode for old PTB-2.\n");
}
// Specific setup of pipeline if real imaging ops are requested:
// Setup mode switch in record:
windowRecord->imagingMode = imagingmode;
// Is this a request for fast Offscreen window support only? The special flag kPsychNeedFastOffscreenWindows,
// if provided without any other flags, will not startup the full pipeline, but only allow creation of FBO-backed
// offscreen windows and fast switching between them and the system framebuffer.
if (imagingmode == kPsychNeedFastOffscreenWindows) {
if (PsychPrefStateGet_Verbosity()>3) printf("PTB-INFO: Support for fast OffscreenWindows enabled.\n");
fflush(NULL);
return;
}
if (PsychPrefStateGet_Verbosity()>2) printf("PTB-INFO: Psychtoolbox imaging pipeline starting up for window with requested imagingmode %i ...\n", imagingmode);
fflush(NULL);
// Safe default:
targetisfinalFB = FALSE;
// Panel fitter requested? If so, framebuffer blit extension supported?
if ((imagingmode & kPsychNeedGPUPanelFitter) && !(windowRecord->gfxcaps & kPsychGfxCapFBOBlit)) {
// This is a no-go:
printf("PTB-WARNING: You requested use of the panel-fitter via the 'clientRect' parameter of Screen('OpenWindow', ...);\n");
printf("PTB-WARNING: but this graphics card or graphics driver does not support the required GL_EXT_framebuffer_blit extension.\n");
printf("PTB-WARNING: Will use a lower performance fallback path to do it anyway. Some restrictions apply, check further status output.\n\n");
}
// Multisampled anti-aliasing requested?
if (multiSample > 0) {
// Yep. Supported by GPU?
if (!(windowRecord->gfxcaps & kPsychGfxCapFBOMultisample)) {
// No. We fall back to non-multisampled mode:
multiSample = 0;
windowRecord->multiSample = 0;
// Tell user if warnings enabled:
if (PsychPrefStateGet_Verbosity() > 1) {
printf("PTB-WARNING: You requested stimulus anti-aliasing by multisampling by setting the multiSample parameter of Screen('OpenWindow', ...) to a non-zero value.\n");
printf("PTB-WARNING: You also requested use of the imaging pipeline. Unfortunately, your combination of operating system, graphics hardware and driver does not\n");
printf("PTB-WARNING: support simultaneous use of the imaging pipeline and multisampled anti-aliasing.\n");
printf("PTB-WARNING: Will therefore continue without anti-aliasing...\n\n");
}
} // Panel scaling requested? If so we need support for scaled multisample resolve blits or multisample textures to satisfy needs of multisampling and scaling:
else if ((imagingmode & kPsychNeedGPUPanelFitter) && !(windowRecord->gfxcaps & kPsychGfxCapFBOScaledResolveBlit) && !glewIsSupported("GL_ARB_texture_multisample")) {
// Not supported by GPU. Disable multisampling to satisfy at least the requirement for panelscaling,
// which is probably more important, as usercode usually only uses panel scaling to workaround serious
// trouble with experimental setups, ie., it is more urgent:
multiSample = 0;
windowRecord->multiSample = 0;
// Tell user if warnings enabled:
if (PsychPrefStateGet_Verbosity() > 1) {
printf("PTB-WARNING: You requested stimulus anti-aliasing by multisampling by setting the multiSample parameter of Screen('OpenWindow', ...) to a non-zero value.\n");
printf("PTB-WARNING: You also requested use of the imaging pipeline and of the GPU panel-fitter / rescaler via the 'clientRect' argument.\n");
printf("PTB-WARNING: Unfortunately, your combination of operating system, graphics hardware and driver does not support simultaneous\n");
printf("PTB-WARNING: use of multisampled anti-aliasing and the panel-fitter. I assume your request for panel fitting is more important.\n");
printf("PTB-WARNING: I will therefore continue without anti-aliasing to make the panel-fitter work.\n");
printf("PTB-WARNING: You would need a graphics card, os or graphics driver that supports the GL_EXT_framebuffer_multisample_blit_scaled\n");
printf("PTB-WARNING: extension or GL_ARB_texture_multisample extension to avoid this degradation of functionality.\n\n");
}
}
else if ((imagingmode & kPsychNeedGPUPanelFitter) && !(windowRecord->gfxcaps & kPsychGfxCapFBOScaledResolveBlit)) {
// Panelfitter wanted and at least multisample texture support works for basic fitter functionality, ie.,
// framebuffer rotation and some multisample resolve and rescaling via texture blitting. However, the scaledresolveblit
// extension is not supported. This means selection or cropping of source regions won't work. A minor limitation for most
// use cases, luckily.
if (PsychPrefStateGet_Verbosity() > 1) {
printf("PTB-WARNING: You requested stimulus anti-aliasing by multisampling by setting the multiSample parameter of Screen('OpenWindow', ...) to a non-zero value.\n");
printf("PTB-WARNING: You also requested use of the imaging pipeline and of the GPU panel-fitter / rescaler via the 'clientRect' argument.\n");
printf("PTB-WARNING: Unfortunately, your combination of operating system, graphics hardware and driver has limited support for simultaneous\n");
printf("PTB-WARNING: use of multisampled anti-aliasing and the panel-fitter. Certain panelfitter scaling modes won't work properly, specifically\n");
printf("PTB-WARNING: the ones that use a non-default source region, e.g., for cropping or scrolling. Most functionality will work though.\n");
printf("PTB-WARNING: You would need a graphics card, os or graphics driver that supports the GL_EXT_framebuffer_multisample_blit_scaled\n");
printf("PTB-WARNING: extension to avoid this small degradation of functionality.\n\n");
}
}
}
// Determine required precision for our framebuffer objects:
// Start off with standard 8 bpc fixed point:
fboInternalFormat = GL_RGBA8; windowRecord->bpc = 8;
// Need 16 bpc fixed point precision?
if (imagingmode & kPsychNeed16BPCFixed) { fboInternalFormat = ((windowRecord->gfxcaps & kPsychGfxCapSNTex16) ? GL_RGBA16_SNORM : GL_RGBA16); windowRecord->bpc = 16; }
// Need 16 bpc floating point precision?
if (imagingmode & kPsychNeed16BPCFloat) { fboInternalFormat = GL_RGBA_FLOAT16_APPLE; windowRecord->bpc = 16; }
// Need 32 bpc floating point precision?
if (imagingmode & kPsychNeed32BPCFloat) { fboInternalFormat = GL_RGBA_FLOAT32_APPLE; windowRecord->bpc = 32; }
// Want dynamic adaption of buffer precision?
if (imagingmode & kPsychUse32BPCFloatAsap) {
// Yes. If the gfx-hardware is capable of unrestricted hardware-accelerated 32 bpc
// float framebuffer blending, we use 32bpc float for drawBufferFBOs, if not -> use 16 bpc.
// Start off with 16 bpc for the stage 0 FBO's.
fboInternalFormat = GL_RGBA_FLOAT16_APPLE; windowRecord->bpc = 16;
// Blending on 32 bpc float FBO's supported? Upgrade to 32 bpc float for stage 0 if possible:
if (windowRecord->gfxcaps & kPsychGfxCapFPBlend32) { fboInternalFormat = GL_RGBA_FLOAT32_APPLE; windowRecord->bpc = 32; }
}
// Floating point framebuffer on OpenGL-ES requested?
if (PsychIsGLES(windowRecord) && (imagingmode & (kPsychNeed16BPCFloat | kPsychNeed32BPCFloat | kPsychUse32BPCFloatAsap))) {
// Yes. We only support 32 bpc float framebuffers with alpha-blending. On less supportive hardware we fail:
if (!(windowRecord->gfxcaps & kPsychGfxCapFPTex32) || !(windowRecord->gfxcaps & kPsychGfxCapFPFBO32)) {
PsychErrorExitMsg(PsychError_user, "Sorry, the requested framebuffer color resolution of 32 bpc floating point is not supported by your graphics card. Game over.");
}
// Supported. Upgrade requested format to 32 bpc float, whatever it was before:
fboInternalFormat = GL_RGBA_FLOAT32_APPLE; windowRecord->bpc = 32;
}
// Sanity check: Is a floating point framebuffer requested which requires floating point texture support and
// the hardware doesn't support float textures? Bail early, if so.
if (((windowRecord->bpc == 16) && !(windowRecord->gfxcaps & kPsychGfxCapFPTex16) && !(imagingmode & kPsychNeed16BPCFixed)) ||
((windowRecord->bpc == 32) && !(windowRecord->gfxcaps & kPsychGfxCapFPTex32))) {
printf("PTB-ERROR: Your script requested a floating point resolution framebuffer with a resolution of more than 8 bits per color channel.\n");
printf("PTB-ERROR: Your graphics hardware doesn't support floating point textures or framebuffers, so this is a no-go. Aborting...\n");
PsychErrorExitMsg(PsychError_user, "Sorry, the requested framebuffer color resolution is not supported by your graphics card. Game over.");
}
if (PsychPrefStateGet_Verbosity()>2) {
switch(fboInternalFormat) {
case GL_RGBA8:
printf("PTB-INFO: Will use 8 bits per color component framebuffer for stimulus drawing.\n");
break;
case GL_RGBA16:
printf("PTB-INFO: Will use 16 bits per color component unsigned integer framebuffer for stimulus drawing. Alpha blending may not work.\n");
break;
case GL_RGBA16_SNORM:
printf("PTB-INFO: Will use 15 bits per color component signed integer framebuffer for stimulus drawing. Alpha blending may not work.\n");
break;
case GL_RGBA_FLOAT16_APPLE:
printf("PTB-INFO: Will use 16 bits per color component floating point framebuffer for stimulus drawing. ");
if (windowRecord->gfxcaps & kPsychGfxCapFPBlend16) {
printf("Alpha blending should work correctly.\n");
if (imagingmode & kPsychUse32BPCFloatAsap) {
printf("PTB-INFO: Can't use 32 bit precision for drawing because hardware doesn't support alpha-blending in 32 bpc.\n");
}
}
else {
printf("Alpha blending may not work on your system with this setup, but only for 8 bits per color component mode.\n");
}
break;
case GL_RGBA_FLOAT32_APPLE:
printf("PTB-INFO: Will use 32 bits per color component floating point framebuffer for stimulus drawing. ");
if (windowRecord->gfxcaps & kPsychGfxCapFPBlend32) {
printf("Alpha blending should work correctly.\n");
}
else {
printf("Alpha blending may not work on your system with this setup, but only for lower precision modes.\n");
}
break;
}
}
// Do we need additional depth buffer attachments?
needzbuffer = (PsychPrefStateGet_3DGfx()>0) ? TRUE : FALSE;
// Do we need separate streams for stereo? Only for OpenGL quad-buffered mode and dual-window stereo mode:
needseparatestreams = (windowRecord->stereomode == kPsychOpenGLStereo || windowRecord->stereomode == kPsychDualWindowStereo ||
windowRecord->stereomode == kPsychFrameSequentialStereo || windowRecord->stereomode == kPsychDualStreamStereo) ? TRUE : FALSE;
// Do we need some intermediate image processing?
needimageprocessing= (imagingmode & kPsychNeedImageProcessing) ? TRUE : FALSE;
// Do we need some final output formatting?
needoutputconversion = (imagingmode & kPsychNeedOutputConversion) ? TRUE : FALSE;
// Do we need fast backing store?
needfastbackingstore = (imagingmode & kPsychNeedFastBackingStore) ? TRUE : FALSE;
// Consolidate settings: Most settings imply kPsychNeedFastBackingStore.
if (needoutputconversion || needimageprocessing || windowRecord->stereomode > 0 || fboInternalFormat!=GL_RGBA8) {
imagingmode|=kPsychNeedFastBackingStore;
needfastbackingstore = TRUE;
}
// Try to allocate and configure proper FBO's:
fbocount = 0;
// Define final default output buffers as system framebuffers: We create some pseudo-FBO's for these
// which describe the system framebuffer (backbuffer). This is done to simplify pipeline design:
// Allocate empty FBO info struct and assign it:
winwidth = (int) PsychGetWidthFromRect(windowRecord->rect);
winheight = (int) PsychGetHeightFromRect(windowRecord->rect);
if (!PsychCreateFBO(&(windowRecord->fboTable[fbocount]), 0, FALSE, winwidth, winheight, 0, 0)) {
// Failed!
PsychErrorExitMsg(PsychError_internal, "Imaging Pipeline setup: Could not setup stage 0 of imaging pipeline.");
}
// The pseudo-FBO initially contains a fboid of zero == system framebuffer, and empty (zero) attachments.
// The up to now only useful information is the viewport geometry ie winwidth and winheight.
// We use the same struct for both buffers, because in the end, there is only one backbuffer. Separate channels
// with same mapping allow some interesting extensions in the future for additional stereo modes or snapshot
// creation. This common assignment gets overriden below for special stereo modes or dual-window/dual-stream
// output modes:
windowRecord->finalizedFBO[0]=fbocount;
windowRecord->finalizedFBO[1]=fbocount;
fbocount++;
// Compute format for a finalizedFBO which is not the backbuffer, but blits unmodified to the backbuffer:
// This is by default always a standard 8bpc fixed point RGBA8 framebuffer without stencil- and z-buffers etc.
// If bit depths of native backbuffer is more than 8 bits, we allocate a float32 FBO though. Should we need a
// 32 bpc float FBO but the GPU doesn't support this, we try a 16 bit snorm FBO. A 16 bit snorm FBO has effective
// 15 bits linear integer precision, which is enough for all currently existing hw framebuffers:
// Query bit depths of native backbuffer: Assume red bits == green bits == blue bits == bit depths.
glGetIntegerv(GL_RED_BITS, &redbits);
// Decide on proper format:
finalizedFBOFormat = (redbits <= 8) ? GL_RGBA8 : ((windowRecord->gfxcaps & kPsychGfxCapFPFBO32) ? GL_RGBA_FLOAT32_APPLE : GL_RGBA16_SNORM);
// Use of VRR mode with our own custom scheduler requested?
if (windowRecord->vrrMode == kPsychVRROwnScheduled) {
// Create one finalizedFBO[0] for the virtual backbuffer that will be blitted into the real backbuffer, then
// VRR scheduled for stimulus onset:
if (!PsychCreateFBO(&(windowRecord->fboTable[fbocount]), finalizedFBOFormat, FALSE, winwidth, winheight, 0, 0)) {
// Failed!
PsychErrorExitMsg(PsychError_system, "Imaging Pipeline setup: Could not setup stage 0 of imaging pipeline for my own VRR scheduler.");
}
windowRecord->finalizedFBO[0] = fbocount;
fbocount++;
}
if ((windowRecord->stereomode == kPsychDualWindowStereo) || (imagingmode & kPsychNeedDualWindowOutput)) {
// Dual-window stereo or dual window output is a special case: This window contains the imaging pipeline for
// both views, but its OpenGL context and framebuffer only represents the left-view channel.
// The right-view channel is represented by a slave window and its associated context. We
// create a framebuffer object and attach it to finalizedFBO[1]. This way, the final left view
// stimulus image gets blitted directly into the system framebuffer for this window, but the
// right view stimulus gets blitted into the finalizedFBO[1]. PsychPreflipOperations() will
// perform a last blit-copy operation at the end of pipeline processing, where it copies the content
// of finalizedFBO[1] into the real system framebuffer for the onscreen window which represents the
// user visible right view. It switches to the OpenGL context for the right view slave window before
// the blit, so blitting finalizedFBO[1] into the system framebuffer blits into the slave windows /
// right view windows back buffer. This bounce buffer trick works, because the OpenGL contexts of
// both windows share resources, ie. OpenGL textures, framebuffer objects etc., and thereby finalizedFBO
// content.
//
// In dual window output mode, as opposed to dual window stereo mode, we only have one single monoscopic view,
// which we want to copy to the secondary slave window, as a copy/clone/mirror image. However, we need to
// switch to finalizedFBO[0] as bounce buffer in this case, as the whole imaging pipeline - configured for
// mono/single-stream processing - blits the final image into finalizedFBO[0]:
if (!PsychCreateFBO(&(windowRecord->fboTable[fbocount]), finalizedFBOFormat, FALSE, winwidth, winheight, 0, 0)) {
// Failed!
PsychErrorExitMsg(PsychError_system, "Imaging Pipeline setup: Could not setup stage 0 of imaging pipeline for dual-window stereo.");
}
windowRecord->finalizedFBO[((windowRecord->stereomode == kPsychDualWindowStereo) ? 1 : 0)] = fbocount;
fbocount++;
}
if (windowRecord->stereomode == kPsychFrameSequentialStereo) {
// Home-Grown frame-sequential stereo mode: Need one real finalizedFBO for each of the
// two stereo streams:
if (!PsychCreateFBO(&(windowRecord->fboTable[fbocount]), finalizedFBOFormat, FALSE, winwidth, winheight, 0, 0)) {
// Failed!
PsychErrorExitMsg(PsychError_system, "Imaging Pipeline setup: Could not setup stage 0 of imaging pipeline for frame-sequential stereo (left eye).");
}
windowRecord->finalizedFBO[0]=fbocount;
fbocount++;
if (!PsychCreateFBO(&(windowRecord->fboTable[fbocount]), finalizedFBOFormat, FALSE, winwidth, winheight, 0, 0)) {
// Failed!
PsychErrorExitMsg(PsychError_system, "Imaging Pipeline setup: Could not setup stage 0 of imaging pipeline for frame-sequential stereo (right eye).");
}
windowRecord->finalizedFBO[1]=fbocount;
fbocount++;
}
// Dualstream stereo definitely needs a separate finalizedFBO[1] PsychFBO for right-eye:
if (windowRecord->stereomode == kPsychDualStreamStereo) {
if (!PsychCreateFBO(&(windowRecord->fboTable[fbocount]), 0, FALSE, winwidth, winheight, 0, 0)) {
// Failed!
PsychErrorExitMsg(PsychError_internal, "Imaging Pipeline setup: Could not setup stage 0 of imaging pipeline.");
}
windowRecord->finalizedFBO[1]=fbocount;
fbocount++;
}
// Now we preinit all further stages with the finalizedFBO assignment.
if (needfastbackingstore) {
// We need at least the 1st level drawBufferFBO's as rendertargets for all
// user-space drawing, ie Screen 2D drawing functions, MOGL OpenGL rendering and
// C-MEX OpenGL rendering plugins...
// Define dimensions of 1st stage FBO:
winwidth=(int)PsychGetWidthFromRect(windowRecord->rect);
winheight=(int)PsychGetHeightFromRect(windowRecord->rect);
// Adapt it for some stereo modes:
if (windowRecord->specialflags & kPsychHalfWidthWindow) {
// Special case for stereo: Only half the real window width:
winwidth = winwidth / 2;
}
if (windowRecord->specialflags & kPsychTwiceWidthWindow) {
// Special case: Twice the real window width:
winwidth = winwidth * 2;
}
if (windowRecord->specialflags & kPsychTripleWidthWindow) {
// Special case: Three times the real window width:
winwidth = winwidth * 3;
}
if (windowRecord->specialflags & kPsychHalfHeightWindow) {
// Special case for stereo: Only half the real window height:
winheight = winheight / 2;
}
// Special setup of FBO size for use with panel-fitter needed?
if (imagingmode & kPsychNeedGPUPanelFitter) {
// Panel-fitter: Use override values from windows clientrectangle:
clientwidth = (int) PsychGetWidthFromRect(windowRecord->clientrect);
clientheight = (int) PsychGetHeightFromRect(windowRecord->clientrect);
if (PsychPrefStateGet_Verbosity() > 2) {
printf("PTB-INFO: Enabling panel fitter. Providing virtual framebuffer of %i x %i pixels size.\n", clientwidth, clientheight);
}
}
else {
// No panel-fitter.
// Output real vs. net size if clientRect is requested despite no use of panel-fitter:
if ((imagingmode & kPsychNeedClientRectNoFitter) && (PsychPrefStateGet_Verbosity() > 2)) {
clientwidth = (int) PsychGetWidthFromRect(windowRecord->clientrect);
clientheight = (int) PsychGetHeightFromRect(windowRecord->clientrect);
printf("PTB-INFO: Providing virtual framebuffer of %i x %i pixels with 2D drawing restricted to %i x %i pixels clientRect size.\n",
winwidth, winheight, clientwidth, clientheight);
}
// In any case, use calculated winwidth x winheight for 1st level drawBufferFBO's:
clientwidth = winwidth;
clientheight = winheight;
}
// These FBO's may need a z-buffer or stencil buffer as well if 3D rendering is
// enabled. Try twice, first with specialFlags 2, to get multisample textures for multisample colorbuffers, then with
// specialFlags 0 with classic multisample renderbuffers, as a fallback for extra robustness. This will always alloc
// standard textures if no multisampling is requested:
if (!PsychCreateFBO(&(windowRecord->fboTable[fbocount]), fboInternalFormat, needzbuffer, clientwidth, clientheight, multiSample, 2) &&
!PsychCreateFBO(&(windowRecord->fboTable[fbocount]), fboInternalFormat, needzbuffer, clientwidth, clientheight, multiSample, 0)) {
// Failed!
PsychErrorExitMsg(PsychError_system, "Imaging Pipeline setup: Could not setup stage 1 of imaging pipeline.");
}
if ((PsychPrefStateGet_Verbosity() > 2) && (windowRecord->fboTable[fbocount]->multisample > 0)) {
printf("PTB-INFO: Created framebuffer for anti-aliasing with %i samples per pixel for use with imaging pipeline.\n", windowRecord->fboTable[fbocount]->multisample);
}
// Assign this FBO as drawBuffer for left-eye or mono channel:
windowRecord->drawBufferFBO[0] = fbocount;
fbocount++;
// If we are in stereo mode, we'll need a 2nd buffer for the right-eye channel:
if (windowRecord->stereomode > 0) {
// Try twice, with specialFlags 2 and as fallback to 0 for multisample textures, then multisample renderbuffers, in case of multisampling:
if (!PsychCreateFBO(&(windowRecord->fboTable[fbocount]), fboInternalFormat, needzbuffer, clientwidth, clientheight, multiSample, 2) &&
!PsychCreateFBO(&(windowRecord->fboTable[fbocount]), fboInternalFormat, needzbuffer, clientwidth, clientheight, multiSample, 0)) {
// Failed!
PsychErrorExitMsg(PsychError_system, "Imaging Pipeline setup: Could not setup stage 1 of imaging pipeline.");
}
// Assign this FBO as drawBuffer for right-eye channel:
windowRecord->drawBufferFBO[1] = fbocount;
fbocount++;
}
// Windows with fast backing store always have 4 color channels RGBA, regardless what the
// associated system framebuffer has:
windowRecord->nrchannels = 4;
}
// Upgrade to 32 bpc float FBO's needed, starting with the 2nd stage of the pipe?
// If so, we can now upgrade, because we won't need alpha-blending anymore in later stages:
if (imagingmode & kPsychUse32BPCFloatAsap) fboInternalFormat = GL_RGBA_FLOAT32_APPLE;
if (PsychPrefStateGet_Verbosity()>2) {
switch (fboInternalFormat) {
case GL_RGBA8:
printf("PTB-INFO: Will use 8 bits per color component framebuffer for stimulus post-processing (if any).\n");
break;
case GL_RGBA16:
printf("PTB-INFO: Will use 16 bits per color component unsigned integer framebuffer for stimulus post-processing (if any).\n");
break;
case GL_RGBA16_SNORM:
printf("PTB-INFO: Will use 15 bits per color component signed integer framebuffer for stimulus post-processing (if any).\n");
break;
case GL_RGBA_FLOAT16_APPLE:
printf("PTB-INFO: Will use 16 bits per color component floating point framebuffer for stimulus post-processing (if any).\n");
break;
case GL_RGBA_FLOAT32_APPLE:
printf("PTB-INFO: Will use 32 bits per color component floating point framebuffer for stimulus post-processing (if any).\n");
break;
}
}
// Multisampling requested? Or panel-fitter active?
if ((multiSample > 0) || (imagingmode & kPsychNeedGPUPanelFitter)) {
// Multisampling or panel-fitting requested. Need to find out if we are an intermediate multisample-resolve / rescaler buffer
// or if this is already the final destination and we can resolve and/or scale-blit directly into system framebuffer/
// into finalizedFBO's:
// The target of the drawBufferFBO's is already the final FB if not processing is needed. This is the case
// if all of the following holds:
// a) No image processing requested.
// b) No stereo mode active, or separate streams for stereo, so no need for any kind of stereo compositing or merging.
// c) No output conversion / final formatting needed.
targetisfinalFB = ( !needimageprocessing && ((windowRecord->stereomode == kPsychMonoscopic) || needseparatestreams) && !needoutputconversion ) ? TRUE : FALSE;
if (!targetisfinalFB) {
// Yes. Setup real inputBuffers as multisample-resolve / scaler targets:
if (!PsychCreateFBO(&(windowRecord->fboTable[fbocount]), fboInternalFormat, FALSE, winwidth, winheight, 0, 0)) {
// Failed!
PsychErrorExitMsg(PsychError_system, "Imaging Pipeline setup: Could not setup stage 1 inputBufferFBO of imaging pipeline.");
}
// Assign this FBO as inputBufferFBO for left-eye or mono channel:
windowRecord->inputBufferFBO[0] = fbocount;
fbocount++;
}
else {
// Nothing further to do! Just set us as final framebuffer:
windowRecord->inputBufferFBO[0] = windowRecord->finalizedFBO[0];
}
// If we are in stereo mode, we'll need a 2nd buffer for the right-eye channel:
if (windowRecord->stereomode > 0) {
if (!targetisfinalFB) {
if (!PsychCreateFBO(&(windowRecord->fboTable[fbocount]), fboInternalFormat, FALSE, winwidth, winheight, 0, 0)) {
// Failed!
PsychErrorExitMsg(PsychError_system, "Imaging Pipeline setup: Could not setup stage 1 inputBufferFBO of imaging pipeline.");
}
// Assign this FBO as drawBuffer for right-eye channel:
windowRecord->inputBufferFBO[1] = fbocount;
fbocount++;
}
else {
// Nothing further to do! Just set us as final framebuffer:
windowRecord->inputBufferFBO[1] = windowRecord->finalizedFBO[1];
}
}
}
else {
// No. Setup pass-through inputBuffers that do nothing: The "pointers" just point to / replicate the
// assignment of the drawBufferFBOs so this is a zero-copy op:
windowRecord->inputBufferFBO[0] = windowRecord->drawBufferFBO[0];
windowRecord->inputBufferFBO[1] = windowRecord->drawBufferFBO[1];
}
// Do we need 2nd stage FBOs? We need them as targets for the processed data if support for misc image processing ops is requested.
if (needimageprocessing) {
// Need real FBO's as targets for image processing:
// Define dimensions of 2nd stage FBO:
winwidth=(int)PsychGetWidthFromRect(windowRecord->rect);
winheight=(int)PsychGetHeightFromRect(windowRecord->rect);
// Adapt it for some stereo modes:
if (windowRecord->specialflags & kPsychHalfWidthWindow) {
// Special case for stereo: Only half the real window width:
winwidth = winwidth / 2;
}
if (windowRecord->specialflags & kPsychTwiceWidthWindow) {
// Special case: Twice the real window width:
winwidth = winwidth * 2;
}
if (windowRecord->specialflags & kPsychTripleWidthWindow) {
// Special case: Three times the real window width:
winwidth = winwidth * 3;
}
if (windowRecord->specialflags & kPsychHalfHeightWindow) {
// Special case for stereo: Only half the real window height:
winheight = winheight / 2;
}
// Is the target of imageprocessing (our processedDrawBufferFBO) the final destination? This is true if there is no further need
// for more rendering passes in later processing stages and we don't do any processing here with more than 2 rendering passes. In that
// case we can directly output to the finalizedFBO without need for one more intermediate buffer -- faster!
// In all other cases, we'll need an additional buffer. We also exclude quad-buffered stereo, because the image processing blit chains
// cannot switch between left- and right backbuffer of the system framebuffer...
targetisfinalFB = ( !(imagingmode & kPsychNeedMultiPass) && (windowRecord->stereomode == kPsychMonoscopic) && !needoutputconversion ) ? TRUE : FALSE;
if (!targetisfinalFB) {
// These FBO's don't need z- or stencil buffers anymore:
if (!PsychCreateFBO(&(windowRecord->fboTable[fbocount]), fboInternalFormat, FALSE, winwidth, winheight, 0, 0)) {
// Failed!
PsychErrorExitMsg(PsychError_system, "Imaging Pipeline setup: Could not setup stage 2 of imaging pipeline.");
}
// Assign this FBO as processedDrawBuffer for left-eye or mono channel:
windowRecord->processedDrawBufferFBO[0] = fbocount;
fbocount++;
}
else {
// Can assign final destination:
windowRecord->processedDrawBufferFBO[0] = windowRecord->finalizedFBO[0];
}
// If we are in stereo mode, we'll need a 2nd buffer for the right-eye channel:
if (windowRecord->stereomode > 0) {
if (!targetisfinalFB) {
// These FBO's don't need z- or stencil buffers anymore:
if (!PsychCreateFBO(&(windowRecord->fboTable[fbocount]), fboInternalFormat, FALSE, winwidth, winheight, 0, 0)) {
// Failed!
PsychErrorExitMsg(PsychError_system, "Imaging Pipeline setup: Could not setup stage 2 of imaging pipeline.");
}
// Assign this FBO as processedDrawBuffer for right-eye channel:
windowRecord->processedDrawBufferFBO[1] = fbocount;
fbocount++;
}
else {
// Can assign final destination:
windowRecord->processedDrawBufferFBO[1] = windowRecord->finalizedFBO[1];
}
}
else {
// Mono mode: No right-eye buffer:
windowRecord->processedDrawBufferFBO[1] = -1;
}
// Allocate a bounce-buffer as well if multi-pass rendering is requested:
if (imagingmode & kPsychNeedDualPass || imagingmode & kPsychNeedMultiPass) {
if (!PsychCreateFBO(&(windowRecord->fboTable[fbocount]), fboInternalFormat, FALSE, winwidth, winheight, 0, 0)) {
// Failed!
PsychErrorExitMsg(PsychError_system, "Imaging Pipeline setup: Could not setup stage 2 of imaging pipeline.");
}
// Assign this FBO as processedDrawBuffer for bounce buffer ops in multi-pass rendering:
windowRecord->processedDrawBufferFBO[2] = fbocount;
fbocount++;
}
else {
// No need for bounce-buffers, only single-pass processing requested.
windowRecord->processedDrawBufferFBO[2] = -1;
}
}
else {
// No image processing: Set 2nd stage FBO's to 1st stage FBO's:
windowRecord->processedDrawBufferFBO[0] = windowRecord->inputBufferFBO[0];
windowRecord->processedDrawBufferFBO[1] = windowRecord->inputBufferFBO[1];
windowRecord->processedDrawBufferFBO[2] = -1;
}
// Stage 2 ready. Any need for real merged FBO's? We need a merged FBO if we are in stereo mode
// and in need to merge output from the two views and to postprocess that output. In all other
// cases there's no need for real merged FBO's and we do just a "pass-through" assignment.
if ((windowRecord->stereomode > 0) && (!needseparatestreams) && (needoutputconversion)) {
// Need real FBO's as targets for merger output.
// Define dimensions of 3rd stage FBO:
winwidth=(int)PsychGetWidthFromRect(windowRecord->rect);
winheight=(int)PsychGetHeightFromRect(windowRecord->rect);
// Must not take half width and half height flags into account,
// but need to make sure we retain info in a double-width buffer
// until we reach the final system framebuffer or final output fbo:
if (windowRecord->specialflags & kPsychTwiceWidthWindow) {
// Special case: Twice the real window width:
winwidth = winwidth * 2;
}
if (windowRecord->specialflags & kPsychTripleWidthWindow) {
// Special case: Three times the real window width:
winwidth = winwidth * 3;
}
// These FBO's don't need z- or stencil buffers anymore:
if (!PsychCreateFBO(&(windowRecord->fboTable[fbocount]), fboInternalFormat, FALSE, winwidth, winheight, 0, 0)) {
// Failed!
PsychErrorExitMsg(PsychError_system, "Imaging Pipeline setup: Could not setup stage 3 of imaging pipeline.");
}
// Assign this FBO for left-eye and right-eye channel: The FBO is shared accross channels...
windowRecord->preConversionFBO[0] = fbocount;
windowRecord->preConversionFBO[1] = fbocount;
fbocount++;
// Request bounce buffer:
windowRecord->preConversionFBO[2] = -1000;
}
else {
if ((windowRecord->stereomode > 0) && (!needseparatestreams)) {
// Need to merge two streams, but don't need any output conversion on them. We
// don't need an extra FBO for the merge results! We just write our merge results
// into whatever the final framebuffer is - Could be another FBO if framebuffer
// snapshotting is requested, but most likely its the pseudo-FBO of the system
// backbuffer. Anyway, the proper ones are stored in finalizedFBO[]:
windowRecord->preConversionFBO[0] = windowRecord->finalizedFBO[0];
windowRecord->preConversionFBO[1] = windowRecord->finalizedFBO[1];
// Request bounce buffer:
windowRecord->preConversionFBO[2] = -1000;
}
else {
// No merge operation needed. Do we need output conversion?
if (needoutputconversion) {
// Output conversion needed. Set input for this stage to output of the
// image processing.
windowRecord->preConversionFBO[0] = windowRecord->processedDrawBufferFBO[0];
windowRecord->preConversionFBO[1] = windowRecord->processedDrawBufferFBO[1];
// Request bounce buffer:
windowRecord->preConversionFBO[2] = -1000;
}
else {
// No merge and no output conversion needed. In that case, PsychPreFlipOperations()
// will behave as if output conversion is requested, but with the identity blit chain,
// and merge stage is skipped, so we need to set the preConversionFBO's as if conversion
// is done.
windowRecord->preConversionFBO[0] = windowRecord->processedDrawBufferFBO[0];
windowRecord->preConversionFBO[1] = windowRecord->processedDrawBufferFBO[1];
// No bounce buffer needed:
windowRecord->preConversionFBO[2] = -1;
}
}
}
// Do we need a bounce buffer for merging and/or conversion?
if (windowRecord->preConversionFBO[2] == -1000) {
// Yes. We can reuse/share the bounce buffer of the image processing stage if
// one exists and is of suitable size i.e. we're not in dual-view stereo - in
// that case all buffers are of same size.
if ((windowRecord->processedDrawBufferFBO[2]!=-1) &&
!(windowRecord->stereomode==kPsychFreeFusionStereo || windowRecord->stereomode==kPsychFreeCrossFusionStereo)) {
// Stage 1 bounce buffer is suitable for sharing, assign it:
windowRecord->preConversionFBO[2] = windowRecord->processedDrawBufferFBO[2];
}
else {
// We need a new, private bounce-buffer:
if (!PsychCreateFBO(&(windowRecord->fboTable[fbocount]), fboInternalFormat, FALSE, winwidth, winheight, 0, 0)) {
// Failed!
PsychErrorExitMsg(PsychError_system, "Imaging Pipeline setup: Could not setup stage 3 of imaging pipeline [1st bounce buffer].");
}
windowRecord->preConversionFBO[2] = fbocount;
fbocount++;
}
// In any case, we need a new private 2nd bounce buffer for the special case of the final processing chain:
if (!PsychCreateFBO(&(windowRecord->fboTable[fbocount]), fboInternalFormat, FALSE, winwidth, winheight, 0, 0)) {
// Failed!
PsychErrorExitMsg(PsychError_system, "Imaging Pipeline setup: Could not setup stage 3 of imaging pipeline [2nd bounce buffer].");
}
windowRecord->preConversionFBO[3] = fbocount;
fbocount++;
}
// If dualwindow output is requested and preConversionFBO[1] isn't assigned yet, or is the system fb,
// then we set it to the same FBO as preConversionFBO[0], so the image data of our one single image
// buffer is distributed to both output pipes for output conversion and display:
if ((imagingmode & kPsychNeedDualWindowOutput) && (windowRecord->preConversionFBO[1] <= 0)) {
windowRecord->preConversionFBO[1] = windowRecord->preConversionFBO[0];
}
// Do we need FBO backed finalizedFBO's, because dual stream / separate stream stereo is requested,
// or userspace requests it via imagingmode flag?
if (windowRecord->stereomode == kPsychDualStreamStereo || imagingmode & kPsychNeedFinalizedFBOSinks) {
// Yes. Check if we can share storage with earlier stages and save memory and processing overhead.
// Any processing on the drawBuffer content for MSAA, panelfitter or post-processing?
if (!needoutputconversion &&
(windowRecord->preConversionFBO[0] == windowRecord->drawBufferFBO[0]) &&
(windowRecord->stereomode == 0 || windowRecord->preConversionFBO[1] == windowRecord->drawBufferFBO[1])) {
// No processing whatsoever after userspace drawing of stimulus into drawBufferFBO's. This means we
// can directly hook our finalizedFBO's sinks into the original source drawBufferFBO's and thereby
// to their OpenGL FBO's as already allocated & setup above in stage 1 setup:
windowRecord->finalizedFBO[0] = windowRecord->drawBufferFBO[0];
windowRecord->finalizedFBO[1] = (windowRecord->drawBufferFBO[1] >= 0) ? windowRecord->drawBufferFBO[1] : windowRecord->finalizedFBO[1];
// Disable MSAA flag which signals the sink should provide or expect MSAA textures, as no MSAA used:
imagingmode &= ~kPsychSinkIsMSAACapable;
if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: No image processing needed. Enabling zero-copy redirected output mode.\n");
}
else {
// Some processing would happen. If it would just be a MSAA resolve from a MSAA texture, but no panel fitting,
// and our external sink is capable of taking unresolved MSAA textures as input, then we can skip the resolve
// step and again directly pass the unprocessed drawBufferFBO's:
if ((windowRecord->inputBufferFBO[0] == windowRecord->finalizedFBO[0]) &&
(windowRecord->stereomode == 0 || windowRecord->inputBufferFBO[1] == windowRecord->finalizedFBO[1]) &&
!(imagingmode & kPsychNeedGPUPanelFitter) &&
((multiSample <= 0) ||
((imagingmode & kPsychSinkIsMSAACapable) && (windowRecord->fboTable[windowRecord->drawBufferFBO[0]]->textarget == GL_TEXTURE_2D_MULTISAMPLE)))) {
// inputBufferFBO would be last buffer stage in pipeline, receiving the final output
// image, so the only processing that could happen from drawBuffer to finalizedFBO is
// MSAA resolve or active GPU panel fitting. With GPU panel fitting excluded, only MSAA
// resolve to a single-sample texture would be needed as processing step. If userspace
// signals via kPsychSinkIsMSAACapable that the final recipient of our output images is
// able to deal with multisample textures as input itself (or even provides them) and
// we already have such a multisample texture allocated, then we can skip this one and
// only processing step and again shortcut our finalizedFBO's directly to the virtual
// framebuffer aka drawBufferFBO's and thereby to their OpenGL FBO's as already allocated
// and setup above in stage 1 setup:
windowRecord->finalizedFBO[0] = windowRecord->drawBufferFBO[0];
windowRecord->finalizedFBO[1] = (windowRecord->drawBufferFBO[1] >= 0) ? windowRecord->drawBufferFBO[1] : windowRecord->finalizedFBO[1];
// Disable MSAA flag which signals the sink should provide or expect MSAA textures if no MSAA used:
if (multiSample <= 0)
imagingmode &= ~kPsychSinkIsMSAACapable;
if (PsychPrefStateGet_Verbosity() > 2)
printf("PTB-INFO: %s image processing needed. Enabling zero-copy redirected output mode.\n", (imagingmode & kPsychSinkIsMSAACapable) ? "Only external MSAA" : "No");
}
else {
// No luck. We need to allocate and setup our own PsychFBO's with attached OpenGL FBO's
// in our current fboTable slots, so final output gets routed into our FBO's:
int winwidth, winheight;
int texflags = 1; // Use GL_TEXTURE_2D non-power-of-two textures for backing store.
// Should and can we allocate a multisample texture?
if ((windowRecord->inputBufferFBO[0] == windowRecord->finalizedFBO[0]) &&
(windowRecord->stereomode == 0 || windowRecord->inputBufferFBO[1] == windowRecord->finalizedFBO[1]) &&
(multiSample > 0) && (imagingmode & kPsychSinkIsMSAACapable) &&
(windowRecord->fboTable[windowRecord->drawBufferFBO[0]]->textarget == GL_TEXTURE_2D_MULTISAMPLE)) {
texflags |= 2; // Request a GL_TEXTURE_2D_MULTISAMPLE
}
else {
// MSAA texture not possible - Operate single-sampled:
imagingmode &= ~kPsychSinkIsMSAACapable;
}
if (PsychPrefStateGet_Verbosity() > 2)
printf("PTB-INFO: Full processing %sneeded for redirected output mode.\n", (texflags & 2) ? "with external MSAA " : ((multiSample > 0) ? "with internal MSAA " : ""));
// Delete and recreate finalizedFBO[0] with our new backingstore:
winwidth = windowRecord->fboTable[windowRecord->finalizedFBO[0]]->width;
winheight = windowRecord->fboTable[windowRecord->finalizedFBO[0]]->height;
PsychDeleteFBO(windowRecord->fboTable[windowRecord->finalizedFBO[0]]);
if (!PsychCreateFBO(&(windowRecord->fboTable[windowRecord->finalizedFBO[0]]), finalizedFBOFormat, FALSE, winwidth, winheight, (texflags & 2) ? multiSample : 0, texflags)) {
PsychErrorExitMsg(PsychError_system, "Imaging Pipeline setup: Could not setup stage 4 of imaging pipeline [finalizedFBO[0] backing buffers for external sink].");
}
// Are we supposed to use externally injected colorbuffer textures?
if (imagingmode & kPsychUseExternalSinkTextures) {
if (PsychPrefStateGet_Verbosity() > 2)
printf("PTB-INFO: Using external textures as sinks for redirected output mode.\n");
}
if (windowRecord->stereomode > 0) {
// Delete and recreate finalizedFBO[1] with our new backingstore:
winwidth = windowRecord->fboTable[windowRecord->finalizedFBO[1]]->width;
winheight = windowRecord->fboTable[windowRecord->finalizedFBO[1]]->height;
PsychDeleteFBO(windowRecord->fboTable[windowRecord->finalizedFBO[1]]);
if (!PsychCreateFBO(&(windowRecord->fboTable[windowRecord->finalizedFBO[1]]), finalizedFBOFormat, FALSE, winwidth, winheight, (texflags & 2) ? multiSample : 0, texflags)) {
PsychErrorExitMsg(PsychError_system, "Imaging Pipeline setup: Could not setup stage 4 of imaging pipeline [finalizedFBO[1] backing buffers for external sink].");
}
}
}
}
// Can we use the drawBufferFBO's as finalizedFBO's?
if (windowRecord->finalizedFBO[0] == windowRecord->drawBufferFBO[0]) {
// Yes. At this point the PsychFBO's we "inherited"/share with the
// drawBufferFBO's are already fully set up with depth/stencil/colorbuffer
// textures attached to a "framebuffer complete" OpenGL FBO.
// Short-circuit the inputBufferFBO's to the drawBufferFBO's, so they are zero-copies of
// them. This so the imaging pipeline processing will skip the actual MSAA resolve.
windowRecord->inputBufferFBO[0] = windowRecord->drawBufferFBO[0];
windowRecord->inputBufferFBO[1] = windowRecord->drawBufferFBO[1];
// Short-circuit the preConversionFBO's to the finalizedFBO's, so they are zero-copies of
// them. This so the final output formatting will skip a redundant/wrong identity blit
// from preConversionFBO -> finalizedFBO:
windowRecord->preConversionFBO[0] = windowRecord->finalizedFBO[0];
windowRecord->preConversionFBO[1] = windowRecord->finalizedFBO[1];
// Are we supposed to use externally injected colorbuffer textures?
if (imagingmode & kPsychUseExternalSinkTextures) {
if (PsychPrefStateGet_Verbosity() > 2)
printf("PTB-INFO: Using external textures as sinks for redirected output mode.\n");
}
// Check if the currently attached color buffer texture is of suitable format.
// If it is a multisampled 2D texture then the format is correct and compatible with
// MSAA enabled and an external sink that can handle multisample textures. Otherwise
// we do not use MSAA and the texture must be a GL_TEXTURE_2D non-pot-texture for export
// to external consumers. If none of this holds then our texture is of incompatible format
// and we need to recreate buffers of suitable format:
if ((windowRecord->fboTable[windowRecord->drawBufferFBO[0]]->textarget != GL_TEXTURE_2D_MULTISAMPLE) &&
(windowRecord->fboTable[windowRecord->drawBufferFBO[0]]->textarget != GL_TEXTURE_2D)) {
// Unsuitable format. Need to rebuild from scratch:
GLenum format;
int winwidth, winheight;
int texflags = 1; // Use GL_TEXTURE_2D non-power-of-two textures for backing store.
// Should and can we allocate a multisample texture?
if ((multiSample > 0) && (imagingmode & kPsychSinkIsMSAACapable)) {
texflags |= 2; // Request a GL_TEXTURE_2D_MULTISAMPLE
}
else {
// MSAA texture not possible - Operate single-sampled:
imagingmode &= ~kPsychSinkIsMSAACapable;
}
if (PsychPrefStateGet_Verbosity() > 3)
printf("PTB-INFO: Recreating 2D npot-texture redirection surfaces %sfor redirected output mode.\n", (texflags & 2) ? "with external MSAA " : "without MSAA anti-aliasing ");
// Delete and recreate finalizedFBO[0] with our new backingstore:
winwidth = windowRecord->fboTable[windowRecord->finalizedFBO[0]]->width;
winheight = windowRecord->fboTable[windowRecord->finalizedFBO[0]]->height;
format = windowRecord->fboTable[windowRecord->finalizedFBO[0]]->format;
PsychDeleteFBO(windowRecord->fboTable[windowRecord->finalizedFBO[0]]);
if (!PsychCreateFBO(&(windowRecord->fboTable[windowRecord->finalizedFBO[0]]), format, needzbuffer, winwidth, winheight, (texflags & 2) ? multiSample : 0, texflags)) {
PsychErrorExitMsg(PsychError_system, "Imaging Pipeline setup: Could not re-setup stage 1 of imaging pipeline [draw/finalizedFBO[0] backing buffers for external sink].");
}
if (windowRecord->stereomode > 0) {
// Delete and recreate finalizedFBO[1] with our new backingstore:
winwidth = windowRecord->fboTable[windowRecord->finalizedFBO[1]]->width;
winheight = windowRecord->fboTable[windowRecord->finalizedFBO[1]]->height;
format = windowRecord->fboTable[windowRecord->finalizedFBO[1]]->format;
PsychDeleteFBO(windowRecord->fboTable[windowRecord->finalizedFBO[1]]);
if (!PsychCreateFBO(&(windowRecord->fboTable[windowRecord->finalizedFBO[1]]), format, needzbuffer, winwidth, winheight, (texflags & 2) ? multiSample : 0, texflags)) {
PsychErrorExitMsg(PsychError_system, "Imaging Pipeline setup: Could not re-setup stage 1 of imaging pipeline [draw/finalizedFBO[1] backing buffers for external sink].");
}
}
}
}
} // Handling of dual-stream stereo / finalizedFBO's with enforced FBO buffers, e.g., for external sinks.
// Setup imaging mode flags:
newimagingmode = (needseparatestreams) ? kPsychNeedSeparateStreams : 0;
if (!needseparatestreams && (windowRecord->stereomode > 0)) newimagingmode |= kPsychNeedStereoMergeOp;
if (needfastbackingstore) newimagingmode |= kPsychNeedFastBackingStore;
if (needoutputconversion) newimagingmode |= kPsychNeedOutputConversion;
if (needimageprocessing) newimagingmode |= kPsychNeedImageProcessing;
if (imagingmode & kPsychNeed32BPCFloat) {
newimagingmode |= kPsychNeed32BPCFloat;
}
else if (imagingmode & kPsychNeed16BPCFloat) {
newimagingmode |= kPsychNeed16BPCFloat;
}
else if (imagingmode & kPsychNeed16BPCFixed) {
newimagingmode |= kPsychNeed16BPCFixed;
}
if (imagingmode & kPsychNeedDualWindowOutput) newimagingmode |= kPsychNeedDualWindowOutput;
if (imagingmode & kPsychNeedGPUPanelFitter) newimagingmode |= kPsychNeedGPUPanelFitter;
if (imagingmode & kPsychNeedClientRectNoFitter) newimagingmode |= kPsychNeedClientRectNoFitter;
if ((imagingmode & kPsychNeedOtherStreamInput) && (windowRecord->stereomode > 0)) newimagingmode |= kPsychNeedOtherStreamInput;
// Signal true finalizedFBO state and caps:
if ((imagingmode & kPsychNeedFinalizedFBOSinks) || (windowRecord->stereomode == kPsychDualStreamStereo)) newimagingmode |= kPsychNeedFinalizedFBOSinks;
if ((newimagingmode & kPsychNeedFinalizedFBOSinks) && (imagingmode & kPsychUseExternalSinkTextures)) newimagingmode |= kPsychUseExternalSinkTextures;
// kPsychSinkIsMSAACapable will be set if we provide or expect MSAA GL_TEXTURE_2D_MULTISAMPLE textures to/from the sink.
// If no MSAA is used, or if we use it for drawing but have to resolve to single-sample textures earlier for some reason,
// e.g., due to image processing, or panel fitting, or lack of support, then the flag gets cleared, so the sink knows to
// provide or expect single-sample standard GL_TEXTURE_2D npot textures:
if ((newimagingmode & kPsychNeedFinalizedFBOSinks) && (imagingmode & kPsychSinkIsMSAACapable)) newimagingmode |= kPsychSinkIsMSAACapable;
// Is use of sRGB rendering and blending on suitable target FBO color buffers requested?
if (imagingmode & kPsychEnableSRGBRendering) {
// Yes, supported by GPU?
if (glewIsSupported("GL_EXT_framebuffer_sRGB") || glewIsSupported("GL_ARB_framebuffer_sRGB")) {
// Yes. Here we go:
if (PsychPrefStateGet_Verbosity() > 2) printf("PTB-INFO: Enabling sRGB rendering (= gamma ~2.2) into suitable framebuffers if supported.\n");
glEnable(GL_FRAMEBUFFER_SRGB);
// Mark this, so secondary OpenGL contexts, e.g., userspace rendering context can set themselves up as well:
newimagingmode |= kPsychEnableSRGBRendering;
}
else {
// Nope, run without it, but warn users about potential unexpected results:
if (PsychPrefStateGet_Verbosity() > 1) printf("PTB-WARNING: Enable of sRGB rendering requested, but this is unsupported by your GPU + driver combo. Ignored.\n");
}
}
// Marked as HDR window? This will use higher texture precision by default, and perform color value / EOTF mapping into HDR range, as appropriate:
if (imagingmode & kPsychNeedHDRWindow) {
newimagingmode |= kPsychNeedHDRWindow;
if (PsychPrefStateGet_Verbosity() > 2)
printf("PTB-INFO: This is a HDR display window: Applying higher precision and suitable range scaling for textures and movie video frames.\n");
}
// Set new final imaging mode and fbocount:
windowRecord->imagingMode = newimagingmode;
windowRecord->fboCount = fbocount;
// The pipelines buffers and information flow are configured now...
if (PsychPrefStateGet_Verbosity()>4) {
int i;
printf("PTB-DEBUG: Buffer mappings follow...\n");
printf("fboCount = %i\n", windowRecord->fboCount);
printf("finalizedFBO = %i, %i\n", windowRecord->finalizedFBO[0], windowRecord->finalizedFBO[1]);
printf("preConversionFBO = %i, %i, %i, %i\n", windowRecord->preConversionFBO[0], windowRecord->preConversionFBO[1], windowRecord->preConversionFBO[2], windowRecord->preConversionFBO[3]);
printf("processedDrawBufferFBO = %i %i %i\n", windowRecord->processedDrawBufferFBO[0], windowRecord->processedDrawBufferFBO[1], windowRecord->processedDrawBufferFBO[2]);
printf("inputBufferFBO = %i %i \n", windowRecord->inputBufferFBO[0], windowRecord->inputBufferFBO[1]);
printf("drawBufferFBO = %i %i \n", windowRecord->drawBufferFBO[0], windowRecord->drawBufferFBO[1]);
printf("\n");
printf("fboTable content:\n");
for (i = 0; i < windowRecord->fboCount; i++)
printf("fboTable[%i]: textarget %i : coltexid %i : format %i : MSAA %i : width %i x height %i\n",
i, windowRecord->fboTable[i]->textarget, windowRecord->fboTable[i]->coltexid,
windowRecord->fboTable[i]->format, windowRecord->fboTable[i]->multisample,
windowRecord->fboTable[i]->width, windowRecord->fboTable[i]->height);
printf("-------------------------------------\n\n");
fflush(NULL);
}
// Setup our default chain: This chain is executed if some stage of the imaging pipe is set up according
// to imagingMode, but the corresponding hook-chain is empty or disabled. In that case we need to copy
// the data for that stage from its input buffers to its output buffers via a simple blit operation.
PsychPipelineAddBuiltinFunctionToHook(windowRecord, "IdentityBlitChain", "Builtin:IdentityBlit", INT_MAX, "");
PsychPipelineEnableHook(windowRecord, "IdentityBlitChain");
// Setup for stereo modes that need some merging or other operations:
// Quad-buffered stereo and mono mode don't need these...
if (windowRecord->stereomode > kPsychOpenGLStereo) {
// Merged stereo mode requested.
glsl = 0;
// Which mode?
switch (windowRecord->stereomode) {
// Anaglyph mode?
case kPsychAnaglyphRGStereo:
case kPsychAnaglyphGRStereo:
case kPsychAnaglyphRBStereo:
case kPsychAnaglyphBRStereo:
// These share all code...
// Create anaglyph shader and set proper defaults: These can be changed from the M-File if wanted.
if (PsychPrefStateGet_Verbosity()>4) printf("PTB-INFO: Creating internal anaglyph stereo compositing shader...\n");
glsl = PsychCreateGLSLProgram(anaglyphshadersrc, NULL, NULL);
if (glsl) {
// Bind it:
glUseProgram(glsl);
// Set channel to texture units assignments:
glUniform1i(glGetUniformLocation(glsl, "Image1"), 0);
glUniform1i(glGetUniformLocation(glsl, "Image2"), 1);
// Set per-channel color gains: 0 masks the channel, >0 enables it. The values can be used
// to compensate for differences in the color reproduction of different monitors to reduce
// cross-talk / ghosting:
// Left-eye channel (channel 1):
rg = (float) ((windowRecord->stereomode==kPsychAnaglyphRGStereo || windowRecord->stereomode==kPsychAnaglyphRBStereo) ? 1.0 : 0.0);
gg = (float) ((windowRecord->stereomode==kPsychAnaglyphGRStereo) ? 1.0 : 0.0);
bg = (float) ((windowRecord->stereomode==kPsychAnaglyphBRStereo) ? 1.0 : 0.0);
glUniform3f(glGetUniformLocation(glsl, "Gains1"), rg, gg, bg);
// Right-eye channel (channel 2):
rg = (float) ((windowRecord->stereomode==kPsychAnaglyphGRStereo || windowRecord->stereomode==kPsychAnaglyphBRStereo) ? 1.0 : 0.0);
gg = (float) ((windowRecord->stereomode==kPsychAnaglyphRGStereo) ? 1.0 : 0.0);
bg = (float) ((windowRecord->stereomode==kPsychAnaglyphRBStereo) ? 1.0 : 0.0);
glUniform3f(glGetUniformLocation(glsl, "Gains2"), rg, gg, bg);
// Define default weights for RGB -> Luminance conversion: We default to the standardized NTSC color weights.
glUniform3f(glGetUniformLocation(glsl, "ColorToGrayWeights"), 0.299f, 0.587f, 0.114f);
// Define background bias color to add: Normally zero for standard anaglyph:
glUniform3f(glGetUniformLocation(glsl, "ChannelBias"), 0.0, 0.0, 0.0);
// Unbind it, its ready!
glUseProgram(0);
if (glsl) {
// Add shader to processing chain:
PsychPipelineAddShaderToHook(windowRecord, "StereoCompositingBlit", "StereoCompositingShaderAnaglyph", INT_MAX, glsl, "", 0) ;
// Enable stereo compositor:
PsychPipelineEnableHook(windowRecord, "StereoCompositingBlit");
}
}
else {
PsychErrorExitMsg(PsychError_user, "PTB-ERROR: Failed to create anaglyph stereo processing shader -- Anaglyph stereo won't work!\n");
}
break;
case kPsychFreeFusionStereo:
case kPsychFreeCrossFusionStereo:
if (PsychPrefStateGet_Verbosity()>4) printf("PTB-INFO: Creating internal dualview stereo compositing shader...\n");
glsl = PsychCreateGLSLProgram(passthroughshadersrc, NULL, NULL);
if (glsl) {
// Bind it:
glUseProgram(glsl);
// Set channel to texture units assignments:
glUniform1i(glGetUniformLocation(glsl, "Image1"), (windowRecord->stereomode == kPsychFreeFusionStereo) ? 0 : 1);
glUseProgram(0);
// Add shader to processing chain:
sprintf(blittercfg, "Builtin:IdentityBlit:Offset:%i:%i", 0, 0);
PsychPipelineAddShaderToHook(windowRecord, "StereoCompositingBlit", "StereoCompositingShaderDualViewLeft", INT_MAX, glsl, blittercfg, 0);
}
else {
PsychErrorExitMsg(PsychError_user, "PTB-ERROR: Failed to create left channel dualview stereo processing shader -- Dualview stereo won't work!\n");
}
glsl = PsychCreateGLSLProgram(passthroughshadersrc, NULL, NULL);
if (glsl) {
// Bind it:
glUseProgram(glsl);
// Set channel to texture units assignments:
glUniform1i(glGetUniformLocation(glsl, "Image1"), (windowRecord->stereomode == kPsychFreeFusionStereo) ? 1 : 0);
glUseProgram(0);
// Add shader to processing chain:
sprintf(blittercfg, "Builtin:IdentityBlit:Offset:%i:%i", (int) PsychGetWidthFromRect(windowRecord->rect)/2, 0);
PsychPipelineAddShaderToHook(windowRecord, "StereoCompositingBlit", "StereoCompositingShaderDualViewRight", INT_MAX, glsl, blittercfg, 0);
}
else {
PsychErrorExitMsg(PsychError_user, "PTB-ERROR: Failed to create right channel dualview stereo processing shader -- Dualview stereo won't work!\n");
}
// Enable stereo compositor:
PsychPipelineEnableHook(windowRecord, "StereoCompositingBlit");
break;
case kPsychCompressedTLBRStereo:
case kPsychCompressedTRBLStereo:
if (PsychPrefStateGet_Verbosity()>4) printf("PTB-INFO: Creating internal vertical split stereo compositing shader...\n");
glsl = PsychCreateGLSLProgram(passthroughshadersrc, NULL, NULL);
if (glsl) {
// Bind it:
glUseProgram(glsl);
// Set channel to texture units assignments:
glUniform1i(glGetUniformLocation(glsl, "Image1"), (windowRecord->stereomode == kPsychCompressedTLBRStereo) ? 0 : 1);
glUseProgram(0);
// Add shader to processing chain:
sprintf(blittercfg, "Builtin:IdentityBlit:Offset:%i:%i:Scaling:%f:%f", 0, 0, 1.0, 0.5);
PsychPipelineAddShaderToHook(windowRecord, "StereoCompositingBlit", "StereoCompositingShaderCompressedTop", INT_MAX, glsl, blittercfg, 0);
}
else {
PsychErrorExitMsg(PsychError_user, "PTB-ERROR: Failed to create left channel dualview stereo processing shader -- Dualview stereo won't work!\n");
}
glsl = PsychCreateGLSLProgram(passthroughshadersrc, NULL, NULL);
if (glsl) {
// Bind it:
glUseProgram(glsl);
// Set channel to texture units assignments:
glUniform1i(glGetUniformLocation(glsl, "Image1"), (windowRecord->stereomode == kPsychCompressedTLBRStereo) ? 1 : 0);
glUseProgram(0);
// Add shader to processing chain:
sprintf(blittercfg, "Builtin:IdentityBlit:Offset:%i:%i:Scaling:%f:%f", 0, (int) PsychGetHeightFromRect(windowRecord->rect)/2, 1.0, 0.5);
PsychPipelineAddShaderToHook(windowRecord, "StereoCompositingBlit", "StereoCompositingShaderCompressedBottom", INT_MAX, glsl, blittercfg, 0);
}
else {
PsychErrorExitMsg(PsychError_user, "PTB-ERROR: Failed to create right channel dualview stereo processing shader -- Dualview stereo won't work!\n");
}
// Enable stereo compositor:
PsychPipelineEnableHook(windowRecord, "StereoCompositingBlit");
break;
case kPsychOpenGLStereo:
case kPsychFrameSequentialStereo:
// Nothing to do for now: Setup of blue-line syncing is done in SCREENOpenWindow.c, because it also
// applies to non-imaging mode...
break;
case kPsychDualWindowStereo:
// Nothing to do for now.
break;
case kPsychDualStreamStereo:
// Nothing to do for now.
break;
default:
PsychErrorExitMsg(PsychError_internal, "Unknown stereo mode encountered! FIX SCREENOpenWindow.c to catch this at the appropriate place!\n");
}
}
//PsychPipelineAddBuiltinFunctionToHook(windowRecord, "FinalOutputFormattingBlit", "Builtin:IdentityBlit", INT_MAX, "");
//PsychPipelineEnableHook(windowRecord, "FinalOutputFormattingBlit");
//PsychPipelineAddBuiltinFunctionToHook(windowRecord, "StereoLeftCompositingBlit", "Builtin:IdentityBlit", INT_MAX, "");
//PsychPipelineAddBuiltinFunctionToHook(windowRecord, "StereoLeftCompositingBlit", "Builtin:FlipFBOs", INT_MAX, "");
//PsychPipelineAddBuiltinFunctionToHook(windowRecord, "StereoLeftCompositingBlit", "Builtin:IdentityBlit", INT_MAX, "");
//PsychPipelineEnableHook(windowRecord, "StereoLeftCompositingBlit");
// Multisampling requested? If so, we need to enable it:
if (multiSample > 0) {
glEnable(GL_MULTISAMPLE);
windowRecord->multiSample = multiSample;
}
// Perform a safe reset of current drawing target. This is a warm-start of PTB's drawing
// engine, so the next drawing command will trigger binding the proper FBO of our pipeline.
// Before this point (==OpenWindow time), all drawing was directly directed to the system
// framebuffer - important for all the timing tests and calibrations to work correctly.
PsychSetDrawingTarget((PsychWindowRecordType*) 0x1);
// Well done.
return;
}
/* PsychCreateGLSLProgram()
* Try to create GLSL shader from source strings and return handle to new shader.
* Returns the shader handle if it worked, 0 otherwise.
*
* fragmentsrc - Source string for fragment shader. NULL if none needed.
* vertexsrc - Source string for vertex shader. NULL if none needed.
* primitivesrc - Source string for primitive shader. NULL if none needed.
*
*/
GLuint PsychCreateGLSLProgram(const char* fragmentsrc, const char* vertexsrc, const char* primitivesrc)
{
GLuint glsl = 0;
GLuint shader;
GLint status;
char errtxt[10000];
(void) primitivesrc;
// Reset error state:
while (glGetError());
// Supported at all on this hardware?
if (!glewIsSupported("GL_ARB_shader_objects") || !glewIsSupported("GL_ARB_shading_language_100")) {
if (PsychPrefStateGet_Verbosity() > 0) printf("PTB-ERROR: Your graphics hardware does not support GLSL fragment shaders! Use of imaging pipeline with current settings impossible!\n");
return(0);
}
// Create GLSL program object:
glsl = glCreateProgram();
// Fragment shader wanted?
if (fragmentsrc) {
if (PsychPrefStateGet_Verbosity()>4) printf("PTB-INFO: Creating the following fragment shader, GLSL source code follows:\n\n%s\n\n", fragmentsrc);
// Supported on this hardware?
if (!glewIsSupported("GL_ARB_fragment_shader")) {
if (PsychPrefStateGet_Verbosity() > 0) printf("PTB-ERROR: Your graphics hardware does not support GLSL fragment shaders! Use of imaging pipeline with current settings impossible!\n");
return(0);
}
// Create shader object:
shader = glCreateShader(GL_FRAGMENT_SHADER);
// Feed it with GLSL source code:
glShaderSource(shader, 1, (const char**) &fragmentsrc, NULL);
// Compile shader:
glCompileShader(shader);
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (status != GL_TRUE) {
if (PsychPrefStateGet_Verbosity() > 0) {
printf("PTB-ERROR: Shader compilation for builtin fragment shader failed:\n");
glGetShaderInfoLog(shader, 9999, NULL, (GLchar*) &errtxt);
printf("%s\n\n", errtxt);
}
glDeleteShader(shader);
glDeleteProgram(glsl);
// Failed!
while (glGetError());
return(0);
}
// Attach it to program object:
glAttachShader(glsl, shader);
}
// Vertex shader wanted?
if (vertexsrc) {
if (PsychPrefStateGet_Verbosity()>4) printf("PTB-INFO: Creating the following vertex shader, GLSL source code follows:\n\n%s\n\n", vertexsrc);
// Supported on this hardware?
if (!glewIsSupported("GL_ARB_vertex_shader")) {
if (PsychPrefStateGet_Verbosity() > 0) printf("PTB-ERROR: Your graphics hardware does not support GLSL vertex shaders! Use of imaging pipeline with current settings impossible!\n");
return(0);
}
// Create shader object:
shader = glCreateShader(GL_VERTEX_SHADER);
// Feed it with GLSL source code:
glShaderSource(shader, 1, (const char**) &vertexsrc, NULL);
// Compile shader:
glCompileShader(shader);
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (status != GL_TRUE) {
if (PsychPrefStateGet_Verbosity() > 0) {
printf("PTB-ERROR: Shader compilation for builtin vertex shader failed:\n");
glGetShaderInfoLog(shader, 9999, NULL, (GLchar*) &errtxt);
printf("%s\n\n", errtxt);
}
glDeleteShader(shader);
glDeleteProgram(glsl);
// Failed!
while (glGetError());
return(0);
}
// Attach it to program object:
glAttachShader(glsl, shader);
}
// Link into final program object:
glLinkProgram(glsl);
// Check link status:
glGetProgramiv(glsl, GL_LINK_STATUS, &status);
if (status != GL_TRUE) {
if (PsychPrefStateGet_Verbosity() > 0) {
printf("PTB-ERROR: Shader link operation for builtin glsl program failed:\n");
glGetProgramInfoLog(glsl, 9999, NULL, (GLchar*) &errtxt);
printf("Error output follows:\n\n%s\n\n", errtxt);
}
glDeleteProgram(glsl);
// Failed!
while (glGetError());
return(0);
}
while (glGetError());
// Return new GLSL program object handle:
return(glsl);
}
static psych_bool PsychUnshareFinalizedFBOIfNeeded(PsychWindowRecordType *windowRecord, int viewid, GLenum formatSpec, int width, int height)
{
if (windowRecord->finalizedFBO[viewid] == windowRecord->drawBufferFBO[viewid]) {
// Yes. That means our interop image and user requested framebuffer are
// deemed compatible wrt. size and MSAA requirements, and that there is
// no need for any post-processing by the imaging pipeline, iow. this is
// a zero-copy opportunity, where usercode renders and the result can go
// directly to the external consumer.
// One catch though: If the image format - ie. color precision - of the
// to be imported interop image would be lower than what the users script
// requested for the drawBufferFBO, we'd get a silent degradation of
// precision, with possible bad results, e.g., fp32 -> RGB10A2, with loss
// of alpha precision from float to only 4 discrete levels, truncation of
// all color values outside of unorm range, and significant stimulus
// precision loss!
//
// So lets check if the imported format meets or exceeds the current
// precision and range requirements of the drawBufferFBO. If not, then
// we'd need to split up into 2 separate buffers at a slight performance
// loss due to one extra framebuffer copy.
PsychFBO *dfbo = windowRecord->fboTable[windowRecord->drawBufferFBO[viewid]];
// First we check if there is a format mismatch -> no mismatch, no trouble. (condition line 1)
// Then we check if the format is in the white-list of formats we can handle under suitable conditions. If not -> unshare! (condition line 2)
// Of the formats which are fine in principle, we check for specific problematic format combinations which would cause
// degradation of value range, and/or clamping, and/or alpha-channel loss, and/or precision loss (remaining conditions, one per line),
// and unshare if that is the case:
if (((GLenum) formatSpec != dfbo->format) /* Mismatched formats -> possible problem */ && (
(formatSpec != GL_RGBA8 && formatSpec != GL_SRGB8_ALPHA8 && formatSpec != GL_RGB10_A2 && formatSpec != GL_RGBA16F && formatSpec != GL_RGBA16 && formatSpec != GL_RGBA16_SNORM && formatSpec != GL_RGBA32F) /* white-list of possible-in-principle formats */ ||
( /* Format was in white-list of in-principle-possible formats -> Check if special unshare triggers exist: */
(formatSpec == GL_RGBA8) /* Target 8 bpc unorm, but db has higher precision/range */ ||
(formatSpec == GL_SRGB8_ALPHA8 && !(dfbo->format == GL_RGBA8)) /* Target can do 8 bpc unorm easily. However, db of 10 bpc unorm might be a stretch? Higher than 10 bpc precision is definitely unattainable */ ||
(formatSpec == GL_RGB10_A2) /* Target 10 bpc unorm for color, but alpha channel less than 8 bit precision for alpha blending, for a db of either higher precision or range, or with need for 8 bit alpha */ ||
(formatSpec == GL_RGBA16F && !(dfbo->format == GL_RGBA8 || dfbo->format == GL_RGB10_A2)) /* fp16 can only store linear 11 bpc, but db has higher precision -> would degrade precision */ ||
(formatSpec == GL_RGBA16 && !(dfbo->format == GL_RGBA8 || dfbo->format == GL_RGB10_A2)) /* 16 bpc unorm insufficient for fp32 in range or precision, but also for fp16 and snorm16, as both are signed, but unorm is not */ ||
(formatSpec == GL_RGBA16_SNORM && !(dfbo->format == GL_RGBA8 || dfbo->format == GL_RGB10_A2)) /* 16 bpc snorm can't represent fp32 in range or precision, fp16 for out of [-1;1] interval values, or 16 bpc unorm wrt. precision */ ))
) {
// Future finalizedFBO / interop format is insufficient in range, sign or precision
// to store drawBufferFBO content faithfully. Need to allocate dedicated PsychFBO and
// hook it up to finalizedFBO:
windowRecord->finalizedFBO[viewid] = windowRecord->fboCount;
windowRecord->fboCount++;
// Hook up all other buffers except drawBufferFBO as well, so various copies
// can be skipped in imaging pipeline PreFlipOperations, knowing there's only
// drawBufferFBO -> finalizedFBO:
windowRecord->preConversionFBO[viewid] = windowRecord->finalizedFBO[viewid];
windowRecord->processedDrawBufferFBO[viewid] = windowRecord->finalizedFBO[viewid];
windowRecord->inputBufferFBO[viewid] = windowRecord->finalizedFBO[viewid];
// Now we need to create a new empty PsychFBO, to be filled with life and actual content downstream:
if (!PsychCreateFBO(&(windowRecord->fboTable[windowRecord->finalizedFBO[viewid]]), 0, FALSE, width, height, 0, 0)) {
if (PsychPrefStateGet_Verbosity() > 0)
printf("PTB-ERROR: PsychUnshareFinalizedFBOIfNeeded: Failed to create new empty finalizedFBO backing PsychFBO()! Skipped.\n");
return(FALSE);
}
if (PsychPrefStateGet_Verbosity() > 3)
printf("PTB-DEBUG: PsychUnshareFinalizedFBOIfNeeded: Unsharing drawBufferFBO and finalizedFBO for viewid %i, triggered by format mismatch.\n", viewid);
}
}
return(TRUE);
}
// Create a new GL_TEXTURE_2D npot texture as finalizedFBO color buffer attachment, and back it by external memory imported via interopMemObjectHandle, with rendering optionally synchronized via interopSemaphoreHandle:
psych_bool PsychSetPipelineExportTextureInteropMemory(PsychWindowRecordType *windowRecord, int viewid, void* interopMemObjectHandle, int allocationSize, int formatSpec, int tilingMode, int memoryOffset, int width, int height, void* interopSemaphoreHandle)
{
GLenum glTextureTarget;
int multiSample = windowRecord->multiSample;
GLint drawFBO = 0, readFBO = 0;
char fbodiag[100];
PsychFBO *fbo;
GLenum fborc = GL_FRAMEBUFFER_COMPLETE_EXT;
// If any interop handle that we still have ownership of was previously assigned to this window, then release it:
#if PSYCH_SYSTEM == PSYCH_WINDOWS
if (windowRecord->interopMemObjectHandle)
CloseHandle(windowRecord->interopMemObjectHandle);
if (windowRecord->interopSemaphoreHandle)
CloseHandle(windowRecord->interopSemaphoreHandle);
#endif
#if PSYCH_SYSTEM == PSYCH_LINUX
if (windowRecord->interopMemObjectHandle)
close((int) (size_t) windowRecord->interopMemObjectHandle);
if (windowRecord->interopSemaphoreHandle)
close((int) (size_t) windowRecord->interopSemaphoreHandle);
#endif
// Assign new interopMemObjectHandle early to the window, so it can be released
// in case of an error abort in the following code. Ditto for interopSemaphoreHandle:
windowRecord->interopMemObjectHandle = interopMemObjectHandle;
windowRecord->interopSemaphoreHandle = interopSemaphoreHandle;
if (!(windowRecord->imagingMode & kPsychNeedFinalizedFBOSinks)) {
if (PsychPrefStateGet_Verbosity() > 0) printf("PTB-ERROR: PsychSetPipelineExportTextureInteropMemory: No kPsychNeedFinalizedFBOSinks! Skipped.\n");
return(FALSE);
}
if (windowRecord->imagingMode & kPsychSinkIsMSAACapable) {
if (multiSample == 0) {
if (PsychPrefStateGet_Verbosity() > 0) printf("PTB-ERROR: PsychSetPipelineExportTextureInteropMemory: Tried to setup MSAA interop texture while onscreen window has MSAA disabled! Skipped.\n");
return(FALSE);
}
glTextureTarget = GL_TEXTURE_2D_MULTISAMPLE;
}
else {
if (multiSample > 0) {
if (PsychPrefStateGet_Verbosity() > 3) printf("PTB-DEBUG: PsychSetPipelineExportTextureInteropMemory: Using non-MSAA capable interop texture for onscreen window with MSAA.\n");
}
multiSample = 0;
glTextureTarget = GL_TEXTURE_2D;
}
if (viewid < 0 || viewid > 1) {
if (PsychPrefStateGet_Verbosity() > 0) printf("PTB-ERROR: PsychSetPipelineExportTextureInteropMemory: Tried to setup invalid viewid %i [not 0 or 1]! Skipped.\n", viewid);
return(FALSE);
}
if (viewid > 0 && !(windowRecord->stereomode == kPsychDualStreamStereo)) {
if (PsychPrefStateGet_Verbosity() > 0) printf("PTB-ERROR: PsychSetPipelineExportTextureInteropMemory: Tried to setup right eye buffer in a purely monoscopic configuration! Skipped.\n");
return(FALSE);
}
// Set OpenGL context of window so we can act on its FBO's:
PsychSetGLContext(windowRecord);
PsychTestForGLErrors();
// Are all required OpenGL extensions supported?
if (!glewIsSupported("GL_EXT_memory_object") || !glewIsSupported("GL_EXT_direct_state_access") ||
(!glewIsSupported("GL_EXT_memory_object_fd") && !glewIsSupported("GL_EXT_memory_object_win32"))) {
if (PsychPrefStateGet_Verbosity() > 0)
printf("PTB-ERROR: PsychSetPipelineExportTextureInteropMemory: This OpenGL implementation lacks support for some required OpenGL memory object extensions [%i %i %i].\n",
glewIsSupported("GL_EXT_memory_object"), glewIsSupported("GL_EXT_memory_object_fd"), glewIsSupported("GL_EXT_direct_state_access"));
// Skip abort and continue on Broadcom VideoCore 6 under zink driver.
// Its GL_EXT_direct_state_access lacks some functions, so above check
// fails, but the stuff we need here actually works at least as of Mesa 23:
if (!strstr((char*) glGetString(GL_RENDERER), "zink (V3D 4.2)"))
return(FALSE);
}
// Backup current fbo assignments before we mess with them:
glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &drawFBO);
glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &readFBO);
// Are finalizedFBO and drawBufferFBO using the same backing PsychFBO? If yes,
// and they are incompatible, then unshare them, fail if this fails:
if (!PsychUnshareFinalizedFBOIfNeeded(windowRecord, viewid, formatSpec, width, height))
return(FALSE);
fbo = windowRecord->fboTable[windowRecord->finalizedFBO[viewid]];
// Create memory object for interop memory import:
glCreateMemoryObjectsEXT(1, &fbo->memoryObject);
PsychTestForGLErrors();
// Semaphore handle provided?
if (interopSemaphoreHandle) {
// Yes. Need to create a OpenGL semaphore which we can associate with this handle:
// Are all required semaphore OpenGL extensions supported?
if (!glewIsSupported("GL_EXT_semaphore") || (!glewIsSupported("GL_EXT_semaphore_fd") && !glewIsSupported("GL_EXT_semaphore_win32"))) {
if (PsychPrefStateGet_Verbosity() > 0) printf("PTB-ERROR: PsychSetPipelineExportTextureInteropMemory: This OpenGL implementation lacks support for required semaphore OpenGL extensions! Skipped.\n");
return(FALSE);
}
// Delete old renderCompleteSemaphore for externally backed color buffer textures, if any:
if ((fbo->renderCompleteSemaphore) && glIsSemaphoreEXT && glIsSemaphoreEXT(fbo->renderCompleteSemaphore)) {
glDeleteSemaphoresEXT(1, &fbo->renderCompleteSemaphore);
}
// Create a new one:
glGenSemaphoresEXT(1, &fbo->renderCompleteSemaphore);
PsychTestForGLErrors();
}
// Platform specific external memory object import:
#if PSYCH_SYSTEM == PSYCH_WINDOWS
// glImportMemoryWin32HandleEXT *does not* transfer ownership of the interopMemObjectHandle to OpenGL, so we *must* close
// it at the end of the session, and therefore keep track of its existence and identity in the windowRecord:
glImportMemoryWin32HandleEXT(fbo->memoryObject, (GLuint64) allocationSize, GL_HANDLE_TYPE_OPAQUE_WIN32_EXT, interopMemObjectHandle);
// Import the semaphore handle into our semaphore, if any. Ownership is not transferred to OpenGL, so we need to release it at end of session:
if (interopSemaphoreHandle) {
glImportSemaphoreWin32HandleEXT(fbo->renderCompleteSemaphore, GL_HANDLE_TYPE_OPAQUE_WIN32_EXT, interopSemaphoreHandle);
}
#else
// glImportMemoryFdEXT transfers ownership of the interopMemObjectHandle to OpenGL, so we do not need to care about it
// anymore, so we can remove our reference to it in the windowRecord:
glImportMemoryFdEXT(fbo->memoryObject, (GLuint64) allocationSize, GL_HANDLE_TYPE_OPAQUE_FD_EXT, (GLint) ((size_t) interopMemObjectHandle));
windowRecord->interopMemObjectHandle = 0;
// Import the semaphore handle into our semaphore, if any. Ownership is transferred to OpenGL, so we are done with the handle:
if (interopSemaphoreHandle) {
glImportSemaphoreFdEXT(fbo->renderCompleteSemaphore, GL_HANDLE_TYPE_OPAQUE_FD_EXT, (GLint) ((size_t) interopSemaphoreHandle));
windowRecord->interopSemaphoreHandle = 0;
}
#endif
PsychTestForGLErrors();
// Unbind fbo, so we can modify it with robustness:
glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, 0);
glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, 0);
// Does OpenGL fbo for this PsychFBO already exist?
if (fbo->fboid) {
// Yes: Detach its colorbuffer texture:
glNamedFramebufferTexture2DEXT(fbo->fboid, GL_COLOR_ATTACHMENT0_EXT, glTextureTarget, 0, 0);
}
else {
// No: Create one:
glGenFramebuffers(1, (GLuint*) &(fbo->fboid));
// Need to bind it once, then unbind for setup, because otherwise fbo->fboid
// would only be a fbo object name, but would not have an actual FBO associated,
// as that only happens at first bind --> Failure a few lines down the code.
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo->fboid);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
}
PsychTestForGLErrors();
// Destroy and recreate texture object, to release all old backing memory
// for the texture image. While the AMD and NVidia drivers on Linux and the
// AMD driver on Windows don't care about omitting this destroy->recreate
// step, the NVidia driver on Windows will *silently* fail OpenGL->Vulkan
// interop if we omit the step! It will only display an all black interop
// image on the Vulkan side. (Category: A weekend i'll never get back :/ ):
if (fbo->coltexid)
glDeleteTextures(1, &fbo->coltexid);
if (PsychPrefStateGet_Verbosity() > 3) printf("PTB-DEBUG: For fbo %i, recreating interop memory texture: Delete old id %i ", fbo->fboid, fbo->coltexid);
glGenTextures(1, &fbo->coltexid);
if (PsychPrefStateGet_Verbosity() > 3) printf("created new one with id %i.\n", fbo->coltexid);
PsychTestForGLErrors();
// Assign tiling mode for rendering into the external memory backed texture:
glTextureParameteriEXT(fbo->coltexid, glTextureTarget, GL_TEXTURE_TILING_EXT, (GLenum) tilingMode);
PsychTestForGLErrors();
// Attach new external memory backing to the texture (this will apply tilingMode):
if (glTextureTarget == GL_TEXTURE_2D_MULTISAMPLE)
glTextureStorageMem2DMultisampleEXT(fbo->coltexid, multiSample, (GLenum) formatSpec, width, height, GL_TRUE, fbo->memoryObject, (GLuint64) memoryOffset);
else
glTextureStorageMem2DEXT(fbo->coltexid, 1, (GLenum) formatSpec, width, height, fbo->memoryObject, (GLuint64) memoryOffset);
PsychTestForGLErrors();
// Set texture filtering to nearest neighbour, for use as a fbo color buffer attachment:
glTextureParameteriEXT(fbo->coltexid, glTextureTarget, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTextureParameteriEXT(fbo->coltexid, glTextureTarget, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
PsychTestForGLErrors();
// Attach it as new colorbuffer backing texture:
glNamedFramebufferTexture2DEXT(fbo->fboid, GL_COLOR_ATTACHMENT0_EXT, glTextureTarget, fbo->coltexid, 0);
PsychTestForGLErrors();
// Bind FBO of view:
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo->fboid);
PsychTestForGLErrors();
// Check for framebuffer completeness:
fborc = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
if (fborc != GL_FRAMEBUFFER_COMPLETE_EXT) {
// Framebuffer incomplete!
while(glGetError()) {};
switch(fborc) {
case GL_FRAMEBUFFER_UNSUPPORTED_EXT:
sprintf(fbodiag, "Unsupported format");
break;
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT:
sprintf(fbodiag, "Framebuffer attachment incomplete.");
break;
case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
sprintf(fbodiag, "Framebuffer attachment multisample incomplete.");
break;
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT:
sprintf(fbodiag, "Framebuffer attachments missing incomplete.");
break;
case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT:
sprintf(fbodiag, "Framebuffer dimensions incomplete.");
break;
case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT:
sprintf(fbodiag, "Framebuffer formats incomplete.");
break;
case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT:
sprintf(fbodiag, "Framebuffer drawbuffer incomplete.");
break;
case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT:
sprintf(fbodiag, "Framebuffer readbuffer incomplete.");
break;
default:
sprintf(fbodiag, "Unknown error: glCheckFramebufferStatusEXT returns error code %i", fborc);
}
if (PsychPrefStateGet_Verbosity() > 0)
printf("PTB-ERROR: PsychSetPipelineExportTextureInteropMemory: Framebuffer viewid=%i incomplete [%s]! Rendering will be broken!\n", viewid, fbodiag);
}
else {
// Success: Assign new values:
fbo->textarget = (GLenum) glTextureTarget;
fbo->format = (GLenum) formatSpec;
fbo->multisample = multiSample;
fbo->width = width;
fbo->height = height;
}
// Done with framebuffers: Reset drawing target to force rebind before regular drawing.
PsychSetDrawingTarget(NULL);
// Restore old framebuffer assignments:
glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, (GLuint) drawFBO);
glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, (GLuint) readFBO);
PsychTestForGLErrors();
return(fborc == GL_FRAMEBUFFER_COMPLETE_EXT);
}
/* PsychSetPipelineExportTexture()
*
* Set new OpenGL color renderbuffer attachment backing textures for the PsychFBO's
* of the finalizedFBO[0/1] output render buffers.
*
* This detaches the old color attachment textures and attaches new ones.
*
* Before doing so it checks if the properties of the new attachments are
* compatible with the properties of the old ones and thereby general
* imaging pipeline setup.
*
* Returns TRUE on success, FALSE on failure.
*
* OpenGL error recovery is not perfect here, so on return of FALSE at least
* in a stereo configuration, the finalizedFBO[0] vs. finalizedFBO[1] could
* be in an inconsistent state. This could be improved but is probably not
* worth it.
*
*/
psych_bool PsychSetPipelineExportTexture(PsychWindowRecordType *windowRecord, int leftglHandle, int rightglHandle, int glTextureTarget, int format,
int multiSample, int width, int height)
{
int viewid;
GLint drawFBO = 0, readFBO = 0;
char fbodiag[100];
PsychFBO *fbo;
GLenum fborc = GL_FRAMEBUFFER_COMPLETE_EXT;
if (!(windowRecord->imagingMode & kPsychNeedFinalizedFBOSinks)) {
if (PsychPrefStateGet_Verbosity() > 0) printf("PTB-ERROR: PsychSetPipelineExportTexture: No kPsychNeedFinalizedFBOSinks! Skipped.\n");
return(FALSE);
}
if (!(windowRecord->imagingMode & kPsychUseExternalSinkTextures)) {
if (PsychPrefStateGet_Verbosity() > 0) printf("PTB-ERROR: PsychSetPipelineExportTexture: Not in mode kPsychUseExternalSinkTextures! Skipped.\n");
return(FALSE);
}
if (windowRecord->imagingMode & kPsychSinkIsMSAACapable) {
if (glTextureTarget != GL_TEXTURE_2D_MULTISAMPLE || multiSample == 0) {
if (PsychPrefStateGet_Verbosity() > 0) printf("PTB-ERROR: PsychSetPipelineExportTexture: Tried to set non-MSAA texture while setup for MSAA! Skipped.\n");
return(FALSE);
}
}
else {
// For the non-MSAA case, we accept both 2D npot textures and 2D rectangle textures, just not multisample textures:
if (((glTextureTarget != GL_TEXTURE_2D) && (glTextureTarget != GL_TEXTURE_RECTANGLE)) || multiSample > 0) {
if (PsychPrefStateGet_Verbosity() > 0) printf("PTB-ERROR: PsychSetPipelineExportTexture: Tried to set MSAA texture while setup for non-MSAA or only internal MSAA! Skipped.\n");
return(FALSE);
}
}
// Set OpenGL context of window so we can act on its FBO's:
PsychSetGLContext(windowRecord);
// Backup current fbo assignments before we mess with them:
glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &drawFBO);
glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &readFBO);
for (viewid = 0; viewid < ((windowRecord->stereomode == kPsychDualStreamStereo) ? 2 : 1) && (fborc == GL_FRAMEBUFFER_COMPLETE_EXT); viewid++) {
// Are finalizedFBO and drawBufferFBO using the same backing PsychFBO? If yes,
// and they are incompatible, then unshare them, fail if this fails:
if (!PsychUnshareFinalizedFBOIfNeeded(windowRecord, viewid, format, width, height)) {
// Failed!
fborc = GL_FRAMEBUFFER_UNSUPPORTED_EXT;
break;
}
fbo = windowRecord->fboTable[windowRecord->finalizedFBO[viewid]];
if ((int) multiSample != fbo->multisample) {
if (PsychPrefStateGet_Verbosity() > 1)
printf("PTB-WARNING: PsychSetPipelineExportTexture: Mismatch between new multiSample count %i and current one %i. May cause trouble.\n",
multiSample, fbo->multisample);
}
// If we don't have an fbo already, e.g., after unsharing of drawBufferFBO and finalizedFBO by PsychUnshareFinalizedFBOIfNeeded(), create a new one.
if (!fbo->fboid) {
glGenFramebuffers(1, (GLuint*) &(fbo->fboid));
}
// Bind FBO of view:
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo->fboid);
PsychTestForGLErrors();
// Attach the new texture as color buffer zero:
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, (GLenum) glTextureTarget, (GLuint) ((viewid == 0) ? leftglHandle : rightglHandle), 0);
PsychTestForGLErrors();
// Check for framebuffer completeness:
fborc = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
if (fborc != GL_FRAMEBUFFER_COMPLETE_EXT) {
// Framebuffer incomplete!
while(glGetError()) {};
switch(fborc) {
case GL_FRAMEBUFFER_UNSUPPORTED_EXT:
sprintf(fbodiag, "Unsupported format");
break;
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT:
sprintf(fbodiag, "Framebuffer attachment incomplete.");
break;
case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
sprintf(fbodiag, "Framebuffer attachment multisample incomplete.");
break;
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT:
sprintf(fbodiag, "Framebuffer attachments missing incomplete.");
break;
case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT:
sprintf(fbodiag, "Framebuffer dimensions incomplete.");
break;
case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT:
sprintf(fbodiag, "Framebuffer formats incomplete.");
break;
case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT:
sprintf(fbodiag, "Framebuffer drawbuffer incomplete.");
break;
case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT:
sprintf(fbodiag, "Framebuffer readbuffer incomplete.");
break;
default:
sprintf(fbodiag, "Unknown error: glCheckFramebufferStatusEXT returns error code %i", fborc);
}
if (PsychPrefStateGet_Verbosity() > 1)
printf("PTB-WARNING: PsychSetPipelineExportTexture: Framebuffer viewid=%i incomplete for new texture %i [%s]! Reverting to previous texture %i\n", viewid,
(viewid == 0) ? leftglHandle : rightglHandle, fbodiag, fbo->coltexid);
// Reattach old texture:
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, fbo->textarget, fbo->coltexid, 0);
PsychTestForGLErrors();
}
else {
// Success: Assign new values:
fbo->coltexid = (GLuint) ((viewid == 0) ? leftglHandle : rightglHandle);
fbo->textarget = (GLenum) glTextureTarget;
fbo->format = (GLenum) format;
fbo->multisample = multiSample;
fbo->width = width;
fbo->height = height;
}
}
// Done with framebuffers: Reset drawing target to force rebind before regular drawing.
PsychSetDrawingTarget(NULL);
// Restore old framebuffer assignments:
glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, (GLuint) drawFBO);
glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, (GLuint) readFBO);
return(fborc == GL_FRAMEBUFFER_COMPLETE_EXT);
}
/* PsychGetPipelineExportTexture()
*
* Get current OpenGL color renderbuffer attachment backing textures for the PsychFBO's
* of the finalizedFBO[0/1] output render buffers, and also the associated OpenGL FBO handles.
*
* Returns TRUE on success, FALSE on failure.
*/
psych_bool PsychGetPipelineExportTexture(PsychWindowRecordType *windowRecord, int *leftglHandle, int *rightglHandle, int *glTextureTarget, int *format,
int *multiSample, int *width, int *height, int *leftFboHandle, int *rightFboHandle)
{
PsychFBO *fbo;
// Nothing to query if imaging pipeline is off or only used for fast offscreen window support:
if (windowRecord->imagingMode == 0 || windowRecord->imagingMode == kPsychNeedFastOffscreenWindows) {
if (PsychPrefStateGet_Verbosity() > 0)
printf("PTB-ERROR: PsychGetPipelineExportTexture: Imaging pipeline not fully enabled, so not usable! Skipped.\n");
return(FALSE);
}
// The PsychFBO* for finalizedFBO's are always valid and point to something valid:
fbo = windowRecord->fboTable[windowRecord->finalizedFBO[0]];
*leftglHandle = (int) fbo->coltexid;
*rightglHandle = (int) windowRecord->fboTable[windowRecord->finalizedFBO[1]]->coltexid;
*leftFboHandle = (int) fbo->fboid;
*rightFboHandle = (int) windowRecord->fboTable[windowRecord->finalizedFBO[1]]->fboid;
*glTextureTarget = (int) fbo->textarget;
*format = (int) fbo->format;
*multiSample = (int) fbo->multisample;
*width = (int) fbo->width;
*height = (int) fbo->height;
// Enable context for this window, so external client can act on the OpenGL textures:
PsychSetGLContext(windowRecord);
return(TRUE);
}
/* PsychCreateFBO()
* Create OpenGL framebuffer object for internal rendering, setup PTB info struct for it.
* This function creates an OpenGL framebuffer object, creates and attaches a texture of suitable size
* (width x height) pixels with format fboInternalFormat as color buffer (color attachment 0). Optionally,
* (if needzbuffer is true) it also creates and attaches suitable z-buffer and stencil-buffer attachments.
* It checks for correct setup and then stores all relevant information in the PsychFBO struct, pointed by
* fbo. On success it returns true, on failure it returns false.
*
* 'specialFlags' 1 = Use GL_TEXTURE_2D texture, GL_TEXTURE_RECTANGLE texture otherwise.
* 2 = Use multisample texture for multisample colorbuffer attachments, use a multisample renderbuffer otherwise.
*/
psych_bool PsychCreateFBO(PsychFBO** fbo, GLenum fboInternalFormat, psych_bool needzbuffer, int width, int height, int multisample, int specialFlags)
{
GLenum texturetarget;
GLenum fborc;
GLint bpc, maxSamples;
GLboolean isFloatBuffer;
char fbodiag[1024];
GLenum glerr;
int twidth, theight;
psych_bool multisampled_cb = FALSE;
psych_bool multisampled_coltex = FALSE;
// Eat all GL errors:
PsychTestForGLErrors();
// Select type of texture target: Always GL_TEXTURE_2D on OpenGL-ES. Also, no multisample anti-aliasing
// on ES:
if (PsychIsGLES(NULL)) {
specialFlags |= 1;
if ((multisample > 0) && (PsychPrefStateGet_Verbosity() > 1)) printf("PTB-WARNING: Requested multisample anti-aliasing unsupported on OpenGL-ES hardware. Disabling.\n");
multisample = 0;
// Eat all errors:
while(glGetError());
}
texturetarget = (specialFlags & 0x1) ? GL_TEXTURE_2D : GL_TEXTURE_RECTANGLE_EXT;
// Use of special multisample-textures as color buffer attachment for multisampling requested,
// instead of classic multisample renderbuffers? Multisample textures supported?
if ((multisample > 0) && (specialFlags & 0x2) && glewIsSupported("GL_ARB_texture_multisample")) {
// Yes: Mark use of multisample textures as colorbuffer attachments. Depth-/Stencil will still
// use multisample renderbuffers.
multisampled_coltex = TRUE;
if (PsychPrefStateGet_Verbosity() > 5) printf("PTB-DEBUG: In PsychCreateFBO(): Using multisample texture for color buffer attachment.\n");
}
// If fboInternalFormat!=1 then we need to allocate and assign a proper PsychFBO struct first:
if (fboInternalFormat!=1) {
*fbo = (PsychFBO*) calloc(1, sizeof(PsychFBO));
if (*fbo == NULL) PsychErrorExitMsg(PsychError_outofMemory, "Out of system memory when trying to allocate PsychFBO struct!");
// Start cleanly for error handling: Not really needed anymore, as we now calloc() above.
(*fbo)->fboid = 0;
(*fbo)->coltexid = 0;
(*fbo)->stexid = 0;
(*fbo)->ztexid = 0;
(*fbo)->format = 0;
(*fbo)->width = width;
(*fbo)->height = height;
(*fbo)->multisample = multisample;
(*fbo)->textarget = texturetarget;
// fboInternalFormat == 0 --> Only allocate and assign, don't initialize FBO.
if (fboInternalFormat==0) return(TRUE);
}
// Initialize target storage size to use size "as is", as a safe default:
twidth = width;
theight = height;
// Standard path w/o multisampling? --> Setup and or bind texture as color attachment:
if (multisample <= 0) {
// Is there already a texture object defined for the color attachment?
if (fboInternalFormat != (GLenum) 1) {
// No, need to create one:
// Build color buffer: Create a new texture handle for the color buffer attachment.
glGenTextures(1, (GLuint*) &((*fbo)->coltexid));
// Bind it:
glBindTexture(texturetarget, (*fbo)->coltexid);
// Create proper texture: Just allocate proper format, don't assign data.
if (PsychIsGLES(NULL)) {
// OpenGL-ES: Internal and external format must match:
if (fboInternalFormat == GL_RGBA8) fboInternalFormat = GL_RGBA;
if (fboInternalFormat == GL_RGB8) fboInternalFormat = GL_RGB;
// Non-power-of-two textures supported on OES?
if (!strstr((const char*) glGetString(GL_EXTENSIONS), "GL_OES_texture_npot")) {
// No: Find size of suitable pot texture (smallest power of two which is
// greater than or equal to the image size:
twidth=1;
while (twidth < width) twidth*=2;
theight=1;
while (theight < height) theight*=2;
}
else {
// Yes: Use size "as is":
twidth = width;
theight = height;
}
if (fboInternalFormat == GL_RGBA_FLOAT32_APPLE || fboInternalFormat == GL_RGB_FLOAT32_APPLE) {
// 32-bpc float path:
if (PsychPrefStateGet_Verbosity() > 5) printf("PTB-DEBUG: In PsychCreateFBO: OpenGL-ES allocated 32-Bit float %s texture.\n",
(fboInternalFormat == GL_RGBA_FLOAT32_APPLE) ? "RGBA32F" : "RGB32F");
glTexImage2D(texturetarget, 0, fboInternalFormat, twidth, theight, 0, (fboInternalFormat == GL_RGBA_FLOAT32_APPLE) ? GL_RGBA : GL_RGB, GL_FLOAT, NULL);
}
else {
// Classic 8-Bit integer path:
glTexImage2D(texturetarget, 0, fboInternalFormat, twidth, theight, 0, fboInternalFormat, GL_UNSIGNED_BYTE, NULL);
if (PsychPrefStateGet_Verbosity() > 5) printf("PTB-DEBUG: In PsychCreateFBO: OpenGL-ES allocated 8-Bit integer texture.\n");
}
}
else {
// Desktop OpenGL: Use size "as is":
twidth = width;
theight = height;
glTexImage2D(texturetarget, 0, fboInternalFormat, twidth, theight, 0, GL_RGBA, GL_FLOAT, NULL);
}
}
else {
// Yes. Bind it as texture:
glBindTexture(texturetarget, (*fbo)->coltexid);
}
if (glGetError()!=GL_NO_ERROR) {
printf("PTB-ERROR: Failed to setup internal framebuffer objects color buffer attachment for imaging pipeline!\n");
printf("PTB-ERROR: Most likely the requested size or colordepth of the window or texture is not supported by your graphics hardware.\n");
return(FALSE);
}
// Setup texture wrapping behaviour to clamp, as other behaviours are
// unsupported on many gfx-cards for rectangle textures:
glTexParameterf(texturetarget,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
glTexParameterf(texturetarget,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
// Setup filtering for the textures - Use nearest neighbour by default, as floating
// point filtering usually unsupported.
glTexParameterf(texturetarget, GL_TEXTURE_MAG_FILTER,GL_NEAREST);
glTexParameterf(texturetarget, GL_TEXTURE_MIN_FILTER,GL_NEAREST);
// Texture ready, unbind it.
glBindTexture(texturetarget, 0);
// Mark use of standard path:
multisampled_cb = FALSE;
}
else {
// Multisampled FBO: Setup a multisampled renderbuffer or texture as color attachment;
if (fboInternalFormat == (GLenum) 1) PsychErrorExitMsg(PsychError_internal, "Tried to setup a multisampled FBO, but fboInternalFormat was == 1. PTB implementation bug!");
if (multisampled_coltex) {
// Multisample textures:
glGenTextures(1, (GLuint*) &((*fbo)->coltexid));
glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, (*fbo)->coltexid);
}
else {
// Multisample renderbuffers:
glGenRenderbuffersEXT(1, (GLuint*) &((*fbo)->coltexid));
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, (*fbo)->coltexid);
}
// Query maximum supported number of samples for multi-sampling:
glGetIntegerv((multisampled_coltex) ? GL_MAX_COLOR_TEXTURE_SAMPLES : GL_MAX_SAMPLES_EXT, &maxSamples);
// Clamp multisample level to maximum, warn user if she aimed to high:
if (multisample > maxSamples) {
if (PsychPrefStateGet_Verbosity() > 1) {
printf("PTB-WARNING: Your graphics hardware does not support anti-aliasing with the requested minimum number of %i samples.\n", multisample);
printf("PTB-WARNING: Will try requesting the theoretical maximum supported value of %i samples instead and see what i can get.\n", maxSamples);
}
multisample = maxSamples;
}
// Try creating multisampled renderbuffers. On failure, decrease requested sample count.
// Hardware may deny requests if insufficient memory is available.
do {
if (PsychPrefStateGet_Verbosity() > 5) printf("PTB-DEBUG: PsychCreateFBO(): Trying to alloc multisample %s with %i samples.\n",
(multisampled_coltex) ? "texture" : "renderbuffer", multisample);
if (multisampled_coltex) {
glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, (GLsizei) multisample--, fboInternalFormat, width, height, TRUE);
}
else {
glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, multisample--, fboInternalFormat, width, height);
}
} while (((glerr = glGetError()) != GL_NO_ERROR) && (multisample >= 0));
// Worked? Worst case we should have gotten at least a renderbuffer with multisample == 0,
// ie., a non-multisampled buffer. If even that failed, then something's screwed, e.g.,
// totally out of memory and we have to give up:
if (glerr != GL_NO_ERROR) {
if (PsychPrefStateGet_Verbosity() > 0) {
printf("PTB-ERROR: Failed to setup internal framebuffer objects color buffer attachment as a multisampled %s for imaging pipeline!\n",
(multisampled_coltex) ? "texture" : "renderbuffer");
if (glerr == GL_OUT_OF_MEMORY) {
printf("PTB-ERROR: Reason seems to be an out of graphics memory condition.\n");
}
else {
printf("PTB-ERROR: Reason for failure is unknown [OpenGL error: %s]\n", gluErrorString(glerr));
}
}
if (multisampled_coltex) {
glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0);
} else {
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);
}
return(FALSE);
}
if (multisampled_coltex) {
// Got some texture. Query real number of samples for texture:
glGetTexLevelParameteriv(GL_TEXTURE_2D_MULTISAMPLE, 0, GL_TEXTURE_SAMPLES, &multisample);
// Unbind, we're done with setup:
glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0);
}
else {
// Got some renderbuffer. Query real number of samples for renderbuffer:
glGetRenderbufferParameterivEXT(GL_RENDERBUFFER_EXT, GL_RENDERBUFFER_SAMPLES_EXT, &multisample);
// Unbind, we're done with setup:
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);
}
if ((multisample < (*fbo)->multisample) && (PsychPrefStateGet_Verbosity() > 1)) {
printf("PTB-WARNING: Could only get %i samples instead of requested %i samples for multi-sampling from hardware.\n", multisample, (*fbo)->multisample);
}
// Assign effective multisample count:
(*fbo)->multisample = multisample;
if (PsychPrefStateGet_Verbosity() > 5) {
printf("PTB-DEBUG: Created framebuffer object for anti-aliasing with %i samples per pixel for use with imaging pipeline.\n", (*fbo)->multisample);
}
// Mark use of multi-sampled renderbuffer path:
multisampled_cb = TRUE;
}
// Create a new framebuffer object and bind it:
glGenFramebuffersEXT(1, (GLuint*) &((*fbo)->fboid));
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, (*fbo)->fboid);
if (!multisampled_cb || multisampled_coltex) {
// Attach the texture as color buffer zero:
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, (multisampled_coltex) ? GL_TEXTURE_2D_MULTISAMPLE : texturetarget, (*fbo)->coltexid, 0);
}
else {
// Attach the multi-sampled renderbuffer as color buffer zero:
glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, (*fbo)->coltexid);
}
if (glGetError()!=GL_NO_ERROR) {
printf("PTB-ERROR: Failed to attach internal framebuffer objects color buffer attachment for imaging pipeline!\n");
printf("PTB-ERROR: Maybe the requested size & depth of the window or texture is not supported by your graphics hardware.\n");
return(FALSE);
}
// Check for framebuffer completeness:
fborc = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
if (fborc!=GL_FRAMEBUFFER_COMPLETE_EXT && fborc!=0) {
// Framebuffer incomplete!
while(glGetError());
printf("PTB-ERROR[Imaging pipeline]: Failed to setup color buffer attachment of internal FBO when trying to prepare drawing into a texture or window.\n");
if (fborc==GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT) {
printf("PTB-ERROR: Your graphics hardware does not support the provided or requested texture- or offscreen window format for drawing into it.\n");
printf("PTB-ERROR: Most graphics cards do not support drawing into textures or offscreen windows which are not true-color, i.e. 1 layer pure\n");
printf("PTB-ERROR: luminance or 2 layer luminance+alpha textures or offscreen windows won't work. Choose a 3-layer RGB or 4-layer RGBA texture\n");
printf("PTB-ERROR: or offscreen window and retry.\n");
}
else if (fborc==GL_FRAMEBUFFER_UNSUPPORTED_EXT) {
printf("PTB-ERROR: Your graphics hardware does not support the provided or requested texture- or offscreen window format for drawing into it.\n");
printf("PTB-ERROR: Could be that the specific color depth of the texture or offscreen window is not supported for drawing on your hardware:\n");
printf("PTB-ERROR: 8 bits per color component are supported on nearly all hardware, 16 bpc or 32 bpc floating point formats only on recent\n");
printf("PTB-ERROR: hardware. 16 bpc fixed precision is not supported on any NVidia hardware, and on many systems only under restricted conditions.\n");
printf("PTB-ERROR: Retry with the lowest acceptable (for your study) size and depth of the onscreen window or offscreen window.\n");
}
else {
printf("PTB-ERROR: Exact reason for failure is unknown, most likely a Psychtoolbox bug, OpenGL-driver bug or unintented use. glCheckFramebufferStatus() returns code %i\n", fborc);
}
return(FALSE);
}
else if (fborc == 0) {
// Checking command itself failed?!?
if (PsychPrefStateGet_Verbosity() > 2) {
// Warn the user:
printf("PTB-WARNING: In setup of framebuffer object color attachment: glCheckFramebufferStatusEXT() malfunctioned. (glGetError reports: %s)\n", gluErrorString(glGetError()));
printf("PTB-WARNING: Therefore can't determine if FBO setup worked or not. Will continue and hope for the best :(\n");
printf("PTB-WARNING: This is most likely a graphics driver bug. You may want to update your graphics drivers, maybe it helps.\n");
}
while(glGetError());
}
// Do we need additional buffers for 3D rendering?
if (needzbuffer) {
// Yes. Try to setup and attach them: We use depth textures if they are supported and no MSAA is needed:
if ((multisample <= 0) && (glewIsSupported("GL_ARB_depth_texture") || strstr((const char*) glGetString(GL_EXTENSIONS), "GL_OES_depth_texture"))) {
// No multisampling requested on FBO and depth textures are supported. Use those to implement depth + stencil buffers:
if (PsychPrefStateGet_Verbosity()>4) printf("PTB-DEBUG: Trying to attach texture depth+stencil attachments to FBO...\n");
// Create texture object for z-buffer (or z+stencil buffer) and set it up:
glGenTextures(1, (GLuint*) &((*fbo)->ztexid));
glBindTexture(texturetarget, (*fbo)->ztexid);
// Setup texture wrapping behaviour to clamp, as other behaviours are
// unsupported on many gfx-cards for rectangle textures:
if (!PsychIsGLES(NULL)) {
glTexParameterf(texturetarget,GL_TEXTURE_WRAP_S,GL_CLAMP);
glTexParameterf(texturetarget,GL_TEXTURE_WRAP_T,GL_CLAMP);
}
else {
glTexParameterf(texturetarget,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
glTexParameterf(texturetarget,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
}
// Setup filtering for the textures - Use nearest neighbour by default, as floating
// point filtering usually unsupported.
glTexParameterf(texturetarget, GL_TEXTURE_MAG_FILTER,GL_NEAREST);
glTexParameterf(texturetarget, GL_TEXTURE_MIN_FILTER,GL_NEAREST);
// Just to be safe...
PsychTestForGLErrors();
// Do we have support for combined 24 bit depth and 8 bit stencil buffer textures?
if (glewIsSupported("GL_EXT_packed_depth_stencil") || (glewIsSupported("GL_NV_packed_depth_stencil") && glewIsSupported("GL_SGIX_depth_texture")) ||
strstr((const char*) glGetString(GL_EXTENSIONS), "GL_OES_packed_depth_stencil")) {
// Yes! Create combined depth and stencil texture:
if (PsychPrefStateGet_Verbosity()>4) printf("PTB-DEBUG: packed_depth_stencil supported. Attaching combined 24 bit depth + 8 bit stencil texture...\n");
// Create proper texture: Just allocate proper format, don't assign data.
if (PsychIsGLES(NULL)) {
glTexImage2D(texturetarget, 0, GL_DEPTH_STENCIL_EXT, twidth, theight, 0, GL_DEPTH_STENCIL_EXT, GL_UNSIGNED_INT_24_8_EXT, NULL);
}
else if (glewIsSupported("GL_EXT_packed_depth_stencil")) {
glTexImage2D(texturetarget, 0, GL_DEPTH24_STENCIL8_EXT, twidth, theight, 0, GL_DEPTH_STENCIL_EXT, GL_UNSIGNED_INT_24_8_EXT, NULL);
}
else {
// Ancient drivers with only NV extension support...
glTexImage2D(texturetarget, 0, GL_DEPTH_COMPONENT24_SGIX, twidth, theight, 0, GL_DEPTH_STENCIL_EXT, GL_UNSIGNED_INT_24_8_EXT, NULL);
}
PsychTestForGLErrors();
// Texture ready, unbind it.
glBindTexture(texturetarget, 0);
// Attach the texture as depth buffer...
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, texturetarget, (*fbo)->ztexid, 0);
PsychTestForGLErrors();
if (!(PsychPrefStateGet_ConserveVRAM() & kPsychDontAttachStencilToFBO)) {
// ... and as stencil buffer ...
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, texturetarget, (*fbo)->ztexid, 0);
if (glGetError()) {
// Attaching stencil buffer doesnt work :( We try to live without it...
while(glGetError());
if (PsychPrefStateGet_Verbosity()>1) {
printf("PTB-WARNING: OpenGL stencil buffers not supported in imagingmode by your hardware. This won't affect Screen 2D drawing functions and won't affect\n");
printf("PTB-WARNING: the majority of OpenGL (MOGL) 3D drawing code either, but OpenGL code that needs a stencil buffer will misbehave or fail in random ways!\n");
printf("PTB-WARNING: If you need to use such code, you'll either have to disable the internal imaging pipeline, or carefully work-around this limitation by\n");
printf("PTB-WARNING: proper modifications and testing of the affected code. Good luck... Alternatively, upgrade your graphics hardware or drivers.\n");
}
}
}
else {
// Override: Do not attach stencil attachment!
(*fbo)->stexid = 0;
if (PsychPrefStateGet_Verbosity()>4) printf("PTB-DEBUG: PsychCreateFBO(): Won't attach a stencil buffer to FBO due to user override...\n");
}
}
else {
// Packed depth+stencil textures unsupported :(
// Allocate a single depth texture and attach it. Then see what we can do about the stencil attachment...
if (PsychPrefStateGet_Verbosity()>4) printf("PTB-DEBUG: packed_depth_stencil unsupported. Attaching 24 bit depth texture and 8 bit stencil renderbuffer...\n");
// Create proper texture: Just allocate proper format, don't assign data.
glTexImage2D(texturetarget, 0, GL_DEPTH_COMPONENT, twidth, theight, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL);
// Depth texture ready, unbind it.
glBindTexture(texturetarget, 0);
// Attach the texture as depth buffer...
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, texturetarget, (*fbo)->ztexid, 0);
if (!(PsychPrefStateGet_ConserveVRAM() & kPsychDontAttachStencilToFBO)) {
// Create and attach renderbuffer as a stencil buffer of 8 bit depths:
glGenRenderbuffersEXT(1, (GLuint*) &((*fbo)->stexid));
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, (*fbo)->stexid);
glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_STENCIL_INDEX8_EXT, twidth, theight);
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);
glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, (*fbo)->stexid);
}
else {
// Override: Do not attach stencil attachment!
(*fbo)->stexid = 0;
if (PsychPrefStateGet_Verbosity()>4) printf("PTB-DEBUG: PsychCreateFBO(): Pathway-2: Won't attach a stencil buffer to FBO due to user override...\n");
}
// See if we are framebuffer complete:
fborc = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
if (GL_FRAMEBUFFER_COMPLETE_EXT != fborc && 0 != fborc) {
// Nope. Our trick doesn't work, this hardware won't let us attach a stencil buffer at all. Remove it
// and live with a depth-buffer only setup.
if (PsychPrefStateGet_Verbosity()>4) printf("PTB-DEBUG: Stencil renderbuffer attachment failed! Detaching stencil buffer...\n");
if (PsychPrefStateGet_Verbosity()>1) {
printf("PTB-WARNING: OpenGL stencil buffers not supported in imagingmode by your hardware. This won't affect Screen 2D drawing functions and won't affect\n");
printf("PTB-WARNING: the majority of OpenGL (MOGL) 3D drawing code either, but OpenGL code that needs a stencil buffer will misbehave or fail in random ways!\n");
printf("PTB-WARNING: If you need to use such code, you'll either have to disable the internal imaging pipeline, or carefully work-around this limitation by\n");
printf("PTB-WARNING: proper modifications and testing of the affected code. Good luck... Alternatively, upgrade your graphics hardware or drivers. According to specs,\n");
printf("PTB-WARNING: all gfx-cards starting with GeForceFX 5200 on Windows and Linux and all cards on Intel-Macs except the Intel GMA cards should work, whereas\n");
printf("PTB-WARNING: none of the PowerPC hardware is supported as of OS-X 10.4.9.\n");
}
glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0);
glDeleteRenderbuffersEXT(1, (GLuint*) &((*fbo)->stexid));
(*fbo)->stexid = 0;
}
else if (fborc == 0) {
// Checking command itself failed?!?
if (PsychPrefStateGet_Verbosity() > 2) {
// Warn the user:
printf("PTB-WARNING: In setup of framebuffer object stencil attachment: glCheckFramebufferStatusEXT() malfunctioned. (glGetError reports: %s)\n", gluErrorString(glGetError()));
printf("PTB-WARNING: Therefore can't determine if FBO setup worked or not. Will continue and hope for the best :(\n");
printf("PTB-WARNING: This is most likely a graphics driver bug. You may want to update your graphics drivers, maybe it helps.\n");
}
while(glGetError());
}
}
} // End of setup code for multiSample == 0.
else {
// Setup code of z- and stencilbuffer for multisampled mode. We must allocate these attachments as renderbuffers,
// as they need the same sample count as the color buffers, and textures do not support multisampling.
// We also use this path for non-multisampled renderbuffer setup if depth textures aren't available.
if (PsychPrefStateGet_Verbosity()>4) {
printf("PTB-DEBUG: Trying to attach %s renderbuffer depth+stencil attachments to FBO...\n", (multisample > 0) ? "multisample" : "");
}
glGenRenderbuffersEXT(1, (GLuint*) &((*fbo)->ztexid));
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, (*fbo)->ztexid);
// Use of depth+stencil requested and packed depth+stencil possible?
if (!(PsychPrefStateGet_ConserveVRAM() & kPsychDontAttachStencilToFBO) &&
(glewIsSupported("GL_EXT_packed_depth_stencil") || strstr((const char*) glGetString(GL_EXTENSIONS), "GL_OES_packed_depth_stencil"))) {
// Try a packed depth + stencil buffer:
if (multisample > 0) {
glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, multisample, GL_DEPTH24_STENCIL8_EXT, twidth, theight);
}
else {
glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH24_STENCIL8_EXT, twidth, theight);
}
(*fbo)->stexid = (*fbo)->ztexid;
}
else {
// Depth buffer only:
if (multisample > 0) {
glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, multisample, GL_DEPTH_COMPONENT24_ARB, twidth, theight);
}
else {
// OES doesn't guarantee 24 bit depth buffers, only 16 bit, so fallback to them on OES if 24 bits are unsupported:
glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT,
(!PsychIsGLES(NULL) || strstr((const char*) glGetString(GL_EXTENSIONS), "GL_OES_depth24")) ? GL_DEPTH_COMPONENT24_ARB : GL_DEPTH_COMPONENT16_ARB,
twidth, theight);
}
(*fbo)->stexid = 0;
}
if (glGetError()!=GL_NO_ERROR) {
printf("PTB-ERROR: Failed to setup internal framebuffer objects depths renderbuffer attachment as a %s renderbuffer for imaging pipeline!\n", (multisample > 0) ? "multisample" : "");
printf("PTB-ERROR: Most likely the requested size, depth and multisampling level is not supported by your graphics hardware.\n");
return(FALSE);
}
if (multisample > 0) {
// Query real number of samples for renderbuffer:
glGetRenderbufferParameterivEXT(GL_RENDERBUFFER_EXT, GL_RENDERBUFFER_SAMPLES_EXT, &multisample);
if ((*fbo)->multisample != multisample) {
printf("PTB-ERROR: Failed to setup internal framebuffer objects depths renderbuffer attachment as a multisampled renderbuffer for imaging pipeline!\n");
printf("PTB-ERROR: Could not get the same number of samples for depths renderbuffer as for color buffer, which is a requirement.\n");
return(FALSE);
}
}
// Unbind, we're done with setup:
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);
// Non-zero stexid marks that we've created a packed depth+stencil renderbuffer above:
if ((*fbo)->stexid) {
// Attach combined z + stencil buffer:
if (glewIsSupported("GL_ARB_framebuffer_object")) {
// New style: Get two attachments for one call:
glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER_EXT, (*fbo)->ztexid);
} else {
// Old style (also OES): Use two separate calls:
glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, (*fbo)->ztexid);
glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, (*fbo)->ztexid);
}
}
else {
// Attach z-buffer only:
glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, (*fbo)->ztexid);
}
// Now try to attach stencil buffer:
if (!((*fbo)->stexid) && !(PsychPrefStateGet_ConserveVRAM() & kPsychDontAttachStencilToFBO)) {
// Create and attach renderbuffer as a stencil buffer of hopefully 8 bit depths:
glGenRenderbuffersEXT(1, (GLuint*) &((*fbo)->stexid));
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, (*fbo)->stexid);
// Try to get stencil buffer with matching sample count to depth and color buffers:
if (multisample > 0) {
glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, multisample, GL_STENCIL_INDEX8_EXT, twidth, theight);
}
else {
// OES does not guarantee 8 bit stencil buffers, only with extension. In fact, it does not even guarantee
// stencil buffers at all, so we aim for 8 bit, fallback to 4 bit and leave it to the error handling below to disable
// stencil buffers if the implementation doesn't support at least the 4 bit case:
glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, (!PsychIsGLES(NULL) || strstr((const char*) glGetString(GL_EXTENSIONS), "GL_OES_stencil8")) ? GL_STENCIL_INDEX8_EXT : GL_STENCIL_INDEX4_EXT, twidth, theight);
}
if (glGetError()!=GL_NO_ERROR) {
if (PsychPrefStateGet_Verbosity() > 2) {
printf("PTB-WARNING: Failed to setup internal framebuffer objects stencil renderbuffer attachment as a %s renderbuffer for imaging pipeline!\n", (multisample > 0) ? "multisample" : "");
}
// Clean up:
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);
glDeleteRenderbuffersEXT(1, (GLuint*) &((*fbo)->stexid));
(*fbo)->stexid = 0;
}
if (multisample > 0) {
// Query real number of samples for renderbuffer:
glGetRenderbufferParameterivEXT(GL_RENDERBUFFER_EXT, GL_RENDERBUFFER_SAMPLES_EXT, &multisample);
if ((*fbo)->multisample != multisample) {
if (PsychPrefStateGet_Verbosity() > 2) {
printf("PTB-WARNING: Failed to setup internal framebuffer objects stencil renderbuffer attachment as a multisampled renderbuffer for imaging pipeline!\n");
printf("PTB-WARNING: Could not get the same number of samples for stencil renderbuffer as for color buffer, which is a requirement.\n");
}
// Clean up:
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);
glDeleteRenderbuffersEXT(1, (GLuint*) &((*fbo)->stexid));
(*fbo)->stexid = 0;
}
}
if ((*fbo)->stexid > 0) {
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);
glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, (*fbo)->stexid);
// See if we are framebuffer complete:
fborc = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
if (GL_FRAMEBUFFER_COMPLETE_EXT != fborc && 0 != fborc) {
// Nope. Our trick doesn't work, this hardware won't let us attach a stencil buffer at all. Remove it
// and live with a depth-buffer only setup.
if (PsychPrefStateGet_Verbosity()>4) printf("PTB-DEBUG: Stencil %s renderbuffer attachment failed! Detaching stencil buffer...\n", (multisample > 0) ? "multisample" : "");
glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0);
glDeleteRenderbuffersEXT(1, (GLuint*) &((*fbo)->stexid));
(*fbo)->stexid = 0;
}
else if (fborc == 0) {
// Checking command itself failed?!?
if (PsychPrefStateGet_Verbosity() > 1) {
// Warn the user:
printf("PTB-WARNING: In setup of framebuffer object %s stencil attachment: glCheckFramebufferStatusEXT() malfunctioned. (glGetError reports: %s)\n",
(multisample > 0) ? "multisample" : "", gluErrorString(glGetError()));
printf("PTB-WARNING: Therefore can't determine if FBO setup worked or not. Will continue and hope for the best :(\n");
printf("PTB-WARNING: This is most likely a graphics driver bug. You may want to update your graphics drivers, maybe it helps.\n");
}
while(glGetError());
}
}
if (((*fbo)->stexid == 0) && (PsychPrefStateGet_Verbosity() > 1)) {
printf("PTB-WARNING: OpenGL %s stencil buffers not supported in imagingmode by your hardware. This won't affect Screen 2D drawing functions and won't affect\n",
(multisample > 0) ? "multisample" : "");
printf("PTB-WARNING: the majority of OpenGL (MOGL) 3D drawing code either, but OpenGL code that needs a stencil buffer will misbehave or fail in random ways!\n");
printf("PTB-WARNING: If you need to use such code, you'll either have to disable the internal imaging pipeline, or carefully work-around this limitation by\n");
printf("PTB-WARNING: proper modifications and testing of the affected code. Good luck... Alternatively, upgrade your graphics hardware or drivers.\n\n");
}
}
else {
// Override: Do not attach stencil attachment, or combined depth+stencil attached?
if ((*fbo)->stexid) {
// Non-Zero stexid indicates we use a combined depth+stencil renderbuffer. Its handle
// is already stored in ztexid, so zero-out stexid to avoid redundant destruction on
// framebuffer cleanup later on:
(*fbo)->stexid = 0;
} // Zero stexid indicates that no stencil buffer shall be used, according to usercode's preferences:
else if (PsychPrefStateGet_Verbosity()>4) printf("PTB-DEBUG: PsychCreateFBO(): Pathway-3: Won't attach a stencil buffer to FBO due to user override...\n");
}
// Ok, all depths- and stencil- renderbuffers with same number of multisamples as color renderbuffer attached. Check for completeness will
// happen further down the road...
}
}
else {
// Initialize additional buffers to zero:
if (PsychPrefStateGet_Verbosity()>4) printf("PTB-DEBUG: Only colorbuffer texture attached to FBO, no depth- or stencil buffers requested...\n");
(*fbo)->stexid = 0;
(*fbo)->ztexid = 0;
}
// Store dimensions:
(*fbo)->width = width;
(*fbo)->height = height;
// Check for framebuffer completeness:
fborc = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
if (fborc!=GL_FRAMEBUFFER_COMPLETE_EXT && fborc!=0) {
// Framebuffer incomplete!
while(glGetError()) {};
switch(fborc) {
case GL_FRAMEBUFFER_UNSUPPORTED_EXT:
sprintf(fbodiag, "Unsupported format");
break;
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT:
sprintf(fbodiag, "Framebuffer attachment incomplete.");
break;
case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
sprintf(fbodiag, "Framebuffer attachment multisample incomplete.");
break;
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT:
sprintf(fbodiag, "Framebuffer attachments missing incomplete.");
break;
case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT:
sprintf(fbodiag, "Framebuffer dimensions incomplete.");
break;
case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT:
sprintf(fbodiag, "Framebuffer formats incomplete.");
break;
case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT:
sprintf(fbodiag, "Framebuffer drawbuffer incomplete.");
break;
case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT:
sprintf(fbodiag, "Framebuffer readbuffer incomplete.");
break;
default:
sprintf(fbodiag, "Unknown error: glCheckFramebufferStatusEXT returns error code %i", fborc);
}
printf("PTB-ERROR: Failed to setup internal framebuffer object for imaging pipeline [%s]! The most likely cause is that your hardware does not support\n", fbodiag);
printf("PTB-ERROR: the required buffers at the given screen resolution (Additional 3D buffers for z- and stencil are %s).\n", (needzbuffer) ? "requested" : "disabled");
printf("PTB-ERROR: You may want to retry with the lowest acceptable (for your study) display resolution or with 3D rendering support disabled.\n");
return(FALSE);
}
else if (fborc == 0) {
// Checking command itself failed?!?
if (PsychPrefStateGet_Verbosity() > 2) {
// Warn the user:
printf("PTB-WARNING: In setup of framebuffer object: glCheckFramebufferStatusEXT() malfunctioned. (glGetError reports: %s)\n", gluErrorString(glGetError()));
printf("PTB-WARNING: Therefore can't determine if FBO setup worked or not. Will continue and hope for the best :(\n");
printf("PTB-WARNING: This is most likely a graphics driver bug. You may want to update your graphics drivers, maybe it helps.\n");
}
while(glGetError());
}
if (PsychPrefStateGet_Verbosity()>4) {
// Output framebuffer properties:
glGetIntegerv(GL_RED_BITS, &bpc);
printf("PTB-DEBUG: FBO has %i bits precision per color component in ", bpc);
if (glewIsSupported("GL_ARB_color_buffer_float") || glewIsSupported("GL_EXT_color_buffer_float")) {
glGetBooleanv(GL_RGBA_FLOAT_MODE_ARB, &isFloatBuffer);
if (isFloatBuffer) {
printf("floating point format ");
}
else {
printf("fixed point format ");
}
}
else if (glewIsSupported("GL_APPLE_float_pixels")) {
glGetBooleanv(GL_COLOR_FLOAT_APPLE, &isFloatBuffer);
if (isFloatBuffer) {
printf("floating point format ");
}
else {
printf("fixed point format ");
}
}
else {
isFloatBuffer = FALSE;
printf("unknown (but likely fixed point) format ");
}
// Tell OpenGL texture id of color attachment textures:
if (!multisampled_cb || multisampled_coltex)
printf("coltexid %i ", (*fbo)->coltexid);
glGetIntegerv(GL_DEPTH_BITS, &bpc);
printf("with %i depths buffer bits ", bpc);
glGetIntegerv(GL_STENCIL_BITS, &bpc);
printf("and %i stencil buffer bits.\n", bpc);
}
// Unbind FBO:
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
// Test all GL errors:
PsychTestForGLErrors();
// Override texture target for color buffer texture if a multi-sample texture
// is in use:
if (multisampled_coltex) (*fbo)->textarget = GL_TEXTURE_2D_MULTISAMPLE;
// Assign final FBO colorbuffer format:
if (fboInternalFormat > 1) (*fbo)->format = fboInternalFormat;
// Well done.
return(TRUE);
}
void PsychDeleteFBO(PsychFBO* fboptr)
{
if (!fboptr)
return;
// Detach and delete color buffer texture/renderbuffer:
if (fboptr->coltexid) {
if (glIsTexture(fboptr->coltexid)) {
// Color buffer is a texture:
glDeleteTextures(1, &(fboptr->coltexid));
if (PsychPrefStateGet_Verbosity() > 4)
printf("PTB-DEBUG:PsychDeleteFBO(%p): Deleted coltexid %i.\n", fboptr, fboptr->coltexid);
}
else {
// Color buffer is a renderbuffer:
glDeleteRenderbuffersEXT(1, &(fboptr->coltexid));
}
}
// Delete memory object for externally backed color buffer textures:
if ((fboptr->memoryObject) && glIsMemoryObjectEXT && glIsMemoryObjectEXT(fboptr->memoryObject)) {
glDeleteMemoryObjectsEXT(1, &fboptr->memoryObject);
}
// Delete renderCompleteSemaphore for externally backed color buffer textures, if any:
if ((fboptr->renderCompleteSemaphore) && glIsSemaphoreEXT && glIsSemaphoreEXT(fboptr->renderCompleteSemaphore)) {
glDeleteSemaphoresEXT(1, &fboptr->renderCompleteSemaphore);
}
// Detach and delete depth buffer (and probably stencil buffer) texture, if any:
if (fboptr->ztexid) {
if (glIsTexture(fboptr->ztexid)) {
// Depths buffer is a texture:
glDeleteTextures(1, &(fboptr->ztexid));
}
else {
// Depths buffer is a renderbuffer:
glDeleteRenderbuffersEXT(1, &(fboptr->ztexid));
}
}
// Detach and delete stencil renderbuffer, if a separate stencil buffer was needed:
if (fboptr->stexid) glDeleteRenderbuffersEXT(1, &(fboptr->stexid));
// Delete FBO itself:
if (fboptr->fboid) glDeleteFramebuffersEXT(1, &(fboptr->fboid));
// Delete PsychFBO struct associated with this FBO:
free(fboptr); fboptr = NULL;
}
/* PsychMSAAResolveToTemp()
*
* Check if given msaaFBO is multi-sampled. If not, return NULL.
* If yes, create a matching single-sample PsychFBO, MSAA resolve
* msaaFBO into it, and return the resolved PsychFBO. Also bind the
* resolved FBO for immediate use.
*/
PsychFBO* PsychMSAAResolveToTemp(PsychFBO* msaaFBO)
{
PsychFBO* resolvedFBO;
// Nothing to do on single-sample buffers:
if (msaaFBO->multisample == 0)
return(NULL);
if (!PsychCreateFBO(&resolvedFBO, msaaFBO->format, FALSE, msaaFBO->width, msaaFBO->height, 0, 0)) {
PsychErrorExitMsg(PsychError_system, "Failed to create temporary MSAA resolve buffer from MSAA drawBuffer!");
}
// Ok, the resolveFBO is a suitable temporary resolve buffer. Perform a multisample resolve blit to it:
// A simple glBlitFramebufferEXT() call will do the copy & downsample operation:
glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, msaaFBO->fboid);
glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, resolvedFBO->fboid);
glBlitFramebufferEXT(0, 0, msaaFBO->width, msaaFBO->height, 0, 0, msaaFBO->width, msaaFBO->height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, resolvedFBO->fboid);
return(resolvedFBO);
}
/* PsychCreateShadowFBOForTexture()
* Check if provided PTB texture already has a PsychFBO attached. Do nothing if so.
* If a FBO is missing, create one.
*
* If asRendertarget is FALSE, we only create the data structure, not a real OpenGL FBO,
* so the texture is only suitable as image source for image processing.
*
* If asRendertraget is TRUE, we create a full blown FBO, so the texture can be used as
* rendertarget.
*
*/
void PsychCreateShadowFBOForTexture(PsychWindowRecordType *textureRecord, psych_bool asRendertarget, int forImagingmode)
{
GLenum fboInternalFormat;
// Do we already have a framebuffer object for this texture? All textures start off without one,
// because most textures are just used for drawing them, not drawing *into* them. Therefore we
// only create a full blown FBO on demand here.
if (textureRecord->drawBufferFBO[0]==-1) {
// No. This texture is used the first time as a drawing target.
// Need to create a framebuffer object for it first.
if (textureRecord->textureNumber > 0) {
// Allocate and assign FBO object info structure PsychFBO:
PsychCreateFBO(&(textureRecord->fboTable[0]), (GLenum) 0, (PsychPrefStateGet_3DGfx() > 0) ? TRUE : FALSE, (int) PsychGetWidthFromRect(textureRecord->rect), (int) PsychGetHeightFromRect(textureRecord->rect), 0, (PsychGetTextureTarget(textureRecord) == GL_TEXTURE_2D) ? 1 : 0);
// Manually set up the color attachment texture id to our texture id:
textureRecord->fboTable[0]->coltexid = textureRecord->textureNumber;
}
else {
// No texture yet. Create suitable one for given imagingmode:
// Start off with standard 8 bpc fixed point:
fboInternalFormat = GL_RGBA8; textureRecord->bpc = 8;
// Need 16 bpc fixed point precision?
if (forImagingmode & kPsychNeed16BPCFixed) { fboInternalFormat = ((textureRecord->gfxcaps & kPsychGfxCapSNTex16) ? GL_RGBA16_SNORM : GL_RGBA16); textureRecord->bpc = 16; }
// Need 16 bpc floating point precision?
if (forImagingmode & kPsychNeed16BPCFloat) { fboInternalFormat = GL_RGBA_FLOAT16_APPLE; textureRecord->bpc = 16; }
// Need 32 bpc floating point precision?
if (forImagingmode & kPsychNeed32BPCFloat) { fboInternalFormat = GL_RGBA_FLOAT32_APPLE; textureRecord->bpc = 32; }
// OpenGL-ES + float precision requested?
if (PsychIsGLES(textureRecord) && (textureRecord->bpc > 8)) {
// Upgrade to full 32bpc float -- we only support this, if at all:
fboInternalFormat = GL_RGBA_FLOAT32_APPLE; textureRecord->bpc = 32;
}
PsychCreateFBO(&(textureRecord->fboTable[0]), fboInternalFormat, (PsychPrefStateGet_3DGfx() > 0) ? TRUE : FALSE, (int) PsychGetWidthFromRect(textureRecord->rect), (int) PsychGetHeightFromRect(textureRecord->rect), 0, (PsychGetTextureTarget(textureRecord) == GL_TEXTURE_2D) ? 1 : 0);
// Manually set up the texture id from our color attachment texture id:
textureRecord->textureNumber = textureRecord->fboTable[0]->coltexid;
}
// Worked. Set up remaining state:
textureRecord->fboCount = 1;
textureRecord->drawBufferFBO[0]=0;
}
// Does it need to be suitable as a rendertarget? If so, check if it is already, upgrade it if neccessary:
if (asRendertarget && textureRecord->fboTable[0]->fboid==0) {
// Initialize and setup real FBO object (optionally with z- and stencilbuffer) and attach the texture
// as color attachment 0, aka main colorbuffer:
if (!PsychCreateFBO(&(textureRecord->fboTable[0]), (GLenum) 1, (PsychPrefStateGet_3DGfx() > 0) ? TRUE : FALSE, (int) PsychGetWidthFromRect(textureRecord->rect), (int) PsychGetHeightFromRect(textureRecord->rect), 0, (PsychGetTextureTarget(textureRecord) == GL_TEXTURE_2D) ? 1 : 0)) {
// Failed!
PsychErrorExitMsg(PsychError_internal, "Preparation of drawing into an offscreen window or texture failed when trying to create associated framebuffer object!");
}
}
return;
}
/* PsychNormalizeTextureOrientation() - On demand texture reswapping.
*
* PTB supports multiple different ways of orienting and formatting textures,
* optimized for different purposes. However, textures that one wants to draw
* to as if they were Offscreen windows or textures to be fed into the image
* processing pipeline (Screen('TransformTexture')) need to be in a standardized
* upright, non-transposed format. This routine checks the orientation of a
* texture and - if neccessary - transforms the texture from its current format
* to the upright standard format. As a side effect, it also converts such textures
* from Luminance or Luminance+Alpha formats into RGB or RGBA formats. This is
* important, because only RGB(A) textures are suitable as FBO color buffer attachments.
*
*/
void PsychNormalizeTextureOrientation(PsychWindowRecordType *sourceRecord)
{
int tmpimagingmode;
PsychFBO *fboptr;
GLint fboInternalFormat;
psych_bool needzbuffer, isplanar;
int width, height;
// Is this a planar encoding texture?
isplanar = (PsychIsTexture(sourceRecord) && (sourceRecord->specialflags & kPsychPlanarTexture)) ? TRUE : FALSE;
// The source texture sourceRecord could be in any of PTB's supported
// internal texture orientations. It may be upright as an Offscreen window,
// or flipped upside down as some textures from the video grabber,
// or transposed, as textures from Matlab/Octave. However, handling all those
// cases for image processing would be a debug and maintenance nightmare.
// Therefore we check the format of the source texture and require it to be
// a normal upright orientation. If this isn't the case, we perform a preprocessing
// step to transform the texture into normalized orientation. Non-planar textures would also
// wreak havoc if not converted into standard pixel-interleaved format:
if (sourceRecord->textureOrientation != 2 || isplanar) {
if (PsychPrefStateGet_Verbosity()>5) printf("PTB-DEBUG: In PsychNormalizeTextureOrientation(): Performing GPU renderswap or format conversion for source gl-texture %i --> ", sourceRecord->textureNumber);
// Soft-reset drawing engine in a safe way:
PsychSetDrawingTarget((PsychWindowRecordType*) 0x1);
// Normalization needed. Create a suitable FBO as rendertarget:
needzbuffer = FALSE;
// First delete FBO of texture if one already exists:
fboptr = sourceRecord->fboTable[0];
if (fboptr!=NULL) {
// Detach and delete color buffer texture:
needzbuffer = (fboptr->ztexid) ? TRUE : FALSE;
// Detach and delete depth buffer (and probably stencil buffer) texture, if any:
if (fboptr->ztexid) {
if (glIsTexture(fboptr->ztexid)) {
glDeleteTextures(1, &(fboptr->ztexid));
}
else {
glDeleteRenderbuffersEXT(1, &(fboptr->ztexid));
}
}
// Detach and delete stencil renderbuffer, if a separate stencil buffer was needed:
if (fboptr->stexid) glDeleteRenderbuffersEXT(1, &(fboptr->stexid));
// Delete FBO itself:
if (fboptr->fboid) glDeleteFramebuffersEXT(1, &(fboptr->fboid));
// Delete PsychFBO struct associated with this FBO:
free(fboptr); fboptr = NULL;
}
// Now recreate with proper format:
// First need to know internal format of texture...
glBindTexture(PsychGetTextureTarget(sourceRecord), sourceRecord->textureNumber);
glGetTexLevelParameteriv(PsychGetTextureTarget(sourceRecord), 0, GL_TEXTURE_INTERNAL_FORMAT, &fboInternalFormat);
// Need to query real size of underlying texture, not the logical size from sourceRecord->rect, otherwise we'd screw
// up for padded textures where the real texture is a bit bigger than its logical size.
if (sourceRecord->textureOrientation > 1) {
// Non-transposed textures, width and height are correct:
glGetTexLevelParameteriv(PsychGetTextureTarget(sourceRecord), 0, GL_TEXTURE_WIDTH, &width);
glGetTexLevelParameteriv(PsychGetTextureTarget(sourceRecord), 0, GL_TEXTURE_HEIGHT, &height);
}
else {
// Transposed textures: Need to swap meaning of width and height:
glGetTexLevelParameteriv(PsychGetTextureTarget(sourceRecord), 0, GL_TEXTURE_WIDTH, &height);
glGetTexLevelParameteriv(PsychGetTextureTarget(sourceRecord), 0, GL_TEXTURE_HEIGHT, &width);
}
glBindTexture(PsychGetTextureTarget(sourceRecord), 0);
// Override detected width and height for planar textures:
if (isplanar) {
// They are actually the net size as specified by their rect's:
width = (int) PsychGetWidthFromRect(sourceRecord->rect);
height = (int) PsychGetHeightFromRect(sourceRecord->rect);
}
// Special mapping for OpenGL-ES:
if (PsychIsGLES(sourceRecord)) {
// Enforce RGBA8 mapping, so all code below proceeds as if this is the case:
fboInternalFormat = GL_RGBA8;
// OpenGL-ES + float precision requested?
if ((sourceRecord->bpc > 8) || ((sourceRecord->depth / sourceRecord->nrchannels) >= 32)) {
// Upgrade to full 32bpc float -- we only support this, if at all:
fboInternalFormat = GL_RGBA_FLOAT32_APPLE;
// This will force code into proper path below:
sourceRecord->textureexternalformat = fboInternalFormat;
}
// Override width and height: Can't query size from OpenGL-ES due to lack of support,
// get net width and height for recreation of FBO:
width = (int) PsychGetWidthFromRect(sourceRecord->rect);
height = (int) PsychGetHeightFromRect(sourceRecord->rect);
}
// Renderable format? Pure luminance or luminance+alpha formats are not renderable on most hardware.
// Upgrade 8 bit luminace to 8 bit RGBA:
if (fboInternalFormat == GL_LUMINANCE8 || fboInternalFormat == GL_LUMINANCE8_ALPHA8 || sourceRecord->depth == 8) fboInternalFormat = GL_RGBA8;
// Upgrade non-renderable floating point formats to their RGB or RGBA counterparts of matching precision:
if (sourceRecord->nrchannels < 3 && fboInternalFormat != GL_RGBA8) {
// Unsupported format for FBO rendertargets. Need to upgrade to something suitable...
if (sourceRecord->textureexternalformat == GL_LUMINANCE) {
// Upgrade luminance to RGBA of matching precision: Why RGBA instead of RGB?
// Because Intel HD gpu's do not support RGB float as render target, so we are
// rather compatible and a bit slower...
// printf("UPGRADING TO RGBFAloat %i\n", (sourceRecord->textureinternalformat == GL_LUMINANCE_FLOAT16_APPLE) ? 0:1);
if (sourceRecord->textureinternalformat == GL_LUMINANCE16_SNORM) {
fboInternalFormat = GL_RGBA16_SNORM;
} else if (sourceRecord->textureinternalformat == GL_LUMINANCE16) {
fboInternalFormat = GL_RGBA16;
} else {
fboInternalFormat = (sourceRecord->textureinternalformat == GL_LUMINANCE_FLOAT16_APPLE) ? GL_RGBA_FLOAT16_APPLE : GL_RGBA_FLOAT32_APPLE;
}
}
else {
// Upgrade luminance+alpha to RGBA of matching precision:
// printf("UPGRADING TO RGBAFloat %i\n", (sourceRecord->textureinternalformat == GL_LUMINANCE_ALPHA_FLOAT16_APPLE) ? 0:1);
if (sourceRecord->textureinternalformat == GL_LUMINANCE16_ALPHA16_SNORM) {
fboInternalFormat = GL_RGBA16_SNORM;
} else if (sourceRecord->textureinternalformat == GL_LUMINANCE16_ALPHA16) {
fboInternalFormat = GL_RGBA16;
} else {
fboInternalFormat = (sourceRecord->textureinternalformat == GL_LUMINANCE_ALPHA_FLOAT16_APPLE) ? GL_RGBA_FLOAT16_APPLE : GL_RGBA_FLOAT32_APPLE;
}
}
}
// Special case: Quicktime movie or video texture, created by CoreVideo in Apple specific YUV format.
// This is a non-framebuffer renderable color format. Need to upgrade it to something safe:
if (fboInternalFormat == GL_YCBCR_422_APPLE) fboInternalFormat = GL_RGBA8;
// Special case: Planar texture encoded in a luminance texture other than LUMINANCE8. Need to
// upgrade to a full RGBA format of sufficient precision:
if (isplanar && (fboInternalFormat != GL_RGBA8 || sourceRecord->depth > 32)) {
if (sourceRecord->textureinternalformat == GL_LUMINANCE16_SNORM) {
fboInternalFormat = GL_RGBA16_SNORM;
} else if (sourceRecord->textureinternalformat == GL_LUMINANCE16) {
fboInternalFormat = GL_RGBA16;
} else {
fboInternalFormat = (sourceRecord->textureinternalformat == GL_LUMINANCE_FLOAT16_APPLE) ? GL_RGBA_FLOAT16_APPLE : GL_RGBA_FLOAT32_APPLE;
}
}
// If we end up with a RGB floating point format, just upgrade to matching RGBA floating point format.
// None of the existing Intel GPU's as of beginning 2015 can deal with RGB16F, RGB32F or RGB16_SNORM,
// so in the interest of portability to Intel HD gpu's, just sacrifice a bit of memory efficiency here:
if (fboInternalFormat == GL_RGB16_SNORM) fboInternalFormat = GL_RGBA16_SNORM;
if (fboInternalFormat == GL_RGB_FLOAT16_APPLE) fboInternalFormat = GL_RGBA_FLOAT16_APPLE;
if (fboInternalFormat == GL_RGB_FLOAT32_APPLE) fboInternalFormat = GL_RGBA_FLOAT32_APPLE;
// Now create proper FBO:
if (!PsychCreateFBO(&(sourceRecord->fboTable[0]), (GLenum) fboInternalFormat, needzbuffer, width, height, 0, (PsychGetTextureTarget(sourceRecord) == GL_TEXTURE_2D) ? 1 : 0)) {
PsychErrorExitMsg(PsychError_internal, "Failed to normalize texture orientation - Creation of framebuffer object failed!");
}
sourceRecord->drawBufferFBO[0] = 0;
sourceRecord->fboCount = 1;
tmpimagingmode = sourceRecord->imagingMode;
sourceRecord->imagingMode = 1;
// Set FBO of sourceRecord as rendertarget, including proper setup of render geometry:
// We can't use PsychSetDrawingTarget() here, as we might get called by that function, i.e.
// infinite recursion or other side effects if we tried to use it.
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, sourceRecord->fboTable[0]->fboid);
PsychSetupView(sourceRecord, FALSE);
// Reset MODELVIEW matrix, after backing it up...
glPushMatrix();
glLoadIdentity();
// For planar textures we need to bind the planar -> interleaved conversion shader:
if (isplanar) {
if ((sourceRecord->textureFilterShader == 0) && (PsychPrefStateGet_Verbosity() > 1)) {
printf("PTB-WARNING: Failed to normalize texture orientation and format: Conversion shader missing for this special planar texture!\n");
}
PsychSetShader(sourceRecord, -1 * sourceRecord->textureFilterShader);
}
// Now blit the old "disoriented" texture into the new FBO: The textureNumber of sourceRecord
// references the old texture, the PsychFBO of sourceRecord defines the new texture...
if (glIsEnabled(GL_BLEND)) {
// Alpha blending enabled. Disable it, blit texture, reenable it:
glDisable(GL_BLEND);
PsychBlitTextureToDisplay(sourceRecord, sourceRecord, sourceRecord->rect, sourceRecord->rect, 0, 0, 1);
glEnable(GL_BLEND);
}
else {
// Alpha blending not enabled. Just blit it:
PsychBlitTextureToDisplay(sourceRecord, sourceRecord, sourceRecord->rect, sourceRecord->rect, 0, 0, 1);
}
// Reset shader binding:
if (isplanar) {
PsychSetShader(sourceRecord, 0);
// Now the texture has been turned into a regular pixel-interleaved texture,
// it is no longer a planar texture, so we remove the planar->interleave
// conversion shader and clear the planar texture flag:
sourceRecord->textureFilterShader = 0;
sourceRecord->specialflags &= ~kPsychPlanarTexture;
}
// Restore modelview matrix:
glPopMatrix();
sourceRecord->imagingMode = tmpimagingmode;
PsychSetDrawingTarget(NULL);
// PsychSetDrawingTarget(NULL); doesn't do the full job of unbinding the fbo, so do
// it manually:
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
// At this point the color attachment of the sourceRecords FBO contains the properly oriented texture.
// Delete the old texture, attach the FBO texture as new one:
// Make sure movie textures are recycled instead of freed if possible:
PsychFreeMovieTexture(sourceRecord);
// Really free the texture if needed:
if (sourceRecord->textureNumber) {
// Standard case:
glDeleteTextures(1, &(sourceRecord->textureNumber));
}
// Assign new texture:
sourceRecord->textureNumber = sourceRecord->fboTable[0]->coltexid;
// Finally sourceRecord has the proper orientation:
sourceRecord->textureOrientation = 2;
// GPU renderswap finished.
if (PsychPrefStateGet_Verbosity()>5) printf("%i.\n", sourceRecord->textureNumber);
}
return;
}
/* PsychShutdownImagingPipeline()
* Shutdown imaging pipeline for a windowRecord and free all ressources associated with it.
*/
void PsychShutdownImagingPipeline(PsychWindowRecordType *windowRecord, psych_bool openglpart)
{
int i, j;
PsychFBO* fboptr;
// Do OpenGL specific cleanup:
if (openglpart) {
// Yes. Mode specific cleanup:
for (i = 0; i < windowRecord->fboCount; i++) {
// Delete i'th FBO, if any:
fboptr = windowRecord->fboTable[i];
if (fboptr != NULL) {
// Delete all remaining references to this fbo:
for (j = 0; j < windowRecord->fboCount; j++)
if (fboptr == windowRecord->fboTable[j])
windowRecord->fboTable[j] = NULL;
// Delete PsychFBO and all underlying OpenGL objects:
PsychDeleteFBO(fboptr);
}
}
}
// The following cleanup must only happen after OpenGL rendering context is already detached and
// destroyed. It's part of phase-2 "post GL shutdown" of Screen('Close') and friends...
if (!openglpart) {
// Clear all hook chains:
for (i=0; i<MAX_SCREEN_HOOKS; i++) {
windowRecord->HookChainEnabled[i]=FALSE;
PsychPipelineResetHook(windowRecord, PsychHookPointNames[i]);
}
// Global off:
windowRecord->imagingMode=0;
}
// If any interop handle that we still have ownership of was previously assigned to this window, then release it:
#if PSYCH_SYSTEM == PSYCH_WINDOWS
if (windowRecord->interopMemObjectHandle)
CloseHandle(windowRecord->interopMemObjectHandle);
if (windowRecord->interopSemaphoreHandle)
CloseHandle(windowRecord->interopSemaphoreHandle);
#endif
#if PSYCH_SYSTEM == PSYCH_LINUX
if (windowRecord->interopMemObjectHandle)
close((int) (size_t) windowRecord->interopMemObjectHandle);
if (windowRecord->interopSemaphoreHandle)
close((int) (size_t) windowRecord->interopSemaphoreHandle);
#endif
windowRecord->interopMemObjectHandle = 0;
windowRecord->interopSemaphoreHandle = 0;
// Cleanup done.
return;
}
void PsychPipelineListAllHooks(PsychWindowRecordType *windowRecord)
{
int i;
(void) windowRecord;
printf("PTB-INFO: The Screen command currently provides the following hook functions:\n");
printf("=============================================================================\n");
for (i=0; i<MAX_SCREEN_HOOKS; i++) {
printf("- %s : %s\n", PsychHookPointNames[i], PsychHookPointSynopsis[i]);
}
printf("=============================================================================\n\n");
fflush(NULL);
// Well done.
return;
}
/* Map a hook name string to its corresponding hook chain index:
* Returns -1 if such a hook name doesn't exist.
*/
int PsychGetHookByName(const char* hookName)
{
int i;
for (i=0; i<MAX_SCREEN_HOOKS; i++) {
if(strcmp(PsychHookPointNames[i], hookName)==0) break;
}
return((i>=MAX_SCREEN_HOOKS) ? -1 : i);
}
/* Internal: PsychAddNewHookFunction() - Add a new hook callback function to a hook-chain.
* This helper function allocates a hook func struct, enqueues it into a hook chain and sets
* all common struct fields to their proper values. Then it returns a pointer to the struct, so
* the calling routine can fill the rest of the struct with information.
*
* windowRecord - The windowRecord of the window to attach to.
* hookString - String with the human-readable name of the hook-chain to attach to.
* idString - Arbitrary name string for this hook function (for debugging and finding it programmatically)
* where - Attachment point: 0 = Prepend to chain (Recommended). INT_MAX = Append to chain (Use with care!), or insert at position 'where'.
* hookfunctype - Symbolic hook function type id, needed for interpreter to distinguish different types.
*
*/
PsychHookFunction* PsychAddNewHookFunction(PsychWindowRecordType *windowRecord, const char* hookString, const char* idString, int where, int hookfunctype)
{
int hookidx, hookslotidx;
PtrPsychHookFunction hookfunc, hookiter, *hookpreiter;
// Lookup hook-chain idx for this name, if any:
if ((hookidx=PsychGetHookByName(hookString))==-1) PsychErrorExitMsg(PsychError_user, "AddHook: Unknown (non-existent) hook name provided.");
// Allocate a hook structure:
hookfunc = (PtrPsychHookFunction) calloc(1, sizeof(PsychHookFunction));
if (hookfunc==NULL) PsychErrorExitMsg(PsychError_outofMemory, "Failed to allocate memory for new hook function.");
// Enqueue at beginning or end of chain:
if (where==0) {
// Prepend it to existing chain:
hookfunc->next = windowRecord->HookChain[hookidx];
windowRecord->HookChain[hookidx] = hookfunc;
}
else {
// Append it to existing chain:
hookfunc->next = NULL;
if (windowRecord->HookChain[hookidx]==NULL) {
windowRecord->HookChain[hookidx]=hookfunc;
}
else {
hookiter = windowRecord->HookChain[hookidx];
hookslotidx = 0;
hookpreiter = &(windowRecord->HookChain[hookidx]);
while ((hookiter->next) && (hookslotidx!=where)) {
hookpreiter = &(hookiter->next);
hookiter = hookiter->next;
hookslotidx++;
}
if (hookslotidx==where) {
// Target slot index for insertion reached: Insert here.
hookfunc->next = hookiter;
*hookpreiter = hookfunc;
}
else {
// End of chain reached: Append new slot, regardless of index:
hookiter->next = hookfunc;
}
}
}
// New hookfunc struct is enqueued and zero initialized. Fill rest of its fields:
hookfunc->idString = (idString) ? strdup(idString) : strdup("");
hookfunc->hookfunctype = hookfunctype;
// Return pointer to new hook slot:
return(hookfunc);
}
/* PsychPipelibneDisableHook - Disable named hook chain. */
void PsychPipelineDisableHook(PsychWindowRecordType *windowRecord, const char* hookString)
{
int hook=PsychGetHookByName(hookString);
if (hook==-1) PsychErrorExitMsg(PsychError_user, "DisableHook: Unknown (non-existent) hook name provided.");
windowRecord->HookChainEnabled[hook] = FALSE;
return;
}
/* PsychPipelibneEnableHook - Enable named hook chain. */
void PsychPipelineEnableHook(PsychWindowRecordType *windowRecord, const char* hookString)
{
int hook=PsychGetHookByName(hookString);
if (hook==-1) PsychErrorExitMsg(PsychError_user, "EnableHook: Unknown (non-existent) hook name provided.");
windowRecord->HookChainEnabled[hook] = TRUE;
return;
}
/* PsychPipelineResetHook() - Reset named hook chain by deleting all assigned callback functions.
* windowRecord - Window/Texture for which processing chain should be reset.
* hookString - Name string of hook chain to reset.
*/
void PsychPipelineResetHook(PsychWindowRecordType *windowRecord, const char* hookString)
{
PtrPsychHookFunction hookfunc, hookiter;
int hookidx=PsychGetHookByName(hookString);
if (hookidx==-1) PsychErrorExitMsg(PsychError_user, "ResetHook: Unknown (non-existent) hook name provided.");
hookiter = windowRecord->HookChain[hookidx];
while(hookiter) {
hookfunc = hookiter;
hookiter = hookiter->next;
// Delete all referenced memory:
free(hookfunc->idString);
free(hookfunc->pString1);
// Delete hookfunc struct itself:
free(hookfunc);
}
// Null-out hook chain:
windowRecord->HookChain[hookidx]=NULL;
return;
}
/* PsychPipelineAddShaderToHook()
* Add a GLSL shader program object to a hook chain. The shader is executed when the corresponding
* hook chain slot is executed, using the specified blitter and OpenGL context configuration and the
* specified lut texture bound to unit 1.
*
* windowRecord - Execute for this window/texture.
* hookString - Attach to this named chain.
* idString - Arbitrary name string for identification (query) and debugging.
* where - Where to attach (0=Beginning, 1=End).
* shaderid - GLSL shader program object id.
* blitterString - Config string to define the used blitter function and its config.
* luttexid1 - Id of texture to be bound to first texture unit (unit 1).
*/
void PsychPipelineAddShaderToHook(PsychWindowRecordType *windowRecord, const char* hookString, const char* idString, int where, unsigned int shaderid, const char* blitterString, unsigned int luttexid1)
{
// Create and attach proper preinitialized hook function and return pointer to it for further initialization:
PtrPsychHookFunction hookfunc = PsychAddNewHookFunction(windowRecord, hookString, idString, where, kPsychShaderFunc);
// Init remaining fields:
hookfunc->shaderid = shaderid;
hookfunc->pString1 = (blitterString) ? strdup(blitterString) : strdup("");
hookfunc->luttexid1 = luttexid1;
return;
}
/* PsychPipelineAddCFunctionToHook()
* Add a C callback function to a hook chain. The C callback function is executed when the corresponding
* hook chain slot is executed, passing a set of parameters via a void* struct pointer. The set of parameters
* is dependent on the exact hook chain, so users of this function must have knowledge of the PTB-3 source code
* to know what to expect.
*
* windowRecord - Execute for this window/texture.
* hookString - Attach to this named chain.
* idString - Arbitrary name string for identification (query) and debugging.
* where - Where to attach (0=Beginning, 1=End).
* procPtr - A void* function pointer which will be cast to a proper function pointer during execution.
*/
void PsychPipelineAddCFunctionToHook(PsychWindowRecordType *windowRecord, const char* hookString, const char* idString, int where, void* procPtr)
{
// Create and attach proper preinitialized hook function and return pointer to it for further initialization:
PtrPsychHookFunction hookfunc = PsychAddNewHookFunction(windowRecord, hookString, idString, where, kPsychCFunc);
// Init remaining fields:
hookfunc->cprocfunc = procPtr;
return;
}
/* PsychPipelineAddRuntimeFunctionToHook()
* Add a runtime environment callback function to a hook chain. The function is executed when the corresponding
* hook chain slot is executed, passing a set of parameters. The set of parameters depends on the exact hook
* chain, so users of this function must have knowledge of the PTB-3 source code to know what to expect.
*
* The mechanism to execute a runtime function depends on the runtime environment. On Matlab and Octave, the
* internal feval() functions are used to call a Matlab- or Octave function, either a builtin function or some
* function defined as M-File or dynamically linked.
*
* windowRecord - Execute for this window/texture.
* hookString - Attach to this named chain.
* idString - Arbitrary name string for identification (query) and debugging.
* where - Where to attach (0=Beginning, 1=End).
* evalString - A function string to be passed to the runtime environment for evaluation during execution.
*/
void PsychPipelineAddRuntimeFunctionToHook(PsychWindowRecordType *windowRecord, const char* hookString, const char* idString, int where, const char* evalString)
{
// Create and attach proper preinitialized hook function and return pointer to it for further initialization:
PtrPsychHookFunction hookfunc = PsychAddNewHookFunction(windowRecord, hookString, idString, where, kPsychMFunc);
// Init remaining fields:
hookfunc->pString1 = (evalString) ? strdup(evalString) : strdup("");
return;
}
/* PsychPipelineAddBuiltinFunctionToHook()
* Add a builtin callback function to a hook chain. The function is executed when the corresponding
* hook chain slot is executed, passing a set of parameters. The set of parameters depends on the exact hook
* chain, so users of this function must have knowledge of the PTB-3 source code to know what to expect.
*
* windowRecord - Execute for this window/texture.
* hookString - Attach to this named chain.
* idString - This idString defines the builtin function to call.
* where - Where to attach (0=Beginning, 1=End).
* configString - A string with configuration parameters.
*/
void PsychPipelineAddBuiltinFunctionToHook(PsychWindowRecordType *windowRecord, const char* hookString, const char* idString, int where, const char* configString)
{
// Create and attach proper preinitialized hook function and return pointer to it for further initialization:
PtrPsychHookFunction hookfunc = PsychAddNewHookFunction(windowRecord, hookString, idString, where, kPsychBuiltinFunc);
// Init remaining fields:
hookfunc->pString1 = (configString) ? strdup(configString) : strdup("");
return;
}
/* PsychPipelineDeleteHookSlot
* Remove slot at index 'slotid', move all slots past this slot one slot up.
*/
void PsychPipelineDeleteHookSlot(PsychWindowRecordType *windowRecord, const char* hookString, int slotid)
{
PtrPsychHookFunction hookfunc;
PtrPsychHookFunction *prehookfunc;
int idx;
int hookidx=PsychGetHookByName(hookString);
if (hookidx==-1) PsychErrorExitMsg(PsychError_user, "RemoveHook: Unknown (non-existent) hook name provided.");
// Perform linear search until proper slot reached or proper name reached:
idx=0;
hookfunc = windowRecord->HookChain[hookidx];
prehookfunc = &(windowRecord->HookChain[hookidx]);
while(hookfunc && idx<slotid) {
prehookfunc = &(hookfunc->next);
hookfunc = hookfunc->next;
idx++;
}
// Anything found?
if(hookfunc == NULL) return;
// hookfunc is to be deleted.
// Detach it from hookchain, update predecessors next pointer so it points to successor:
*prehookfunc = hookfunc->next;
// Detached. Delete hookfunc:
free(hookfunc->pString1);
free(hookfunc->idString);
free(hookfunc);
hookfunc = NULL;
// Done.
return;
}
/* PsychPipelineQueryHookSlot
* Query properties of a specific hook slot in a specific hook chain of a specific window:
* windowRecord - Query for this window/texture.
* hookString - Query this named chain.
* idString - This string defines the specific slot to query. Can contain an integral number, then the associated slot is
* queried, or a idString (as assigned during creation), then a slot with that name is queried. Partial name
* matches are also accepted to search for substrings...
*
* On successfull return, the following values are assigned, on unsuccessfull return (=-1), nothing is assigned:
* insertString = The subcommand one would need to issue to (re-)add this slot at exactly the same place. E.g., 'InsertAt4MFunction' if slot is a M-Function at position 4.
* idString = The name string of this slot *Read-Only*
* blitterString = Config string for this slot.
* doubleptr = Double encoded void* to the C-Callback function, if any.
* shaderid = Double encoded shader handle for GLSL shader, if any.
* luttexid = Double encoded lut texture handle for unit 1, if any.
*
* The return value contains the hook slot index where the function was found, or -1 if no matching function could be found.
*/
int PsychPipelineQueryHookSlot(PsychWindowRecordType *windowRecord, const char* hookString, char** insertString, char** idString, char** blitterString, double* doubleptr, double* shaderid, double* luttexid1)
{
PtrPsychHookFunction hookfunc;
char myinsertString[100];
char mytypeString[80];
int targetidx, idx;
int nrassigned = sscanf((*idString), "%i", &targetidx);
int hookidx=PsychGetHookByName(hookString);
if (hookidx==-1) PsychErrorExitMsg(PsychError_user, "QueryHook: Unknown (non-existent) hook name provided.");
if (nrassigned != 1) targetidx=-1;
idx=0;
// Perform linear search until proper slot reached or proper name reached:
hookfunc = windowRecord->HookChain[hookidx];
while(hookfunc && ((targetidx>-1 && idx<targetidx) || (targetidx==-1 && strstr(hookfunc->idString, *idString)==NULL))) {
hookfunc = hookfunc->next;
idx++;
}
// If hookfunc is non-NULL then we found our slot:
if (hookfunc==NULL) {
*insertString = NULL;
*idString = NULL;
*blitterString = NULL;
*doubleptr = 0;
*shaderid = 0;
*luttexid1 = 0;
return(-1);
}
switch(hookfunc->hookfunctype) {
case kPsychBuiltinFunc:
sprintf(mytypeString, "Builtin");
break;
case kPsychMFunc:
sprintf(mytypeString, "MFunction");
break;
case kPsychCFunc:
sprintf(mytypeString, "CFunction");
break;
case kPsychShaderFunc:
sprintf(mytypeString, "Shader");
break;
default:
PsychErrorExitMsg(PsychError_internal, "Unknown id for hookfunction in PsychPipelineQueryHookSlot()! Update the code and recompile!!");
}
sprintf(myinsertString, "InsertAt%i%s", idx, mytypeString);
*insertString = strdup(myinsertString);
*idString = hookfunc->idString;
*blitterString = hookfunc->pString1;
*doubleptr = PsychPtrToDouble(hookfunc->cprocfunc);
*shaderid = (double) hookfunc->shaderid;
*luttexid1= (double) hookfunc->luttexid1;
return(idx);
}
/* PsychPipelineDumpHook
* Dump properties of a specific hook chain of a specific window in a human-readable format into
* the console of the scripting environment:
*
* windowRecord - Query for this window/texture.
* hookString - Query this named chain.
*/
void PsychPipelineDumpHook(PsychWindowRecordType *windowRecord, const char* hookString)
{
PtrPsychHookFunction hookfunc;
int i=0;
int hookidx=PsychGetHookByName(hookString);
if (hookidx==-1) PsychErrorExitMsg(PsychError_user, "DumpHook: Unknown (non-existent) hook name provided.");
hookfunc = windowRecord->HookChain[hookidx];
printf("Hook chain %s is currently %s.\n", hookString, (windowRecord->HookChainEnabled[hookidx]) ? "enabled" : "disabled");
if (hookfunc==NULL) {
printf("No processing assigned to this hook-chain.\n");
}
else {
printf("Following hook slots are assigned to this hook-chain:\n");
printf("=====================================================\n");
}
while(hookfunc) {
printf("Slot %i: Id='%s' : ", i, hookfunc->idString);
switch(hookfunc->hookfunctype) {
case kPsychShaderFunc:
printf("GLSL-Shader : id=%i , luttex1=%i , blitter=%s\n", hookfunc->shaderid, hookfunc->luttexid1, hookfunc->pString1);
break;
case kPsychCFunc:
printf("C-Callback : void*= %p\n", hookfunc->cprocfunc);
break;
case kPsychMFunc:
printf("Runtime-Function : Evalstring= %s\n", hookfunc->pString1);
break;
case kPsychBuiltinFunc:
printf("Builtin-Function : Name= %s\n", hookfunc->idString);
break;
}
// Next one, if any:
i++;
hookfunc = hookfunc->next;
}
printf("=====================================================\n\n");
fflush(NULL);
return;
}
/* PsychPipelineDumpAllHooks
* Dump current state of all hook-points for given window. See PsychPipelineDumpHook()
* for more info.
*/
void PsychPipelineDumpAllHooks(PsychWindowRecordType *windowRecord)
{
int i;
for (i=0; i<MAX_SCREEN_HOOKS; i++) {
PsychPipelineDumpHook(windowRecord, PsychHookPointNames[i]);
}
return;
}
psych_bool PsychIsHookChainOperational(PsychWindowRecordType *windowRecord, int hookid)
{
// Child protection:
if (hookid<0 || hookid>=MAX_SCREEN_HOOKS) PsychErrorExitMsg(PsychError_internal, "In PsychIsHookChainOperational: Was asked to check unknown (non-existent) hook chain with invalid id!");
// Hook chain enabled for processing and contains at least one hook slot?
if ((!windowRecord->HookChainEnabled[hookid]) || (windowRecord->HookChain[hookid] == NULL)) {
// Chain is empty or disabled.
return(FALSE);
}
// Chain operational:
return(TRUE);
}
/* PsychPipelineExecuteHook()
* Execute the full hook processing chain for a specific hook and a specific windowRecord.
* This checks if the chain is enabled. If it isn't enabled, it skips processing.
* If it is enabled, it iterates over the full chain, executes all assigned hook functions in order and uses the FBO's between minfbo and maxfbo
* as pingpong buffers if neccessary.
*/
psych_bool PsychPipelineExecuteHook(PsychWindowRecordType *windowRecord, int hookId, void* hookUserData, void* hookBlitterFunction, psych_bool srcIsReadonly, psych_bool allowFBOSwizzle, PsychFBO** srcfbo1, PsychFBO** srcfbo2, PsychFBO** dstfbo, PsychFBO** bouncefbo)
{
PtrPsychHookFunction hookfunc;
int i=0;
int pendingFBOpingpongs = 0;
PsychFBO *mysrcfbo1, *mysrcfbo2, *mydstfbo, *mynxtfbo;
PsychFBO **bouncefbo2 = NULL;
psych_bool gfxprocessing;
GLint restorefboid = 0;
psych_bool scissor_ignore = FALSE;
psych_bool scissor_enabled = FALSE;
int sciss_x, sciss_y, sciss_w, sciss_h;
// Child protection:
if (hookId<0 || hookId>=MAX_SCREEN_HOOKS) PsychErrorExitMsg(PsychError_internal, "In PsychPipelineExecuteHook: Was asked to execute unknown (non-existent) hook chain with invalid id!");
// Hook chain enabled for processing and contains at least one hook slot?
if ((!windowRecord->HookChainEnabled[hookId]) || (windowRecord->HookChain[hookId] == NULL)) {
// Chain is empty or disabled.
return(TRUE);
}
// Is this an image processing hook?
gfxprocessing = (dstfbo!=NULL) ? TRUE : FALSE;
// Get start of enabled chain:
hookfunc = windowRecord->HookChain[hookId];
// Count number of needed ping-pong FBO switches inside this chain:
while(hookfunc) {
// Pingpong command?
if (hookfunc->hookfunctype == kPsychBuiltinFunc && strcmp(hookfunc->idString, "Builtin:FlipFBOs")==0) pendingFBOpingpongs++;
// Process next hookfunc slot in chain, if any:
hookfunc = hookfunc->next;
}
if (gfxprocessing) {
// Prepare gfx-processing:
// Slightly ugly, because it is a layering violation, but kind'a unavoidable,
// as the final output formatting blit chain is a special case...
// Assign bouncefbo2 if it is available and needed, otherwise assign dstfbo:
// It is available if preConversionFBO[3]>=0. It is needed if pendingFBOpingpongs > 1
// and this is one of the final output formatting blit chains. Other chains don't need
// this special treatment with a 2nd bounce buffer:
if ((windowRecord->preConversionFBO[3]>=0) && (pendingFBOpingpongs > 1) &&
(hookId == kPsychFinalOutputFormattingBlit || hookId == kPsychFinalOutputFormattingBlit0 || hookId == kPsychFinalOutputFormattingBlit1)) {
// Assign special 2nd bounce buffer:
bouncefbo2 = &(windowRecord->fboTable[windowRecord->preConversionFBO[3]]);
}
else {
// Standard case, dstfbo acts as final target and as 2nd bounce buffer if needed for multi-slot chains:
bouncefbo2 = dstfbo;
}
// Backup scissoring state:
scissor_enabled = glIsEnabled(GL_SCISSOR_TEST);
// If this is a multi-pass chain we'll need a bounce buffer FBO:
if ((pendingFBOpingpongs > 0 && bouncefbo == NULL) || (pendingFBOpingpongs > 1 && ((*bouncefbo2)->fboid == 0))) {
printf("PTB-ERROR: Hook processing chain '%s' is a multi-pass processing chain with %i passes,\n", PsychHookPointNames[hookId], pendingFBOpingpongs + 1);
printf("PTB-ERROR: but imaging pipeline is not configured for multi-pass processing! You need to supply the additional flag\n");
printf("PTB-ERROR: %s as imagingmode to Screen('OpenWindow') to tell PTB about these requirements and then restart.\n\n",
(pendingFBOpingpongs > 1) ? "kPsychNeedMultiPass" : "kPsychNeedDualPass");
// Ok, abort...
PsychErrorExitMsg(PsychError_user, "Insufficient pipeline configuration for processing. Adapt the 'imagingmode' flag according to my tips!");
}
if ((pendingFBOpingpongs % 2) == 0) {
// Even number of ping-pongs needed in this chain. We stream from source fbo to
// destination fbo in first pass.
mysrcfbo1 = (srcfbo1) ? *srcfbo1 : NULL;
mysrcfbo2 = (srcfbo2) ? *srcfbo2 : NULL;
mydstfbo = *bouncefbo2;
mynxtfbo = (bouncefbo) ? *bouncefbo : NULL;
}
else {
// Odd number of ping-pongs needed. Initially stream from source to bouncefbo:
mysrcfbo1 = (srcfbo1) ? *srcfbo1 : NULL;
mysrcfbo2 = (srcfbo2) ? *srcfbo2 : NULL;
mydstfbo = (bouncefbo) ? *bouncefbo : NULL;
mynxtfbo = *bouncefbo2;
}
// Special case: If this is the last processing slot, aka pendingFBOpingpongs == 0,
// then mydstfbo must be our real destination framebuffer:
if (pendingFBOpingpongs == 0) mydstfbo = *dstfbo;
// Enable associated GL context:
PsychSetGLContext(windowRecord);
// Save current FBO bindings for later restore on classic desktop OpenGL1/2:
if (glBindFramebufferEXT && PsychIsGLClassic(windowRecord)) {
glGetIntegerv(GL_FRAMEBUFFER_BINDING_EXT, &restorefboid);
}
else {
// Unsupported on OES and next gen: TODO FIXME - Implement proper state tracking.
restorefboid = 0;
}
// Setup initial source -> target binding:
PsychPipelineSetupRenderFlow(mysrcfbo1, mysrcfbo2, mydstfbo, scissor_ignore);
}
// Reget start of enabled chain:
hookfunc = windowRecord->HookChain[hookId];
// Iterate over all slots:
while(hookfunc) {
// Debug output, if requested:
if (PsychPrefStateGet_Verbosity()>4) {
printf("Hookchain '%s' : Slot %i: Id='%s' : ", PsychHookPointNames[hookId], i, hookfunc->idString);
switch(hookfunc->hookfunctype) {
case kPsychShaderFunc:
printf("GLSL-Shader : id=%i , luttex1=%i , blitter=%s\n", hookfunc->shaderid, hookfunc->luttexid1, hookfunc->pString1);
break;
case kPsychCFunc:
printf("C-Callback : void*= %p\n", hookfunc->cprocfunc);
break;
case kPsychMFunc:
printf("Runtime-Function : Evalstring= %s\n", hookfunc->pString1);
break;
case kPsychBuiltinFunc:
printf("Builtin-Function : Name= %s : Params= %s\n", hookfunc->idString, hookfunc->pString1);
break;
}
}
// Is this a ping-pong command?
if ((hookfunc->hookfunctype == kPsychBuiltinFunc) && gfxprocessing && (strcmp(hookfunc->idString, "Builtin:FlipFBOs")==0)) {
// Ping pong buffer swap requested:
pendingFBOpingpongs--;
mysrcfbo1 = mydstfbo;
mydstfbo = mynxtfbo;
if ((pendingFBOpingpongs % 2) == 0) {
// Even number of ping-pongs remaining in this chain.
mynxtfbo = (bouncefbo) ? *bouncefbo : NULL;
}
else {
// Odd number of ping-pongs remaining.
mynxtfbo = *bouncefbo2;
}
// Special case: If this is the last processing slot, aka pendingFBOpingpongs == 0,
// then mydstfbo must be our real destination framebuffer:
if (pendingFBOpingpongs == 0) mydstfbo = *dstfbo;
if (PsychPrefStateGet_Verbosity()>4) printf("PTB-DEBUG: SWAPPING PING-PONG FBOS, %i swaps pending...\n", pendingFBOpingpongs);
// Set new src -> dst binding:
PsychPipelineSetupRenderFlow(mysrcfbo1, mysrcfbo2, mydstfbo, scissor_ignore);
}
else {
// Restricted area processing?
if (hookfunc->hookfunctype == kPsychBuiltinFunc && strstr(hookfunc->idString, "Builtin:RestrictToScissorROI")) {
// Restrict pixel processing to specified region of interest ROI by setting
// up a proper scissor rectangle and enabling scissor tests. The special
// ROI (-1,-1,-1,-1) means: Disable scissor testing -> Unrestrict.
if (4!=sscanf(hookfunc->pString1, "%i:%i:%i:%i", &sciss_x, &sciss_y, &sciss_w, &sciss_h)) {
if (PsychPrefStateGet_Verbosity()>0) printf("PTB-ERROR: In PsychPipelineExecuteHook: Builtin:RestrictToScissorROI - Parameter parse error in string %s\n", hookfunc->idString);
return(FALSE);
}
if (sciss_x==-1 && sciss_y==-1 && sciss_w==-1 && sciss_h==-1) {
// Disable scissor tests:
glDisable(GL_SCISSOR_TEST);
scissor_ignore = FALSE;
}
else {
// Setup and enable scissor test:
glEnable(GL_SCISSOR_TEST);
glScissor(sciss_x, sciss_y, sciss_w, sciss_h);
// Make sure PsychSetupRenderFlow() ignores scissor setup:
scissor_ignore = TRUE;
}
}
else if (hookfunc->hookfunctype == kPsychBuiltinFunc && strstr(hookfunc->idString, "Builtin:ActivateOpenGLContext")) {
// Enable associated GL context with no other side effects:
PsychSetGLContext(windowRecord);
}
else {
// Normal hook function - Process this hook function:
if (!PsychPipelineExecuteHookSlot(windowRecord, hookId, hookfunc, hookUserData, hookBlitterFunction, srcIsReadonly, allowFBOSwizzle, &mysrcfbo1, &mysrcfbo2, &mydstfbo, &mynxtfbo)) {
// Failed!
if (PsychPrefStateGet_Verbosity()>0) {
printf("PTB-ERROR: Failed in processing of Hookchain '%s' : Slot %i: Id='%s' --> Aborting chain processing. Set verbosity to 5 for extended debug output.\n", PsychHookPointNames[hookId], i, hookfunc->idString);
}
return(FALSE);
}
}
}
// Process next hookfunc slot in chain, if any:
i++;
hookfunc = hookfunc->next;
}
if (gfxprocessing) {
// Disable renderflow:
PsychPipelineSetupRenderFlow(NULL, NULL, NULL, scissor_ignore);
// A bit of a hack: If srcfbo1 has a multisample texture as colorbuffer,
// then unbind it to disable multisample texturetarget. We currently only
// support multisample colorbuffer textures on srcfbo1 and texture unit zero,
// hence this special case for efficiency.
if (mysrcfbo1 && (mysrcfbo1->textarget == GL_TEXTURE_2D_MULTISAMPLE)) {
glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0);
}
// Restore old FBO bindings:
if (glBindFramebufferEXT) glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, restorefboid);
// Restore scissor state:
if (scissor_enabled) {
glEnable(GL_SCISSOR_TEST);
}
else {
glDisable(GL_SCISSOR_TEST);
}
}
// Done.
return(TRUE);
}
/* PsychPipelineProcessMacros()
* Expand given cmdString, based on info in given windowRecord, return expanded string.
* The expanded string is returned as a char* and the caller is responsible for freeing
* the allocated memory.
*
* Returns 1 on succcess, 0 on error.
*/
int PsychPipelineProcessMacros(PsychWindowRecordType *windowRecord, char* cmdString)
{
psych_bool repeatit = TRUE;
char varName[256];
char* pCurrent = strdup(cmdString);
char* pToken = NULL;
int i, rc;
double* dbltarget = NULL;
PsychGenericScriptType* newvar = NULL;
while ((repeatit) && (pCurrent) && (pCurrent[0]!=0)) {
// Reset repeatit. Will be set by following code again if another parse-iteration is needed:
repeatit = FALSE;
dbltarget = NULL;
newvar = NULL;
if (PsychPrefStateGet_Verbosity() > 10) printf("PTB-DEBUG: PsychPipelineProcessMacros: cmd = %s\n", pCurrent);
// Check current remaining command string for certain keywords to process:
// -----------------------------------------------------------------------
// Return of current gammatable requested?
sprintf(varName, "IMAGINGPIPE_GAMMATABLE");
if ((pToken = strstr(pCurrent, varName))) {
// Wants us to assign current gammatable from Screen('LoadNormalizedGammatable', ..., 2) call
// to the variable IMAGINGPIPE_GAMMATABLE:
// Delete the varName from string:
memset(pToken, 'X', strlen(varName));
repeatit = TRUE;
// Any pending gammatable stored internally for update? If not, we skip further processing:
if (windowRecord->inRedTable == NULL) {
if (PsychPrefStateGet_Verbosity() > 10) printf("PTB-DEBUG: PsychPipelineProcessMacros: IMAGINGPIPE_GAMMATABLE variable assignment failed. No suitable CLUT set in Screen('LoadNormalizedGammaTable'). Skipped slot!\n");
// Return error code zero to abort processing of this hook slot:
rc = 0;
goto macros_out;
}
if (windowRecord->inTableSize < 1) {
if (PsychPrefStateGet_Verbosity() > 10) printf("PTB-DEBUG: PsychPipelineProcessMacros: IMAGINGPIPE_GAMMATABLE variable assignment failed. CLUT has less than the required 1 slots. Skipped slot!\n");
// Return error code zero to abort processing of this hook slot:
rc = 0;
goto macros_out;
}
// Allocate runtime double matrix of sufficient size: 'newvar' is the handle of it,
// dbltarget is a pointer to the target double matrix we need to fill with the clut:
PsychAllocateNativeDoubleMat(windowRecord->inTableSize, 3, 1, &dbltarget, &newvar);
for (i = 0; i < windowRecord->inTableSize; i++) *(dbltarget++) = (double) windowRecord->inRedTable[i];
for (i = 0; i < windowRecord->inTableSize; i++) *(dbltarget++) = (double) windowRecord->inGreenTable[i];
for (i = 0; i < windowRecord->inTableSize; i++) *(dbltarget++) = (double) windowRecord->inBlueTable[i];
// Release the gamma table:
free(windowRecord->inRedTable); windowRecord->inRedTable = NULL;
free(windowRecord->inGreenTable); windowRecord->inGreenTable = NULL;
free(windowRecord->inBlueTable); windowRecord->inBlueTable = NULL;
windowRecord->inTableSize = 0;
windowRecord->loadGammaTableOnNextFlip = 0;
// Copy to caller workspace:
if (PsychRuntimePutVariable("caller", varName, newvar)) {
if (PsychPrefStateGet_Verbosity() > 0) printf("PTB-ERROR: PsychPipelineProcessMacros: IMAGINGPIPE_GAMMATABLE variable assignment failed in runtime! Skipped slot!\n");
rc = 0;
goto macros_out;
}
else {
if (PsychPrefStateGet_Verbosity() > 10) printf("PTB-DEBUG: PsychPipelineProcessMacros: IMAGINGPIPE_GAMMATABLE variable assignment success in runtime!\n");
}
// Next parseloop iteration:
continue;
}
// Return of current flipcount requested?
sprintf(varName, "IMAGINGPIPE_FLIPCOUNT");
if ((pToken = strstr(pCurrent, varName))) {
// Wants us to assign current flipCount to the variable IMAGINGPIPE_FLIPCOUNT:
// Delete the varName from string:
memset(pToken, 'X', strlen(varName));
repeatit = TRUE;
// Allocate runtime double matrix of scalar size: 'newvar' is the handle of it,
// dbltarget is a pointer to the target double matrix we need to fill with the flipCount:
PsychAllocateNativeDoubleMat(1, 1, 1, &dbltarget, &newvar);
*dbltarget = (double) windowRecord->flipCount;
// Copy to caller workspace:
if (PsychRuntimePutVariable("caller", varName, newvar)) {
if (PsychPrefStateGet_Verbosity() > 0) printf("PTB-ERROR: PsychPipelineProcessMacros: IMAGINGPIPE_FLIPCOUNT variable assignment failed in runtime! Skipped slot!\n");
rc = 0;
goto macros_out;
}
else {
if (PsychPrefStateGet_Verbosity() > 10) printf("PTB-DEBUG: PsychPipelineProcessMacros: ASSIGNED %f\n", (float) *dbltarget);
}
// Next parseloop iteration:
continue;
}
// Return of usercode provided tWhen target flip time requested?
sprintf(varName, "IMAGINGPIPE_FLIPTWHEN");
if ((pToken = strstr(pCurrent, varName))) {
// Wants us to assign current Screen('Flip', win, tWhen, ...) tWhen time to the variable IMAGINGPIPE_FLIPTWHEN:
// Delete the varName from string:
memset(pToken, 'X', strlen(varName));
repeatit = TRUE;
if ((!(windowRecord->flipInfo) || (windowRecord->flipInfo->flipwhen == -DBL_MAX)) && (PsychPrefStateGet_Verbosity() > 9))
printf("PTB-DEBUG: PsychPipelineProcessMacros: IMAGINGPIPE_FLIPTWHEN variable requested, but not yet set up! Screen('DrawingFinished') improper call?!?\n");
// Allocate runtime double matrix of scalar size: 'newvar' is the handle of it,
// dbltarget is a pointer to the target double matrix we need to fill with the tWhen time:
PsychAllocateNativeDoubleMat(1, 1, 1, &dbltarget, &newvar);
*dbltarget = (double) ((windowRecord->flipInfo && (windowRecord->flipInfo->flipwhen != -DBL_MAX)) ? windowRecord->flipInfo->flipwhen : -DBL_MAX);
// Copy to caller workspace:
if (PsychRuntimePutVariable("caller", varName, newvar)) {
if (PsychPrefStateGet_Verbosity() > 0) printf("PTB-ERROR: PsychPipelineProcessMacros: IMAGINGPIPE_FLIPTWHEN variable assignment failed in runtime! Skipped slot!\n");
rc = 0;
goto macros_out;
}
else {
if (PsychPrefStateGet_Verbosity() > 10) printf("PTB-DEBUG: PsychPipelineProcessMacros: ASSIGNED %f\n", (float) *dbltarget);
}
// Next parseloop iteration:
continue;
}
// Return of usercode provided vbl_synclevel for Flip requested?
sprintf(varName, "IMAGINGPIPE_FLIPVBLSYNCLEVEL");
if ((pToken = strstr(pCurrent, varName))) {
// Wants us to assign current Screen('Flip', win, tWhen, dontclear, vbl_synclevel...) vbl_synclevel to the variable IMAGINGPIPE_FLIPVBLSYNCLEVEL:
// Delete the varName from string:
memset(pToken, 'X', strlen(varName));
repeatit = TRUE;
if ((!(windowRecord->flipInfo) || (windowRecord->flipInfo->flipwhen == -DBL_MAX)) && (PsychPrefStateGet_Verbosity() > 9))
printf("PTB-DEBUG: PsychPipelineProcessMacros: IMAGINGPIPE_FLIPVBLSYNCLEVEL variable requested, but not yet set up! Screen('DrawingFinished') improper call?!?\n");
// Allocate runtime double matrix of scalar size: 'newvar' is the handle of it,
// dbltarget is a pointer to the target double matrix we need to fill with the vbl_synclevel time:
PsychAllocateNativeDoubleMat(1, 1, 1, &dbltarget, &newvar);
*dbltarget = (double) ((windowRecord->flipInfo && (windowRecord->flipInfo->flipwhen != -DBL_MAX)) ? windowRecord->flipInfo->vbl_synclevel : -DBL_MAX);
// Copy to caller workspace:
if (PsychRuntimePutVariable("caller", varName, newvar)) {
if (PsychPrefStateGet_Verbosity() > 0) printf("PTB-ERROR: PsychPipelineProcessMacros: IMAGINGPIPE_FLIPVBLSYNCLEVEL variable assignment failed in runtime! Skipped slot!\n");
rc = 0;
goto macros_out;
}
else {
if (PsychPrefStateGet_Verbosity() > 10) printf("PTB-DEBUG: PsychPipelineProcessMacros: ASSIGNED %f\n", (float) *dbltarget);
}
// Next parseloop iteration:
continue;
}
// Return of usercode provided dontclear flag for Flip requested?
sprintf(varName, "IMAGINGPIPE_FLIPDONTCLEAR");
if ((pToken = strstr(pCurrent, varName))) {
// Wants us to assign current Screen('Flip', win, tWhen, dontclear, ...) dontclear to the variable IMAGINGPIPE_FLIPDONTCLEAR:
// Delete the varName from string:
memset(pToken, 'X', strlen(varName));
repeatit = TRUE;
if ((!(windowRecord->flipInfo) || (windowRecord->flipInfo->flipwhen == -DBL_MAX)) && (PsychPrefStateGet_Verbosity() > 9))
printf("PTB-DEBUG: PsychPipelineProcessMacros: IMAGINGPIPE_FLIPDONTCLEAR variable requested, but not yet set up! Screen('DrawingFinished') improper call?!?\n");
// Allocate runtime double matrix of scalar size: 'newvar' is the handle of it,
// dbltarget is a pointer to the target double matrix we need to fill with the vbl_synclevel time:
PsychAllocateNativeDoubleMat(1, 1, 1, &dbltarget, &newvar);
*dbltarget = (double) ((windowRecord->flipInfo && (windowRecord->flipInfo->flipwhen != -DBL_MAX)) ? windowRecord->flipInfo->dont_clear : -DBL_MAX);
// Copy to caller workspace:
if (PsychRuntimePutVariable("caller", varName, newvar)) {
if (PsychPrefStateGet_Verbosity() > 0) printf("PTB-ERROR: PsychPipelineProcessMacros: IMAGINGPIPE_FLIPDONTCLEAR variable assignment failed in runtime! Skipped slot!\n");
rc = 0;
goto macros_out;
}
else {
if (PsychPrefStateGet_Verbosity() > 10) printf("PTB-DEBUG: PsychPipelineProcessMacros: ASSIGNED %f\n", (float) *dbltarget);
}
// Next parseloop iteration:
continue;
}
// Next parse loop iteration, if any...
} // Parse loop.
// Successfully processed string:
rc = 1;
macros_out:
free(pCurrent);
return(rc);
}
/* PsychPipelineExecuteHookSlot()
* Execute a single hookfunction slot in a hook chain for a specific window.
*/
psych_bool PsychPipelineExecuteHookSlot(PsychWindowRecordType *windowRecord, int hookId, PsychHookFunction* hookfunc, void* hookUserData, void* hookBlitterFunction, psych_bool srcIsReadonly, psych_bool allowFBOSwizzle, PsychFBO** srcfbo1, PsychFBO** srcfbo2, PsychFBO** dstfbo, PsychFBO** bouncefbo)
{
psych_bool dispatched = FALSE;
// Dispatch by hook function type:
switch(hookfunc->hookfunctype) {
case kPsychShaderFunc:
// Call a GLSL shader to do some image processing: We just execute the blitter, the shader gets assigned inside
// this function.
if (!PsychPipelineExecuteBlitter(windowRecord, hookfunc, hookUserData, hookBlitterFunction, srcIsReadonly, allowFBOSwizzle, srcfbo1, srcfbo2, dstfbo, bouncefbo)) {
// Blitter failed!
return(FALSE);
}
dispatched=TRUE;
break;
case kPsychCFunc:
// Call a C callback function via the given memory function pointer:
printf("TODO: EXECUTE -- C-Callback : void*= %p\n", hookfunc->cprocfunc);
dispatched=TRUE;
break;
case kPsychMFunc:
// Call the eval() function of our scripting runtime environment to evaluate
// function string pString1. Currently supported are Matlab & Octave, so this
// can be the call string of an arbitrary Matlab/Octave builtin or M-Function.
// Care has to be taken that the called functions do not invoke any Screen
// subfunctions! Screen is not reentrant, so that would likely screw seriously!
// Process certain macro keywords inside pString1 before calling the pString itself:
if (PsychPipelineProcessMacros(windowRecord, hookfunc->pString1)) {
// Call the runtime environment to process the command string:
PsychRuntimeEvaluateString(hookfunc->pString1);
}
dispatched=TRUE;
break;
case kPsychBuiltinFunc:
// Dispatch to a builtin function:
if (strcmp(hookfunc->idString, "Builtin:FlipFBOs")==0) { dispatched=TRUE; } // No op here. Done in upper layer...
if (strstr(hookfunc->idString, "Builtin:RestrictToScissorROI")) { dispatched=TRUE; } // No op here. Done in upper layer...
if (strstr(hookfunc->idString, "Builtin:IdentityBlit")) {
// Perform the most simple blit operation: A simple one-to-one copy of input FBO to output FBO:
if (!PsychPipelineExecuteBlitter(windowRecord, hookfunc, hookUserData, hookBlitterFunction, TRUE, FALSE, srcfbo1, NULL, dstfbo, NULL)) {
// Blitter failed!
return(FALSE);
}
dispatched=TRUE;
}
if (strcmp(hookfunc->idString, "Builtin:RenderClutBits++")==0) {
// Compute the T-Lock encoded CLUT for Cambridge Research Bits++ system in Bits++ mode. The CLUT
// is set via the standard Screen('LoadNormalizedGammaTable', ..., loadOnNextFlip) call by setting
// loadOnNextFlip to a value of 2.
if (!PsychPipelineBuiltinRenderClutBitsPlusPlus(windowRecord, hookfunc)) {
// Operation failed!
return(FALSE);
}
dispatched=TRUE;
}
if (strcmp(hookfunc->idString, "Builtin:RenderClutViaRuntime")==0) {
// Pass the last CLUT that was set via the standard Screen('LoadNormalizedGammaTable', ..., loadOnNextFlip) call by setting
// loadOnNextFlip to a value of 2 to the runtime environment.
if (!PsychPipelineBuiltinRenderClutViaRuntime(windowRecord, hookfunc)) {
// Operation failed!
return(FALSE);
}
dispatched=TRUE;
}
if (strcmp(hookfunc->idString, "Builtin:RenderStereoSyncLine")==0) {
// Draw a blue-line-sync sync line at the bottom of the current framebuffer. This is needed
// to drive stereo shutter glasses with blueline-sync in quad-buffered frame-sequential stereo
// mode.
if (!PsychPipelineBuiltinRenderStereoSyncLine(windowRecord, hookId, hookfunc)) {
// Operation failed!
return(FALSE);
}
dispatched=TRUE;
}
if (strcmp(hookfunc->idString, "Builtin:AlphaPostMultiply")==0) {
// Draw a fullscreen quad with constant alpha, essentially post-multiplying all alpha
// values in the framebuffer with the specified alpha. Needed, e.g., for Wayland transparency.
if (!PsychPipelineBuiltinRenderAlphaPostMultiply(windowRecord, hookfunc)) {
// Operation failed!
return(FALSE);
}
dispatched=TRUE;
}
break;
default:
PsychErrorExitMsg(PsychError_internal, "In PsychPipelineExecuteHookSlot: Was asked to execute unknown (non-existent) hook function type!");
}
if (!dispatched) {
if (PsychPrefStateGet_Verbosity()>0) printf("PTB-ERROR: Failed to dispatch hook slot - Unknown command or failure in command execution.\n");
return(FALSE);
}
return(TRUE);
}
void PsychPipelineSetupRenderFlow(PsychFBO* srcfbo1, PsychFBO* srcfbo2, PsychFBO* dstfbo, psych_bool scissor_ignore)
{
static int ow=0;
static int oh=0;
int w, h;
// Select rendertarget:
if (glBindFramebufferEXT) glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, (dstfbo) ? dstfbo->fboid : 0);
// Assign color texture of srcfbo2, if any, to texture unit 1:
glActiveTextureARB(GL_TEXTURE1_ARB);
if (srcfbo2) {
// srcfbo2 is valid: Assign its color buffer texture:
if (PsychPrefStateGet_Verbosity()>4) printf("TexUnit 1 reading from texid -- %i\n", srcfbo2->coltexid);
glBindTexture(srcfbo2->textarget, srcfbo2->coltexid);
// Set texture application mode to replace:
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glTexParameteri(srcfbo2->textarget, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(srcfbo2->textarget, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(srcfbo2->textarget, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(srcfbo2->textarget, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glDisable(GL_TEXTURE_2D);
glDisable(GL_TEXTURE_RECTANGLE_EXT);
glEnable(srcfbo2->textarget);
}
else {
// srcfbo2 doesn't exist: Unbind and deactivate 2nd unit:
if (PsychPrefStateGet_Verbosity() > 10) printf("TexUnit 1 not reading from srcfbo2\n");
glBindTexture(GL_TEXTURE_RECTANGLE_EXT, 0);
glDisable(GL_TEXTURE_RECTANGLE_EXT);
glBindTexture(GL_TEXTURE_2D, 0);
glDisable(GL_TEXTURE_2D);
}
// Assign color texture of srcfbo1 to texture unit 0:
glActiveTextureARB(GL_TEXTURE0_ARB);
if (srcfbo1) {
// srcfbo1 is valid: Assign its color buffer texture:
if (PsychPrefStateGet_Verbosity()>4) printf("TexUnit 0 reading from texid -- %i\n", srcfbo1->coltexid);
glBindTexture(srcfbo1->textarget, srcfbo1->coltexid);
// Set texture application mode to replace:
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glDisable(GL_TEXTURE_2D);
glDisable(GL_TEXTURE_RECTANGLE_EXT);
// No sampler state setup or glEnable() for 2D multisample texture targets!
// Such textures are only accessible from within shaders via texelFetch().
if (srcfbo1->textarget != GL_TEXTURE_2D_MULTISAMPLE) {
glTexParameteri(srcfbo1->textarget, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(srcfbo1->textarget, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(srcfbo1->textarget, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(srcfbo1->textarget, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glEnable(srcfbo1->textarget);
}
}
else {
// srcfbo1 doesn't exist: Unbind and deactivate 1st unit:
if (PsychPrefStateGet_Verbosity() > 10) printf("TexUnit 0 not reading from srcfbo1\n");
glBindTexture(GL_TEXTURE_RECTANGLE_EXT, 0);
glDisable(GL_TEXTURE_RECTANGLE_EXT);
glBindTexture(GL_TEXTURE_2D, 0);
glDisable(GL_TEXTURE_2D);
}
if (dstfbo) {
// Setup viewport, scissor rectangle and projection matrix for orthonormal rendering into the
// target FBO or system framebuffer:
w = (int) dstfbo->width;
h = (int) dstfbo->height;
if (PsychPrefStateGet_Verbosity()>4) {
if (dstfbo->fboid > 0) {
printf("Blitting to Targettex = %i , w x h = %i %i\n", dstfbo->coltexid, w, h);
} else {
printf("Blitting to system framebuffer, w x h = %i %i\n", w, h);
}
}
// Settings changed? We skip if not - state changes are expensive...
if ((w!=ow || h!=oh) && PsychIsMasterThread()) {
ow=w;
oh=h;
// Setup viewport and scissor for full FBO area:
glViewport(0, 0, w, h);
if (!scissor_ignore) glScissor(0, 0, w, h);
// Setup projection matrix for a proper orthonormal projection for this framebuffer:
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (!PsychIsGLES(NULL)) {
gluOrtho2D(0, w, h, 0);
}
else {
glOrthof(0, (float) w, (float) h, 0, -1, 1);
}
// Switch back to modelview matrix, but leave it unaltered:
glMatrixMode(GL_MODELVIEW);
}
}
else {
if (PsychIsMasterThread()) {
// Reset our cached settings:
ow=0;
oh=0;
}
}
return;
}
static void resetTexUnit(void)
{
glDisable(GL_TEXTURE_1D);
glDisable(GL_TEXTURE_2D);
glDisable(GL_TEXTURE_3D);
glDisable(GL_TEXTURE_RECTANGLE_EXT);
glBindTexture(GL_TEXTURE_1D, 0);
glBindTexture(GL_TEXTURE_2D, 0);
glBindTexture(GL_TEXTURE_3D, 0);
glBindTexture(GL_TEXTURE_RECTANGLE_EXT, 0);
}
psych_bool PsychPipelineExecuteBlitter(PsychWindowRecordType *windowRecord, PsychHookFunction* hookfunc, void* hookUserData, void* hookBlitterFunction, psych_bool srcIsReadonly, psych_bool allowFBOSwizzle, PsychFBO** srcfbo1, PsychFBO** srcfbo2, PsychFBO** dstfbo, PsychFBO** bouncefbo)
{
psych_bool rc = TRUE;
PsychBlitterFunc blitterfnc = NULL;
GLenum glerr;
char* pstrpos = NULL;
int texunit, texid;
psych_bool needTexPopAttrib = FALSE;
// Select proper blitter function:
// Initialize with master blitter function (if any). If none set,
// this will init to NULL:
blitterfnc = hookBlitterFunction;
// Any special override blitter defined in parameter string?
if (strstr(hookfunc->pString1, "Blitter:")) {
// Yes. Which one?
blitterfnc = NULL;
// Standard blitter? This one does a one-to-one copy without special geometric transformations.
if (strstr(hookfunc->pString1, "Blitter:IdentityBlit")) blitterfnc = &PsychBlitterIdentity; // Assign our standard one-to-one blitter.
// Displaylist blitter? This one calls an externally setup OpenGL display list to perform complex geometric transformations:
if (strstr(hookfunc->pString1, "Blitter:DisplayListBlit")) blitterfnc = &PsychBlitterDisplayList;
// Blitter assigned?
if (blitterfnc == NULL) {
if (PsychPrefStateGet_Verbosity()>0) printf("PTB-ERROR: Invalid (unknown) blitter specified in blitter string. Blit aborted.\n");
return(FALSE);
}
}
if (blitterfnc == NULL) {
// No blitter set up to now. Assign the default blitter:
blitterfnc = &PsychBlitterIdentity; // Assign our standard one-to-one blitter.
}
// TODO: Common setup code for texturing, filtering, alpha blending, z-test and such...
// If any texture setup is used, store previous state on attrib stack, disable everything
// to avoid interference by current, potentially incompatible, settings:
if (strstr(hookfunc->pString1, "TEXTURE") != NULL) {
needTexPopAttrib = TRUE;
glPushAttrib(GL_ENABLE_BIT | GL_TEXTURE_BIT);
}
// Setup code for 1D textures:
pstrpos = hookfunc->pString1;
while ((pstrpos=strstr(pstrpos, "TEXTURE1D"))) {
if (2==sscanf(pstrpos, "TEXTURE1D(%i)=%i", &texunit, &texid)) {
glActiveTextureARB(GL_TEXTURE0_ARB + texunit);
resetTexUnit();
glEnable(GL_TEXTURE_1D);
glBindTexture(GL_TEXTURE_1D, texid);
if (PsychPrefStateGet_Verbosity()>4) printf("PTB-DEBUG: Binding gltexid %i to GL_TEXTURE_1D target of texunit %i\n", texid, texunit);
}
pstrpos++;
}
// Setup code for 2D textures:
pstrpos = hookfunc->pString1;
while ((pstrpos=strstr(pstrpos, "TEXTURE2D"))) {
if (2==sscanf(pstrpos, "TEXTURE2D(%i)=%i", &texunit, &texid)) {
glActiveTextureARB(GL_TEXTURE0_ARB + texunit);
resetTexUnit();
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texid);
if (PsychPrefStateGet_Verbosity()>4) printf("PTB-DEBUG: Binding gltexid %i to GL_TEXTURE_2D target of texunit %i\n", texid, texunit);
}
pstrpos++;
}
// Setup code for 2D rectangle textures:
pstrpos = hookfunc->pString1;
while ((pstrpos=strstr(pstrpos, "TEXTURERECT2D"))) {
if (2==sscanf(pstrpos, "TEXTURERECT2D(%i)=%i", &texunit, &texid)) {
glActiveTextureARB(GL_TEXTURE0_ARB + texunit);
resetTexUnit();
glEnable(GL_TEXTURE_RECTANGLE_EXT);
glBindTexture(GL_TEXTURE_RECTANGLE_EXT, texid);
if (PsychPrefStateGet_Verbosity()>4) printf("PTB-DEBUG: Binding gltexid %i to GL_TEXTURE_RECTANGLE_EXT target of texunit %i\n", texid, texunit);
}
pstrpos++;
}
// Setup code for 3D textures:
pstrpos = hookfunc->pString1;
while ((pstrpos=strstr(pstrpos, "TEXTURE3D"))) {
if (2==sscanf(pstrpos, "TEXTURE3D(%i)=%i", &texunit, &texid)) {
glActiveTextureARB(GL_TEXTURE0_ARB + texunit);
resetTexUnit();
glEnable(GL_TEXTURE_3D);
glBindTexture(GL_TEXTURE_3D, texid);
if (PsychPrefStateGet_Verbosity()>4) printf("PTB-DEBUG: Binding gltexid %i to GL_TEXTURE_3D target of texunit %i\n", texid, texunit);
}
pstrpos++;
}
glActiveTextureARB(GL_TEXTURE0_ARB);
// Need a shader for this blit op?
if (hookfunc->shaderid) {
// Setup shader, if any:
if (!glUseProgram){
if (PsychPrefStateGet_Verbosity()>0) printf("PTB-ERROR: Blitter invocation failed: Blitter needs to attach GLSL shaders, but shaders are not supported on your hardware!\n");
rc = FALSE;
} else {
// Attach shader:
if (!(PsychPrefStateGet_ConserveVRAM() & kPsychAvoidCPUGPUSync)) while(glGetError());
glUseProgram(hookfunc->shaderid);
if (!(PsychPrefStateGet_ConserveVRAM() & kPsychAvoidCPUGPUSync) && ((glerr = glGetError())!=GL_NO_ERROR)) {
if (PsychPrefStateGet_Verbosity()>0) printf("PTB-ERROR: Blitter invocation failed: glUseProgram(%i) failed with error: %s\n", hookfunc->shaderid, gluErrorString(glerr));
rc = FALSE;
}
#if PSYCH_SYSTEM == PSYCH_OSX
// On OS-X we can query the OS if the bound shader is running on the GPU or if it is running in emulation mode on the CPU.
// This is an expensive operation - it triggers OpenGL internal state revalidation. Only use for debugging and testing!
if (PsychPrefStateGet_Verbosity()>5) {
GLint vsgpu=0, fsgpu=0;
CGLGetParameter(CGLGetCurrentContext(), kCGLCPGPUVertexProcessing, &vsgpu);
CGLGetParameter(CGLGetCurrentContext(), kCGLCPGPUFragmentProcessing, &fsgpu);
printf("PTB-DEBUG: Imaging pipeline GPU shading state: Vertex processing on %s : Fragment processing on %s.\n", (vsgpu) ? "GPU" : "CPU!!", (fsgpu) ? "GPU" : "CPU!!");
}
#endif
}
}
// Execute blitter function:
rc = (rc && blitterfnc(windowRecord, hookfunc, hookUserData, srcIsReadonly, allowFBOSwizzle, srcfbo1, srcfbo2, dstfbo, bouncefbo));
if (!rc) {
if (PsychPrefStateGet_Verbosity()>0) printf("PTB-ERROR: Blitter invocation failed: OpenGL error state is: %s\n", gluErrorString(glGetError()));
while(glGetError());
}
// TODO: Common teardown code for texturing, filtering and such...
// Teardown code for textures:
if (needTexPopAttrib)
glPopAttrib();
glActiveTextureARB(GL_TEXTURE0_ARB);
// Reset shader assignment, if any:
if ((hookfunc->shaderid) && glUseProgram) glUseProgram(0);
// Return result code:
return(rc);
}
/* PsychBlitterIdentity() -- Default blitter.
*
* Identity blitter: Blits from srcfbo1 color attachment to dstfbo without geometric transformations or other extras.
* This is the most common one for one-to-one copies or simple shader image processing. It gets automatically used
* when no special (non-default) blitter is requested by core code or users blitter parameter string:
*/
psych_bool PsychBlitterIdentity(PsychWindowRecordType *windowRecord, PsychHookFunction* hookfunc, void* hookUserData, psych_bool srcIsReadonly, psych_bool allowFBOSwizzle, PsychFBO** srcfbo1, PsychFBO** srcfbo2, PsychFBO** dstfbo, PsychFBO** bouncefbo)
{
int w, h, x, y, wf, hf;
float sx, sy, wt, ht, angle, cx, cy;
char* strp;
psych_bool bilinearfiltering;
// hookUserData, if non-NULL, can provide override parameter string:
char* pString1 = (hookUserData) ? (char*) hookUserData : hookfunc->pString1;
(void) srcIsReadonly, (void) allowFBOSwizzle, (void) srcfbo2, (void) dstfbo, (void) bouncefbo;
// Child protection:
if (!(srcfbo1 && (*srcfbo1))) {
PsychErrorExitMsg(PsychError_internal, "In PsychBlitterIdentity(): srcfbo1 is a NULL - Pointer!!!");
}
// Query dimensions of viewport:
w = (*srcfbo1)->width;
h = (*srcfbo1)->height;
// Same for texture coordinate space, depending on type of texture in use:
wt = ((*srcfbo1)->textarget == GL_TEXTURE_2D) ? 1 : (float) w;
ht = ((*srcfbo1)->textarget == GL_TEXTURE_2D) ? 1 : (float) h;
// This pot-textures remapping mostly applies to OpenGL-ES 1.x hardware:
if (((*srcfbo1)->textarget == GL_TEXTURE_2D) && !(windowRecord->gfxcaps & kPsychGfxCapNPOTTex)) {
// Only power-of-two GL_TEXTURE_2D targets supported. Find real width of
// FBO color buffer backing texture (wf, hf):
wf = 1;
while (wf < w) wf *= 2;
hf = 1;
while (hf < h) hf *= 2;
// Remap texture coordinates relative to (wf, hf) to select a proper
// subrectangle for the blit - the subrectangle with actual meaningful
// framebuffer content:
wt = (float) w / (float) wf;
ht = (float) h / (float) hf;
}
// Multisample texture? Needs special shader treatment.
if ((*srcfbo1)->textarget == GL_TEXTURE_2D_MULTISAMPLE) {
// This is a multisample texture. It needs a special shader to fetch texels from,
// as it can't get accessed by the fixed function pipeline in a conventional way.
if (windowRecord->multiSampleFetchShader == 0) {
// No fetch shader yet for this onscreen window. Create and assign one:
windowRecord->multiSampleFetchShader = PsychCreateGLSLProgram(multisampletexfetchshadersrc, NULL, NULL);
}
// Bind fetch shader for texture mapping:
if (glUseProgram && windowRecord->multiSampleFetchShader) {
glUseProgram(windowRecord->multiSampleFetchShader);
// Assign number of samples for this multisample texture, so shader can do proper averaging:
glUniform1i(glGetUniformLocation(windowRecord->multiSampleFetchShader, "nrsamples"), (*srcfbo1)->multisample);
}
}
// Check for override width x height parameter in the blitterString: An integral (w,h)
// size the blit. This allows to blit a target quad with a size different from srcfbo1, without
// scaling or filtering it. Mostly useful in conjunction with specific shaders.
if ((strp=strstr(pString1, "OvrSize:"))) {
// Parse and assign offset:
if (sscanf(strp, "OvrSize:%i:%i", &w, &h)!=2) {
PsychErrorExitMsg(PsychError_internal, "In PsychBlitterIdentity(): OvrSize: blit string parameter is invalid! Parse error...\n");
}
}
// Bilinear filtering of srcfbo1 texture requested? Obey request, unless multisample texture is in use - doesn't support this:
if (strstr(pString1, "Bilinear") && ((*srcfbo1)->textarget != GL_TEXTURE_2D_MULTISAMPLE)) {
// Yes. Enable it.
bilinearfiltering = TRUE;
glTexParameteri((*srcfbo1)->textarget, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri((*srcfbo1)->textarget, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
else {
bilinearfiltering = FALSE;
}
// Check for offset parameter in the blitterString: An integral (x,y)
// offset for the destination of the blit. This allows to blit the srcfbo1, without
// scaling or filtering it, to a different start location than (0,0):
x=y=0;
if ((strp=strstr(pString1, "Offset:"))) {
// Parse and assign offset:
if (sscanf(strp, "Offset:%i:%i", &x, &y)!=2) {
PsychErrorExitMsg(PsychError_internal, "In PsychBlitterIdentity(): Offset: blit string parameter is invalid! Parse error...\n");
}
}
// Check for scaling parameter:
sx = sy = 1.0;
if ((strp=strstr(pString1, "Scaling:"))) {
// Parse and assign offset:
if (sscanf(strp, "Scaling:%f:%f", &sx, &sy)!=2) {
PsychErrorExitMsg(PsychError_internal, "In PsychBlitterIdentity(): Scaling: blit string parameter is invalid! Parse error...\n");
}
}
// Check for rotation angle parameter:
angle = 0.0;
if ((strp=strstr(pString1, "Rotation:"))) {
// Parse and assign rotation angle:
if (sscanf(strp, "Rotation:%f", &angle)!=1) {
PsychErrorExitMsg(PsychError_internal, "In PsychBlitterIdentity(): Rotation: blit string parameter is invalid! Parse error...\n");
}
}
cx = (float) w / 2;
cy = (float) h / 2;
if ((strp=strstr(pString1, "RotCenter:"))) {
// Parse and assign rotation angle:
if (sscanf(strp, "RotCenter:%f:%f", &cx, &cy)!=2) {
PsychErrorExitMsg(PsychError_internal, "In PsychBlitterIdentity(): RotCenter: blit string parameter is invalid! Parse error...\n");
}
}
if (x!=0 || y!=0 || sx!=1.0 || sy!=1.0 || angle!=0.0) {
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
// Apply global (x,y) offset:
glTranslatef((float) x, (float) y, 0);
// Apply rotation around center:
if (angle != 0.0) {
glTranslatef(cx, cy, 0);
glRotatef(angle, 0.0, 0.0, 1.0);
glTranslatef(-cx, -cy, 0);
}
// Apply scaling:
glScalef(sx, sy, 1);
}
if (PsychPrefStateGet_Verbosity()>4) {
printf("PTB-DEBUG: PsychBlitterIdentity: Blitting x=%i y=%i sx=%f sy=%f w=%i h=%i angle=%f, rx=%f, ry=%f\n", x, y, sx, sy, w, h, angle, cx, cy);
}
if (PsychIsGLClassic(windowRecord)) {
// OpenGL-1/2: Do the blit, using a rectangular quad:
glBegin(GL_QUADS);
// Note the swapped y-coord for textures wrt. y-coord of vertex position!
// Texture coordinate system has origin at bottom-left, y-axis pointing upward,
// but PTB has framebuffer coordinate system with origin at top-left, with
// y-axis pointing downward! Normally OpenGL would have origin always bottom-left,
// but PTB has to use a different system (changed by special gluOrtho2D) transform),
// because our 2D coordinate system needs to conform to the standards of the old
// Psychtoolboxes and of typical windowing systems. -- A tribute to the past.
// Upper left vertex in window
glTexCoord2f(0, ht);
glVertex2f(0, 0);
// Lower left vertex in window
glTexCoord2f(0, 0);
glVertex2f(0, (float) h);
// Lower right vertex in window
glTexCoord2f(wt, 0);
glVertex2f((float) w, (float) h);
// Upper right in window
glTexCoord2f(wt, ht);
glVertex2f((float) w, 0);
glEnd();
}
else {
// Other. Need to emulate immediate mode GL-QUADS via GL_TRIANGLE_STRIPs:
// Also need to avoid immediate mode functions and use our own vertex arrray
// on our local function call stack, because this blitter can be called from
// async flipper threads for frame-sequential stereo emulation, so can't use
// global convenience helpers (GLBEGIN, GLEND etc.), as they'd use shared data
// This glverts array is local on our stack, thereby thread-local. Also our
// thread has its own OpenGL context, so no danger there either:
GLfloat glverts[4*4] = { 0, 0, 0, (float) h,
0, ht, 0, 0,
wt, 0, (float) w, (float) h,
wt, ht, (float) w, 0};
glVertexPointer(2, GL_FLOAT, 4 * sizeof(GLfloat), &glverts[2]);
glTexCoordPointer(2, GL_FLOAT, 4 * sizeof(GLfloat), &glverts[0]);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}
if (x!=0 || y!=0 || sx!=1.0 || sy!=1.0 || angle!=0.0) {
glPopMatrix();
}
if (bilinearfiltering) {
// Disable filtering again:
glTexParameteri((*srcfbo1)->textarget, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri((*srcfbo1)->textarget, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}
// Disable special fetch shader if it was used for multisample texture:
if (((*srcfbo1)->textarget == GL_TEXTURE_2D_MULTISAMPLE) && glUseProgram) {
glUseProgram(0);
}
// Done.
return(TRUE);
}
/* PsychBlitterDisplayList() -- Displaylist blitter.
*
* Blits from srcfbo1 color attachment to dstfbo by calling a premade OpenGL display list.
* Useful for application of geometric transformations, e.g., warping during blit. Typically
* used for geometric display undistortion.
*/
psych_bool PsychBlitterDisplayList(PsychWindowRecordType *windowRecord, PsychHookFunction* hookfunc, void* hookUserData, psych_bool srcIsReadonly, psych_bool allowFBOSwizzle, PsychFBO** srcfbo1, PsychFBO** srcfbo2, PsychFBO** dstfbo, PsychFBO** bouncefbo)
{
int x, y;
GLuint gllist;
float sx, sy;
char* strp;
psych_bool bilinearfiltering;
(void) hookUserData, (void) srcIsReadonly, (void) allowFBOSwizzle, (void) srcfbo2, (void) dstfbo, (void) bouncefbo;
// Not available on non-classic OpenGL. Need to find some replacement for display lists at some point in time to make this work :(
if (!PsychIsGLClassic(windowRecord)) {
if (PsychPrefStateGet_Verbosity() > 0) printf("PTB-ERROR: PsychBlitterDisplayList(): Called, but function unsupported on this non-OpenGL-1/2 rendering context! Aborted.\n");
return(FALSE);
}
// Child protection:
if (!(srcfbo1 && (*srcfbo1))) {
PsychErrorExitMsg(PsychError_internal, "In PsychBlitterDisplayList(): srcfbo1 is a NULL - Pointer!!!");
}
// Query display list handle:
if ((strp=strstr(hookfunc->pString1, "Handle:"))) {
// Parse and assign offset:
if (sscanf(strp, "Handle:%i", &gllist)!=1) {
PsychErrorExitMsg(PsychError_internal, "In PsychBlitterDisplayList(): Handle: Parse error fetching display list handle!\n");
}
}
else {
PsychErrorExitMsg(PsychError_internal, "In PsychBlitterDisplayList(): No display list handle provided or parse-error fetching display list handle!\n");
}
// Handle valid?
if (!glIsList(gllist)) PsychErrorExitMsg(PsychError_internal, "In PsychBlitterDisplayList(): Invalid display list handle provided!\n");
// Bilinear filtering of srcfbo1 texture requested?
if (strstr(hookfunc->pString1, "Bilinear")) {
// Yes. Enable it.
bilinearfiltering = TRUE;
glTexParameteri((*srcfbo1)->textarget, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri((*srcfbo1)->textarget, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
else {
bilinearfiltering = FALSE;
}
// Check for offset parameter in the blitterString: An integral (x,y)
// offset for the destination of the blit. This allows to blit the srcfbo1, without
// scaling or filtering it, to a different start location than (0,0):
x=y=0;
if ((strp=strstr(hookfunc->pString1, "Offset:"))) {
// Parse and assign offset:
if (sscanf(strp, "Offset:%i:%i", &x, &y)!=2) {
PsychErrorExitMsg(PsychError_internal, "In PsychBlitterDisplayList(): Offset: blit string parameter is invalid! Parse error...\n");
}
}
// Check for scaling parameter:
sx = sy = 1.0;
if ((strp=strstr(hookfunc->pString1, "Scaling:"))) {
// Parse and assign offset:
if (sscanf(strp, "Scaling:%f:%f", &sx, &sy)!=2) {
PsychErrorExitMsg(PsychError_internal, "In PsychBlitterDisplayList(): Scaling: blit string parameter is invalid! Parse error...\n");
}
}
if (x!=0 || y!=0 || sx!=1.0 || sy!=1.0) {
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
// Apply global (x,y) offset:
glTranslatef((float) x, (float) y, 0);
// Apply scaling:
glScalef(sx, sy, 1);
}
// Note the swapped y-coord for textures wrt. y-coord of vertex position!
// Texture coordinate system has origin at bottom-left, y-axis pointing upward,
// but PTB has framebuffer coordinate system with origin at top-left, with
// y-axis pointing downward! Normally OpenGL would have origin always bottom-left,
// but PTB has to use a different system (changed by special gluOrtho2D) transform),
// because our 2D coordinate system needs to conform to the standards of the old
// Psychtoolboxes and of typical windowing systems. -- A tribute to the past.
// Call the display list: This will perform the blit operation.
glCallList(gllist);
if (x!=0 || y!=0 || sx!=1.0 || sy!=1.0) {
glPopMatrix();
}
if (bilinearfiltering) {
// Disable filtering again:
glTexParameteri((*srcfbo1)->textarget, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri((*srcfbo1)->textarget, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}
// Done.
return(TRUE);
}
psych_bool PsychPipelineBuiltinRenderAlphaPostMultiply(PsychWindowRecordType *windowRecord, PsychHookFunction* hookfunc)
{
float globalAlpha;
psych_bool blendingOn = glIsEnabled(GL_BLEND);
if (1 != sscanf(hookfunc->pString1, "%f", &globalAlpha)) {
if (PsychPrefStateGet_Verbosity() > 0) printf("PTB-ERROR: PsychPipelineBuiltinRenderAlphaPostMultiply() failed due to lack of or invalid global alpha. Skipped!\n");
return(FALSE);
}
// Setup alpha blending for alpha-postmultiply of framebuffer pixels with globalAlpha:
glEnable(GL_BLEND);
glBlendFuncSeparate(GL_ZERO, GL_ONE, GL_ZERO, GL_CONSTANT_ALPHA);
glBlendColor(1.0, 1.0, 1.0, (GLfloat) globalAlpha);
// Blit a fullscreen quad, just to drive the alpha-postmultiply:
PsychGLRect(windowRecord->rect);
// Restore a well defined blending state:
glBlendFuncSeparate(GL_ZERO, GL_ONE, GL_ZERO, GL_ONE);
if (!blendingOn) glDisable(GL_BLEND);
return(TRUE);
}
/* PsychPipelineBuiltinRenderClutBitsPlusPlus - Encode Bits++ CLUT into framebuffer.
*
* This builtin routine takes the current gamma table for this windowRecord, encodes it into a Bits++
* compatible T-Lock CLUT and renders it into the framebuffer.
*/
psych_bool PsychPipelineBuiltinRenderClutBitsPlusPlus(PsychWindowRecordType *windowRecord, PsychHookFunction* hookfunc)
{
char* strp;
const int bitshift = 16; // Bits++ expects 16 bit numbers, but ignores 2 least significant bits --> Effective 14 bit.
int i, j, x, y;
unsigned int r, g, b;
GLubyte col[3 * 524];
double t1, t2;
y=1;
x=0;
if (windowRecord->loadGammaTableOnNextFlip != 0 || windowRecord->inRedTable == NULL) {
if (PsychPrefStateGet_Verbosity()>0) printf("PTB-ERROR: Bits++ CLUT encoding failed. No suitable CLUT set in Screen('LoadNormalizedGammaTable'). Skipped!\n");
return(FALSE);
}
if (windowRecord->inTableSize < 256) {
if (PsychPrefStateGet_Verbosity()>0) printf("PTB-ERROR: Bits++ CLUT encoding failed. CLUT has less than the required 256 entries. Skipped!\n");
return(FALSE);
}
if (PsychPrefStateGet_Verbosity() > 4) {
glFinish();
PsychGetAdjustedPrecisionTimerSeconds(&t1);
}
// Options provided?
if (strlen(hookfunc->pString1)>0) {
// Check for override vertical position for line. Default is first scanline of display.
if ((strp=strstr(hookfunc->pString1, "yPosition="))) {
// Parse and assign offset:
if (sscanf(strp, "yPosition=%i", &y)!=1) {
PsychErrorExitMsg(PsychError_user, "builtin:RenderClutBitsPlusPlus: yPosition parameter for T-Lock line position is invalid! Parse error...\n");
}
}
// Check for override horizontal position for line. Default is first pixel of scanline.
if ((strp=strstr(hookfunc->pString1, "xPosition="))) {
// Parse and assign offset:
if (sscanf(strp, "xPosition=%i", &x)!=1) {
PsychErrorExitMsg(PsychError_user, "builtin:RenderClutBitsPlusPlus: xPosition parameter for T-Lock line position is invalid! Parse error...\n");
}
}
}
// Render CLUT as horizontal sequence of single pixels:
j = 0;
glRasterPos2i(x, y);
// First the T-Lock unlock key:
col[j++] = 36; col[j++] = 106; col[j++] = 133;
col[j++] = 63; col[j++] = 136; col[j++] = 163;
col[j++] = 8; col[j++] = 19; col[j++] = 138;
col[j++] = 211; col[j++] = 25; col[j++] = 46;
col[j++] = 3; col[j++] = 115; col[j++] = 164;
col[j++] = 112; col[j++] = 68; col[j++] = 9;
col[j++] = 56; col[j++] = 41; col[j++] = 49;
col[j++] = 34; col[j++] = 159; col[j++] = 208;
col[j++] = 0; col[j++] = 0; col[j++] = 0;
col[j++] = 0; col[j++] = 0; col[j++] = 0;
col[j++] = 0; col[j++] = 0; col[j++] = 0;
col[j++] = 0; col[j++] = 0; col[j++] = 0;
// Now the encoded CLUT: We encode 16 bit values in a high and a low pixel,
// Bits++ throws away the two least significant bits - get 14 bit output resolution.
for (i=0; i<256; i++) {
// Convert 0.0 - 1.0 float value into 0 - 2^14 -1 integer range of Bits++
r = (unsigned int)(windowRecord->inRedTable[i] * (float)((1 << bitshift) - 1) + 0.5f);
g = (unsigned int)(windowRecord->inGreenTable[i] * (float)((1 << bitshift) - 1) + 0.5f);
b = (unsigned int)(windowRecord->inBlueTable[i] * (float)((1 << bitshift) - 1) + 0.5f);
// Pixel with high-byte of 16 bit value:
col[j++] = (GLubyte) ((r >> 8) & 0xff);
col[j++] = (GLubyte) ((g >> 8) & 0xff);
col[j++] = (GLubyte) ((b >> 8) & 0xff);
// Pixel with low-byte of 16 bit value:
col[j++] = (GLubyte) (r & 0xff);
col[j++] = (GLubyte) (g & 0xff);
col[j++] = (GLubyte) (b & 0xff);
}
glDrawPixels(524, 1, GL_RGB, GL_UNSIGNED_BYTE, col);
if (PsychPrefStateGet_Verbosity() > 4) {
glFinish();
PsychGetAdjustedPrecisionTimerSeconds(&t2);
printf("PTB-DEBUG: Execution time of built-in Bits++ CLUT encoder was %lf ms.\n", (t2 - t1) * 1000.0f);
}
// Done.
return(TRUE);
}
/* PsychPipelineBuiltinRenderClutViaRuntime() - Encode CLUT via callback to runtime environment.
*
* This builtin routine takes the current gamma table for this windowRecord and calls back into
* the runtime environment to execute some function and passes it the CLUT.
*/
psych_bool PsychPipelineBuiltinRenderClutViaRuntime(PsychWindowRecordType *windowRecord, PsychHookFunction* hookfunc)
{
char* strp;
char* outcmd = NULL;
int i, cmdlen;
double t1, t2;
// Be lazy: Only execute call if there is actually a pending CLUT for update:
if (windowRecord->inRedTable == NULL) {
if (PsychPrefStateGet_Verbosity()>10) printf("PTB-DEBUG: PsychPipelineBuiltinRenderClutViaRuntime: No new CLUT set via Screen('LoadNormalizedGammaTable'). Skipped!\n");
return(TRUE);
}
if (windowRecord->inTableSize < 1) {
if (PsychPrefStateGet_Verbosity()>0) printf("PTB-ERROR: PsychPipelineBuiltinRenderClutViaRuntime: CLUT encoding failed. CLUT has less than the required 1 entries. Skipped!\n");
return(FALSE);
}
if (PsychPrefStateGet_Verbosity() > 4) {
PsychGetAdjustedPrecisionTimerSeconds(&t1);
}
cmdlen = (int) strlen(hookfunc->pString1);
outcmd = (char*) calloc(cmdlen + 10 + (windowRecord->inTableSize * 3 * 10), sizeof(char));
sprintf(outcmd, "%s [", hookfunc->pString1);
strp = &outcmd[strlen(outcmd)];
for (i = 0; i < windowRecord->inTableSize; i++) {
sprintf(strp, "%06f %06f %06f ; ", windowRecord->inRedTable[i], windowRecord->inGreenTable[i], windowRecord->inBlueTable[i]);
strp = &outcmd[strlen(outcmd)];
// printf("%06f %06f %06f ; ", windowRecord->inRedTable[i], windowRecord->inGreenTable[i], windowRecord->inBlueTable[i]);
}
strp = &outcmd[strlen(outcmd)];
sprintf(strp, "]); ");
// Release the gamma table:
free(windowRecord->inRedTable); windowRecord->inRedTable = NULL;
free(windowRecord->inGreenTable); windowRecord->inGreenTable = NULL;
free(windowRecord->inBlueTable); windowRecord->inBlueTable = NULL;
windowRecord->inTableSize = 0;
windowRecord->loadGammaTableOnNextFlip = 0;
// Execute callback into runtime:
PsychRuntimeEvaluateString(outcmd);
free(outcmd);
if (PsychPrefStateGet_Verbosity() > 4) {
PsychGetAdjustedPrecisionTimerSeconds(&t2);
printf("PTB-DEBUG: PsychPipelineBuiltinRenderClutViaRuntime: Execution time was %lf ms.\n", (t2 - t1) * 1000.0f);
}
// Done.
return(TRUE);
}
/* PsychPipelineBuiltinRenderStereoSyncLine() -- Render sync trigger lines for quad-buffered stereo contexts.
*
* A builtin function to be called for drawing of blue-line-sync marker lines in quad-buffered stereo mode.
*/
psych_bool PsychPipelineBuiltinRenderStereoSyncLine(PsychWindowRecordType *windowRecord, int hookId, PsychHookFunction* hookfunc)
{
GLenum draw_buffer;
char* strp;
float blackpoint, r, g, b;
float fraction = 0.25;
float w = (float) PsychGetWidthFromRect(windowRecord->rect);
float h = (float) PsychGetHeightFromRect(windowRecord->rect);
r=g=b=1.0;
// We default to display height minus 1 for position of sync-line, instead of the lower most row
// of the display: This is to account for a few display drivers that are off-by-one, so they would
// actually clip the line outside display area if provided with correct coordinates (e.g., NVidia Geforce8600M on OS/X 10.4.10 and 10.5)!
h = h - 1;
// Options provided?
if (strlen(hookfunc->pString1)>0) {
// Check for override vertical position for sync line. Default is last scanline of display.
if ((strp=strstr(hookfunc->pString1, "yPosition="))) {
// Parse and assign offset:
if (sscanf(strp, "yPosition=%f", &h)!=1) {
PsychErrorExitMsg(PsychError_user, "builtin:RenderStereoSyncLine: yPosition parameter for horizontal stereo blue-sync line position is invalid! Parse error...\n");
}
}
// Check for override horizontal fraction for sync line. Default is 25% for left eye, 75% for right eye.
if ((strp=strstr(hookfunc->pString1, "hFraction="))) {
// Parse and assign offset:
if ((sscanf(strp, "hFraction=%f", &fraction)!=1) || (fraction < 0.0) || (fraction > 1.0)) {
PsychErrorExitMsg(PsychError_user, "builtin:RenderStereoSyncLine: hFraction parameter for horizontal stereo blue-sync line length is invalid!\n");
}
}
// Check for override color of sync-line. Default is white.
if ((strp=strstr(hookfunc->pString1, "Color="))) {
// Parse and assign offset:
if (sscanf(strp, "Color=%f %f %f", &r, &g, &b)!=3) {
PsychErrorExitMsg(PsychError_user, "builtin:RenderStereoSyncLine: Color spec for stereo sync-line is invalid!\n");
}
}
}
// Query current target buffer:
glGetIntegerv(GL_DRAW_BUFFER, (GLint*) &draw_buffer);
// If a FBO is bound, we use the hookId of the originating chain to find out if this is left view or right view:
if (draw_buffer == GL_COLOR_ATTACHMENT0_EXT) draw_buffer = ((hookId == kPsychLeftFinalizerBlit) ? GL_BACK_LEFT : GL_BACK_RIGHT);
if (draw_buffer == GL_BACK_LEFT || draw_buffer == GL_FRONT_LEFT) {
// Left stereo buffer:
blackpoint = fraction;
}
else if (draw_buffer == GL_BACK_RIGHT || draw_buffer == GL_FRONT_RIGHT) {
// Right stereo buffer:
blackpoint = 1 - fraction;
}
else {
// No stereo buffer! No stereo mode. This routine is a no-op...
if (PsychPrefStateGet_Verbosity() > 4) printf("PTB-INFO: Stereo sync line renderer called on non-stereo framebuffer!?!\n");
return(TRUE);
}
// There must not be any image content below the sync-lines! Clear out everything to black:
glColor3f(0, 0, 0);
glBegin(GL_QUADS);
glVertex2f(0, h-2);
glVertex2f(w, h-2);
glVertex2f(w, (float) PsychGetHeightFromRect(windowRecord->rect)+1);
glVertex2f(0, (float) PsychGetHeightFromRect(windowRecord->rect)+1);
glEnd();
// Draw the sync-lines -- actually a quad 3 scanlines high, to compensate for
// driver positioning bugs:
glBegin(GL_QUADS);
glColor3f(r, g, b);
glVertex2f(0, h);
glVertex2f(w*blackpoint, h);
glVertex2f(w*blackpoint, h+2);
glVertex2f(0, h+2);
glEnd();
return(TRUE);
}
/* PsychAssignHighPrecisionTextureShaders()
*
* Helper function, used by all functions that create textures.
*
* This function checks for a given texture 'textureRecord' and its parent 'windowRecord', if
* special GLSL texture filter shaders (for bilinear filterin) and texture lookup shaders
* (for nearest neighbour sampling) should be assigned, based on the properties of the
* textures, parent window and provided request flags.
*
* If shaders are needed, assigns them. On first invocation, creates the neccessary
* shaders.
*
* Conditions under which shaders are assigned:
* a) Calling code absolutely wants it ('userRequest' > 0).
* b) Color clamping is disabled via Screen('ColorRange') and gfx-hw is incapable of doing
* this internally and at high precision, so this works around lacking hw support/precision.
* c) It is a floating point texture format that the hw can't handle with its built-in
* filtering facilities, so this is a workaround for such hw. (usefloatformat == 1 for 16bpc float, 2 == 32 bpc float).
*
* Returns true on success, false on error, but performs error/warning output itself.
*/
psych_bool PsychAssignHighPrecisionTextureShaders(PsychWindowRecordType* textureRecord, PsychWindowRecordType* windowRecord, int usefloatformat, int userRequest)
{
// Detect if its a GL_TEXTURE_2D texture: Currently not handled by our shaders...
unsigned int usepoweroftwo = (PsychGetTextureTarget(textureRecord) == GL_TEXTURE_2D) ? 1 : 0;
// Remap windowRecord to its parent if any. We want the associated "toplevel" onscreen window,
// because only that contains the required settings for colorrange, shaders and gfcaps in
// a reliable way:
windowRecord = PsychGetParentWindow(windowRecord);
// Use a GLSL shader for texture mapping / filtering?
// We use a GLSL shader (instead of the standard nearest-neighbour, or bilinear hardware samplers),
// if any of these is true:
// a) It is a floating point texture and the gfx-hardware is incapable of filtering it in hardware.
// b) Color clamping is disabled via Screen('ColorRange') and the gfx-hardware is incapable of high precision vertex color interpolation / non-clamped mode.
// c) The script wants us to use shaders via the 'userRequest' setting > 0.
if ((userRequest > 0) || ((windowRecord->colorRange < 0) && !(windowRecord->gfxcaps & kPsychGfxCapVCGood)) || ((usefloatformat == 1) && !(windowRecord->gfxcaps & kPsychGfxCapFPFilter16)) || ((usefloatformat == 2) && !(windowRecord->gfxcaps & kPsychGfxCapFPFilter32))) {
// Need filtershaders at least for bilinear filtering:
// Do we have bilinear filtershader already? Don't have this stuff for GL_TEXTURE_2D btw...
if (windowRecord->textureFilterShader == 0 && !(usepoweroftwo & 1)) {
// Nope. Need to create one:
windowRecord->textureFilterShader = PsychCreateGLSLProgram(textureBilinearFilterFragmentShaderSrc, textureBilinearFilterVertexShaderSrc, NULL);
if ((windowRecord->textureFilterShader == 0) && PsychPrefStateGet_Verbosity() > 1) {
printf("PTB-WARNING: Created a floating point texture as requested, or manual filtering wanted, but was unable to create a float filter shader.\n");
printf("PTB-WARNING: (Custom) Filtering - and therefore anti-aliasing - of this texture won't work or at least not at the requested precision.\n");
}
else {
if (PsychPrefStateGet_Verbosity() > 3) {
if (userRequest > 0) {
printf("PTB-INFO: GLSL fragment filtershader created for custom high quality texture filtering.\n");
}
else if (windowRecord->colorRange < 0) {
printf("PTB-INFO: GLSL fragment filtershader created for high quality texture filtering in high-precision unclamped color mode\n");
}
else if (usefloatformat > 0) {
printf("PTB-INFO: %i bpc Floating point texture created. This gfx-hardware doesn't support automatic filtering of such\n", 16 * usefloatformat);
printf("PTB-INFO: textures. A GLSL fragment filtershader was generated to work-around this.\n");
}
}
}
}
else if ((usepoweroftwo & 1) && PsychPrefStateGet_Verbosity() > 1) {
printf("PTB-WARNING: Created a power of two texture as requested, and you wanted high-precision texturing, but don't have a GLSL filter shader.\n");
printf("PTB-WARNING: Filtering - and therefore anti-aliasing - and high-precision drawing of power of two textures may not work.\n");
}
// Do we need a simple texture lookup & modulate with vertex color shader for non-filtered texture
// mapping? This is not needed for floating point textures per se (all hw can nearest neighbour sample them),
// but it is needed if user wants it (userRequest flag > 0) or if unclamped high-precision drawing is
// requested but the hw is not up to that task:
if ((userRequest > 0) || ((windowRecord->colorRange < 0) && !(windowRecord->gfxcaps & kPsychGfxCapVCGood))) {
// Yes, need it - Create a shader if one doesn't yet exist:
if (windowRecord->textureLookupShader == 0 && !(usepoweroftwo & 1)) {
// Create one:
windowRecord->textureLookupShader = PsychCreateGLSLProgram(textureLookupFragmentShaderSrc, textureBilinearFilterVertexShaderSrc, NULL);
if ((windowRecord->textureLookupShader == 0) && PsychPrefStateGet_Verbosity() > 1) {
printf("PTB-WARNING: Failed to create a texture lookup shader. High precision texture drawing therefore won't work.\n");
}
}
else if ((usepoweroftwo & 1) && PsychPrefStateGet_Verbosity() > 1) {
printf("PTB-WARNING: Created a power of two texture as requested, and you wanted high-precision texturing, but don't have a GLSL shader for that.\n");
printf("PTB-WARNING: High-precision drawing of power of two textures therefore may not work.\n");
}
}
// Assign our onscreen windows filtershader to this texture, unless something else has already assigned
// a suitable shader:
if (textureRecord->textureFilterShader == 0)
textureRecord->textureFilterShader = windowRecord->textureFilterShader;
if (textureRecord->textureLookupShader == 0)
textureRecord->textureLookupShader = windowRecord->textureLookupShader;
}
// Done.
return(TRUE);
}
psych_bool PsychAssignPlanarTextureShaders(PsychWindowRecordType* textureRecord, PsychWindowRecordType* windowRecord, int channels)
{
// Remap windowRecord to its parent if any. We want the associated "toplevel" onscreen window,
// because only that contains the required shaders and gfcaps in a reliable way:
windowRecord = PsychGetParentWindow(windowRecord);
// Do we have a planar texture shader for this channels-count already?
if (windowRecord->texturePlanarShader[channels - 1] == 0) {
// Nope. Need to create one:
switch (channels) {
case 1:
windowRecord->texturePlanarShader[channels - 1] = PsychCreateGLSLProgram(texturePlanar1FragmentShaderSrc, texturePlanarVertexShaderSrc, NULL);
break;
case 2:
windowRecord->texturePlanarShader[channels - 1] = PsychCreateGLSLProgram(texturePlanar2FragmentShaderSrc, texturePlanarVertexShaderSrc, NULL);
break;
case 3:
windowRecord->texturePlanarShader[channels - 1] = PsychCreateGLSLProgram(texturePlanar3FragmentShaderSrc, texturePlanarVertexShaderSrc, NULL);
break;
case 4:
windowRecord->texturePlanarShader[channels - 1] = PsychCreateGLSLProgram(texturePlanar4FragmentShaderSrc, texturePlanarVertexShaderSrc, NULL);
break;
default:
printf("PTB-BUG: In PsychAssignPlanarTextureShaders() unknown channels count of %i !!\n", channels);
return(FALSE);
}
if (windowRecord->texturePlanarShader[channels - 1] == 0) {
printf("PTB-ERROR: Failed to create planar filter shader for planar texture (specialFlags == 4 in Screen('MakeTexture')). This will lead to a corrupted texture!\n");
return(FALSE);
}
}
// Assign our onscreen windows planarshader to this texture:
// We don't support GL_TEXTURE_2D textures yet though, so only auto-assign shader for rectangle textures.
if (textureRecord && !(PsychGetTextureTarget(textureRecord) == GL_TEXTURE_2D)) textureRecord->textureFilterShader = -1 * windowRecord->texturePlanarShader[channels - 1];
// Done.
return(TRUE);
}
psych_bool PsychAssignPlanarI420TextureShader(PsychWindowRecordType* textureRecord, PsychWindowRecordType* windowRecord)
{
// Remap windowRecord to its parent if any. We want the associated "toplevel" onscreen window,
// because only that contains the required shader and gfcaps in a reliable way:
windowRecord = PsychGetParentWindow(windowRecord);
// Do we already have a I420 planar sampling texture shader?
if (windowRecord->textureI420PlanarShader == 0) {
// Nope. Need to create one:
windowRecord->textureI420PlanarShader = PsychCreateGLSLProgram(texturePlanarI420FragmentShaderSrc, texturePlanarVertexShaderSrc, NULL);
if (windowRecord->textureI420PlanarShader == 0) {
printf("PTB-ERROR: Failed to create planar YUV-I420 filter shader for video texture.\n");
return(FALSE);
}
}
// Assign our onscreen windows planar I420 shader to this texture:
// We don't support GL_TEXTURE_2D textures yet though, so only auto-assign shader for rectangle textures.
if (textureRecord && !(PsychGetTextureTarget(textureRecord) == GL_TEXTURE_2D)) textureRecord->textureFilterShader = -1 * windowRecord->textureI420PlanarShader;
// Done.
return(TRUE);
}
psych_bool PsychAssignPlanarI800TextureShader(PsychWindowRecordType* textureRecord, PsychWindowRecordType* windowRecord)
{
// Remap windowRecord to its parent if any. We want the associated "toplevel" onscreen window,
// because only that contains the required shader and gfcaps in a reliable way:
windowRecord = PsychGetParentWindow(windowRecord);
// Do we already have a I800 planar sampling texture shader?
if (windowRecord->textureI800PlanarShader == 0) {
// Nope. Need to create one:
windowRecord->textureI800PlanarShader = PsychCreateGLSLProgram(texturePlanarI800FragmentShaderSrc, texturePlanarVertexShaderSrc, NULL);
if (windowRecord->textureI800PlanarShader == 0) {
printf("PTB-ERROR: Failed to create planar Y8-I800 filter shader for video texture.\n");
return(FALSE);
}
}
// Assign our onscreen windows planar I800 shader to this texture:
// We don't support GL_TEXTURE_2D textures yet though, so only auto-assign shader for rectangle textures.
if (textureRecord && !(PsychGetTextureTarget(textureRecord) == GL_TEXTURE_2D)) textureRecord->textureFilterShader = -1 * windowRecord->textureI800PlanarShader;
// Done.
return(TRUE);
}
|