1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512
|
/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2019-2022 Baldur Karlsson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
#include "ShaderViewer.h"
#include <QComboBox>
#include <QFontDatabase>
#include <QHBoxLayout>
#include <QKeyEvent>
#include <QListWidget>
#include <QMenu>
#include <QMouseEvent>
#include <QPainter>
#include <QPen>
#include <QSet>
#include <QShortcut>
#include <QToolTip>
#include "Code/Resources.h"
#include "Code/ScintillaSyntax.h"
#include "Widgets/Extended/RDLabel.h"
#include "Widgets/FindReplace.h"
#include "scintilla/include/SciLexer.h"
#include "scintilla/include/qt/ScintillaEdit.h"
#include "toolwindowmanager/ToolWindowManager.h"
#include "toolwindowmanager/ToolWindowManagerArea.h"
#include "ui_ShaderViewer.h"
struct AccessedResourceTag
{
AccessedResourceTag() : type(VarType::Unknown), step(0) { bind.bind = -1; }
AccessedResourceTag(uint32_t s) : type(VarType::Unknown), step(s) { bind.bind = -1; }
AccessedResourceTag(BindpointIndex bp, VarType t) : bind(bp), type(t), step(0) {}
AccessedResourceTag(ShaderVariable var) : step(0), type(var.type)
{
if(var.type == VarType::ReadOnlyResource || var.type == VarType::ReadWriteResource)
bind = var.GetBinding();
else
bind.bind = -1;
}
BindpointIndex bind;
VarType type;
uint32_t step;
};
Q_DECLARE_METATYPE(VariableTag);
Q_DECLARE_METATYPE(AccessedResourceTag);
ShaderViewer::ShaderViewer(ICaptureContext &ctx, QWidget *parent)
: QFrame(parent), ui(new Ui::ShaderViewer), m_Ctx(ctx)
{
ui->setupUi(this);
ui->constants->setFont(Formatter::PreferredFont());
ui->accessedResources->setFont(Formatter::PreferredFont());
ui->debugVars->setFont(Formatter::PreferredFont());
ui->sourceVars->setFont(Formatter::PreferredFont());
ui->watch->setFont(Formatter::PreferredFont());
ui->inputSig->setFont(Formatter::PreferredFont());
ui->outputSig->setFont(Formatter::PreferredFont());
ui->callstack->setFont(Formatter::PreferredFont());
// we create this up front so its state stays persistent as much as possible.
m_FindReplace = new FindReplace(this);
m_FindResults = MakeEditor(lit("findresults"), QString(), SCLEX_NULL);
m_FindResults->setReadOnly(true);
m_FindResults->setWindowTitle(lit("Find Results"));
// remove margins
m_FindResults->setMarginWidthN(0, 0);
m_FindResults->setMarginWidthN(1, 0);
m_FindResults->setMarginWidthN(2, 0);
QObject::connect(m_FindReplace, &FindReplace::performFind, this, &ShaderViewer::performFind);
QObject::connect(m_FindReplace, &FindReplace::performFindAll, this, &ShaderViewer::performFindAll);
QObject::connect(m_FindReplace, &FindReplace::performReplace, this, &ShaderViewer::performReplace);
QObject::connect(m_FindReplace, &FindReplace::performReplaceAll, this,
&ShaderViewer::performReplaceAll);
QObject::connect(m_FindReplace, &FindReplace::keyPress, [this](QKeyEvent *e) {
if(e->key() == Qt::Key_Escape)
{
// the find replace dialog is the only thing allowed to float. If it's in a floating area,
// hide it on escape
ToolWindowManagerArea *area = ui->docking->areaOf(m_FindReplace);
if(area && ui->docking->isFloating(m_FindReplace))
{
ui->docking->hideToolWindow(m_FindReplace);
}
}
});
ui->docking->addToolWindow(m_FindReplace, ToolWindowManager::NoArea);
ui->docking->setToolWindowProperties(m_FindReplace, ToolWindowManager::HideOnClose);
ui->docking->addToolWindow(m_FindResults, ToolWindowManager::NoArea);
ui->docking->setToolWindowProperties(
m_FindResults, ToolWindowManager::HideOnClose | ToolWindowManager::DisallowFloatWindow);
QObject::connect(m_FindResults, &ScintillaEdit::doubleClick, this,
&ShaderViewer::resultsDoubleClick);
{
m_DisassemblyView =
MakeEditor(lit("scintillaDisassem"), QString(),
m_Ctx.APIProps().pipelineType == GraphicsAPI::Vulkan ? SCLEX_GLSL : SCLEX_HLSL);
m_DisassemblyView->setReadOnly(true);
QObject::connect(m_DisassemblyView, &ScintillaEdit::keyPressed, this,
&ShaderViewer::readonly_keyPressed);
m_Scintillas.push_back(m_DisassemblyView);
m_DisassemblyFrame = new QWidget(this);
m_DisassemblyFrame->setWindowTitle(tr("Disassembly"));
m_DisassemblyToolbar = new QFrame(this);
m_DisassemblyToolbar->setFrameShape(QFrame::Panel);
m_DisassemblyToolbar->setFrameShadow(QFrame::Raised);
QHBoxLayout *toolbarlayout = new QHBoxLayout(m_DisassemblyToolbar);
toolbarlayout->setSpacing(2);
toolbarlayout->setContentsMargins(3, 3, 3, 3);
m_DisassemblyType = new QComboBox(m_DisassemblyToolbar);
m_DisassemblyType->setMaxVisibleItems(12);
m_DisassemblyType->setSizeAdjustPolicy(QComboBox::AdjustToContents);
toolbarlayout->addWidget(new QLabel(tr("Disassembly type:"), m_DisassemblyToolbar));
toolbarlayout->addWidget(m_DisassemblyType);
toolbarlayout->addItem(new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum));
QVBoxLayout *framelayout = new QVBoxLayout(m_DisassemblyFrame);
framelayout->setSpacing(0);
framelayout->setMargin(0);
framelayout->addWidget(m_DisassemblyToolbar);
framelayout->addWidget(m_DisassemblyView);
ui->docking->addToolWindow(m_DisassemblyFrame, ToolWindowManager::EmptySpace);
ui->docking->setToolWindowProperties(m_DisassemblyFrame,
ToolWindowManager::HideCloseButton |
ToolWindowManager::DisallowFloatWindow |
ToolWindowManager::AlwaysDisplayFullTabs);
}
{
QMenu *snippetsMenu = new QMenu(this);
QAction *constants = new QAction(tr("Per-texture constants"), this);
QAction *samplers = new QAction(tr("Point && Linear Samplers"), this);
QAction *resources = new QAction(tr("Texture Resources"), this);
snippetsMenu->addAction(constants);
snippetsMenu->addAction(samplers);
snippetsMenu->addAction(resources);
QObject::connect(constants, &QAction::triggered, this, &ShaderViewer::snippet_constants);
QObject::connect(samplers, &QAction::triggered, this, &ShaderViewer::snippet_samplers);
QObject::connect(resources, &QAction::triggered, this, &ShaderViewer::snippet_resources);
ui->snippets->setMenu(snippetsMenu);
}
QVBoxLayout *layout = new QVBoxLayout(this);
layout->setSpacing(3);
layout->setContentsMargins(3, 3, 3, 3);
layout->addWidget(ui->toolbar);
layout->addWidget(ui->docking);
m_Ctx.AddCaptureViewer(this);
}
void ShaderViewer::editShader(ResourceId id, ShaderStage stage, const QString &entryPoint,
const rdcstrpairs &files, KnownShaderTool knownTool,
ShaderEncoding shaderEncoding, ShaderCompileFlags flags)
{
m_Scintillas.removeOne(m_DisassemblyView);
ui->docking->removeToolWindow(m_DisassemblyFrame);
m_DisassemblyView = NULL;
m_Stage = stage;
m_Flags = flags;
m_CustomShader = (id == ResourceId());
m_EditingShader = id;
// set up compilation parameters
for(ShaderEncoding i : values<ShaderEncoding>())
if(IsTextRepresentation(i) || shaderEncoding == i)
m_Encodings << i;
QStringList strs;
strs.clear();
for(ShaderEncoding i : m_Encodings)
strs << ToQStr(i);
ui->encoding->addItems(strs);
ui->encoding->setCurrentIndex(m_Encodings.indexOf(shaderEncoding));
ui->entryFunc->setText(entryPoint);
QObject::connect(ui->entryFunc, &QLineEdit::textChanged,
[this](const QString &) { MarkModification(); });
QObject::connect(ui->toolCommandLine, &QTextEdit::textChanged, [this]() { MarkModification(); });
PopulateCompileTools();
QObject::connect(ui->encoding, OverloadedSlot<int>::of(&QComboBox::currentIndexChanged),
[this](int) {
PopulateCompileTools();
MarkModification();
});
QObject::connect(ui->compileTool, OverloadedSlot<int>::of(&QComboBox::currentIndexChanged),
[this](int) {
PopulateCompileToolParameters();
MarkModification();
});
// if we know the shader was originally compiled with a specific tool, pick the first matching
// tool we have configured.
if(knownTool != KnownShaderTool::Unknown)
{
for(const ShaderProcessingTool &tool : m_Ctx.Config().ShaderProcessors)
{
// skip tools that can't accept our inputs, or doesn't produce a supported output
if(tool.tool == knownTool)
{
for(int i = 0; i < ui->compileTool->count(); i++)
{
if(ui->compileTool->itemText(i) == tool.name)
{
ui->compileTool->setCurrentIndex(i);
break;
}
}
break;
}
}
}
// if it's a custom shader, hide the group entirely (don't allow customisation of compile
// parameters). We can still use it to store the parameters passed in. When visible we collapse it
// by default.
if(m_CustomShader)
ui->compilationGroup->hide();
// hide debugging windows
ui->watch->hide();
ui->debugVars->hide();
ui->constants->hide();
ui->resourcesPanel->hide();
ui->callstack->hide();
ui->sourceVars->hide();
if(m_CustomShader)
{
ui->snippets->show();
ui->refresh->setText(tr("Refresh"));
ui->resetEdits->hide();
ui->unrefresh->hide();
ui->editStatusLabel->hide();
}
else
{
ui->snippets->hide();
}
// hide debugging toolbar buttons
ui->editSep->hide();
ui->execBackwards->hide();
ui->execForwards->hide();
ui->regFormatSep->hide();
ui->intView->hide();
ui->floatView->hide();
ui->debugToggleSep->hide();
ui->debugToggle->hide();
// hide signatures
ui->inputSig->hide();
ui->outputSig->hide();
QString title;
QWidget *sel = NULL;
for(const rdcstrpair &kv : files)
{
QString name = QFileInfo(kv.first).fileName();
QString text = kv.second;
ScintillaEdit *scintilla = AddFileScintilla(name, text, shaderEncoding);
scintilla->setReadOnly(false);
QObject::connect(scintilla, &ScintillaEdit::keyPressed, this, &ShaderViewer::editable_keyPressed);
QObject::connect(scintilla, &ScintillaEdit::modified, [this](int type, int, int, int,
const QByteArray &, int, int, int) {
if(type & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT | SC_MOD_BEFOREINSERT | SC_MOD_BEFOREDELETE))
m_FindState = FindState();
MarkModification();
});
m_Ctx.GetMainWindow()->RegisterShortcut(QKeySequence(QKeySequence::Refresh).toString(), this,
[this](QWidget *) { on_refresh_clicked(); });
ui->refresh->setToolTip(ui->refresh->toolTip() +
lit(" (%1)").arg(QKeySequence(QKeySequence::Refresh).toString()));
QWidget *w = (QWidget *)scintilla;
w->setProperty("filename", kv.first);
w->setProperty("origText", kv.second);
if(sel == NULL)
{
sel = scintilla;
title = tr(" - %1 - %2()").arg(name).arg(entryPoint);
}
}
if(sel != NULL)
ToolWindowManager::raiseToolWindow(sel);
if(m_CustomShader)
title.prepend(tr("Editing %1 Shader").arg(ToQStr(stage, m_Ctx.APIProps().pipelineType)));
else
title.prepend(tr("Editing %1").arg(m_Ctx.GetResourceNameUnsuffixed(id)));
setWindowTitle(title);
if(files.count() > 2)
addFileList();
m_Errors = MakeEditor(lit("errors"), QString(), SCLEX_NULL);
m_Errors->setReadOnly(true);
m_Errors->setWindowTitle(lit("Errors"));
// remove margins
m_Errors->setMarginWidthN(0, 0);
m_Errors->setMarginWidthN(1, 0);
m_Errors->setMarginWidthN(2, 0);
QObject::connect(m_Errors, &ScintillaEdit::keyPressed, this, &ShaderViewer::readonly_keyPressed);
ui->docking->addToolWindow(
m_Errors, ToolWindowManager::AreaReference(ToolWindowManager::BottomOf,
ui->docking->areaOf(m_Scintillas.front()), 0.2f));
ui->docking->setToolWindowProperties(
m_Errors, ToolWindowManager::HideCloseButton | ToolWindowManager::DisallowFloatWindow);
if(!m_CustomShader)
{
ui->compilationGroup->setWindowTitle(tr("Compilation Settings"));
ui->docking->addToolWindow(ui->compilationGroup,
ToolWindowManager::AreaReference(
ToolWindowManager::LeftOf, ui->docking->areaOf(m_Errors), 0.5f));
ui->docking->setToolWindowProperties(
ui->compilationGroup,
ToolWindowManager::HideCloseButton | ToolWindowManager::DisallowFloatWindow);
}
}
void ShaderViewer::cacheResources()
{
m_ReadOnlyResources = m_Ctx.CurPipelineState().GetReadOnlyResources(m_Stage, false);
m_ReadWriteResources = m_Ctx.CurPipelineState().GetReadWriteResources(m_Stage, false);
}
void ShaderViewer::debugShader(const ShaderBindpointMapping *bind, const ShaderReflection *shader,
ResourceId pipeline, ShaderDebugTrace *trace,
const QString &debugContext)
{
if(bind)
m_Mapping = *bind;
m_ShaderDetails = shader;
m_Pipeline = pipeline;
m_Trace = trace;
m_Stage = ShaderStage::Vertex;
m_DebugContext = debugContext;
// no recompilation happening, hide that group
ui->compilationGroup->hide();
// no replacing allowed, stay in find mode
m_FindReplace->allowUserModeChange(false);
if(!bind || !m_ShaderDetails)
m_Trace = NULL;
if(m_ShaderDetails)
{
m_Stage = m_ShaderDetails->stage;
QPointer<ShaderViewer> me(this);
m_Ctx.Replay().AsyncInvoke([me, this](IReplayController *r) {
if(!me)
return;
rdcarray<rdcstr> targets = r->GetDisassemblyTargets(m_Pipeline != ResourceId());
if(m_Pipeline == ResourceId())
{
rdcarray<rdcstr> pipelineTargets = r->GetDisassemblyTargets(true);
if(pipelineTargets.size() > targets.size())
{
m_PipelineTargets = pipelineTargets;
m_PipelineTargets.removeIf([&targets](const rdcstr &t) { return targets.contains(t); });
}
}
rdcstr disasm = r->DisassembleShader(m_Pipeline, m_ShaderDetails, "");
if(!me)
return;
GUIInvoke::call(this, [this, targets, disasm]() {
QStringList targetNames;
for(int i = 0; i < targets.count(); i++)
{
QString target = targets[i];
targetNames << QString(targets[i]);
if(i == 0)
{
// add any custom decompiling tools we have after the first one
for(const ShaderProcessingTool &d : m_Ctx.Config().ShaderProcessors)
{
if(d.input == m_ShaderDetails->encoding)
targetNames << targetName(d);
}
}
}
if(!m_PipelineTargets.empty())
targetNames << tr("More disassembly formats...");
m_DisassemblyType->clear();
m_DisassemblyType->addItems(targetNames);
m_DisassemblyType->setCurrentIndex(0);
QObject::connect(m_DisassemblyType, OverloadedSlot<int>::of(&QComboBox::currentIndexChanged),
this, &ShaderViewer::disassemble_typeChanged);
// read-only applies to us too!
m_DisassemblyView->setReadOnly(false);
SetTextAndUpdateMargin0(m_DisassemblyView, disasm);
m_DisassemblyView->setReadOnly(true);
});
});
}
updateWindowTitle();
// we always want to highlight words/registers
QObject::connect(m_DisassemblyView, &ScintillaEdit::buttonReleased, this,
&ShaderViewer::disassembly_buttonReleased);
if(m_Trace)
{
if(m_Stage == ShaderStage::Vertex)
{
ANALYTIC_SET(ShaderDebug.Vertex, true);
}
else if(m_Stage == ShaderStage::Pixel)
{
ANALYTIC_SET(ShaderDebug.Pixel, true);
}
else if(m_Stage == ShaderStage::Compute)
{
ANALYTIC_SET(ShaderDebug.Compute, true);
}
m_DisassemblyFrame->layout()->removeWidget(m_DisassemblyToolbar);
}
if(m_ShaderDetails && !m_ShaderDetails->debugInfo.files.isEmpty())
{
updateWindowTitle();
// add all the files, skipping any that have empty contents. We push a NULL in that case so the
// indices still match up with what the debug info expects. Debug info *shouldn't* point us at
// an empty file, but if it does we'll just bail out when we see NULL
m_FileScintillas.reserve(m_ShaderDetails->debugInfo.files.count());
QWidget *sel = NULL;
int32_t entryFile = m_ShaderDetails->debugInfo.entryLocation.fileIndex;
int32_t i = -1;
for(const ShaderSourceFile &f : m_ShaderDetails->debugInfo.files)
{
i++;
if(f.contents.isEmpty())
{
m_FileScintillas.push_back(NULL);
continue;
}
QString name = QFileInfo(f.filename).fileName();
QString text = f.contents;
ScintillaEdit *scintilla = AddFileScintilla(name, text, m_ShaderDetails->debugInfo.encoding);
if(sel == NULL)
sel = scintilla;
if(i == entryFile)
{
sel = scintilla;
if(m_ShaderDetails->debugInfo.entryLocation.lineStart > 0)
{
GUIInvoke::defer(scintilla, [scintilla, this]() {
ensureLineScrolled(scintilla, m_ShaderDetails->debugInfo.entryLocation.lineStart);
});
}
}
m_FileScintillas.push_back(scintilla);
}
if(m_Trace || sel == NULL)
sel = m_DisassemblyFrame;
if(m_ShaderDetails->debugInfo.files.size() > 2)
addFileList();
ToolWindowManager::raiseToolWindow(sel);
}
// hide edit buttons
ui->refresh->hide();
ui->unrefresh->hide();
ui->resetEdits->hide();
ui->editStatusLabel->hide();
ui->snippets->hide();
ui->editSep->hide();
if(m_Trace)
{
// hide signatures
ui->inputSig->hide();
ui->outputSig->hide();
// hide int/float toggles except on DXBC, other encodings are strongly typed
if(m_ShaderDetails->encoding != ShaderEncoding::DXBC)
{
ui->intView->hide();
ui->floatView->hide();
}
if(!m_ShaderDetails->debugInfo.sourceDebugInformation)
{
ui->debugToggle->setEnabled(false);
ui->debugToggle->setText(tr("Source debugging Unavailable"));
}
ui->debugVars->setColumns({tr("Name"), tr("Value")});
ui->debugVars->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
ui->debugVars->header()->setSectionResizeMode(1, QHeaderView::Interactive);
ui->sourceVars->setColumns({tr("Name"), tr("Register(s)"), tr("Type"), tr("Value")});
ui->sourceVars->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
ui->sourceVars->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
ui->sourceVars->header()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
ui->sourceVars->header()->setSectionResizeMode(3, QHeaderView::Interactive);
ui->constants->setColumns({tr("Name"), tr("Register(s)"), tr("Type"), tr("Value")});
ui->constants->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
ui->constants->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
ui->constants->header()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
ui->constants->header()->setSectionResizeMode(3, QHeaderView::Interactive);
ui->constants->header()->resizeSection(0, 80);
ui->accessedResources->setColumns({tr("Location"), tr("Type"), tr("Info")});
ui->accessedResources->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
ui->accessedResources->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
ui->accessedResources->header()->setSectionResizeMode(2, QHeaderView::Interactive);
ui->accessedResources->header()->resizeSection(0, 80);
ui->debugVars->setTooltipElidedItems(false);
ui->constants->setTooltipElidedItems(false);
ui->accessedResources->setTooltipElidedItems(false);
ui->watch->setColumns({tr("Name"), tr("Register(s)"), tr("Type"), tr("Value")});
ui->watch->header()->setSectionResizeMode(0, QHeaderView::Interactive);
ui->watch->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
ui->watch->header()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
ui->watch->header()->setSectionResizeMode(3, QHeaderView::Interactive);
ui->watch->header()->resizeSection(0, 80);
ui->watch->setItemDelegate(new FullEditorDelegate(ui->watch));
ToolWindowManager::ToolWindowProperty windowProps =
ToolWindowManager::HideCloseButton | ToolWindowManager::DisallowFloatWindow;
ui->watch->setWindowTitle(tr("Watch"));
ui->docking->addToolWindow(
ui->watch, ToolWindowManager::AreaReference(ToolWindowManager::BottomOf,
ui->docking->areaOf(m_DisassemblyFrame), 0.25f));
ui->docking->setToolWindowProperties(ui->watch, windowProps);
ui->debugVars->setWindowTitle(tr("Variable Values"));
ui->docking->addToolWindow(
ui->debugVars,
ToolWindowManager::AreaReference(ToolWindowManager::AddTo, ui->docking->areaOf(ui->watch)));
ui->docking->setToolWindowProperties(ui->debugVars, windowProps);
ui->constants->setWindowTitle(tr("Constants && Resources"));
ui->docking->addToolWindow(
ui->constants, ToolWindowManager::AreaReference(ToolWindowManager::LeftOf,
ui->docking->areaOf(ui->debugVars), 0.5f));
ui->docking->setToolWindowProperties(ui->constants, windowProps);
ui->resourcesPanel->setWindowTitle(tr("Accessed Resources"));
ui->docking->addToolWindow(
ui->resourcesPanel, ToolWindowManager::AreaReference(ToolWindowManager::AddTo,
ui->docking->areaOf(ui->constants)));
ui->docking->setToolWindowProperties(ui->resourcesPanel, windowProps);
ui->docking->raiseToolWindow(ui->constants);
ui->callstack->setWindowTitle(tr("Callstack"));
ui->docking->addToolWindow(
ui->callstack, ToolWindowManager::AreaReference(ToolWindowManager::RightOf,
ui->docking->areaOf(ui->debugVars), 0.2f));
ui->docking->setToolWindowProperties(ui->callstack, windowProps);
ui->sourceVars->setWindowTitle(tr("High-level Variables"));
ui->docking->addToolWindow(
ui->sourceVars, ToolWindowManager::AreaReference(ToolWindowManager::AddTo,
ui->docking->areaOf(ui->debugVars)));
ui->docking->setToolWindowProperties(ui->sourceVars, windowProps);
bool hasLineInfo = false;
LineColumnInfo prevLine;
for(uint32_t inst = 0; inst < m_Trace->instInfo.size(); inst++)
{
const InstructionSourceInfo &instInfo = m_Trace->instInfo[inst];
LineColumnInfo line = instInfo.lineInfo;
int disasmLine = (int)line.disassemblyLine;
if(disasmLine > 0 && disasmLine >= m_AsmLine2Inst.size())
{
int oldSize = m_AsmLine2Inst.size();
m_AsmLine2Inst.resize(disasmLine + 1);
for(int i = oldSize; i < disasmLine; i++)
m_AsmLine2Inst[i] = -1;
}
if(disasmLine > 0)
m_AsmLine2Inst[disasmLine] = (int)instInfo.instruction;
if(line.fileIndex < 0)
continue;
hasLineInfo = true;
// store the source location *without* any disassembly line
line.disassemblyLine = 0;
// skip any instructions with the same mapping as the last one, this is a contiguous block
if(line.SourceEqual(prevLine))
continue;
prevLine = line;
m_Location2Inst[line].push_back(instInfo.instruction);
}
// if we don't have line mapping info, assume we also don't have useful high-level variable
// info. Show the debug variables first rather than a potentially empty source variables panel.
if(!hasLineInfo)
ui->docking->raiseToolWindow(ui->debugVars);
// set up stepping/running actions
// we register the shortcuts via MainWindow so that it works regardless of the active scintilla
// but still handles multiple shader viewers being present (the one with focus will get the
// input)
// all shortcuts have a reverse version with shift. This means step out is Ctrl-F11 instead of
// Shift-F11, but otherwise the shortcuts behave the same as visual studio
{
QMenu *backwardsMenu = new QMenu(this);
QAction *act;
act = MakeExecuteAction(tr("&Run backwards"), Icons::control_start_blue(),
tr("Run backwards to the start of the shader"),
QKeySequence(Qt::Key_F5 | Qt::ShiftModifier));
QObject::connect(act, &QAction::triggered, [this]() { runTo(~0U, false); });
backwardsMenu->addAction(act);
act = MakeExecuteAction(
tr("Run backwards to &Cursor"), Icons::control_reverse_cursor_blue(),
tr("Run backwards until execution reaches the cursor, or the start of the shader"),
QKeySequence(Qt::Key_F10 | Qt::ControlModifier | Qt::ShiftModifier));
QObject::connect(act, &QAction::triggered, [this]() { runToCursor(false); });
backwardsMenu->addAction(act);
act = MakeExecuteAction(tr("Run backwards to &Sample"), Icons::control_reverse_sample_blue(),
tr("Run backwards until execution reads from a resource, or the "
"start of the shader is reached"),
QKeySequence());
QObject::connect(act, &QAction::triggered,
[this]() { runTo(~0U, false, ShaderEvents::SampleLoadGather); });
backwardsMenu->addAction(act);
act = MakeExecuteAction(
tr("Run backwards to &NaN/Inf"), Icons::control_reverse_nan_blue(),
tr("Run backwards until a floating point instruction generates a NaN "
"or Inf, an integer instruction divides by 0, or the start of the shader is reached"),
QKeySequence());
QObject::connect(act, &QAction::triggered,
[this]() { runTo(~0U, false, ShaderEvents::GeneratedNanOrInf); });
backwardsMenu->addAction(act);
backwardsMenu->addSeparator();
act = MakeExecuteAction(tr("Step backwards &Over"), Icons::control_reverse_blue(),
tr("Step backwards, and don't enter functions when source debugging"),
QKeySequence(Qt::Key_F10 | Qt::ShiftModifier));
QObject::connect(act, &QAction::triggered, [this]() { step(false, StepOver); });
backwardsMenu->addAction(act);
act = MakeExecuteAction(tr("Step backwards &Into"), Icons::control_reverse_blue(),
tr("Step backwards, entering functions when source debugging"),
QKeySequence(Qt::Key_F11 | Qt::ShiftModifier));
QObject::connect(act, &QAction::triggered, [this]() { step(false, StepInto); });
backwardsMenu->addAction(act);
act =
MakeExecuteAction(tr("Step backwards Ou&t"), Icons::control_reverse_blue(),
tr("Step backwards, out of the current function when source debugging"),
QKeySequence(Qt::Key_F11 | Qt::ControlModifier | Qt::ShiftModifier));
QObject::connect(act, &QAction::triggered, [this]() { step(false, StepOut); });
backwardsMenu->addAction(act);
ui->execBackwards->setMenu(backwardsMenu);
}
{
QMenu *forwardsMenu = new QMenu(this);
QAction *act;
act = MakeExecuteAction(tr("&Run forwards"), Icons::control_end_blue(),
tr("Run forwards to the start of the shader"),
QKeySequence(Qt::Key_F5));
QObject::connect(act, &QAction::triggered, [this]() { runTo(~0U, true); });
forwardsMenu->addAction(act);
act = MakeExecuteAction(
tr("Run forwards to &Cursor"), Icons::control_cursor_blue(),
tr("Run forwards until execution reaches the cursor, or the end of the shader"),
QKeySequence(Qt::Key_F10 | Qt::ControlModifier));
QObject::connect(act, &QAction::triggered, [this]() { runToCursor(true); });
forwardsMenu->addAction(act);
act = MakeExecuteAction(tr("Run forwards to &Sample"), Icons::control_sample_blue(),
tr("Run forwards until execution reads from a resource, or the "
"end of the shader is reached"),
QKeySequence());
QObject::connect(act, &QAction::triggered,
[this]() { runTo(~0U, true, ShaderEvents::SampleLoadGather); });
forwardsMenu->addAction(act);
act = MakeExecuteAction(
tr("Run forwards to &NaN/Inf"), Icons::control_nan_blue(),
tr("Run forwards until a floating point instruction generates a NaN "
"or Inf, an integer instruction divides by 0, or the end of the shader is reached"),
QKeySequence());
QObject::connect(act, &QAction::triggered,
[this]() { runTo(~0U, true, ShaderEvents::GeneratedNanOrInf); });
forwardsMenu->addAction(act);
forwardsMenu->addSeparator();
act = MakeExecuteAction(tr("Step forwards &Over"), Icons::control_play_blue(),
tr("Step forwards, and don't enter functions when source debugging"),
QKeySequence(Qt::Key_F10));
QObject::connect(act, &QAction::triggered, [this]() { step(true, StepOver); });
forwardsMenu->addAction(act);
act = MakeExecuteAction(tr("Step forwards &Into"), Icons::control_play_blue(),
tr("Step forwards, entering functions when source debugging"),
QKeySequence(Qt::Key_F11));
QObject::connect(act, &QAction::triggered, [this]() { step(true, StepInto); });
forwardsMenu->addAction(act);
act =
MakeExecuteAction(tr("Step forwards Ou&t"), Icons::control_play_blue(),
tr("Step forwards, out of the current function when source debugging"),
QKeySequence(Qt::Key_F11 | Qt::ControlModifier));
QObject::connect(act, &QAction::triggered, [this]() { step(true, StepOut); });
forwardsMenu->addAction(act);
ui->execForwards->setMenu(forwardsMenu);
}
for(ScintillaEdit *edit : m_Scintillas)
{
edit->setMarginWidthN(1, 20.0 * devicePixelRatioF());
// display current line in margin 2, distinct from breakpoint in margin 1
sptr_t markMask = (1 << CURRENT_MARKER) | (1 << FINISHED_MARKER);
edit->setMarginMaskN(1, edit->marginMaskN(1) & ~markMask);
edit->setMarginMaskN(2, edit->marginMaskN(2) | markMask);
// suppress the built-in context menu and hook up our own
edit->usePopUp(SC_POPUP_NEVER);
edit->setContextMenuPolicy(Qt::CustomContextMenu);
QObject::connect(edit, &ScintillaEdit::customContextMenuRequested, this,
&ShaderViewer::debug_contextMenu);
edit->setMouseDwellTime(500);
QObject::connect(edit, &ScintillaEdit::dwellStart, this, &ShaderViewer::disasm_tooltipShow);
QObject::connect(edit, &ScintillaEdit::dwellEnd, this, &ShaderViewer::disasm_tooltipHide);
}
// toggle breakpoint - F9
m_Ctx.GetMainWindow()->RegisterShortcut(QKeySequence(Qt::Key_F9).toString(), this,
[this](QWidget *) { ToggleBreakpointOnInstruction(); });
// event filter to pick up tooltip events
ui->constants->installEventFilter(this);
ui->accessedResources->installEventFilter(this);
ui->debugVars->installEventFilter(this);
ui->watch->installEventFilter(this);
cacheResources();
m_BackgroundRunning.release();
QPointer<ShaderViewer> me(this);
m_DeferredInit = true;
m_Ctx.Replay().AsyncInvoke([this, me](IReplayController *r) {
if(!me)
return;
rdcarray<ShaderDebugState> *states = new rdcarray<ShaderDebugState>();
states->append(r->ContinueDebug(m_Trace->debugger));
rdcarray<ShaderDebugState> nextStates;
bool finished = false;
do
{
if(!me)
{
delete states;
return;
}
nextStates = r->ContinueDebug(m_Trace->debugger);
if(!me)
{
delete states;
return;
}
finished = nextStates.empty();
states->append(std::move(nextStates));
} while(!finished && m_BackgroundRunning.available() == 1);
if(!me)
{
delete states;
return;
}
m_BackgroundRunning.tryAcquire(1);
r->SetFrameEvent(m_Ctx.CurEvent(), true);
if(!me)
{
delete states;
return;
}
GUIInvoke::call(this, [this, states]() {
m_States.swap(*states);
delete states;
if(!m_States.empty())
{
for(const ShaderVariableChange &c : GetCurrentState().changes)
m_Variables.push_back(c.after);
}
bool preferSourceDebug = false;
for(const ShaderCompileFlag &flag : m_ShaderDetails->debugInfo.compileFlags.flags)
{
if(flag.name == "preferSourceDebug")
{
preferSourceDebug = true;
break;
}
}
updateDebugState();
// we do updateDebugging() again because the first call finds the scintilla for the current
// source file, the second time jumps to it.
if(preferSourceDebug)
{
// if we're not on a source line, move forward to the first source line
while(!m_CurInstructionScintilla)
{
do
{
applyForwardsChange();
if(GetCurrentInstInfo().lineInfo.fileIndex >= 0)
break;
if(IsLastState())
break;
} while(true);
updateDebugState();
if(IsLastState())
break;
}
// if we got to the last state something's wrong - we're preferring source debug but we
// didn't ever reach an instruction mapped to source lines? just reverse course and don't
// switch to source debugging
if(IsLastState())
{
m_FirstSourceStateIdx = ~0U;
runTo(~0U, false);
}
else
{
m_FirstSourceStateIdx = m_CurrentStateIdx;
gotoSourceDebugging();
updateDebugState();
}
}
m_DeferredInit = false;
for(std::function<void(ShaderViewer *)> &f : m_DeferredCommands)
f(this);
m_DeferredCommands.clear();
});
});
GUIInvoke::defer(this, [this, debugContext]() {
// wait a short while before displaying the progress dialog (which won't show if we're already
// done by the time we reach it)
for(int i = 0; m_BackgroundRunning.available() == 1 && i < 100; i++)
QThread::msleep(5);
ShowProgressDialog(this, tr("Debugging %1").arg(debugContext),
[this]() { return m_BackgroundRunning.available() == 0; }, NULL,
[this]() { m_BackgroundRunning.acquire(); });
});
m_CurrentStateIdx = 0;
QObject::connect(ui->watch, &RDTreeWidget::keyPress, this, &ShaderViewer::watch_keyPress);
ui->watch->setContextMenuPolicy(Qt::CustomContextMenu);
QObject::connect(ui->watch, &RDTreeWidget::customContextMenuRequested, this,
&ShaderViewer::variables_contextMenu);
ui->constants->setContextMenuPolicy(Qt::CustomContextMenu);
QObject::connect(ui->constants, &RDTreeWidget::customContextMenuRequested, this,
&ShaderViewer::variables_contextMenu);
ui->debugVars->setContextMenuPolicy(Qt::CustomContextMenu);
QObject::connect(ui->debugVars, &RDTreeWidget::customContextMenuRequested, this,
&ShaderViewer::variables_contextMenu);
ui->sourceVars->setContextMenuPolicy(Qt::CustomContextMenu);
QObject::connect(ui->sourceVars, &RDTreeWidget::customContextMenuRequested, this,
&ShaderViewer::variables_contextMenu);
ui->accessedResources->setContextMenuPolicy(Qt::CustomContextMenu);
QObject::connect(ui->accessedResources, &RDTreeWidget::customContextMenuRequested, this,
&ShaderViewer::accessedResources_contextMenu);
RDTreeWidgetItem *item = new RDTreeWidgetItem({
QVariant(), QVariant(), QVariant(), QVariant(),
});
item->setEditable(0, true);
ui->watch->addTopLevelItem(item);
ToolWindowManager::raiseToolWindow(m_DisassemblyFrame);
}
else
{
// hide watch, constants, variables
ui->watch->hide();
ui->debugVars->hide();
ui->constants->hide();
ui->resourcesPanel->hide();
ui->sourceVars->hide();
ui->callstack->hide();
// hide debugging toolbar buttons
ui->editSep->hide();
ui->execBackwards->hide();
ui->execForwards->hide();
ui->regFormatSep->hide();
ui->intView->hide();
ui->floatView->hide();
ui->debugToggleSep->hide();
ui->debugToggle->hide();
// show input and output signatures
ui->inputSig->setColumns(
{tr("Name"), tr("Index"), tr("Reg"), tr("Type"), tr("SysValue"), tr("Mask"), tr("Used")});
for(int i = 0; i < ui->inputSig->header()->count(); i++)
ui->inputSig->header()->setSectionResizeMode(i, QHeaderView::ResizeToContents);
ui->outputSig->setColumns(
{tr("Name"), tr("Index"), tr("Reg"), tr("Type"), tr("SysValue"), tr("Mask"), tr("Used")});
for(int i = 0; i < ui->outputSig->header()->count(); i++)
ui->outputSig->header()->setSectionResizeMode(i, QHeaderView::ResizeToContents);
if(m_ShaderDetails)
{
for(const SigParameter &s : m_ShaderDetails->inputSignature)
{
QString name = s.varName.isEmpty()
? QString(s.semanticName)
: QFormatStr("%1 (%2)").arg(s.varName).arg(s.semanticName);
if(s.semanticName.isEmpty())
name = s.varName;
QString semIdx = s.needSemanticIndex ? QString::number(s.semanticIndex) : QString();
QString regIdx =
s.systemValue == ShaderBuiltin::Undefined ? QString::number(s.regIndex) : lit("-");
ui->inputSig->addTopLevelItem(new RDTreeWidgetItem(
{name, semIdx, regIdx, TypeString(s), ToQStr(s.systemValue),
GetComponentString(s.regChannelMask), GetComponentString(s.channelUsedMask)}));
}
bool multipleStreams = false;
for(const SigParameter &s : m_ShaderDetails->outputSignature)
{
if(s.stream > 0)
{
multipleStreams = true;
break;
}
}
for(const SigParameter &s : m_ShaderDetails->outputSignature)
{
QString name = s.varName.isEmpty()
? QString(s.semanticName)
: QFormatStr("%1 (%2)").arg(s.varName).arg(s.semanticName);
if(s.semanticName.isEmpty())
name = s.varName;
if(multipleStreams)
name = QFormatStr("Stream %1 : %2").arg(s.stream).arg(name);
QString semIdx = s.needSemanticIndex ? QString::number(s.semanticIndex) : QString();
QString regIdx =
s.systemValue == ShaderBuiltin::Undefined ? QString::number(s.regIndex) : lit("-");
ui->outputSig->addTopLevelItem(new RDTreeWidgetItem(
{name, semIdx, regIdx, TypeString(s), ToQStr(s.systemValue),
GetComponentString(s.regChannelMask), GetComponentString(s.channelUsedMask)}));
}
}
ui->inputSig->setWindowTitle(tr("Input Signature"));
ui->docking->addToolWindow(ui->inputSig, ToolWindowManager::AreaReference(
ToolWindowManager::BottomOf,
ui->docking->areaOf(m_DisassemblyFrame), 0.2f));
ui->docking->setToolWindowProperties(
ui->inputSig, ToolWindowManager::HideCloseButton | ToolWindowManager::DisallowFloatWindow);
ui->outputSig->setWindowTitle(tr("Output Signature"));
ui->docking->addToolWindow(
ui->outputSig, ToolWindowManager::AreaReference(ToolWindowManager::RightOf,
ui->docking->areaOf(ui->inputSig), 0.5f));
ui->docking->setToolWindowProperties(
ui->outputSig, ToolWindowManager::HideCloseButton | ToolWindowManager::DisallowFloatWindow);
}
for(ScintillaEdit *edit : m_Scintillas)
{
// C# LightCoral
edit->markerSetBack(CURRENT_MARKER, SCINTILLA_COLOUR(240, 128, 128));
edit->markerSetBack(CURRENT_MARKER + 1, SCINTILLA_COLOUR(240, 128, 128));
edit->markerDefine(CURRENT_MARKER, SC_MARK_SHORTARROW);
edit->markerDefine(CURRENT_MARKER + 1, SC_MARK_BACKGROUND);
edit->indicSetFore(CURRENT_INDICATOR, SCINTILLA_COLOUR(240, 128, 128));
edit->indicSetAlpha(CURRENT_INDICATOR, 220);
edit->indicSetOutlineAlpha(CURRENT_INDICATOR, 255);
edit->indicSetUnder(CURRENT_INDICATOR, true);
edit->indicSetStyle(CURRENT_INDICATOR, INDIC_STRAIGHTBOX);
edit->indicSetHoverFore(CURRENT_INDICATOR, SCINTILLA_COLOUR(240, 128, 128));
edit->indicSetHoverStyle(CURRENT_INDICATOR, INDIC_STRAIGHTBOX);
// C# LightSlateGray
edit->markerSetBack(FINISHED_MARKER, SCINTILLA_COLOUR(119, 136, 153));
edit->markerSetBack(FINISHED_MARKER + 1, SCINTILLA_COLOUR(119, 136, 153));
edit->markerDefine(FINISHED_MARKER, SC_MARK_ROUNDRECT);
edit->markerDefine(FINISHED_MARKER + 1, SC_MARK_BACKGROUND);
edit->indicSetFore(FINISHED_INDICATOR, SCINTILLA_COLOUR(119, 136, 153));
edit->indicSetAlpha(FINISHED_INDICATOR, 220);
edit->indicSetOutlineAlpha(FINISHED_INDICATOR, 255);
edit->indicSetUnder(FINISHED_INDICATOR, true);
edit->indicSetStyle(FINISHED_INDICATOR, INDIC_STRAIGHTBOX);
edit->indicSetHoverFore(FINISHED_INDICATOR, SCINTILLA_COLOUR(119, 136, 153));
edit->indicSetHoverStyle(FINISHED_INDICATOR, INDIC_STRAIGHTBOX);
// C# Red
edit->markerSetBack(BREAKPOINT_MARKER, SCINTILLA_COLOUR(255, 0, 0));
edit->markerSetBack(BREAKPOINT_MARKER + 1, SCINTILLA_COLOUR(255, 0, 0));
edit->markerDefine(BREAKPOINT_MARKER, SC_MARK_CIRCLE);
edit->markerDefine(BREAKPOINT_MARKER + 1, SC_MARK_BACKGROUND);
}
}
QAction *ShaderViewer::MakeExecuteAction(QString name, const QIcon &icon, QString tooltip,
QKeySequence shortcut)
{
QAction *act = new QAction(name, this);
// set the shortcut context to something that shouldn't fire, since we want to handle this
// ourselves - we just want Qt to *display* the shortcut
act->setShortcutContext(Qt::WidgetShortcut);
act->setToolTip(tooltip);
act->setIcon(icon);
if(!shortcut.isEmpty())
{
act->setShortcut(shortcut);
m_Ctx.GetMainWindow()->RegisterShortcut(act->shortcut().toString(), this,
[act](QWidget *) { act->activate(QAction::Trigger); });
}
return act;
}
void ShaderViewer::updateWindowTitle()
{
if(m_ShaderDetails)
{
QString shaderName = m_Ctx.GetResourceNameUnsuffixed(m_ShaderDetails->resourceId);
// On D3D12, get the shader name from the pipeline rather than the shader itself
// for the benefit of D3D12 which doesn't have separate shader objects
if(m_Ctx.CurPipelineState().IsCaptureD3D12())
shaderName = QFormatStr("%1 %2")
.arg(m_Ctx.GetResourceNameUnsuffixed(m_Pipeline))
.arg(m_Ctx.CurPipelineState().Abbrev(m_ShaderDetails->stage));
if(m_Trace)
setWindowTitle(QFormatStr("Debugging %1 - %2").arg(shaderName).arg(m_DebugContext));
else
setWindowTitle(shaderName);
}
}
void ShaderViewer::gotoSourceDebugging()
{
if(m_CurInstructionScintilla)
{
ToolWindowManager::raiseToolWindow(m_CurInstructionScintilla);
m_CurInstructionScintilla->setFocus(Qt::MouseFocusReason);
}
}
void ShaderViewer::gotoDisassemblyDebugging()
{
ToolWindowManager::raiseToolWindow(m_DisassemblyFrame);
m_DisassemblyFrame->setFocus(Qt::MouseFocusReason);
}
ShaderViewer *ShaderViewer::LoadEditor(ICaptureContext &ctx, QVariantMap data,
IShaderViewer::SaveCallback saveCallback,
IShaderViewer::RevertCallback revertCallback,
ModifyCallback modifyCallback, QWidget *parent)
{
if(data.isEmpty())
return NULL;
ResourceId id;
{
QVariant v = data[lit("id")];
RichResourceTextInitialise(v, &ctx);
id = v.value<ResourceId>();
}
ShaderStage stage = (ShaderStage)data[lit("stage")].toUInt();
rdcstr entryPoint = data[lit("entryPoint")].toString();
ShaderEncoding encoding = (ShaderEncoding)data[lit("encoding")].toUInt();
QString commandLine = data[lit("commandLine")].toString();
QString toolName = data[lit("tool")].toString();
ShaderCompileFlags flags;
{
QVariantMap v = data[lit("flags")].toMap();
for(const QString &str : v.keys())
flags.flags.push_back({(rdcstr)str, (rdcstr)v[str].toString()});
}
rdcstrpairs files;
{
QVariantList v = data[lit("files")].toList();
for(QVariant f : v)
{
QVariantMap file = f.toMap();
files.push_back(
{(rdcstr)file[lit("name")].toString(), (rdcstr)file[lit("contents")].toString()});
}
}
rdcstr errors;
if((uint32_t)encoding >= (uint32_t)ShaderEncoding::Count)
{
errors += tr("Unrecognised shader encoding '%1'").arg(ToStr(encoding));
// with no other information let's guess HLSL as the most likely
encoding = ShaderEncoding::HLSL;
}
ShaderViewer *view =
EditShader(ctx, id, stage, entryPoint, files, KnownShaderTool::Unknown, encoding, flags,
saveCallback, revertCallback, modifyCallback, parent);
int toolIndex = -1;
for(int i = 0; i < view->ui->compileTool->count(); i++)
{
QString tool = view->ui->compileTool->itemText(i);
if(tool == toolName)
{
toolIndex = i;
break;
}
}
if(toolIndex == -1)
{
errors += tr("Unknown shader tool '%1'").arg(toolName);
// let's pick the highest priority tool for the current encoding
toolIndex = 0;
}
view->ui->encoding->setCurrentIndex(view->m_Encodings.indexOf(encoding));
view->ui->compileTool->setCurrentIndex(toolIndex);
view->ui->entryFunc->setText(entryPoint);
view->ui->toolCommandLine->setText(commandLine);
return view;
}
QVariantMap ShaderViewer::SaveEditor()
{
QVariantMap ret;
if(m_EditingShader != ResourceId())
{
ret[lit("id")] = m_EditingShader;
ret[lit("stage")] = (uint32_t)m_Stage;
ret[lit("entryPoint")] = ui->entryFunc->text();
ret[lit("encoding")] = (uint32_t)currentEncoding();
ret[lit("commandLine")] = ui->toolCommandLine->toPlainText();
ret[lit("tool")] = ui->compileTool->currentText();
{
QVariantMap v;
for(const ShaderCompileFlag &flag : m_Flags.flags)
v[flag.name] = QString(flag.value);
ret[lit("flags")] = v;
}
{
QVariantList v;
for(ScintillaEdit *edit : m_Scintillas)
{
QWidget *w = (QWidget *)edit;
QVariantMap f;
f[lit("name")] = w->property("filename").toString();
f[lit("contents")] = QString::fromUtf8(edit->getText(edit->textLength() + 1));
v.push_back(f);
}
ret[lit("files")] = v;
}
}
return ret;
}
ShaderViewer::~ShaderViewer()
{
delete m_FindResults;
m_FindResults = NULL;
// don't want to async invoke while using 'this', so save the trace separately
ShaderDebugTrace *trace = m_Trace;
// unregister any shortcuts on this window
m_Ctx.GetMainWindow()->UnregisterShortcut(QString(), this);
m_Ctx.Replay().AsyncInvoke([trace](IReplayController *r) { r->FreeTrace(trace); });
if(m_RevertCallback)
m_RevertCallback(&m_Ctx, this, m_EditingShader);
if(m_ModifyCallback)
m_ModifyCallback(this, true);
m_Ctx.RemoveCaptureViewer(this);
delete ui;
}
void ShaderViewer::OnCaptureLoaded()
{
}
void ShaderViewer::OnCaptureClosed()
{
ToolWindowManager::closeToolWindow(this);
}
void ShaderViewer::OnEventChanged(uint32_t eventId)
{
updateDebugState();
updateWindowTitle();
}
ScintillaEdit *ShaderViewer::AddFileScintilla(const QString &name, const QString &text,
ShaderEncoding encoding)
{
ScintillaEdit *scintilla = MakeEditor(lit("scintilla") + name, text,
encoding == ShaderEncoding::HLSL ? SCLEX_HLSL : SCLEX_GLSL);
scintilla->setReadOnly(true);
scintilla->setWindowTitle(name);
((QWidget *)scintilla)->setProperty("name", name);
QObject::connect(scintilla, &ScintillaEdit::keyPressed, this, &ShaderViewer::readonly_keyPressed);
ToolWindowManager::AreaReference ref(ToolWindowManager::EmptySpace);
if(!m_Scintillas.empty())
ref = ToolWindowManager::AreaReference(ToolWindowManager::AddTo,
ui->docking->areaOf(m_Scintillas[0]));
ui->docking->addToolWindow(scintilla, ref);
ui->docking->setToolWindowProperties(scintilla, ToolWindowManager::HideCloseButton |
ToolWindowManager::DisallowFloatWindow |
ToolWindowManager::AlwaysDisplayFullTabs);
m_Scintillas.push_back(scintilla);
return scintilla;
}
ScintillaEdit *ShaderViewer::MakeEditor(const QString &name, const QString &text, int lang)
{
ScintillaEdit *ret = new ScintillaEdit(this);
ret->setMarginLeft(4.0 * devicePixelRatioF());
ret->setMarginWidthN(1, 0);
ret->setMarginWidthN(2, 16.0 * devicePixelRatioF());
ret->setObjectName(name);
ret->styleSetFont(STYLE_DEFAULT, Formatter::FixedFont().family().toUtf8().data());
ret->styleSetSize(STYLE_DEFAULT, Formatter::FixedFont().pointSize());
// C# DarkGreen
ret->indicSetFore(INDICATOR_REGHIGHLIGHT, SCINTILLA_COLOUR(0, 100, 0));
ret->indicSetStyle(INDICATOR_REGHIGHLIGHT, INDIC_ROUNDBOX);
// set up find result highlight style
ret->indicSetFore(INDICATOR_FINDRESULT, SCINTILLA_COLOUR(200, 200, 64));
ret->indicSetStyle(INDICATOR_FINDRESULT, INDIC_FULLBOX);
ret->indicSetAlpha(INDICATOR_FINDRESULT, 50);
ret->indicSetOutlineAlpha(INDICATOR_FINDRESULT, 80);
QColor highlightColor = palette().color(QPalette::Highlight).toRgb();
ret->indicSetFore(
INDICATOR_FINDALLHIGHLIGHT,
SCINTILLA_COLOUR(highlightColor.red(), highlightColor.green(), highlightColor.blue()));
ret->indicSetStyle(INDICATOR_FINDALLHIGHLIGHT, INDIC_FULLBOX);
ret->indicSetAlpha(INDICATOR_FINDALLHIGHLIGHT, 120);
ret->indicSetOutlineAlpha(INDICATOR_FINDALLHIGHLIGHT, 180);
ConfigureSyntax(ret, lang);
ret->setTabWidth(4);
ret->setScrollWidth(1);
ret->setScrollWidthTracking(true);
ret->colourise(0, -1);
SetTextAndUpdateMargin0(ret, text);
ret->emptyUndoBuffer();
return ret;
}
void ShaderViewer::SetTextAndUpdateMargin0(ScintillaEdit *sc, const QString &text)
{
sc->setText(text.toUtf8().data());
int numLines = sc->lineCount();
// don't make the margin too narrow, it looks strange even if there are only 5 lines in a file
// we also add on an extra character for padding (with the *10)
numLines = qMax(1000, numLines * 10);
sptr_t width = sc->textWidth(SC_MARGIN_RTEXT, QString::number(numLines).toUtf8().data());
sc->setMarginWidthN(0, int(width * devicePixelRatioF()));
}
void ShaderViewer::readonly_keyPressed(QKeyEvent *event)
{
if(event->key() == Qt::Key_F && (event->modifiers() & Qt::ControlModifier))
{
m_FindReplace->setReplaceMode(false);
ScintillaEdit *edit = qobject_cast<ScintillaEdit *>(QObject::sender());
if(edit)
{
// if there's a selection, fill the find prompt with that
if(!edit->getSelText().isEmpty())
{
m_FindReplace->setFindText(QString::fromUtf8(edit->getSelText()));
}
else
{
// otherwise pick the word under the cursor, if there is one
sptr_t scintillaPos = edit->currentPos();
sptr_t start = edit->wordStartPosition(scintillaPos, true);
sptr_t end = edit->wordEndPosition(scintillaPos, true);
QByteArray text = edit->textRange(start, end);
if(!text.isEmpty())
m_FindReplace->setFindText(QString::fromUtf8(text));
}
}
on_findReplace_clicked();
}
if(event->key() == Qt::Key_F3)
{
find((event->modifiers() & Qt::ShiftModifier) == 0);
}
}
void ShaderViewer::editable_keyPressed(QKeyEvent *event)
{
if(event->key() == Qt::Key_H && (event->modifiers() & Qt::ControlModifier))
{
m_FindReplace->setReplaceMode(true);
on_findReplace_clicked();
}
}
void ShaderViewer::debug_contextMenu(const QPoint &pos)
{
ScintillaEdit *edit = qobject_cast<ScintillaEdit *>(QObject::sender());
bool isDisasm = (edit == m_DisassemblyView);
int scintillaPos = edit->positionFromPoint(pos.x(), pos.y());
QMenu contextMenu(this);
QAction gotoOther(isDisasm ? tr("Go to Source") : tr("Go to Disassembly"), this);
QObject::connect(&gotoOther, &QAction::triggered, [this, isDisasm]() {
if(isDisasm)
gotoSourceDebugging();
else
gotoDisassemblyDebugging();
updateDebugState();
});
QAction intDisplay(tr("Integer register display"), this);
QAction floatDisplay(tr("Float register display"), this);
intDisplay.setCheckable(true);
floatDisplay.setCheckable(true);
intDisplay.setChecked(ui->intView->isChecked());
floatDisplay.setChecked(ui->floatView->isChecked());
QObject::connect(&intDisplay, &QAction::triggered, this, &ShaderViewer::on_intView_clicked);
QObject::connect(&floatDisplay, &QAction::triggered, this, &ShaderViewer::on_floatView_clicked);
if(isDisasm && m_CurInstructionScintilla == NULL)
gotoOther.setEnabled(false);
contextMenu.addAction(&gotoOther);
contextMenu.addSeparator();
contextMenu.addAction(&intDisplay);
contextMenu.addAction(&floatDisplay);
contextMenu.addSeparator();
QAction addBreakpoint(tr("Toggle breakpoint here"), this);
QAction runForwardCursor(tr("Run forwards to Cursor"), this);
QAction runBackwardCursor(tr("Run backwards to Cursor"), this);
addBreakpoint.setShortcut(QKeySequence(Qt::Key_F9));
runForwardCursor.setShortcut(QKeySequence(Qt::Key_F10 | Qt::ControlModifier));
runBackwardCursor.setShortcut(QKeySequence(Qt::Key_F10 | Qt::ControlModifier | Qt::ShiftModifier));
QObject::connect(&addBreakpoint, &QAction::triggered, [this, scintillaPos] {
m_DisassemblyView->setSelection(scintillaPos, scintillaPos);
ToggleBreakpointOnInstruction();
});
QObject::connect(&runForwardCursor, &QAction::triggered, [this, scintillaPos] {
m_DisassemblyView->setSelection(scintillaPos, scintillaPos);
runToCursor(true);
});
QObject::connect(&runBackwardCursor, &QAction::triggered, [this, scintillaPos] {
m_DisassemblyView->setSelection(scintillaPos, scintillaPos);
runToCursor(false);
});
contextMenu.addAction(&addBreakpoint);
contextMenu.addAction(&runBackwardCursor);
contextMenu.addAction(&runForwardCursor);
contextMenu.addSeparator();
QAction watchExpr(tr("Add Watch Expression"), this);
watchExpr.setEnabled(!edit->selectionEmpty());
QObject::connect(&watchExpr, &QAction::triggered, [this, edit] {
QString expr =
QString::fromUtf8(edit->get_text_range(edit->selectionStart(), edit->selectionEnd()));
for(QString e : expr.split(QLatin1Char(' ')))
AddWatch(e);
});
contextMenu.addAction(&watchExpr);
contextMenu.addSeparator();
QAction copyText(tr("Copy"), this);
QAction selectAll(tr("Select All"), this);
copyText.setEnabled(!edit->selectionEmpty());
QObject::connect(©Text, &QAction::triggered,
[edit] { edit->copyRange(edit->selectionStart(), edit->selectionEnd()); });
QObject::connect(&selectAll, &QAction::triggered, [edit] { edit->selectAll(); });
contextMenu.addAction(©Text);
contextMenu.addAction(&selectAll);
contextMenu.addSeparator();
RDDialog::show(&contextMenu, edit->viewport()->mapToGlobal(pos));
}
void ShaderViewer::variables_contextMenu(const QPoint &pos)
{
QAbstractItemView *w = qobject_cast<QAbstractItemView *>(QObject::sender());
QMenu contextMenu(this);
QAction copyValue(tr("Copy"), this);
QAction addWatch(tr("Add Watch"), this);
QAction deleteWatch(tr("Delete Watch"), this);
QMenu interpretMenu(tr("Interpret As..."), this);
QAction clearAll(tr("Clear All"), this);
QAction interpDefault(tr("Default"), this);
QAction interpFloat(tr("Floating point"), this);
QAction interpSInt(tr("Signed decimal"), this);
QAction interpUInt(tr("Unsigned decimal"), this);
QAction interpHex(tr("Unsigned hexadecimal"), this);
QAction interpOctal(tr("Unsigned octal"), this);
QAction interpBinary(tr("Unsigned binary"), this);
QAction interpColor(tr("Float RGB color"), this);
interpDefault.setCheckable(true);
interpFloat.setCheckable(true);
interpSInt.setCheckable(true);
interpUInt.setCheckable(true);
interpHex.setCheckable(true);
interpOctal.setCheckable(true);
interpBinary.setCheckable(true);
interpColor.setCheckable(true);
interpretMenu.addAction(&interpDefault);
interpretMenu.addAction(&interpFloat);
interpretMenu.addAction(&interpSInt);
interpretMenu.addAction(&interpUInt);
interpretMenu.addAction(&interpHex);
interpretMenu.addAction(&interpOctal);
interpretMenu.addAction(&interpBinary);
interpretMenu.addAction(&interpColor);
contextMenu.addAction(©Value);
contextMenu.addSeparator();
contextMenu.addAction(&addWatch);
if(QObject::sender() == ui->watch)
{
QObject::connect(©Value, &QAction::triggered, [this] { ui->watch->copySelection(); });
contextMenu.addMenu(&interpretMenu);
contextMenu.addAction(&deleteWatch);
contextMenu.addSeparator();
contextMenu.addAction(&clearAll);
// start with no row selected
RDTreeWidgetItem *item = ui->watch->selectedItem();
int topLevelIdx = ui->watch->indexOfTopLevelItem(item);
// last top level item is the empty entry for adding new values, it's not valid
if(topLevelIdx == ui->watch->topLevelItemCount() - 1)
topLevelIdx = -1;
// if we have a top-level item selected, we can re-interpret or delete
interpretMenu.setEnabled(topLevelIdx >= 0);
deleteWatch.setEnabled(topLevelIdx >= 0);
VariableTag tag;
if(item)
tag = item->tag().value<VariableTag>();
// we can add any selected item as a watch that has a path to reference
addWatch.setEnabled(item != NULL && !tag.absoluteRefPath.empty());
if(topLevelIdx >= 0)
{
if(tag.state == WatchVarState::Valid)
{
QString baseUninterpText = item->text(0);
int comma = baseUninterpText.lastIndexOf(QLatin1Char(','));
if(comma < 0)
{
interpDefault.setChecked(true);
}
else
{
QChar interp = baseUninterpText[comma + 1];
baseUninterpText = baseUninterpText.left(comma);
if(interp == QLatin1Char('f'))
interpFloat.setChecked(true);
else if(interp == QLatin1Char('c'))
interpColor.setChecked(true);
else if(interp == QLatin1Char('d') || interp == QLatin1Char('i'))
interpSInt.setChecked(true);
else if(interp == QLatin1Char('u'))
interpUInt.setChecked(true);
else if(interp == QLatin1Char('x'))
interpHex.setChecked(true);
else if(interp == QLatin1Char('o'))
interpOctal.setChecked(true);
else if(interp == QLatin1Char('b'))
interpBinary.setChecked(true);
}
QObject::connect(&interpFloat, &QAction::triggered, [item, baseUninterpText] {
item->setText(0, baseUninterpText + lit(",f"));
});
QObject::connect(&interpColor, &QAction::triggered, [item, baseUninterpText] {
item->setText(0, baseUninterpText + lit(",c"));
});
QObject::connect(&interpSInt, &QAction::triggered, [item, baseUninterpText] {
item->setText(0, baseUninterpText + lit(",i"));
});
QObject::connect(&interpUInt, &QAction::triggered, [item, baseUninterpText] {
item->setText(0, baseUninterpText + lit(",u"));
});
QObject::connect(&interpHex, &QAction::triggered, [item, baseUninterpText] {
item->setText(0, baseUninterpText + lit(",x"));
});
QObject::connect(&interpOctal, &QAction::triggered, [item, baseUninterpText] {
item->setText(0, baseUninterpText + lit(",o"));
});
QObject::connect(&interpBinary, &QAction::triggered, [item, baseUninterpText] {
item->setText(0, baseUninterpText + lit(",b"));
});
}
else
{
interpretMenu.setEnabled(false);
}
}
QObject::connect(&addWatch, &QAction::triggered,
[this, item] { AddWatch(item->tag().value<VariableTag>().absoluteRefPath); });
QObject::connect(&deleteWatch, &QAction::triggered, [this, topLevelIdx] {
RDTreeViewExpansionState expansion;
ui->watch->saveExpansion(expansion, 0);
ui->watch->beginUpdate();
delete ui->watch->takeTopLevelItem(topLevelIdx);
ui->watch->endUpdate();
ui->watch->applyExpansion(expansion, 0);
});
QObject::connect(&clearAll, &QAction::triggered, [this] {
ui->watch->clear();
RDTreeWidgetItem *item = new RDTreeWidgetItem({
QVariant(), QVariant(), QVariant(), QVariant(),
});
item->setEditable(0, true);
ui->watch->addTopLevelItem(item);
});
}
else
{
RDTreeWidget *tree = qobject_cast<RDTreeWidget *>(w);
QObject::connect(©Value, &QAction::triggered, [tree] { tree->copySelection(); });
RDTreeWidgetItem *item = tree->selectedItem();
VariableTag tag;
if(item)
tag = item->tag().value<VariableTag>();
// we can add any selected item as a watch that has a path to reference
addWatch.setEnabled(item != NULL && !tag.absoluteRefPath.empty());
QObject::connect(&addWatch, &QAction::triggered, [this, tree] {
RDTreeWidgetItem *item = tree->selectedItem();
VariableTag tag = item->tag().value<VariableTag>();
if(!tag.absoluteRefPath.empty())
AddWatch(tag.absoluteRefPath);
else
AddWatch(item->text(0));
});
}
RDDialog::show(&contextMenu, w->viewport()->mapToGlobal(pos));
}
void ShaderViewer::accessedResources_contextMenu(const QPoint &pos)
{
QAbstractItemView *w = qobject_cast<QAbstractItemView *>(QObject::sender());
RDTreeWidget *tree = qobject_cast<RDTreeWidget *>(w);
if(tree->selectedItem() == NULL)
return;
const AccessedResourceTag &tag = tree->selectedItem()->tag().value<AccessedResourceTag>();
if(tag.type == VarType::Unknown)
{
// Right clicked on an instruction row
QMenu contextMenu(this);
QAction gotoInstr(tr("Go to Step"), this);
contextMenu.addAction(&gotoInstr);
QObject::connect(&gotoInstr, &QAction::triggered, [this, tag] {
bool forward = (tag.step >= m_CurrentStateIdx);
runTo(m_States[tag.step].nextInstruction, forward);
});
RDDialog::show(&contextMenu, w->viewport()->mapToGlobal(pos));
}
else
{
// Right clicked on a resource row
QMenu contextMenu(this);
QAction prevAccess(tr("Run to Previous Access"), this);
QAction nextAccess(tr("Run to Next Access"), this);
contextMenu.addAction(&prevAccess);
contextMenu.addAction(&nextAccess);
QObject::connect(&prevAccess, &QAction::triggered,
[this, tag] { runToResourceAccess(false, tag.type, tag.bind); });
QObject::connect(&nextAccess, &QAction::triggered,
[this, tag] { runToResourceAccess(true, tag.type, tag.bind); });
RDDialog::show(&contextMenu, w->viewport()->mapToGlobal(pos));
}
}
void ShaderViewer::disassembly_buttonReleased(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
sptr_t scintillaPos = m_DisassemblyView->positionFromPoint(event->x(), event->y());
sptr_t start = m_DisassemblyView->wordStartPosition(scintillaPos, true);
sptr_t end = m_DisassemblyView->wordEndPosition(scintillaPos, true);
QString text = QString::fromUtf8(m_DisassemblyView->textRange(start, end));
QRegularExpression regexp(lit("^[xyzwrgba]+$"));
// if we match a swizzle look before that for the variable
if(regexp.match(text).hasMatch())
{
start--;
while(isspace(m_DisassemblyView->charAt(start)))
start--;
if(m_DisassemblyView->charAt(start) == '.')
{
end = m_DisassemblyView->wordEndPosition(start - 1, true);
start = m_DisassemblyView->wordStartPosition(start - 1, true);
text = QString::fromUtf8(m_DisassemblyView->textRange(start, end));
}
}
if(!text.isEmpty())
{
if(getVarFromPath(text))
{
start = 0;
end = m_DisassemblyView->length();
QColor highlightColor = QColor::fromHslF(
0.333f, 1.0f, qBound(0.25, palette().color(QPalette::Base).lightnessF(), 0.85));
highlightMatchingVars(ui->debugVars->invisibleRootItem(), text, highlightColor);
highlightMatchingVars(ui->constants->invisibleRootItem(), text, highlightColor);
highlightMatchingVars(ui->accessedResources->invisibleRootItem(), text, highlightColor);
highlightMatchingVars(ui->sourceVars->invisibleRootItem(), text, highlightColor);
m_DisassemblyView->setIndicatorCurrent(INDICATOR_REGHIGHLIGHT);
m_DisassemblyView->indicatorClearRange(start, end);
sptr_t flags = SCFIND_MATCHCASE | SCFIND_WHOLEWORD | SCFIND_REGEXP | SCFIND_POSIX;
text += lit("\\.[xyzwrgba]+");
QByteArray findUtf8 = text.toUtf8();
QPair<int, int> result;
do
{
result = m_DisassemblyView->findText(flags, findUtf8.data(), start, end);
if(result.first >= 0)
m_DisassemblyView->indicatorFillRange(result.first, result.second - result.first);
start = result.second;
} while(result.first >= 0);
}
}
}
}
void ShaderViewer::disassemble_typeChanged(int index)
{
if(m_ShaderDetails == NULL)
return;
QString targetStr = m_DisassemblyType->currentText();
for(const ShaderProcessingTool &disasm : m_Ctx.Config().ShaderProcessors)
{
if(targetStr == targetName(disasm))
{
ShaderToolOutput out = disasm.DisassembleShader(this, m_ShaderDetails, "");
rdcstr text;
if(out.result.isEmpty())
text = out.log;
else
text.assign((const char *)out.result.data(), out.result.size());
m_DisassemblyView->setReadOnly(false);
SetTextAndUpdateMargin0(m_DisassemblyView, text);
m_DisassemblyView->setReadOnly(true);
m_DisassemblyView->emptyUndoBuffer();
return;
}
}
if(targetStr == tr("More disassembly formats..."))
{
QString text;
text =
tr("; More disassembly formats are available with a pipeline. This shader view is not\n"
"; associated with any specific pipeline and shows only the shader itself.\n\n"
"; Viewing the shader from the pipeline state view with a pipeline bound will expose\n"
"; these other formats:\n\n");
for(const rdcstr &t : m_PipelineTargets)
text += QFormatStr("%1\n").arg(QString(t));
m_DisassemblyView->setReadOnly(false);
SetTextAndUpdateMargin0(m_DisassemblyView, text);
m_DisassemblyView->setReadOnly(true);
m_DisassemblyView->emptyUndoBuffer();
return;
}
QPointer<ShaderViewer> me(this);
m_Ctx.Replay().AsyncInvoke([me, this, targetStr](IReplayController *r) {
if(!me)
return;
rdcstr disasm = r->DisassembleShader(m_Pipeline, m_ShaderDetails, targetStr);
if(!me)
return;
GUIInvoke::call(this, [this, disasm]() {
m_DisassemblyView->setReadOnly(false);
SetTextAndUpdateMargin0(m_DisassemblyView, disasm);
m_DisassemblyView->setReadOnly(true);
m_DisassemblyView->emptyUndoBuffer();
});
});
}
void ShaderViewer::watch_keyPress(QKeyEvent *event)
{
if(event->key() == Qt::Key_Delete || event->key() == Qt::Key_Backspace)
{
int idx = ui->watch->indexOfTopLevelItem(ui->watch->selectedItem());
if(idx >= 0 && idx < ui->watch->topLevelItemCount() - 1)
{
RDTreeViewExpansionState expansion;
ui->watch->saveExpansion(expansion, 0);
ui->watch->beginUpdate();
delete ui->watch->takeTopLevelItem(idx);
ui->watch->endUpdate();
ui->watch->applyExpansion(expansion, 0);
}
}
}
void ShaderViewer::on_watch_itemChanged(RDTreeWidgetItem *item, int column)
{
// ignore changes to the type/value columns. Only look at name changes, which must be by the user
if(column != 0)
return;
QSignalBlocker block(ui->watch);
VariableTag tag = item->tag().value<VariableTag>();
tag.state = WatchVarState::Invalid;
item->setTag(QVariant::fromValue(tag));
// remove any children
item->clear();
// if the item is now empty, remove it. Only top-level items are editable so this must be one
if(item->text(0).isEmpty())
delete ui->watch->takeTopLevelItem(ui->watch->indexOfTopLevelItem(item));
// ensure we have a trailing row for adding new watch items.
if(ui->watch->topLevelItemCount() == 0 ||
!ui->watch->topLevelItem(ui->watch->topLevelItemCount() - 1)->text(0).isEmpty())
{
RDTreeWidgetItem *blankItem = new RDTreeWidgetItem({
QVariant(), QVariant(), QVariant(), QVariant(),
});
blankItem->setEditable(0, true);
ui->watch->addTopLevelItem(blankItem);
}
updateDebugState();
}
bool ShaderViewer::step(bool forward, StepMode mode)
{
if(!m_Trace || m_States.empty())
return false;
if((forward && IsLastState()) || (!forward && IsFirstState()))
return false;
// also stop if we reach the first real source-mapped instruction, while source debugging
if(!forward && isSourceDebugging() && m_CurrentStateIdx == m_FirstSourceStateIdx)
return false;
m_VariablesChanged.clear();
if(isSourceDebugging())
{
LineColumnInfo oldLine = GetCurrentInstInfo().lineInfo;
rdcarray<rdcstr> oldStack = GetCurrentState().callstack;
do
{
// step once in the right direction
if(forward)
applyForwardsChange();
else
applyBackwardsChange();
LineColumnInfo curLine = GetCurrentLineInfo();
// break out if we hit a breakpoint, no matter what
if(m_Breakpoints.contains({-1, curLine.disassemblyLine}) ||
m_Breakpoints.contains({curLine.fileIndex, curLine.lineStart}))
break;
// if we've reached the limit, break
if((forward && IsLastState()) || (!forward && IsFirstState()))
break;
// also stop if we reach the first real source-mapped instruction, while source debugging
if(!forward && isSourceDebugging() && m_CurrentStateIdx == m_FirstSourceStateIdx)
break;
// keep going if we're still on the same source line as we started
if(curLine.SourceEqual(oldLine))
continue;
// if we're in an invalid file, skip it as unmapped instructions
if(curLine.fileIndex == -1)
continue;
// we're on a different line so we can probably stop, but that might not be enough for Step
// Out or Step Over
rdcarray<rdcstr> curStack = GetCurrentState().callstack;
// first/last instruction may not have a stack - treat any change from no stack to stack as
// hitting the step condition
if(oldStack.empty() || curStack.empty())
break;
// if we're stepping into, any line different from the previous is sufficient to stop stepping
if(mode == StepInto)
break;
// if the stack has shrunk we must have exited the function, don't continue stepping
if(curStack.size() < oldStack.size())
break;
// if the stack is identical we haven't left this function (to our knowledge. We can't
// differentiate between inlining causing us to immediately jump back into this function, a
// kind of A-B-A problem, but there's not much we can do about that here.
if(curStack == oldStack)
{
// if we're stepping over, we can stop stepping now as we've gotten to a different line in
// the same function without going into a new one
if(mode == StepOver)
break;
// if we're stepping out keep going - we want to leave this function.
if(mode == StepOut)
continue;
}
// if the stack common subset is different, we have stepped into a different function due to
// inlining, so stop stepping. This covers the case where StepOut hasn't seen a stack shrink
// yet as well as StepOver where the stack has grown but now has a different root from when we
// started.
//
// E.g. A() -> B() StepOver A() -> C() -> D()
//
// Or A() -> B() StepOut A() -> C()
bool different = false;
for(size_t i = 0; i < qMin(curStack.size(), oldStack.size()); i++)
{
if(oldStack[i] != curStack[i])
{
different = true;
break;
}
}
if(different)
break;
// otherwise we either went into a bigger callstack and continue stepping over it, or else we
// haven't yet stepped out of the callstack that we started in
} while(true);
oldLine = GetCurrentLineInfo();
oldStack = GetCurrentState().callstack;
if(!forward)
{
// ignore disassembly line for comparison in map below
oldLine.disassemblyLine = 0;
// now since a line can have multiple instructions, we may only be on the last one of several
// instructions that map to this source location.
// Keep stepping until we reach the first instruction this line info
// We only do this when stepping over, otherwise we could miss a backwards step-into when the
// same source line is mapped before and after a function call. For step-into we go strictly
// by contiguous sets of instructions with the same source mapping
if(m_Location2Inst.contains(oldLine) && mode == StepOver)
{
const rdcarray<uint32_t> &targetInsts = m_Location2Inst[oldLine];
// keep going until we hit the closest instruction of any block that maps to this function
while(!IsFirstState() && !targetInsts.contains(GetCurrentState().nextInstruction))
{
const rdcarray<rdcstr> &prevStack = GetPreviousState().callstack;
if((oldStack == prevStack || (!prevStack.empty() && oldStack.size() > prevStack.size())) &&
!oldLine.SourceEqual(GetPreviousInstInfo().lineInfo))
{
// if we hit this case, it means we jumped to an instruction in the same call which maps
// to a different line (perhaps through a loop or branch), or we lost a function in the
// callstack. In either event, the contiguous group of instructions we were trying to
// step over is not so contiguous so don't move back any further.
break;
}
applyBackwardsChange();
LineColumnInfo curLine = GetCurrentLineInfo();
// still need to check for instruction-level breakpoints
if(m_Breakpoints.contains({-1, curLine.disassemblyLine}))
break;
}
}
else
{
while(!IsFirstState() && GetPreviousInstInfo().lineInfo.SourceEqual(oldLine))
{
applyBackwardsChange();
LineColumnInfo curLine = GetCurrentLineInfo();
// still need to check for instruction-level breakpoints
if(m_Breakpoints.contains({-1, curLine.disassemblyLine}))
break;
}
}
}
updateDebugState();
}
else
{
// non-source stepping is easy, we just do one instruction in that direction regardless of step
// mode
if(forward)
applyForwardsChange();
else
applyBackwardsChange();
updateDebugState();
}
return true;
}
void ShaderViewer::runToCursor(bool forward)
{
if(!m_Trace || m_States.empty())
return;
// don't update the UI or remove any breakpoints
m_TempBreakpoint = true;
QSet<QPair<int, uint32_t>> oldBPs = m_Breakpoints;
// add a temporary breakpoint on the current instruction
ToggleBreakpointOnInstruction(-1);
// run in the direction
runTo(~0U, forward);
// turn off temp breakpoint state
m_TempBreakpoint = false;
// restore the set of breakpoints to what it was (this handles the case of doing 'run to cursor'
// on a line that already has a breakpoint)
m_Breakpoints = oldBPs;
}
int ShaderViewer::instructionForDisassemblyLine(sptr_t line)
{
// go from scintilla's lines (0-based) to ours (1-based)
line++;
if(line < m_AsmLine2Inst.size())
return m_AsmLine2Inst[line];
return -1;
}
bool ShaderViewer::IsFirstState() const
{
return m_CurrentStateIdx == 0;
}
bool ShaderViewer::IsLastState() const
{
return m_CurrentStateIdx == m_States.size() - 1;
}
const ShaderDebugState &ShaderViewer::GetPreviousState() const
{
if(m_CurrentStateIdx > 0)
return m_States[m_CurrentStateIdx - 1];
return m_States.front();
}
const ShaderDebugState &ShaderViewer::GetCurrentState() const
{
if(m_CurrentStateIdx < m_States.size())
return m_States[m_CurrentStateIdx];
return m_States.back();
}
const ShaderDebugState &ShaderViewer::GetNextState() const
{
if(m_CurrentStateIdx + 1 < m_States.size())
return m_States[m_CurrentStateIdx + 1];
return m_States.back();
}
const InstructionSourceInfo &ShaderViewer::GetPreviousInstInfo() const
{
return GetInstInfo(GetPreviousState().nextInstruction);
}
const InstructionSourceInfo &ShaderViewer::GetCurrentInstInfo() const
{
return GetInstInfo(GetCurrentState().nextInstruction);
}
const InstructionSourceInfo &ShaderViewer::GetNextInstInfo() const
{
return GetInstInfo(GetNextState().nextInstruction);
}
const InstructionSourceInfo &ShaderViewer::GetInstInfo(uint32_t instruction) const
{
InstructionSourceInfo search;
search.instruction = instruction;
auto it = std::lower_bound(m_Trace->instInfo.begin(), m_Trace->instInfo.end(), search);
if(it == m_Trace->instInfo.end())
{
qCritical() << "Couldn't find instruction info for" << instruction;
return m_Trace->instInfo[0];
}
return *it;
}
const LineColumnInfo &ShaderViewer::GetCurrentLineInfo() const
{
return GetCurrentInstInfo().lineInfo;
}
void ShaderViewer::runTo(uint32_t runToInstruction, bool forward, ShaderEvents condition)
{
rdcarray<uint32_t> insts = {runToInstruction};
runTo(insts, forward, condition);
}
void ShaderViewer::runTo(const rdcarray<uint32_t> &runToInstructions, bool forward,
ShaderEvents condition)
{
if(!m_Trace || m_States.empty())
return;
m_VariablesChanged.clear();
bool firstStep = true;
LineColumnInfo oldLine = GetCurrentLineInfo();
// this is effectively infinite as we break out before moving to next/previous state if that would
// be first/last
while((forward && !IsLastState()) || (!forward && !IsFirstState()))
{
// break immediately even on the very first step if it's the one we want to go to
if(runToInstructions.contains(GetCurrentState().nextInstruction))
break;
// after the first step, break on condition
if(!firstStep && (GetCurrentState().flags & condition))
break;
// or breakpoint
LineColumnInfo curLine = GetCurrentLineInfo();
if(!firstStep && (m_Breakpoints.contains({-1, curLine.disassemblyLine}) ||
m_Breakpoints.contains({curLine.fileIndex, curLine.lineStart})))
break;
if(isSourceDebugging())
{
if(!curLine.SourceEqual(oldLine))
firstStep = false;
}
else
{
firstStep = false;
}
if(forward)
{
if(IsLastState())
break;
applyForwardsChange();
}
else
{
if(IsFirstState())
break;
// also stop if we reach the first real source-mapped instruction, while source debugging
if(isSourceDebugging() && m_CurrentStateIdx == m_FirstSourceStateIdx)
break;
applyBackwardsChange();
}
}
updateDebugState();
}
void ShaderViewer::runToResourceAccess(bool forward, VarType type, const BindpointIndex &resource)
{
if(!m_Trace || m_States.empty())
return;
m_VariablesChanged.clear();
// this is effectively infinite as we break out before moving to next/previous state if that would
// be first/last
while((forward && !IsLastState()) || (!forward && !IsFirstState()))
{
if(forward)
{
if(IsLastState())
break;
applyForwardsChange();
}
else
{
if(IsFirstState())
break;
applyBackwardsChange();
}
// Break if the current state references the specific resource requested
bool foundResource = false;
for(const ShaderVariableChange &c : GetCurrentState().changes)
{
if(c.after.type == type && c.after.GetBinding() == resource)
{
foundResource = true;
break;
}
}
if(foundResource)
break;
// or breakpoint
LineColumnInfo curLine = GetCurrentLineInfo();
if(m_Breakpoints.contains({-1, curLine.disassemblyLine}) ||
m_Breakpoints.contains({curLine.fileIndex, curLine.lineStart}))
break;
}
updateDebugState();
}
void ShaderViewer::applyBackwardsChange()
{
if(IsFirstState())
return;
for(const ShaderVariableChange &c : GetCurrentState().changes)
{
// if the before name is empty, this is a variable that came into scope/was created
if(c.before.name.empty())
{
m_VariablesChanged.push_back(c.after.name);
m_VariableLastUpdate[c.after.name] = m_UpdateID;
// delete the matching variable (should only be one)
for(int i = 0; i < m_Variables.count(); i++)
{
if(c.after.name == m_Variables[i].name)
{
m_Variables.removeAt(i);
break;
}
}
}
else
{
m_VariablesChanged.push_back(c.before.name);
m_VariableLastUpdate[c.before.name] = m_UpdateID;
ShaderVariable *v = NULL;
for(int i = 0; i < m_Variables.count(); i++)
{
if(c.before.name == m_Variables[i].name)
{
v = &m_Variables[i];
break;
}
}
if(v)
*v = c.before;
else
m_Variables.insert(0, c.before);
}
}
m_CurrentStateIdx--;
m_UpdateID++;
}
void ShaderViewer::applyForwardsChange()
{
if(IsLastState())
return;
m_CurrentStateIdx++;
rdcarray<AccessedResourceData> newAccessedResources;
for(const ShaderVariableChange &c : GetCurrentState().changes)
{
// if the after name is empty, this is a variable going out of scope/being deleted
if(c.after.name.empty())
{
m_VariablesChanged.push_back(c.before.name);
m_VariableLastUpdate[c.before.name] = m_UpdateID;
// delete the matching variable (should only be one)
for(int i = 0; i < m_Variables.count(); i++)
{
if(c.before.name == m_Variables[i].name)
{
m_Variables.removeAt(i);
break;
}
}
}
else
{
m_VariablesChanged.push_back(c.after.name);
m_VariableLastUpdate[c.after.name] = m_UpdateID;
ShaderVariable *v = NULL;
for(int i = 0; i < m_Variables.count(); i++)
{
if(c.after.name == m_Variables[i].name)
{
v = &m_Variables[i];
break;
}
}
if(v)
*v = c.after;
else
m_Variables.insert(0, c.after);
if(c.after.type == VarType::ReadOnlyResource || c.after.type == VarType::ReadWriteResource)
{
bool found = false;
for(size_t i = 0; i < m_AccessedResources.size(); i++)
{
if(c.after.GetBinding() == m_AccessedResources[i].resource.GetBinding())
{
found = true;
if(m_AccessedResources[i].steps.indexOf(m_CurrentStateIdx) < 0)
m_AccessedResources[i].steps.push_back(m_CurrentStateIdx);
break;
}
}
if(!found)
newAccessedResources.push_back({c.after, {m_CurrentStateIdx}});
}
}
}
m_AccessedResources.insert(0, newAccessedResources);
m_UpdateID++;
}
QString ShaderViewer::stringRep(const ShaderVariable &var, uint32_t row)
{
VarType type = var.type;
if(type == VarType::Unknown)
type = ui->intView->isChecked() ? VarType::SInt : VarType::Float;
if(type == VarType::ReadOnlyResource || type == VarType::ReadWriteResource ||
type == VarType::Sampler)
{
BindpointIndex varBind = var.GetBinding();
rdcarray<BoundResourceArray> resList;
if(type == VarType::ReadOnlyResource)
resList = m_ReadOnlyResources;
else if(type == VarType::ReadWriteResource)
resList = m_ReadWriteResources;
else if(type == VarType::Sampler)
resList = m_Ctx.CurPipelineState().GetSamplers(m_Stage);
int32_t bindIdx = resList.indexOf(Bindpoint(varBind));
if(bindIdx < 0)
return QString();
BoundResourceArray res = resList[bindIdx];
if(varBind.arrayIndex >= res.resources.size())
return QString();
if(type == VarType::Sampler)
return samplerRep(varBind, varBind.arrayIndex, res.resources[varBind.arrayIndex].resourceId);
return ToQStr(res.resources[varBind.arrayIndex].resourceId);
}
return RowString(var, row, type);
}
QString ShaderViewer::samplerRep(Bindpoint bind, uint32_t arrayIndex, ResourceId id)
{
if(id == ResourceId())
{
QString contents;
if(bind.bindset > 0)
{
// a bit ugly to do an API-specific switch here but we don't have a better way to refer
// by binding
contents = IsD3D(m_Ctx.APIProps().pipelineType) ? tr("space%1, ") : tr("Set %1, ");
contents = contents.arg(bind.bindset);
}
if(arrayIndex == ~0U)
contents += QString::number(bind.bind);
else
contents += QFormatStr("%1[%2]").arg(bind.bind).arg(arrayIndex);
return contents;
}
else
{
return ToQStr(id);
}
}
QString ShaderViewer::targetName(const ShaderProcessingTool &disasm)
{
return lit("%1 (%2)").arg(ToQStr(disasm.output)).arg(disasm.name);
}
void ShaderViewer::addFileList()
{
QListWidget *list = new QListWidget(this);
list->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
list->setSelectionMode(QAbstractItemView::SingleSelection);
QObject::connect(list, &QListWidget::currentRowChanged, [this](int idx) {
QWidget *raiseWidget = m_Scintillas[idx];
if(m_Scintillas[idx] == m_DisassemblyView)
raiseWidget = m_DisassemblyFrame;
ToolWindowManager::raiseToolWindow(raiseWidget);
});
list->setWindowTitle(tr("File List"));
for(ScintillaEdit *s : m_Scintillas)
{
if(s == m_DisassemblyView)
list->addItem(m_DisassemblyFrame->windowTitle());
else
list->addItem(s->windowTitle());
}
ui->docking->addToolWindow(
list, ToolWindowManager::AreaReference(ToolWindowManager::LeftOf,
ui->docking->areaOf(m_Scintillas.front()), 0.2f));
ui->docking->setToolWindowProperties(
list, ToolWindowManager::HideCloseButton | ToolWindowManager::DisallowFloatWindow);
}
void ShaderViewer::combineStructures(RDTreeWidgetItem *root, int skipPrefixLength)
{
RDTreeWidgetItem temp;
// we perform a filter moving from root to temp. At each point we check the node:
// * if the node has no struct or array prefix, it gets moved
// * if the node does have a prefix, we sweep finding all matching elements with the same prefix,
// strip the prefix off them and make a combined node, then recurse to combine anything
// underneath. We aren't greedy in picking prefixes so this should generate a struct/array tree.
// * in the event that a node has no matching elements we move it across as if it had no prefix.
// * we iterate from last to first, because when combining elements that may be spread out in the
// list of children, we want to combine up to the position of the last item, not the position of
// the first.
for(int c = root->childCount() - 1; c >= 0;)
{
RDTreeWidgetItem *child = root->takeChild(c);
c--;
QString name = child->text(0);
int dotIndex = name.indexOf(QLatin1Char('.'), skipPrefixLength);
int arrIndex = name.indexOf(QLatin1Char('['), skipPrefixLength);
// if this node doesn't have any segments, just move it across.
if(dotIndex < 0 && arrIndex < 0)
{
temp.insertChild(0, child);
continue;
}
// store the index of the first separator
int sepIndex = dotIndex;
bool isLeafArray = (sepIndex == -1);
if(sepIndex == -1 || (arrIndex > 0 && arrIndex < sepIndex))
sepIndex = arrIndex;
// we have a valid node to match against, record the prefix (including separator character)
QString prefix = name.mid(0, sepIndex + 1);
QVector<RDTreeWidgetItem *> matches = {child};
// iterate down from the next item
for(int n = c; n >= 0; n--)
{
RDTreeWidgetItem *testNode = root->child(n);
QString testName = testNode->text(0);
QString testprefix = testName.mid(0, sepIndex + 1);
// no match - continue
if(testprefix != prefix)
continue;
// match, take this child
matches.push_back(root->takeChild(n));
// also decrement c since we're taking a child ahead of where that loop will go.
c--;
}
// Sort the children by offset, then global source var index, then by text.
// Using the global source var index allows resource arrays to be presented in index order
// rather than by name, so for example arr[2] comes before arr[10]
std::sort(matches.begin(), matches.end(),
[](const RDTreeWidgetItem *a, const RDTreeWidgetItem *b) {
VariableTag at = a->tag().value<VariableTag>();
VariableTag bt = b->tag().value<VariableTag>();
if(at.offset != bt.offset)
return at.offset < bt.offset;
return a->text(0) < b->text(0);
});
// create a new parent with just the prefix
prefix.chop(1);
QVariantList values = {prefix};
for(int i = 1; i < child->dataCount(); i++)
values.push_back(QVariant());
RDTreeWidgetItem *parent = new RDTreeWidgetItem(values);
VariableTag tag;
tag.absoluteRefPath = prefix;
parent->setTag(QVariant::fromValue(tag));
// add all the children (stripping the prefix from their name)
for(RDTreeWidgetItem *item : matches)
{
if(sepIndex == dotIndex)
item->setText(0, item->text(0).mid(sepIndex + 1));
parent->addChild(item);
if(item->background().color().isValid())
parent->setBackground(item->background());
if(item->foreground().color().isValid())
parent->setForeground(item->foreground());
}
// recurse and combine members of this object if a struct
if(!isLeafArray)
{
if(sepIndex != dotIndex)
combineStructures(parent, sepIndex + 1);
else
combineStructures(parent);
}
// now add to the list
temp.insertChild(0, parent);
}
if(root->childCount() > 0)
qCritical() << "Some objects left on root!";
// move all the children back from the temp object into the parameter
while(temp.childCount() > 0)
root->addChild(temp.takeChild(0));
}
QString ShaderViewer::getRegNames(const RDTreeWidgetItem *item, uint32_t swizzle, uint32_t child)
{
VariableTag tag = item->tag().value<VariableTag>();
if(tag.absoluteRefPath.empty())
return QString();
if(tag.debugVarType != DebugVariableType::Undefined)
{
DebugVariableReference debugVar;
debugVar.type = tag.debugVarType;
debugVar.name = tag.absoluteRefPath;
const ShaderVariable *reg = GetDebugVariable(debugVar);
return reg->name;
}
SourceVariableMapping mapping;
VariableTag itemTag = tag;
// if this an expanded node (when a single source variable maps to a complex struct/array)
// search up to the nearest parent which isn't
const RDTreeWidgetItem *cur = item;
while(tag.expanded)
{
cur = cur->parent();
tag = cur->tag().value<VariableTag>();
}
// check if it's a local or global source var and look up the mapping
if(tag.globalSourceVar && tag.sourceVarIdx >= 0 && tag.sourceVarIdx < m_Trace->sourceVars.count())
{
mapping = m_Trace->sourceVars[tag.sourceVarIdx];
}
else if(!tag.globalSourceVar && tag.sourceVarIdx >= 0 &&
tag.sourceVarIdx < GetCurrentInstInfo().sourceVars.count())
{
mapping = GetCurrentInstInfo().sourceVars[tag.sourceVarIdx];
}
else
{
// if there's no source mapping, we assume this is a root node of a struct, which has no reg
// names
return QString();
}
QString ret;
// if we have a 'tail' referencing values inside this mapping, need to evaluate that
if(cur != item)
{
// we don't support combining complex structs from multiple places, we should only have one
// mapping here
if(mapping.variables.size() != 1)
return QString();
const ShaderVariable *reg = GetDebugVariable(mapping.variables[0]);
// return the base name with the suffix/tail that we have
ret = reg->name + itemTag.absoluteRefPath.substr(tag.absoluteRefPath.size());
if(child < 4)
ret += lit(".row%1").arg(child);
return ret;
}
if(mapping.type == VarType::Sampler || mapping.type == VarType::ReadOnlyResource ||
mapping.type == VarType::ReadWriteResource)
{
const ShaderVariable *reg = GetDebugVariable(mapping.variables[0]);
ret = reg->name;
if(mapping.type == VarType::Sampler)
{
rdcarray<BoundResourceArray> samplers = m_Ctx.CurPipelineState().GetSamplers(m_Stage);
int32_t idx = m_Mapping.samplers.indexOf(Bindpoint(reg->GetBinding()));
if(idx < 0)
return QString();
Bindpoint bind = m_Mapping.samplers[idx];
if(bind.arraySize == ~0U)
return ret + lit("[unbounded]");
if(bind.arraySize > 1 && child != ~0U)
return QFormatStr("%1[%2]").arg(ret).arg(child);
return ret;
}
else if(mapping.type == VarType::ReadOnlyResource)
{
const bool isReadOnlyResource = mapping.type == VarType::ReadOnlyResource;
rdcarray<BoundResourceArray> &resList =
isReadOnlyResource ? m_ReadOnlyResources : m_ReadWriteResources;
int32_t idx = (isReadOnlyResource ? m_Mapping.readOnlyResources : m_Mapping.readWriteResources)
.indexOf(Bindpoint(reg->GetBinding()));
if(idx < 0)
return QString();
Bindpoint bind =
isReadOnlyResource ? m_Mapping.readOnlyResources[idx] : m_Mapping.readWriteResources[idx];
if(bind.arraySize == ~0U)
return ret + lit("[unbounded]");
if(bind.arraySize > 1 && child != ~0U)
return QFormatStr("%1[%2]").arg(ret).arg(child);
return ret;
}
return ret;
}
uint32_t start = 0;
uint32_t count = (uint32_t)mapping.variables.size();
if(mapping.rows > 1 && mapping.variables.size() > mapping.columns)
{
count = mapping.columns;
if(child < mapping.rows)
start += count * child;
swizzle = ~0U;
}
DebugVariableReference prevRef;
const QString xyzw = lit("xyzw");
for(uint32_t i = start; i < start + count; i++)
{
uint32_t swiz_i = i;
if(swizzle != ~0U)
{
swiz_i = (swizzle >> (i * 8)) & 0xff;
if(swiz_i == 0xff)
{
// swizzle has finished, truncate
break;
}
}
const DebugVariableReference &r = mapping.variables[swiz_i];
if(!ret.isEmpty())
ret += lit(", ");
if(r.name.empty())
{
ret += lit("-");
}
else
{
const ShaderVariable *reg = GetDebugVariable(r);
if(reg)
{
if(!reg->members.empty())
return QString();
if(i > start && r.name == prevRef.name &&
(r.component / reg->columns) == (prevRef.component / reg->columns))
{
// if the previous register was the same, just append our component
// remove the auto-appended ", " - there must be one because this isn't the first
// register
ret.chop(2);
ret += xyzw[r.component % 4];
}
else
{
if(reg->rows > 1)
ret += QFormatStr("%1.row%2.%3")
.arg(reg->name)
.arg(r.component / reg->columns)
.arg(xyzw[r.component % 4]);
else
ret += QFormatStr("%1.%2").arg(r.name).arg(xyzw[r.component % 4]);
}
}
else
{
ret += lit("-");
}
}
prevRef = r;
}
return ret;
}
const RDTreeWidgetItem *ShaderViewer::evaluateVar(const RDTreeWidgetItem *item, uint32_t swizzle,
ShaderVariable *var)
{
VariableTag tag = item->tag().value<VariableTag>();
// if the tag is invalid, it's not a proper match
if(tag.absoluteRefPath.empty())
return NULL;
// if we have a debug var tag then it's easy-mode
if(tag.debugVarType != DebugVariableType::Undefined)
{
// found a match. If we don't want the variable contents, just return true now
if(!var)
return item;
DebugVariableReference debugVar;
debugVar.type = tag.debugVarType;
debugVar.name = tag.absoluteRefPath;
const ShaderVariable *reg = GetDebugVariable(debugVar);
if(reg)
{
*var = *reg;
var->name = debugVar.name;
if(swizzle != ~0U)
{
// only support swizzles if the debug variable is a plain vector or scalar
if(!reg->members.empty() || reg->rows > 1)
return NULL;
var->value = ShaderValue();
size_t compSize = VarTypeByteSize(var->type);
for(uint32_t i = 0; i < 4; i++)
{
uint8_t sw = (swizzle >> (i * 8)) & 0xff;
if(sw == 0xff)
{
// swizzle has finished, truncate
break;
}
else if(sw < reg->columns)
{
var->columns = i + 1;
memcpy(var->value.u8v.data() + compSize * i, reg->value.u8v.data() + compSize * sw,
compSize);
}
else
{
return NULL;
}
}
}
}
else
{
qCritical() << "Couldn't find expected debug variable!" << ToQStr(debugVar.type)
<< QString(debugVar.name);
return NULL;
}
return item;
}
else
{
// found a match. If we don't want the variable contents, just return true now
if(!var)
return item;
SourceVariableMapping mapping;
VariableTag itemTag = tag;
// if this an expanded node (when a single source variable maps to a complex struct/array)
// search up to the nearest parent which isn't
const RDTreeWidgetItem *cur = item;
while(tag.expanded)
{
cur = cur->parent();
tag = cur->tag().value<VariableTag>();
}
// check if it's a local or global source var and look up the mapping
if(tag.globalSourceVar && tag.sourceVarIdx >= 0 && tag.sourceVarIdx < m_Trace->sourceVars.count())
{
mapping = m_Trace->sourceVars[tag.sourceVarIdx];
}
else if(!tag.globalSourceVar && tag.sourceVarIdx >= 0 &&
tag.sourceVarIdx < GetCurrentInstInfo().sourceVars.count())
{
mapping = GetCurrentInstInfo().sourceVars[tag.sourceVarIdx];
}
else
{
// if there's no source mapping, we assume this is a root node of a struct, so build the
// ShaderVariable that way. We should not have encountered any expanded nodes, and we should
// have children
if(cur != item)
return NULL;
if(item->childCount() == 0)
return NULL;
ShaderVariable &ret = *var;
ret.name = item->text(0);
for(int i = 0; i < item->childCount(); i++)
{
ret.members.push_back(ShaderVariable());
if(!evaluateVar(item->child(i), ~0U, &ret.members.back()))
return NULL;
}
return item;
}
if(mapping.variables.empty())
return NULL;
// if we have a 'tail' referencing values inside this mapping, need to evaluate that
if(cur != item)
{
// we don't support combining complex structs from multiple places, we should only have one
// mapping here
if(mapping.variables.size() != 1)
return NULL;
DebugVariableReference ref = mapping.variables[0];
// append on our suffix
ref.name += itemTag.absoluteRefPath.substr(tag.absoluteRefPath.size());
ref.component = 0;
mapping.variables.clear();
const ShaderVariable *reg = GetDebugVariable(ref);
// expect to find the variable
if(!reg)
return NULL;
// update the mapping
mapping.name = reg->name;
mapping.rows = reg->rows;
mapping.columns = reg->columns;
mapping.type = reg->type;
// add a mapping for each component in the resulting variable referenced. Swizzles are handled
// separately
for(uint8_t c = 0; c < std::max(1, reg->rows * reg->columns); c++)
{
ref.component = c;
mapping.variables.push_back(ref);
}
}
ShaderVariable &ret = *var;
ret.name = mapping.name;
ret.flags |= ShaderVariableFlags::RowMajorMatrix;
ret.rows = mapping.rows;
ret.columns = mapping.columns;
ret.type = mapping.type;
size_t dataSize = VarTypeByteSize(ret.type);
if(dataSize == 0)
dataSize = 4;
if(ret.type == VarType::Sampler || ret.type == VarType::ReadOnlyResource ||
ret.type == VarType::ReadWriteResource)
dataSize = 16;
// only support swizzling on vectors
if(swizzle != ~0U && (ret.rows > 1 || mapping.variables.size() > 4))
return NULL;
DebugVariableReference prevRef;
for(uint32_t i = 0; i < mapping.variables.size(); i++)
{
uint32_t swiz_i = i;
if(swizzle != ~0U)
{
swiz_i = (swizzle >> (i * 8)) & 0xff;
if(swiz_i == 0xff)
{
// swizzle has finished, truncate
break;
}
else if(swiz_i < mapping.variables.size())
{
ret.columns = i + 1;
}
}
const DebugVariableReference &r = mapping.variables[swiz_i];
const ShaderVariable *reg = GetDebugVariable(r);
if(reg)
{
if(!reg->members.empty())
{
ret.members = reg->members;
if(mapping.variables.size() != 1)
return NULL;
break;
}
if(dataSize == 16)
ret.value = reg->value;
else if(dataSize == 8)
ret.value.u64v[i] = reg->value.u64v[r.component];
else if(dataSize == 4)
ret.value.u32v[i] = reg->value.u32v[r.component];
else if(dataSize == 2)
ret.value.u16v[i] = reg->value.u16v[r.component];
else
ret.value.u8v[i] = reg->value.u8v[r.component];
}
prevRef = r;
}
return item;
}
}
const RDTreeWidgetItem *ShaderViewer::getVarFromPath(const rdcstr &path, const RDTreeWidgetItem *root,
ShaderVariable *var, uint32_t *swizzlePtr)
{
VariableTag tag = root->tag().value<VariableTag>();
// if the path is an exact match, return the evaluation directly
if(tag.absoluteRefPath == path)
{
return evaluateVar(root, ~0U, var);
}
for(int i = 0; i < root->childCount(); i++)
{
RDTreeWidgetItem *child = root->child(i);
tag = child->tag().value<VariableTag>();
// if this child has a longer path, it can't be what we're looking for
if(tag.absoluteRefPath.size() > path.size())
continue;
// if the path is an exact match, return the evaluation directly
if(tag.absoluteRefPath == path)
{
return evaluateVar(child, ~0U, var);
}
// after the common prefix, if the next value is . or [ then this is the next child, so recurse.
// it can't be any other child since we don't support multiple members with the same name, so if
// this recursion fails there is no better option
// we know it's not an exact match (or the path would have been identical above) but the
// recursion will handle any trailing swizzle
rdcstr common = path.substr(0, tag.absoluteRefPath.size());
if(common == tag.absoluteRefPath &&
(path[tag.absoluteRefPath.size()] == '.' || path[tag.absoluteRefPath.size()] == '['))
{
return getVarFromPath(path, child, var, swizzlePtr);
}
}
if(root->childCount() == 0)
{
// if there are no children but we got here instead of earlying out elsewhere, there might be a
// trailing swizzle
QRegularExpression swizzleRE(lit("^(.*)\\.([xyzwrgba][xyzwrgba]?[xyzwrgba]?[xyzwrgba]?)$"));
QRegularExpressionMatch match = swizzleRE.match(path);
// if we exactly match without the swizzle, we can evaluate this node
if(match.hasMatch() && QString(tag.absoluteRefPath) == match.captured(1))
{
QString swizzle = match.captured(2);
uint32_t swizzleMask = 0;
int s = 0;
for(; s < swizzle.count(); s++)
{
switch(swizzle[s].toLatin1())
{
case 'x':
case 'r': swizzleMask |= (0x00U << (s * 8)); break;
case 'y':
case 'g': swizzleMask |= (0x01U << (s * 8)); break;
case 'z':
case 'b': swizzleMask |= (0x02U << (s * 8)); break;
case 'w':
case 'a': swizzleMask |= (0x03U << (s * 8)); break;
default: return NULL;
}
}
for(; s < 4; s++)
{
swizzleMask |= (0xffU << (s * 8));
}
if(swizzlePtr)
*swizzlePtr = swizzleMask;
return evaluateVar(root, swizzleMask, var);
}
}
return NULL;
}
const RDTreeWidgetItem *ShaderViewer::getVarFromPath(const rdcstr &path, ShaderVariable *var,
uint32_t *swizzle)
{
if(!m_Trace || m_States.empty())
return NULL;
// prioritise source mapped variables, in the event that source vars have the same name as debug
// vars we want to prioritise source vars. After that look through constants (some/all of which
// may be source mapped as well) before searching debug vars
RDTreeWidget *widgets[] = {ui->sourceVars, ui->constants, ui->debugVars};
rdcstr root;
int idx = path.find_first_of("[.");
if(idx > 0)
root = path.substr(0, idx);
else
root = path;
// we do a 'breadth first' type search. First look for any direct descendents which match the
// first part of the path we're looking for. If that doesn't find anything, look for any children
// of the top level items that match. This fixes issues with e.g. constant buffer names where they
// aren't actually namespaced
for(int pass = 0; pass < 2; pass++)
{
for(RDTreeWidget *w : widgets)
{
for(int i = 0; i < w->topLevelItemCount(); i++)
{
RDTreeWidgetItem *item = w->topLevelItem(i);
if(item->text(0) == root)
{
const RDTreeWidgetItem *ret = getVarFromPath(path, item, var, swizzle);
if(ret)
return ret;
}
if(pass == 1)
{
for(int j = 0; j < item->childCount(); j++)
{
RDTreeWidgetItem *child = item->child(j);
if(child->text(0) == root)
{
VariableTag tag = item->tag().value<VariableTag>();
const RDTreeWidgetItem *ret =
getVarFromPath(tag.absoluteRefPath + "." + path, child, var, swizzle);
if(ret)
return ret;
}
}
}
}
}
}
return NULL;
}
void ShaderViewer::updateEditState()
{
if(m_EditingShader != ResourceId())
{
QString statusString, statusTooltip;
// check if the shader is replaced and update the status
if(m_Ctx.IsResourceReplaced(m_EditingShader))
{
statusString = tr("Status: Edited Shader Active");
statusTooltip = tr("The replay currently has the original shader active");
}
else
{
statusString = tr("Status: Original Shader Active");
statusTooltip = tr("The replay currently has an edited version of the shader active");
// if we expected it to be saved something went wrong
if(m_Saved)
{
// we're still 'modified' as in have unsaved changes
m_Modified = true;
statusTooltip.append(tr("\n\nSomething went wrong applying changes."));
}
}
ui->editStatusLabel->setText(statusString);
ui->editStatusLabel->setToolTip(statusTooltip);
if(m_Modified)
{
QString title = windowTitle();
if(title[0] != QLatin1Char('*'))
title.prepend(lit("* "));
setWindowTitle(title);
}
else
{
QString title = windowTitle();
if(title[0] == QLatin1Char('*'))
title.remove(0, 2);
setWindowTitle(title);
}
}
}
void ShaderViewer::highlightMatchingVars(RDTreeWidgetItem *root, const QString varName,
const QColor highlightColor)
{
for(int i = 0; i < root->childCount(); i++)
{
RDTreeWidgetItem *item = root->child(i);
if(item->tag().value<VariableTag>().absoluteRefPath == rdcstr(varName))
item->setBackgroundColor(highlightColor);
else
item->setBackground(QBrush());
highlightMatchingVars(item, varName, highlightColor);
}
}
void ShaderViewer::updateAccessedResources()
{
RDTreeViewExpansionState expansion;
ui->accessedResources->saveExpansion(expansion, 0);
ui->accessedResources->beginUpdate();
ui->accessedResources->clear();
switch(m_AccessedResourceView)
{
case AccessedResourceView::SortByResource:
{
for(size_t i = 0; i < m_AccessedResources.size(); ++i)
{
// Check if the resource was accessed prior to this step
bool accessed = false;
for(size_t j = 0; j < m_AccessedResources[i].steps.size(); ++j)
{
if(m_AccessedResources[i].steps[j] <= m_CurrentStateIdx)
{
accessed = true;
break;
}
}
if(!accessed)
continue;
RDTreeWidgetItem *resourceNode = makeAccessedResourceNode(m_AccessedResources[i].resource);
if(resourceNode)
{
// Add a child for each step that it was accessed
for(size_t j = 0; j < m_AccessedResources[i].steps.size(); ++j)
{
accessed = m_AccessedResources[i].steps[j] <= m_CurrentStateIdx;
if(accessed)
{
RDTreeWidgetItem *stepNode = new RDTreeWidgetItem(
{tr("Step %1").arg(m_AccessedResources[i].steps[j]), lit("Access"), lit("")});
stepNode->setTag(QVariant::fromValue(
AccessedResourceTag((uint32_t)m_AccessedResources[i].steps[j])));
if(m_CurrentStateIdx == m_AccessedResources[i].steps[j])
stepNode->setForegroundColor(QColor(Qt::red));
resourceNode->addChild(stepNode);
}
}
ui->accessedResources->addTopLevelItem(resourceNode);
}
}
break;
}
case AccessedResourceView::SortByStep:
{
rdcarray<rdcpair<size_t, RDTreeWidgetItem *>> stepNodes;
for(size_t i = 0; i < m_AccessedResources.size(); ++i)
{
// Add a root node for each instruction, and place the resource node as a child
for(size_t j = 0; j < m_AccessedResources[i].steps.size(); ++j)
{
bool accessed = m_AccessedResources[i].steps[j] <= m_CurrentStateIdx;
if(accessed)
{
int32_t nodeIdx = -1;
for(int32_t k = 0; k < stepNodes.count(); ++k)
{
if(stepNodes[k].first == m_AccessedResources[i].steps[j])
{
nodeIdx = k;
break;
}
}
RDTreeWidgetItem *resourceNode =
makeAccessedResourceNode(m_AccessedResources[i].resource);
if(nodeIdx == -1)
{
RDTreeWidgetItem *stepNode = new RDTreeWidgetItem(
{tr("Step %1").arg(m_AccessedResources[i].steps[j]), lit("Access"), lit("")});
stepNode->setTag(QVariant::fromValue(
AccessedResourceTag((uint32_t)m_AccessedResources[i].steps[j])));
if(m_CurrentStateIdx == m_AccessedResources[i].steps[j])
stepNode->setForegroundColor(QColor(Qt::red));
stepNode->addChild(resourceNode);
stepNodes.push_back({m_AccessedResources[i].steps[j], stepNode});
}
else
{
stepNodes[nodeIdx].second->addChild(resourceNode);
}
}
}
}
std::sort(stepNodes.begin(), stepNodes.end(),
[](const rdcpair<size_t, RDTreeWidgetItem *> &a,
const rdcpair<size_t, RDTreeWidgetItem *> &b) { return a.first < b.first; });
for(size_t i = 0; i < stepNodes.size(); ++i)
ui->accessedResources->addTopLevelItem(stepNodes[i].second);
break;
}
}
ui->accessedResources->endUpdate();
ui->accessedResources->applyExpansion(expansion, 0);
}
void ShaderViewer::updateDebugState()
{
if(!m_Trace || m_States.empty())
return;
if(ui->debugToggle->isEnabled())
{
if(isSourceDebugging())
ui->debugToggle->setText(tr("Debug in Assembly"));
else
ui->debugToggle->setText(tr("Debug in Source"));
}
const ShaderDebugState &state = GetCurrentState();
const bool done = IsLastState();
// add current instruction marker
m_DisassemblyView->markerDeleteAll(CURRENT_MARKER);
m_DisassemblyView->markerDeleteAll(CURRENT_MARKER + 1);
m_DisassemblyView->markerDeleteAll(FINISHED_MARKER);
m_DisassemblyView->markerDeleteAll(FINISHED_MARKER + 1);
if(m_CurInstructionScintilla)
{
m_CurInstructionScintilla->markerDeleteAll(CURRENT_MARKER);
m_CurInstructionScintilla->markerDeleteAll(CURRENT_MARKER + 1);
m_CurInstructionScintilla->markerDeleteAll(FINISHED_MARKER);
m_CurInstructionScintilla->markerDeleteAll(FINISHED_MARKER + 1);
m_CurInstructionScintilla->indicatorClearRange(0, m_CurInstructionScintilla->length());
m_CurInstructionScintilla = NULL;
}
ui->callstack->clear();
for(const rdcstr &s : state.callstack)
ui->callstack->insertItem(0, s);
{
LineColumnInfo lineInfo = GetInstInfo(state.nextInstruction).lineInfo;
// highlight the current line
{
m_DisassemblyView->markerAdd(lineInfo.disassemblyLine - 1,
done ? FINISHED_MARKER : CURRENT_MARKER);
m_DisassemblyView->markerAdd(lineInfo.disassemblyLine - 1,
done ? FINISHED_MARKER + 1 : CURRENT_MARKER + 1);
int pos = m_DisassemblyView->positionFromLine(lineInfo.disassemblyLine - 1);
m_DisassemblyView->setSelection(pos, pos);
ensureLineScrolled(m_DisassemblyView, lineInfo.disassemblyLine - 1);
}
if(IsLastState() && (lineInfo.fileIndex < 0 || lineInfo.fileIndex >= m_FileScintillas.count()))
{
// if the last state doesn't have source mapping information, display the line info for the
// last state which did.
for(int stateLookbackIdx = (int)m_CurrentStateIdx; stateLookbackIdx > 0; stateLookbackIdx--)
{
lineInfo = GetInstInfo(m_States[stateLookbackIdx].nextInstruction).lineInfo;
if(lineInfo.fileIndex >= 0 && lineInfo.fileIndex < m_FileScintillas.count())
break;
}
}
if(lineInfo.fileIndex >= 0 && lineInfo.fileIndex < m_FileScintillas.count())
{
m_CurInstructionScintilla = m_FileScintillas[lineInfo.fileIndex];
if(m_CurInstructionScintilla)
{
for(sptr_t line = lineInfo.lineStart; line <= (sptr_t)lineInfo.lineEnd; line++)
{
if(line == (sptr_t)lineInfo.lineEnd)
m_CurInstructionScintilla->markerAdd(line - 1, done ? FINISHED_MARKER : CURRENT_MARKER);
if(lineInfo.colStart == 0)
{
// with no column info, add a marker on the whole line
m_CurInstructionScintilla->markerAdd(line - 1,
done ? FINISHED_MARKER + 1 : CURRENT_MARKER + 1);
}
else
{
// otherwise add an indicator on the column range.
// Start from the full position/length for this line
sptr_t pos = m_CurInstructionScintilla->positionFromLine(line - 1);
sptr_t len = m_CurInstructionScintilla->lineEndPosition(line - 1) - pos;
// if we're on the last line of the range, restrict the length to end on the last column
if(line == (sptr_t)lineInfo.lineEnd && lineInfo.colEnd != 0)
len = lineInfo.colEnd;
// if we're on the start of the range (which may also be the last line above too), shift
// inwards towards the first column
if(line == (sptr_t)lineInfo.lineStart)
{
pos += lineInfo.colStart - 1;
len -= lineInfo.colStart - 1;
}
m_CurInstructionScintilla->setIndicatorCurrent(done ? FINISHED_INDICATOR
: CURRENT_INDICATOR);
m_CurInstructionScintilla->indicatorFillRange(pos, len);
}
}
if(isSourceDebugging() ||
ui->docking->areaOf(m_CurInstructionScintilla) != ui->docking->areaOf(m_DisassemblyFrame))
ToolWindowManager::raiseToolWindow(m_CurInstructionScintilla);
int pos = m_CurInstructionScintilla->positionFromLine(lineInfo.lineStart - 1);
m_CurInstructionScintilla->setSelection(pos, pos);
ensureLineScrolled(m_CurInstructionScintilla, lineInfo.lineStart - 1);
}
}
}
if(ui->constants->topLevelItemCount() == 0)
{
// track all debug variables that have been mapped by source vars
QSet<QString> varsMapped;
RDTreeWidgetItem fakeroot;
for(int globalVarIdx = 0; globalVarIdx < m_Trace->sourceVars.count(); globalVarIdx++)
{
const SourceVariableMapping &sourceVar = m_Trace->sourceVars[globalVarIdx];
if(!sourceVar.variables.empty() && sourceVar.variables[0].type == DebugVariableType::Variable)
continue;
for(const DebugVariableReference &r : sourceVar.variables)
varsMapped.insert(r.name);
if(sourceVar.rows == 0 || sourceVar.columns == 0)
continue;
fakeroot.addChild(makeSourceVariableNode(sourceVar, globalVarIdx, -1));
}
// recursively combine nodes with the same prefix together
combineStructures(&fakeroot);
while(fakeroot.childCount() > 0)
ui->constants->addTopLevelItem(fakeroot.takeChild(0));
// add any raw registers that weren't mapped with something better. We assume for inputs that
// everything has a source mapping, even if it's faked from reflection info, but just to be sure
// we add any remainders here. Constants might be un-touched by reflection info
for(int i = 0; i < m_Trace->constantBlocks.count(); i++)
{
rdcstr name = m_Trace->constantBlocks[i].name;
if(varsMapped.contains(name))
continue;
RDTreeWidgetItem *node = new RDTreeWidgetItem({name, name, lit("Constant"), QString()});
node->setTag(QVariant::fromValue(VariableTag(DebugVariableType::Constant, name)));
for(int j = 0; j < m_Trace->constantBlocks[i].members.count(); j++)
{
if(m_Trace->constantBlocks[i].members[j].rows > 0 ||
m_Trace->constantBlocks[i].members[j].columns > 0)
{
rdcstr childname = name + "." + m_Trace->constantBlocks[i].members[j].name;
if(!varsMapped.contains(name))
{
RDTreeWidgetItem *child = new RDTreeWidgetItem(
{name, name, lit("Constant"), stringRep(m_Trace->constantBlocks[i].members[j])});
child->setTag(QVariant::fromValue(VariableTag(DebugVariableType::Constant, childname)));
node->addChild(child);
}
}
else
{
// Check if this is a constant buffer array
int arrayCount = m_Trace->constantBlocks[i].members[j].members.count();
for(int k = 0; k < arrayCount; k++)
{
if(m_Trace->constantBlocks[i].members[j].members[k].rows > 0 ||
m_Trace->constantBlocks[i].members[j].members[k].columns > 0)
{
rdcstr childname = name + "." + m_Trace->constantBlocks[i].members[j].members[k].name;
RDTreeWidgetItem *child =
new RDTreeWidgetItem({name, name, lit("Constant"),
stringRep(m_Trace->constantBlocks[i].members[j].members[k])});
node->setTag(QVariant::fromValue(VariableTag(DebugVariableType::Constant, childname)));
node->addChild(child);
}
}
}
}
if(node->childCount() == 0)
{
delete node;
continue;
}
ui->constants->addTopLevelItem(node);
}
for(int i = 0; i < m_Trace->inputs.count(); i++)
{
const ShaderVariable &input = m_Trace->inputs[i];
if(varsMapped.contains(input.name))
continue;
if(input.rows > 0 || input.columns > 0)
{
RDTreeWidgetItem *node =
new RDTreeWidgetItem({input.name, input.name, lit("Input"), stringRep(input)});
node->setTag(QVariant::fromValue(VariableTag(DebugVariableType::Input, input.name)));
ui->constants->addTopLevelItem(node);
}
}
rdcarray<BoundResourceArray> &roBinds = m_ReadOnlyResources;
for(int i = 0; i < m_Trace->readOnlyResources.count(); i++)
{
const ShaderVariable &ro = m_Trace->readOnlyResources[i];
if(varsMapped.contains(ro.name))
continue;
int32_t idx = m_Mapping.readOnlyResources.indexOf(Bindpoint(ro.GetBinding()));
if(idx < 0)
continue;
Bindpoint bind = m_Mapping.readOnlyResources[idx];
if(!bind.used)
continue;
int32_t bindIdx = roBinds.indexOf(bind);
if(bindIdx < 0)
continue;
BoundResourceArray &roBind = roBinds[bindIdx];
if(bind.arraySize == 1)
{
if(!roBind.resources.empty())
{
RDTreeWidgetItem *node =
new RDTreeWidgetItem({m_ShaderDetails->readOnlyResources[i].name, ro.name,
lit("Resource"), ToQStr(roBind.resources[0].resourceId)});
node->setTag(QVariant::fromValue(VariableTag(DebugVariableType::ReadOnlyResource, ro.name)));
ui->constants->addTopLevelItem(node);
}
}
else if(bind.arraySize == ~0U)
{
RDTreeWidgetItem *node = new RDTreeWidgetItem(
{m_ShaderDetails->readOnlyResources[i].name, ro.name, lit("[unbounded]"), QString()});
node->setTag(QVariant::fromValue(VariableTag(DebugVariableType::ReadOnlyResource, ro.name)));
ui->constants->addTopLevelItem(node);
}
else
{
RDTreeWidgetItem *node =
new RDTreeWidgetItem({m_ShaderDetails->readOnlyResources[i].name, ro.name,
QFormatStr("[%1]").arg(bind.arraySize), QString()});
node->setTag(QVariant::fromValue(VariableTag(DebugVariableType::ReadOnlyResource, ro.name)));
uint32_t count = qMin(bind.arraySize, (uint32_t)roBind.resources.size());
for(uint32_t a = 0; a < count; a++)
{
QString childName = QFormatStr("%1[%2]").arg(ro.name).arg(a);
RDTreeWidgetItem *child = new RDTreeWidgetItem({
QFormatStr("%1[%2]").arg(m_ShaderDetails->readOnlyResources[i].name).arg(a),
childName, lit("Resource"), ToQStr(roBind.resources[a].resourceId),
});
child->setTag(
QVariant::fromValue(VariableTag(DebugVariableType::ReadOnlyResource, childName)));
node->addChild(child);
}
ui->constants->addTopLevelItem(node);
}
}
rdcarray<BoundResourceArray> &rwBinds = m_ReadWriteResources;
for(int i = 0; i < m_Trace->readWriteResources.count(); i++)
{
const ShaderVariable &rw = m_Trace->readWriteResources[i];
if(varsMapped.contains(rw.name))
continue;
int32_t idx = m_Mapping.readWriteResources.indexOf(Bindpoint(rw.GetBinding()));
if(idx < 0)
continue;
Bindpoint bind = m_Mapping.readWriteResources[idx];
if(!bind.used)
continue;
int32_t bindIdx = rwBinds.indexOf(bind);
if(bindIdx < 0)
continue;
BoundResourceArray &rwBind = rwBinds[bindIdx];
if(bind.arraySize == 1)
{
if(!rwBind.resources.empty())
{
RDTreeWidgetItem *node =
new RDTreeWidgetItem({m_ShaderDetails->readWriteResources[i].name, rw.name,
lit("Resource"), ToQStr(rwBind.resources[0].resourceId)});
node->setTag(
QVariant::fromValue(VariableTag(DebugVariableType::ReadWriteResource, rw.name)));
ui->constants->addTopLevelItem(node);
}
}
else if(bind.arraySize == ~0U)
{
RDTreeWidgetItem *node = new RDTreeWidgetItem(
{m_ShaderDetails->readWriteResources[i].name, rw.name, lit("[unbounded]"), QString()});
node->setTag(QVariant::fromValue(VariableTag(DebugVariableType::ReadWriteResource, rw.name)));
ui->constants->addTopLevelItem(node);
}
else
{
RDTreeWidgetItem *node =
new RDTreeWidgetItem({m_ShaderDetails->readWriteResources[i].name, rw.name,
QFormatStr("[%1]").arg(bind.arraySize), QString()});
node->setTag(QVariant::fromValue(VariableTag(DebugVariableType::ReadWriteResource, rw.name)));
uint32_t count = qMin(bind.arraySize, (uint32_t)rwBind.resources.size());
for(uint32_t a = 0; a < count; a++)
{
QString childName = QFormatStr("%1[%2]").arg(rw.name).arg(a);
RDTreeWidgetItem *child = new RDTreeWidgetItem({
QFormatStr("%1[%2]").arg(m_ShaderDetails->readWriteResources[i].name).arg(a),
childName, lit("RW Resource"), ToQStr(rwBind.resources[a].resourceId),
});
child->setTag(
QVariant::fromValue(VariableTag(DebugVariableType::ReadWriteResource, childName)));
node->addChild(child);
}
ui->constants->addTopLevelItem(node);
}
}
rdcarray<BoundResourceArray> samplers = m_Ctx.CurPipelineState().GetSamplers(m_Stage);
for(int i = 0; i < m_Trace->samplers.count(); i++)
{
const ShaderVariable &s = m_Trace->samplers[i];
if(varsMapped.contains(s.name))
continue;
int32_t idx = m_Mapping.samplers.indexOf(Bindpoint(s.GetBinding()));
if(idx < 0)
continue;
Bindpoint bind = m_Mapping.samplers[idx];
if(!bind.used)
continue;
int32_t bindIdx = samplers.indexOf(bind);
if(bindIdx < 0)
continue;
BoundResourceArray sampBind = samplers[bindIdx];
if(bind.arraySize == 1)
{
if(!sampBind.resources.empty())
{
RDTreeWidgetItem *node =
new RDTreeWidgetItem({m_ShaderDetails->samplers[i].name, s.name, lit("Sampler"),
samplerRep(bind, ~0U, sampBind.resources[0].resourceId)});
node->setTag(QVariant::fromValue(VariableTag(DebugVariableType::Sampler, s.name)));
ui->constants->addTopLevelItem(node);
}
}
else if(bind.arraySize == ~0U)
{
RDTreeWidgetItem *node = new RDTreeWidgetItem(
{m_ShaderDetails->samplers[i].name, s.name, lit("[unbounded]"), QString()});
node->setTag(QVariant::fromValue(VariableTag(DebugVariableType::Sampler, s.name)));
ui->constants->addTopLevelItem(node);
}
else
{
RDTreeWidgetItem *node =
new RDTreeWidgetItem({m_ShaderDetails->samplers[i].name, s.name,
QFormatStr("[%1]").arg(bind.arraySize), QString()});
node->setTag(QVariant::fromValue(VariableTag(DebugVariableType::Sampler, s.name)));
for(uint32_t a = 0; a < bind.arraySize; a++)
{
QString childName = QFormatStr("%1[%2]").arg(s.name).arg(a);
RDTreeWidgetItem *child = new RDTreeWidgetItem({
QFormatStr("%1[%2]").arg(m_ShaderDetails->samplers[i].name).arg(a), childName,
lit("Sampler"), samplerRep(bind, a, sampBind.resources[a].resourceId),
});
child->setTag(QVariant::fromValue(VariableTag(DebugVariableType::Sampler, childName)));
node->addChild(child);
}
ui->constants->addTopLevelItem(node);
}
}
}
{
RDTreeViewExpansionState expansion;
ui->sourceVars->saveExpansion(expansion, 0);
ui->sourceVars->beginUpdate();
ui->sourceVars->clear();
RDTreeWidgetItem fakeroot;
for(int globalVarIdx = 0; globalVarIdx < m_Trace->sourceVars.count(); globalVarIdx++)
{
const SourceVariableMapping &sourceVar = m_Trace->sourceVars[globalVarIdx];
if(!sourceVar.variables.empty() && sourceVar.variables[0].type != DebugVariableType::Variable)
continue;
if(sourceVar.rows == 0 || sourceVar.columns == 0)
continue;
fakeroot.addChild(makeSourceVariableNode(sourceVar, globalVarIdx, -1));
}
const rdcarray<SourceVariableMapping> &sourceVars = GetCurrentInstInfo().sourceVars;
for(size_t lidx = 0; lidx < sourceVars.size(); lidx++)
{
int32_t localVarIdx = int32_t(sourceVars.size() - 1 - lidx);
// iterate in reverse order, so newest locals tend to end up on top
const SourceVariableMapping &l = sourceVars[localVarIdx];
bool hasNonError = false;
for(const DebugVariableReference &v : l.variables)
hasNonError |= (GetDebugVariable(v) != NULL);
// don't display source variables that map to non-existant debug variables. This can happen
// when flow control means those debug variables were never created, but they would be mapped
// at this point.
if(!hasNonError)
continue;
RDTreeWidgetItem *node = makeSourceVariableNode(l, -1, localVarIdx);
fakeroot.addChild(node);
}
// recursively combine nodes with the same prefix together
combineStructures(&fakeroot);
QList<RDTreeWidgetItem *> nodes;
while(fakeroot.childCount() > 0)
nodes.push_back(fakeroot.takeChild(0));
// sort more recently updated variables to the top
std::sort(nodes.begin(), nodes.end(), [](const RDTreeWidgetItem *a, const RDTreeWidgetItem *b) {
VariableTag at = a->tag().value<VariableTag>();
VariableTag bt = b->tag().value<VariableTag>();
return at.updateID > bt.updateID;
});
for(RDTreeWidgetItem *n : nodes)
ui->sourceVars->addTopLevelItem(n);
ui->sourceVars->endUpdate();
ui->sourceVars->applyExpansion(expansion, 0);
}
{
RDTreeViewExpansionState expansion;
ui->debugVars->saveExpansion(expansion, 0);
ui->debugVars->beginUpdate();
ui->debugVars->clear();
for(int i = 0; i < m_Variables.count(); i++)
{
ui->debugVars->addTopLevelItem(makeDebugVariableNode(m_Variables[i], ""));
}
ui->debugVars->endUpdate();
ui->debugVars->applyExpansion(expansion, 0);
}
updateAccessedResources();
updateWatchVariables();
ui->debugVars->resizeColumnToContents(0);
ui->debugVars->resizeColumnToContents(1);
updateVariableTooltip();
}
void ShaderViewer::markWatchStale(RDTreeWidgetItem *item)
{
VariableTag tag = item->tag().value<VariableTag>();
if(tag.state != WatchVarState::Invalid)
{
tag.state = WatchVarState::Stale;
item->setItalic(true);
item->setText(1, tr("Unavailable"));
item->setTag(QVariant::fromValue(tag));
}
for(int i = 0; i < item->childCount(); i++)
markWatchStale(item->child(i));
}
bool ShaderViewer::updateWatchVariable(RDTreeWidgetItem *watchItem, const RDTreeWidgetItem *varItem,
const rdcstr &path, uint32_t swizzle,
const ShaderVariable &var, QChar regcast)
{
if(!var.members.empty())
{
QSet<QString> existing, current;
// see which members we have already
for(int i = 0; i < watchItem->childCount(); i++)
existing.insert(watchItem->child(i)->text(0));
// see which members are in the variable
for(int i = 0; i < var.members.count(); i++)
current.insert(var.members[i].name);
// if there are no new members in the variable, the existing set will contain the current set
if(!existing.contains(current))
{
// the current variable has some new members in its set - this may be a different structure.
// Clear the existing watch before updating
watchItem->clear();
}
// iterate over every sub-variable we know about
QVector<bool> valid;
valid.resize(watchItem->childCount());
for(int i = 0; i < var.members.count(); i++)
{
int idx = -1;
QString name = var.members[i].name;
for(int j = 0; j < watchItem->childCount(); j++)
{
if(name == watchItem->child(j)->text(0))
{
idx = j;
break;
}
}
if(idx == -1)
{
idx = watchItem->childCount();
RDTreeWidgetItem *item = new RDTreeWidgetItem({
name, QVariant(), QVariant(), QVariant(),
});
VariableTag tag = VariableTag(DebugVariableType::Variable, path);
tag.state = WatchVarState::Valid;
item->setTag(QVariant::fromValue(tag));
watchItem->addChild(item);
valid.push_back(false);
}
valid[idx] = true;
rdcstr sep = var.members[i].name[0] == '[' ? "" : ".";
updateWatchVariable(watchItem->child(idx), varItem->child(i),
path + sep + var.members[i].name, ~0U, var.members[i], regcast);
}
// any children that weren't marked as valid are now stale
for(int i = 0; i < watchItem->childCount(); i++)
{
if(valid[i])
continue;
markWatchStale(watchItem->child(i));
}
// resort the watch item members
QVector<RDTreeWidgetItem *> members;
while(watchItem->childCount())
members.push_back(watchItem->takeChild(0));
std::sort(members.begin(), members.end(),
[](const RDTreeWidgetItem *a, const RDTreeWidgetItem *b) {
VariableTag at = a->tag().value<VariableTag>();
VariableTag bt = b->tag().value<VariableTag>();
if(at.offset != bt.offset)
return at.offset < bt.offset;
return a->text(0) < b->text(0);
});
for(int i = 0; i < members.count(); i++)
watchItem->addChild(members[i]);
watchItem->setText(1, QString());
watchItem->setText(2, QString());
watchItem->setText(3, QString());
VariableTag tag = VariableTag(DebugVariableType::Variable, path);
tag.state = WatchVarState::Valid;
watchItem->setTag(QVariant::fromValue(tag));
return true;
}
else
{
// if the node has no children, clear any stale children we might have had from a previous node
// (note if a struct disappears entirely, we won't have a varNode here so the node will just be
// marked stale. We get here if we have a non-struct)
watchItem->clear();
}
size_t dataSize = VarTypeByteSize(var.type);
if(var.rows > 1 && !var.members.empty())
{
watchItem->clear();
watchItem->setText(1, QString());
watchItem->setText(2, QString());
watchItem->setText(3, QString());
for(uint32_t r = 0; r < var.rows; r++)
{
ShaderVariable rowVar = var;
rowVar.name += ".row" + ToStr(r);
rowVar.rows = 1;
if(r > 0)
memcpy(rowVar.value.u8v.data(), rowVar.value.u8v.data() + dataSize * var.columns * r,
dataSize * var.columns);
RDTreeWidgetItem *item = new RDTreeWidgetItem({
rowVar.name, QVariant(), QVariant(), QVariant(),
});
updateWatchVariable(item, varItem->child(r), path + ".row" + ToStr(r), ~0U, rowVar, regcast);
item->setText(1, getRegNames(varItem, ~0U, r));
item->setTag(QVariant());
watchItem->addChild(item);
}
VariableTag tag = VariableTag(DebugVariableType::Variable, path);
tag.state = WatchVarState::Valid;
watchItem->setTag(QVariant::fromValue(tag));
return true;
}
if(var.type == VarType::Unknown || dataSize == 0)
dataSize = 4;
if(regcast == QLatin1Char(' '))
{
switch(var.type)
{
case VarType::Float:
case VarType::Double:
case VarType::Half: regcast = QLatin1Char('f'); break;
case VarType::Bool:
case VarType::ULong:
case VarType::UInt:
case VarType::UShort:
case VarType::UByte: regcast = QLatin1Char('u'); break;
case VarType::SLong:
case VarType::SInt:
case VarType::SShort:
case VarType::SByte: regcast = QLatin1Char('i'); break;
case VarType::Struct:
case VarType::Enum:
case VarType::GPUPointer:
regcast = QLatin1Char('#');
dataSize = 8;
break;
case VarType::ConstantBlock:
case VarType::ReadOnlyResource:
case VarType::ReadWriteResource:
case VarType::Sampler:
regcast = QLatin1Char('#');
dataSize = 4;
break;
case VarType::Unknown:
regcast = ui->intView->isChecked() ? QLatin1Char('i') : QLatin1Char('f');
dataSize = 4;
break;
}
}
QString val;
QColor swatchColor;
for(uint8_t i = 0; i < var.columns; i++)
{
ShaderValue value = {};
memcpy(&value, var.value.u8v.data() + i * dataSize, dataSize);
if(regcast == QLatin1Char('#'))
{
if(var.type == VarType::GPUPointer)
val += ToQStr(var.GetPointer());
else
val += stringRep(var, 0);
}
else if(regcast == QLatin1Char('i') || regcast == QLatin1Char('d'))
{
if(dataSize == 8)
val += Formatter::Format(value.s64v[0]);
else if(dataSize == 4)
val += Formatter::Format(value.s32v[0]);
else if(dataSize == 2)
val += Formatter::Format(value.s16v[0]);
else
val += Formatter::Format(value.s8v[0]);
}
else if(regcast == QLatin1Char('f') || regcast == QLatin1Char('c'))
{
float f;
if(dataSize == 8)
{
val += Formatter::Format(value.f64v[0]);
f = (float)value.f64v[0];
}
else if(dataSize == 4)
{
val += Formatter::Format(value.f32v[0]);
f = (float)value.f32v[0];
}
else
{
val += Formatter::Format(value.f16v[0]);
f = (float)value.f16v[0];
}
if(regcast == QLatin1Char('c') && i < 3)
{
if(i == 0)
{
swatchColor = QColor(0, 0, 0, 255);
swatchColor.setRedF(f);
}
else if(i == 1)
{
swatchColor.setGreenF(f);
}
else
{
swatchColor.setBlueF(f);
}
}
}
else if(regcast == QLatin1Char('u'))
{
val += Formatter::Format(value.u64v[0]);
}
else if(regcast == QLatin1Char('x'))
{
if(dataSize == 8)
val += Formatter::Format(value.u64v[0], true);
else if(dataSize == 4)
val += Formatter::Format(value.u32v[0], true);
else if(dataSize == 2)
val += Formatter::Format(value.u16v[0], true);
else
val += Formatter::Format(value.u8v[0], true);
}
else if(regcast == QLatin1Char('b'))
{
val += QFormatStr("%1").arg(value.u64v[0], (int)dataSize * 8, 2, QLatin1Char('0'));
}
else if(regcast == QLatin1Char('o'))
{
val += QFormatStr("0%1").arg(value.u64v[0], 0, 8, QLatin1Char('0'));
}
if(i < var.columns - 1)
val += lit(", ");
}
watchItem->setText(1, getRegNames(varItem, swizzle));
watchItem->setText(2, TypeString(var));
if(!swatchColor.isValid())
{
watchItem->setIcon(3, QIcon());
}
else
{
int h = ui->watch->fontMetrics().height();
QPixmap pm(1, 1);
pm.fill(swatchColor);
pm = pm.scaled(QSize(h, h));
{
QPainter painter(&pm);
QPen pen(ui->watch->palette().foreground(), 1.0);
painter.setPen(pen);
painter.drawLine(QPoint(0, 0), QPoint(h - 1, 0));
painter.drawLine(QPoint(h - 1, 0), QPoint(h - 1, h - 1));
painter.drawLine(QPoint(h - 1, h - 1), QPoint(0, h - 1));
painter.drawLine(QPoint(0, h - 1), QPoint(0, 0));
}
watchItem->setIcon(3, QIcon(pm));
}
watchItem->setText(3, val);
watchItem->setItalic(false);
VariableTag tag = VariableTag(DebugVariableType::Variable, path);
tag.state = WatchVarState::Valid;
watchItem->setTag(QVariant::fromValue(tag));
return true;
}
void ShaderViewer::updateWatchVariables()
{
QSignalBlocker block(ui->watch);
RDTreeViewExpansionState expansion;
ui->watch->saveExpansion(expansion, 0);
ui->watch->beginUpdate();
for(int i = 0; i < ui->watch->topLevelItemCount() - 1; i++)
{
RDTreeWidgetItem *item = ui->watch->topLevelItem(i);
QString expr = item->text(0).trimmed();
QRegularExpression exprRE(
lit("^" // beginning of the line
"([^,]+)" // variable path
"(,[iduxbocf])?" // optional typecast
"$")); // end of the line
QRegularExpressionMatch match = exprRE.match(expr);
QString error = tr("Error evaluating expression");
if(match.hasMatch())
{
QString path = match.captured(1);
QChar regcast = QLatin1Char(' ');
if(!match.captured(2).isEmpty())
regcast = match.captured(2)[1];
ShaderVariable var;
uint32_t swizzle = ~0U;
const RDTreeWidgetItem *varItem = getVarFromPath(path, &var, &swizzle);
if(varItem)
{
if(updateWatchVariable(item, varItem, path, swizzle, var, regcast))
continue;
error = tr("Couldn't evaluate watch for '%1'").arg(expr);
}
else if(item->childCount())
{
markWatchStale(item);
continue;
}
else
{
error = tr("Couldn't find variable for '%1'").arg(path);
}
}
// if we got here, something went wrong.
VariableTag tag;
item->setItalic(false);
item->setText(1, QString());
item->setText(2, QString());
item->setText(3, error);
item->setTag(QVariant::fromValue(tag));
}
ui->watch->endUpdate();
ui->watch->applyExpansion(expansion, 0);
}
RDTreeWidgetItem *ShaderViewer::makeSourceVariableNode(const ShaderVariable &var,
const rdcstr &debugVarPath,
VariableTag baseTag)
{
QString typeName;
typeName = ToQStr(var.type);
QString rowTypeName = typeName;
if(var.rows > 1)
{
typeName += QFormatStr("%1x%2").arg(var.rows).arg(var.columns);
if(var.columns > 1)
rowTypeName += QString::number(var.columns);
}
else if(var.columns > 1)
{
typeName += QString::number(var.columns);
}
QString value = var.rows == 1 && var.members.empty() ? stringRep(var) : QString();
rdcstr sep = var.name[0] == '[' ? "" : ".";
rdcstr debugName = debugVarPath + sep + var.name;
if(!var.members.empty())
typeName = QString();
RDTreeWidgetItem *node = new RDTreeWidgetItem({var.name, debugName, typeName, value});
VariableTag tag;
tag.absoluteRefPath = baseTag.absoluteRefPath + sep + var.name;
tag.expanded = true;
tag.modified = HasChanged(baseTag.absoluteRefPath + sep + var.name);
tag.updateID = CalcUpdateID(tag.updateID, baseTag.absoluteRefPath + sep + var.name);
for(const ShaderVariable &child : var.members)
{
RDTreeWidgetItem *item = makeSourceVariableNode(child, debugName, tag);
tag.modified |= item->tag().value<VariableTag>().modified;
node->addChild(item);
}
// if this is a matrix, even if it has no explicit row members add the rows as children
if(var.members.empty() && var.rows > 1)
{
for(uint32_t row = 0; row < var.rows; row++)
{
rdcstr rowsuffix = ".row" + ToStr(row);
node->addChild(new RDTreeWidgetItem(
{var.name + rowsuffix, debugName + rowsuffix, rowTypeName, stringRep(var, row)}));
}
}
node->setTag(QVariant::fromValue(tag));
if(tag.modified)
node->setForegroundColor(QColor(Qt::red));
return node;
}
RDTreeWidgetItem *ShaderViewer::makeSourceVariableNode(const SourceVariableMapping &l,
int globalVarIdx, int localVarIdx)
{
QString localName = l.name;
QString typeName;
QString value;
typeName = ToQStr(l.type);
VariableTag baseTag;
baseTag.absoluteRefPath = localName;
baseTag.offset = l.offset;
if(globalVarIdx >= 0)
{
baseTag.globalSourceVar = true;
baseTag.sourceVarIdx = globalVarIdx;
}
else
{
baseTag.sourceVarIdx = localVarIdx;
}
QList<RDTreeWidgetItem *> children;
uint32_t childCount = 0;
{
if(l.rows > 1 && l.variables.size() > l.columns)
typeName += QFormatStr("%1x%2").arg(l.rows).arg(l.columns);
else if(l.columns > 1)
typeName += QString::number(l.columns);
if(l.rows > 1 && l.variables.size() > l.columns)
childCount = l.rows;
for(size_t i = 0; i < l.variables.size(); i++)
{
const DebugVariableReference &r = l.variables[i];
baseTag.modified |= HasChanged(r.name);
baseTag.updateID = CalcUpdateID(baseTag.updateID, r.name);
if(!value.isEmpty())
value += lit(", ");
if(r.name.empty())
{
value += lit("?");
}
else if(r.type == DebugVariableType::Sampler)
{
const ShaderVariable *reg = GetDebugVariable(r);
if(reg == NULL)
continue;
typeName = lit("Sampler");
rdcarray<BoundResourceArray> samplers = m_Ctx.CurPipelineState().GetSamplers(m_Stage);
int32_t idx = m_Mapping.samplers.indexOf(Bindpoint(reg->GetBinding()));
if(idx < 0)
continue;
Bindpoint bind = m_Mapping.samplers[idx];
int32_t bindIdx = samplers.indexOf(bind);
if(bindIdx < 0)
continue;
BoundResourceArray &res = samplers[bindIdx];
if(bind.arraySize == 1)
{
if(!res.resources.empty())
value = samplerRep(bind, ~0U, res.resources[0].resourceId);
}
else if(bind.arraySize == ~0U)
{
typeName = lit("[unbounded]");
value = QString();
}
else
{
for(uint32_t a = 0; a < bind.arraySize; a++)
children.push_back(new RDTreeWidgetItem({
QFormatStr("%1[%2]").arg(localName).arg(a), QString(), typeName,
samplerRep(bind, a, res.resources[a].resourceId),
}));
childCount += bind.arraySize;
typeName = QFormatStr("[%1]").arg(bind.arraySize);
value = QString();
}
}
else if(r.type == DebugVariableType::ReadOnlyResource ||
r.type == DebugVariableType::ReadWriteResource)
{
const bool isReadOnlyResource = r.type == DebugVariableType::ReadOnlyResource;
const ShaderVariable *reg = GetDebugVariable(r);
if(reg == NULL)
continue;
typeName = isReadOnlyResource ? lit("Resource") : lit("RW Resource");
rdcarray<BoundResourceArray> &resList =
isReadOnlyResource ? m_ReadOnlyResources : m_ReadWriteResources;
int32_t idx =
(isReadOnlyResource ? m_Mapping.readOnlyResources : m_Mapping.readWriteResources)
.indexOf(Bindpoint(reg->GetBinding()));
if(idx < 0)
continue;
Bindpoint bind = isReadOnlyResource ? m_Mapping.readOnlyResources[idx]
: m_Mapping.readWriteResources[idx];
int32_t bindIdx = resList.indexOf(bind);
if(bindIdx < 0)
continue;
BoundResourceArray &res = resList[bindIdx];
if(bind.arraySize == 1)
{
if(!res.resources.empty())
value = ToQStr(res.resources[0].resourceId);
}
else if(bind.arraySize == ~0U)
{
typeName = lit("[unbounded]");
value = QString();
}
else
{
uint32_t count = qMin(bind.arraySize, (uint32_t)res.resources.size());
for(uint32_t a = 0; a < count; a++)
children.push_back(new RDTreeWidgetItem({
QFormatStr("%1[%2]").arg(localName).arg(a), QString(), typeName,
ToQStr(res.resources[a].resourceId),
}));
childCount += bind.arraySize;
typeName = QFormatStr("[%1]").arg(bind.arraySize);
value = QString();
}
}
else
{
const ShaderVariable *reg = GetDebugVariable(r);
if(reg)
{
if(!reg->members.empty())
{
// if the register we were pointed at is a complex type (struct/array/etc), embed it as
// a child
typeName = QString();
value = QString();
for(const ShaderVariable &child : reg->members)
children.push_back(makeSourceVariableNode(child, reg->name, baseTag));
break;
}
switch(l.type)
{
case VarType::Float: value += Formatter::Format(reg->value.f32v[r.component]); break;
case VarType::Double: value += Formatter::Format(reg->value.f64v[r.component]); break;
case VarType::Half: value += Formatter::Format(reg->value.f16v[r.component]); break;
case VarType::Bool:
value += Formatter::Format(reg->value.u32v[r.component] ? true : false);
break;
case VarType::ULong: value += Formatter::Format(reg->value.u64v[r.component]); break;
case VarType::UInt: value += Formatter::Format(reg->value.u32v[r.component]); break;
case VarType::UShort: value += Formatter::Format(reg->value.u16v[r.component]); break;
case VarType::UByte: value += Formatter::Format(reg->value.u8v[r.component]); break;
case VarType::SLong: value += Formatter::Format(reg->value.s64v[r.component]); break;
case VarType::SInt: value += Formatter::Format(reg->value.s32v[r.component]); break;
case VarType::SShort: value += Formatter::Format(reg->value.s16v[r.component]); break;
case VarType::SByte: value += Formatter::Format(reg->value.s8v[r.component]); break;
case VarType::GPUPointer: value += ToQStr(reg->GetPointer()); break;
case VarType::ConstantBlock:
case VarType::ReadOnlyResource:
case VarType::ReadWriteResource:
case VarType::Sampler:
case VarType::Enum:
case VarType::Struct: value += stringRep(*reg, 0); break;
case VarType::Unknown:
qCritical() << "Unexpected unknown variable" << (QString)l.name;
break;
}
}
else
{
value += lit("<error>");
}
}
if(l.rows > 1 && l.variables.size() > l.columns)
{
if(((i + 1) % l.columns) == 0)
{
QString localBaseName = localName;
int dot = localBaseName.lastIndexOf(QLatin1Char('.'));
if(dot >= 0)
localBaseName = localBaseName.mid(dot + 1);
uint32_t row = (uint32_t)i / l.columns;
children.push_back(new RDTreeWidgetItem(
{QFormatStr("%1.row%2").arg(localBaseName).arg(row), QString(), typeName, value}));
value = QString();
}
}
}
}
RDTreeWidgetItem *node = new RDTreeWidgetItem({localName, QString(), typeName, value});
for(RDTreeWidgetItem *c : children)
{
baseTag.modified |= c->tag().value<VariableTag>().modified;
node->addChild(c);
}
if(baseTag.modified)
node->setForegroundColor(QColor(Qt::red));
node->setTag(QVariant::fromValue(baseTag));
if(childCount > 0)
{
for(uint32_t i = 0; i < childCount && i < (uint32_t)node->childCount(); i++)
node->child(i)->setText(1, getRegNames(node, ~0U, i));
}
else
{
node->setText(1, getRegNames(node, ~0U));
}
return node;
}
RDTreeWidgetItem *ShaderViewer::makeDebugVariableNode(const ShaderVariable &v, rdcstr prefix)
{
rdcstr basename = prefix + v.name;
RDTreeWidgetItem *node =
new RDTreeWidgetItem({v.name, v.rows == 1 && v.members.empty() ? stringRep(v) : QString()});
VariableTag tag(DebugVariableType::Variable, basename);
tag.modified = HasChanged(basename);
tag.updateID = CalcUpdateID(tag.updateID, basename);
for(const ShaderVariable &m : v.members)
{
rdcstr childprefix = basename + ".";
if(m.name.beginsWith(basename + "["))
childprefix = basename;
RDTreeWidgetItem *child = makeDebugVariableNode(m, childprefix);
tag.modified |= child->tag().value<VariableTag>().modified;
node->addChild(child);
}
// if this is a matrix, even if it has no explicit row members add the rows as children
if(v.members.empty() && v.rows > 1)
{
for(uint32_t row = 0; row < v.rows; row++)
{
rdcstr rowsuffix = ".row" + ToStr(row);
RDTreeWidgetItem *child = new RDTreeWidgetItem({v.name + rowsuffix, stringRep(v, row)});
child->setTag(
QVariant::fromValue(VariableTag(DebugVariableType::Variable, basename + rowsuffix)));
node->addChild(child);
}
}
node->setTag(QVariant::fromValue(tag));
if(tag.modified)
node->setForegroundColor(QColor(Qt::red));
return node;
}
RDTreeWidgetItem *ShaderViewer::makeAccessedResourceNode(const ShaderVariable &v)
{
BindpointIndex bp = v.GetBinding();
ResourceId resId;
QString typeName;
if(v.type == VarType::ReadOnlyResource)
{
typeName = lit("Resource");
int32_t idx = m_Mapping.readOnlyResources.indexOf(Bindpoint(bp));
if(idx >= 0)
{
Bindpoint bind = m_Mapping.readOnlyResources[idx];
if(bind.used)
{
int32_t bindIdx = m_ReadOnlyResources.indexOf(bind);
if(bindIdx >= 0)
{
BoundResourceArray &roBind = m_ReadOnlyResources[bindIdx];
if(bp.arrayIndex < roBind.resources.size())
resId = roBind.resources[bp.arrayIndex].resourceId;
}
}
}
}
else if(v.type == VarType::ReadWriteResource)
{
typeName = lit("RW Resource");
int32_t idx = m_Mapping.readWriteResources.indexOf(Bindpoint(bp));
if(idx >= 0)
{
Bindpoint bind = m_Mapping.readWriteResources[idx];
if(bind.used)
{
int32_t bindIdx = m_ReadWriteResources.indexOf(bind);
if(bindIdx >= 0)
{
BoundResourceArray &rwBind = m_ReadWriteResources[bindIdx];
if(bp.arrayIndex < rwBind.resources.size())
resId = rwBind.resources[bp.arrayIndex].resourceId;
}
}
}
}
RDTreeWidgetItem *node = new RDTreeWidgetItem({v.name, typeName, ToQStr(resId)});
if(resId != ResourceId())
node->setTag(QVariant::fromValue(AccessedResourceTag(bp, v.type)));
if(HasChanged(v.name))
node->setForegroundColor(QColor(Qt::red));
return node;
}
bool ShaderViewer::HasChanged(rdcstr debugVarName) const
{
return m_VariablesChanged.contains(debugVarName);
}
uint32_t ShaderViewer::CalcUpdateID(uint32_t prevID, rdcstr debugVarName) const
{
return qMax(prevID, m_VariableLastUpdate[debugVarName]);
}
// this function is a bit messy, we want a base recursion container of either QList or rdcarray
// but further recursion is always rdcarray because of ShaderVariable::members
template <typename Container>
const ShaderVariable *GetShaderDebugVariable(rdcstr path, const Container &vars)
{
rdcstr elem;
// pick out the next element in the path
// if this is an array index, grab that
if(path[0] == '[')
{
int idx = path.indexOf(']');
if(idx < 0)
return NULL;
elem = path.substr(0, idx + 1);
// skip past any .s
if(path[idx + 1] == '.')
idx++;
path = path.substr(idx + 1);
}
else
{
// otherwise look for the next identifier
int idx = path.find_first_of("[.");
if(idx < 0)
{
// no results means that all that's left of the path is an identifier
elem.swap(path);
}
else
{
elem = path.substr(0, idx);
// skip past any .s
if(path[idx] == '.')
idx++;
path = path.substr(idx);
}
}
// look in our current set of vars for a matching variable
for(int i = 0; i < vars.count(); i++)
{
if(vars[i].name == elem)
{
// If there's no more path, we've found the exact match, otherwise continue
if(path.empty())
return &vars[i];
// otherwise recurse
return GetShaderDebugVariable(path, vars[i].members);
}
}
return NULL;
}
const ShaderVariable *ShaderViewer::GetDebugVariable(const DebugVariableReference &r)
{
if(r.type == DebugVariableType::ReadOnlyResource)
{
for(int i = 0; i < m_Trace->readOnlyResources.count(); i++)
if(m_Trace->readOnlyResources[i].name == r.name)
return &m_Trace->readOnlyResources[i];
return NULL;
}
else if(r.type == DebugVariableType::ReadWriteResource)
{
for(int i = 0; i < m_Trace->readWriteResources.count(); i++)
if(m_Trace->readWriteResources[i].name == r.name)
return &m_Trace->readWriteResources[i];
return NULL;
}
else if(r.type == DebugVariableType::Sampler)
{
for(int i = 0; i < m_Trace->samplers.count(); i++)
if(m_Trace->samplers[i].name == r.name)
return &m_Trace->samplers[i];
return NULL;
}
else if(r.type == DebugVariableType::Input)
{
return GetShaderDebugVariable(r.name, m_Trace->inputs);
}
else if(r.type == DebugVariableType::Constant)
{
return GetShaderDebugVariable(r.name, m_Trace->constantBlocks);
}
else if(r.type == DebugVariableType::Variable)
{
return GetShaderDebugVariable(r.name, m_Variables);
}
return NULL;
}
void ShaderViewer::ensureLineScrolled(ScintillaEdit *s, int line)
{
int firstLine = s->firstVisibleLine();
int linesVisible = s->linesOnScreen();
if(s->isVisible() && (line < firstLine || line > (firstLine + linesVisible - 1)))
s->setFirstVisibleLine(qMax(0, line - linesVisible / 2));
}
uint32_t ShaderViewer::CurrentStep()
{
return (uint32_t)m_CurrentStateIdx;
}
void ShaderViewer::SetCurrentStep(uint32_t step)
{
if(!m_Trace || m_States.empty())
return;
m_VariablesChanged.clear();
while(GetCurrentState().stepIndex != step)
{
if(GetCurrentState().stepIndex < step)
{
// move forward if possible
if(!IsLastState())
applyForwardsChange();
else
break;
}
else
{
// move backward if possible
if(!IsFirstState())
applyBackwardsChange();
else
break;
}
}
updateDebugState();
}
void ShaderViewer::ToggleBreakpointOnInstruction(int32_t instruction)
{
if(m_DeferredInit)
{
m_DeferredCommands.push_back(
[instruction](ShaderViewer *v) { v->ToggleBreakpointOnInstruction(instruction); });
return;
}
if(!m_Trace || m_States.empty())
return;
QPair<int, uint32_t> sourceBreakpoint = {-1, 0};
QList<QPair<int, uint32_t>> disasmBreakpoints;
if(instruction >= 0)
{
const LineColumnInfo &instLine = GetInstInfo(instruction).lineInfo;
sourceBreakpoint = {instLine.fileIndex, instLine.lineStart};
disasmBreakpoints.push_back({-1, instLine.disassemblyLine});
}
else
{
ScintillaEdit *cur = currentScintilla();
// search forward for an instruction
if(cur != m_DisassemblyView)
{
int scintillaIndex = m_FileScintillas.indexOf(cur);
if(scintillaIndex < 0)
return;
// add one to go from scintilla line numbers (0-based) to ours (1-based)
sptr_t i = cur->lineFromPosition(cur->currentPos()) + 1;
LineColumnInfo sourceLine;
sourceLine.fileIndex = scintillaIndex;
sourceLine.lineStart = sourceLine.lineEnd = i;
auto it = m_Location2Inst.lowerBound(sourceLine);
// find the next source location that has an instruction mapped. If there was an exact match
// this won't loop, if the lower bound was earlier we'll step at most once to get to the next
// line past it.
if(it != m_Location2Inst.end() && (sptr_t)it.key().lineEnd < i)
it++;
// set a breakpoint on all instructions that match this line
if(it != m_Location2Inst.end())
{
sourceBreakpoint = {scintillaIndex, (uint32_t)i};
for(uint32_t inst : it.value())
disasmBreakpoints.push_back({-1, GetInstInfo(inst).lineInfo.disassemblyLine});
}
else
{
return;
}
}
else
{
int32_t disassemblyLine = m_DisassemblyView->lineFromPosition(m_DisassemblyView->currentPos());
for(; disassemblyLine < m_DisassemblyView->lineCount(); disassemblyLine++)
{
if(instructionForDisassemblyLine(disassemblyLine) >= 0)
break;
}
if(disassemblyLine < m_DisassemblyView->lineCount())
disasmBreakpoints.push_back({-1, (uint32_t)disassemblyLine + 1});
}
}
// if we have a source breakpoint, treat that as 'canonical' whether or not the corresponding
// disasm ones are set
if(sourceBreakpoint.first >= 0)
{
if(m_TempBreakpoint)
{
m_Breakpoints.insert(sourceBreakpoint);
for(QPair<int, uint32_t> &d : disasmBreakpoints)
m_Breakpoints.insert(d);
}
else if(m_Breakpoints.contains(sourceBreakpoint))
{
m_Breakpoints.remove(sourceBreakpoint);
m_FileScintillas[sourceBreakpoint.first]->markerDelete(sourceBreakpoint.second - 1,
BREAKPOINT_MARKER);
m_FileScintillas[sourceBreakpoint.first]->markerDelete(sourceBreakpoint.second - 1,
BREAKPOINT_MARKER + 1);
for(QPair<int, uint32_t> &d : disasmBreakpoints)
{
m_Breakpoints.remove(d);
m_DisassemblyView->markerDelete(d.second - 1, BREAKPOINT_MARKER);
m_DisassemblyView->markerDelete(d.second - 1, BREAKPOINT_MARKER + 1);
}
}
else
{
m_Breakpoints.insert(sourceBreakpoint);
m_FileScintillas[sourceBreakpoint.first]->markerAdd(sourceBreakpoint.second - 1,
BREAKPOINT_MARKER);
m_FileScintillas[sourceBreakpoint.first]->markerAdd(sourceBreakpoint.second - 1,
BREAKPOINT_MARKER + 1);
for(QPair<int, uint32_t> &d : disasmBreakpoints)
{
m_Breakpoints.insert(d);
m_DisassemblyView->markerAdd(d.second - 1, BREAKPOINT_MARKER);
m_DisassemblyView->markerAdd(d.second - 1, BREAKPOINT_MARKER + 1);
}
}
}
else
{
if(disasmBreakpoints.empty())
return;
QPair<int, uint32_t> &bp = disasmBreakpoints[0];
if(m_TempBreakpoint)
{
m_Breakpoints.insert(bp);
}
else if(m_Breakpoints.contains(bp))
{
m_Breakpoints.remove(bp);
m_DisassemblyView->markerDelete(bp.second - 1, BREAKPOINT_MARKER);
m_DisassemblyView->markerDelete(bp.second - 1, BREAKPOINT_MARKER + 1);
}
else
{
m_Breakpoints.insert(bp);
m_DisassemblyView->markerAdd(bp.second - 1, BREAKPOINT_MARKER);
m_DisassemblyView->markerAdd(bp.second - 1, BREAKPOINT_MARKER + 1);
}
}
}
void ShaderViewer::ToggleBreakpointOnDisassemblyLine(int32_t disassemblyLine)
{
if(!m_Trace || m_States.empty())
return;
// move forward to the next actual mapped line
for(; disassemblyLine < m_DisassemblyView->lineCount(); disassemblyLine++)
{
if(instructionForDisassemblyLine(disassemblyLine - 1) >= 0)
break;
}
if(disassemblyLine >= m_DisassemblyView->lineCount())
return;
if(m_TempBreakpoint)
{
m_Breakpoints.insert({-1, (uint32_t)disassemblyLine});
}
else if(m_Breakpoints.contains({-1, (uint32_t)disassemblyLine}))
{
m_Breakpoints.remove({-1, (uint32_t)disassemblyLine});
m_DisassemblyView->markerDelete(disassemblyLine - 1, BREAKPOINT_MARKER);
m_DisassemblyView->markerDelete(disassemblyLine - 1, BREAKPOINT_MARKER + 1);
}
else
{
m_Breakpoints.insert({-1, (uint32_t)disassemblyLine});
m_DisassemblyView->markerAdd(disassemblyLine - 1, BREAKPOINT_MARKER);
m_DisassemblyView->markerAdd(disassemblyLine - 1, BREAKPOINT_MARKER + 1);
}
}
void ShaderViewer::RunForward()
{
if(m_DeferredInit)
{
m_DeferredCommands.push_back([](ShaderViewer *v) { v->RunForward(); });
return;
}
runTo(~0U, true);
}
void ShaderViewer::ShowErrors(const rdcstr &errors)
{
if(m_Errors)
{
m_Errors->setReadOnly(false);
SetTextAndUpdateMargin0(m_Errors, errors);
m_Errors->setReadOnly(true);
if(!errors.isEmpty())
ToolWindowManager::raiseToolWindow(m_Errors);
}
updateEditState();
}
void ShaderViewer::AddWatch(const rdcstr &variable)
{
if(variable.isEmpty())
return;
RDTreeWidgetItem *item = new RDTreeWidgetItem({
QString(variable), QVariant(), QVariant(), QVariant(),
});
item->setEditable(0, true);
ui->watch->insertTopLevelItem(ui->watch->topLevelItemCount() - 1, item);
ToolWindowManager::raiseToolWindow(ui->watch);
ui->watch->activateWindow();
ui->watch->QWidget::setFocus();
updateWatchVariables();
}
rdcstrpairs ShaderViewer::GetCurrentFileContents()
{
rdcstrpairs files;
for(ScintillaEdit *s : m_Scintillas)
{
// don't include the disassembly view
if(m_DisassemblyView == s)
continue;
QWidget *w = (QWidget *)s;
files.push_back(
{w->property("filename").toString(), QString::fromUtf8(s->getText(s->textLength() + 1))});
}
return files;
}
int ShaderViewer::snippetPos()
{
ShaderEncoding encoding = currentEncoding();
if(encoding != ShaderEncoding::GLSL)
return 0;
if(m_Scintillas.isEmpty())
return 0;
QPair<int, int> ver =
m_Scintillas[0]->findText(SCFIND_REGEXP, "#version.*", 0, m_Scintillas[0]->length());
if(ver.first < 0)
return 0;
return ver.second + 1;
}
void ShaderViewer::insertSnippet(const QString &text)
{
if(text.isEmpty())
return;
if(m_Scintillas.isEmpty())
return;
m_Scintillas[0]->insertText(snippetPos(), text.toUtf8().data());
m_Scintillas[0]->setSelection(0, 0);
}
void ShaderViewer::snippet_constants()
{
ShaderEncoding encoding = currentEncoding();
QString text;
if(encoding == ShaderEncoding::GLSL)
{
text = lit(R"(
/////////////////////////////////////
// Constants //
/////////////////////////////////////
// possible values (these are only return values from this function, NOT texture binding points):
// RD_TextureType_1D
// RD_TextureType_2D
// RD_TextureType_3D
// RD_TextureType_Cube (OpenGL only)
// RD_TextureType_1D_Array (OpenGL only)
// RD_TextureType_2D_Array (OpenGL only)
// RD_TextureType_Cube_Array (OpenGL only)
// RD_TextureType_Rect (OpenGL only)
// RD_TextureType_Buffer (OpenGL only)
// RD_TextureType_2DMS
// RD_TextureType_2DMS_Array (OpenGL only)
uint RD_TextureType();
// selected sample, or -numSamples for resolve
int RD_SelectedSample();
uint RD_SelectedSliceFace();
uint RD_SelectedMip();
// xyz = width, height, depth (or array size). w = # mips
uvec4 RD_TexDim();
// x = horizontal downsample rate (1 full rate, 2 half rate)
// y = vertical downsample rate
// z = number of planes in input texture
// w = number of bits per component (8, 10, 16)
uvec4 RD_YUVDownsampleRate();
// x = where Y channel comes from
// y = where U channel comes from
// z = where V channel comes from
// w = where A channel comes from
// each index will be [0,1,2,3] for xyzw in first plane,
// [4,5,6,7] for xyzw in second plane texture, etc.
// it will be 0xff = 255 if the channel does not exist.
uvec4 RD_YUVAChannels();
// a pair with minimum and maximum selected range values
vec2 RD_SelectedRange();
/////////////////////////////////////
)");
}
else if(encoding == ShaderEncoding::HLSL)
{
text = lit(R"(
/////////////////////////////////////
// Constants //
/////////////////////////////////////
// possible values (these are only return values from this function, NOT texture binding points):
// RD_TextureType_1D
// RD_TextureType_2D
// RD_TextureType_3D
// RD_TextureType_Depth
// RD_TextureType_DepthStencil
// RD_TextureType_DepthMS
// RD_TextureType_DepthStencilMS
// RD_TextureType_2DMS
uint RD_TextureType();
// selected sample, or -numSamples for resolve
int RD_SelectedSample();
uint RD_SelectedSliceFace();
uint RD_SelectedMip();
// xyz = width, height, depth. w = # mips
uint4 RD_TexDim();
// x = horizontal downsample rate (1 full rate, 2 half rate)
// y = vertical downsample rate
// z = number of planes in input texture
// w = number of bits per component (8, 10, 16)
uint4 RD_YUVDownsampleRate();
// x = where Y channel comes from
// y = where U channel comes from
// z = where V channel comes from
// w = where A channel comes from
// each index will be [0,1,2,3] for xyzw in first plane,
// [4,5,6,7] for xyzw in second plane texture, etc.
// it will be 0xff = 255 if the channel does not exist.
uint4 RD_YUVAChannels();
// a pair with minimum and maximum selected range values
float2 RD_SelectedRange();
/////////////////////////////////////
)");
}
else if(encoding == ShaderEncoding::SPIRVAsm)
{
text = lit("; Can't insert snippets for SPIR-V ASM");
}
insertSnippet(text);
}
void ShaderViewer::snippet_samplers()
{
ShaderEncoding encoding = currentEncoding();
if(encoding == ShaderEncoding::HLSL)
{
insertSnippet(lit(R"(
/////////////////////////////////////
// Samplers //
/////////////////////////////////////
SamplerState pointSampler : register(RD_POINT_SAMPLER_BINDING);
SamplerState linearSampler : register(RD_LINEAR_SAMPLER_BINDING);
/////////////////////////////////////
)"));
}
else
{
insertSnippet(lit(R"(
/////////////////////////////////////
// Samplers //
/////////////////////////////////////
#ifdef VULKAN
layout(binding = RD_POINT_SAMPLER_BINDING) uniform sampler pointSampler;
layout(binding = RD_LINEAR_SAMPLER_BINDING) uniform sampler linearSampler;
#endif
/////////////////////////////////////
)"));
}
}
void ShaderViewer::snippet_resources()
{
ShaderEncoding encoding = currentEncoding();
GraphicsAPI api = m_Ctx.APIProps().localRenderer;
if(encoding == ShaderEncoding::HLSL)
{
insertSnippet(lit(R"(
/////////////////////////////////////
// Resources //
/////////////////////////////////////
// Float Textures
Texture1DArray<float4> texDisplayTex1DArray : register(RD_FLOAT_1D_ARRAY_BINDING);
Texture2DArray<float4> texDisplayTex2DArray : register(RD_FLOAT_2D_ARRAY_BINDING);
Texture3D<float4> texDisplayTex3D : register(RD_FLOAT_3D_BINDING);
Texture2DMSArray<float4> texDisplayTex2DMSArray : register(RD_FLOAT_2DMS_ARRAY_BINDING);
Texture2DArray<float4> texDisplayYUVArray : register(RD_FLOAT_YUV_ARRAY_BINDING);
// only used on D3D
Texture2DArray<float2> texDisplayTexDepthArray : register(RD_FLOAT_DEPTH_ARRAY_BINDING);
Texture2DArray<uint2> texDisplayTexStencilArray : register(RD_FLOAT_STENCIL_ARRAY_BINDING);
Texture2DMSArray<float2> texDisplayTexDepthMSArray : register(RD_FLOAT_DEPTHMS_ARRAY_BINDING);
Texture2DMSArray<uint2> texDisplayTexStencilMSArray : register(RD_FLOAT_STENCILMS_ARRAY_BINDING);
// Int Textures
Texture1DArray<int4> texDisplayIntTex1DArray : register(RD_INT_1D_ARRAY_BINDING);
Texture2DArray<int4> texDisplayIntTex2DArray : register(RD_INT_2D_ARRAY_BINDING);
Texture3D<int4> texDisplayIntTex3D : register(RD_INT_3D_BINDING);
Texture2DMSArray<int4> texDisplayIntTex2DMSArray : register(RD_INT_2DMS_ARRAY_BINDING);
// Unsigned int Textures
Texture1DArray<uint4> texDisplayUIntTex1DArray : register(RD_UINT_1D_ARRAY_BINDING);
Texture2DArray<uint4> texDisplayUIntTex2DArray : register(RD_UINT_2D_ARRAY_BINDING);
Texture3D<uint4> texDisplayUIntTex3D : register(RD_UINT_3D_BINDING);
Texture2DMSArray<uint4> texDisplayUIntTex2DMSArray : register(RD_UINT_2DMS_ARRAY_BINDING);
/////////////////////////////////////
)"));
}
else if(encoding == ShaderEncoding::GLSL)
{
insertSnippet(lit(R"(
/////////////////////////////////////
// Resources //
/////////////////////////////////////
// Float Textures
layout (binding = RD_FLOAT_1D_ARRAY_BINDING) uniform sampler1DArray tex1DArray;
layout (binding = RD_FLOAT_2D_ARRAY_BINDING) uniform sampler2DArray tex2DArray;
layout (binding = RD_FLOAT_3D_BINDING) uniform sampler3D tex3D;
layout (binding = RD_FLOAT_2DMS_ARRAY_BINDING) uniform sampler2DMSArray tex2DMSArray;
// YUV textures only supported on vulkan
#ifdef VULKAN
layout(binding = RD_FLOAT_YUV_ARRAY_BINDING) uniform sampler2DArray texYUVArray[2];
#endif
// OpenGL has more texture types to match
#ifndef VULKAN
layout (binding = RD_FLOAT_1D_BINDING) uniform sampler1D tex1D;
layout (binding = RD_FLOAT_2D_BINDING) uniform sampler2D tex2D;
layout (binding = RD_FLOAT_CUBE_BINDING) uniform samplerCube texCube;
layout (binding = RD_FLOAT_CUBE_ARRAY_BINDING) uniform samplerCubeArray texCubeArray;
layout (binding = RD_FLOAT_RECT_BINDING) uniform sampler2DRect tex2DRect;
layout (binding = RD_FLOAT_BUFFER_BINDING) uniform samplerBuffer texBuffer;
layout (binding = RD_FLOAT_2DMS_BINDING) uniform sampler2DMS tex2DMS;
#endif
// Int Textures
layout (binding = RD_INT_1D_ARRAY_BINDING) uniform isampler1DArray texSInt1DArray;
layout (binding = RD_INT_2D_ARRAY_BINDING) uniform isampler2DArray texSInt2DArray;
layout (binding = RD_INT_3D_BINDING) uniform isampler3D texSInt3D;
layout (binding = RD_INT_2DMS_ARRAY_BINDING) uniform isampler2DMSArray texSInt2DMSArray;
#ifndef VULKAN
layout (binding = RD_INT_1D_BINDING) uniform isampler1D texSInt1D;
layout (binding = RD_INT_2D_BINDING) uniform isampler2D texSInt2D;
layout (binding = RD_INT_RECT_BINDING) uniform isampler2DRect texSInt2DRect;
layout (binding = RD_INT_BUFFER_BINDING) uniform isamplerBuffer texSIntBuffer;
layout (binding = RD_INT_2DMS_BINDING) uniform isampler2DMS texSInt2DMS;
#endif
// Unsigned int Textures
layout (binding = RD_UINT_1D_ARRAY_BINDING) uniform usampler1DArray texUInt1DArray;
layout (binding = RD_UINT_2D_ARRAY_BINDING) uniform usampler2DArray texUInt2DArray;
layout (binding = RD_UINT_3D_BINDING) uniform usampler3D texUInt3D;
layout (binding = RD_UINT_2DMS_ARRAY_BINDING) uniform usampler2DMSArray texUInt2DMSArray;
#ifndef VULKAN
layout (binding = RD_UINT_1D_BINDING) uniform usampler1D texUInt1D;
layout (binding = RD_UINT_2D_BINDING) uniform usampler2D texUInt2D;
layout (binding = RD_UINT_RECT_BINDING) uniform usampler2DRect texUInt2DRect;
layout (binding = RD_UINT_BUFFER_BINDING) uniform usamplerBuffer texUIntBuffer;
layout (binding = RD_UINT_2DMS_BINDING) uniform usampler2DMS texUInt2DMS;
#endif
/////////////////////////////////////
)"));
}
}
bool ShaderViewer::eventFilter(QObject *watched, QEvent *event)
{
if(event->type() == QEvent::ToolTip)
{
QHelpEvent *he = (QHelpEvent *)event;
RDTreeWidget *tree = qobject_cast<RDTreeWidget *>(watched);
if(tree)
{
RDTreeWidgetItem *item = tree->itemAt(tree->viewport()->mapFromGlobal(QCursor::pos()));
if(item)
{
VariableTag tag = item->tag().value<VariableTag>();
showVariableTooltip(tag.absoluteRefPath);
}
}
}
if(event->type() == QEvent::MouseMove || event->type() == QEvent::Leave)
{
hideVariableTooltip();
}
return QFrame::eventFilter(watched, event);
}
void ShaderViewer::MarkModification()
{
if(m_ModifyCallback)
m_ModifyCallback(this, false);
m_Modified = true;
updateEditState();
}
void ShaderViewer::disasm_tooltipShow(int x, int y)
{
// do nothing if there's no trace
if(!m_Trace || m_States.empty())
return;
ScintillaEdit *sc = qobject_cast<ScintillaEdit *>(QObject::sender());
if(!sc)
return;
// ignore any messages if we're already outside the viewport
if(!sc->rect().contains(sc->mapFromGlobal(QCursor::pos())))
return;
if(sc->isVisible())
{
sptr_t scintillaPos = sc->positionFromPoint(x, y);
sptr_t start = sc->wordStartPosition(scintillaPos, true);
sptr_t end = sc->wordEndPosition(scintillaPos, true);
do
{
// expand leftwards through simple struct . access
// TODO handle arrays
while(isspace(sc->charAt(start - 1)))
start--;
if(sc->charAt(start - 1) == '.')
start = sc->wordStartPosition(start - 2, true);
else
break;
} while(true);
QString text = QString::fromUtf8(sc->textRange(start, end)).trimmed();
if(!text.isEmpty())
showVariableTooltip(text);
}
}
void ShaderViewer::disasm_tooltipHide(int x, int y)
{
hideVariableTooltip();
}
void ShaderViewer::showVariableTooltip(QString name)
{
m_TooltipVarPath = name.replace(QRegularExpression(lit("\\s+")), QString());
m_TooltipPos = QCursor::pos();
updateVariableTooltip();
}
void ShaderViewer::updateVariableTooltip()
{
if(!m_Trace || m_States.empty())
return;
ShaderVariable var;
if(!getVarFromPath(m_TooltipVarPath, &var))
return;
if(var.type != VarType::Unknown)
{
QString tooltip;
if(var.type == VarType::Sampler || var.type == VarType::ReadOnlyResource ||
var.type == VarType::ReadWriteResource || var.type == VarType::GPUPointer)
{
tooltip = QFormatStr("%1: ").arg(var.name) + RichResourceTextFormat(m_Ctx, stringRep(var, 0));
}
else if(var.type == VarType::ConstantBlock)
{
tooltip = QFormatStr("<pre>%1: { ... }</pre>").arg(var.name);
}
else
{
tooltip = QFormatStr("<pre>%1: %2\n").arg(var.name).arg(RowString(var, 0));
QString spacing = QString(var.name.count(), QLatin1Char(' '));
for(int i = 1; i < var.rows; i++)
tooltip += QFormatStr("%1 %2\n").arg(spacing).arg(RowString(var, i));
tooltip += lit("</pre>");
}
QToolTip::showText(m_TooltipPos, tooltip);
return;
}
else if(var.members.size() == 2 && var.members[0].type == VarType::ReadOnlyResource &&
var.members[1].type == VarType::Sampler)
{
// combined image/sampler structs
QToolTip::showText(m_TooltipPos,
QFormatStr("%1: %2 & %3")
.arg(var.name)
.arg(RichResourceTextFormat(m_Ctx, stringRep(var.members[0], 0)))
.arg(RichResourceTextFormat(m_Ctx, stringRep(var.members[1], 0))));
return;
}
else if(!var.members.empty())
{
// other structs
QToolTip::showText(m_TooltipPos, lit("{ ... }"));
return;
}
QString text = QFormatStr("<pre>%1\n").arg(var.name);
text +=
lit(" X Y Z W \n"
"--------------------------------------------------------\n");
text += QFormatStr("float | %1 %2 %3 %4\n")
.arg(Formatter::Format(var.value.f32v[0]), 11)
.arg(Formatter::Format(var.value.f32v[1]), 11)
.arg(Formatter::Format(var.value.f32v[2]), 11)
.arg(Formatter::Format(var.value.f32v[3]), 11);
text += QFormatStr("uint | %1 %2 %3 %4\n")
.arg(var.value.u32v[0], 11, 10, QLatin1Char(' '))
.arg(var.value.u32v[1], 11, 10, QLatin1Char(' '))
.arg(var.value.u32v[2], 11, 10, QLatin1Char(' '))
.arg(var.value.u32v[3], 11, 10, QLatin1Char(' '));
text += QFormatStr("int | %1 %2 %3 %4\n")
.arg(var.value.s32v[0], 11, 10, QLatin1Char(' '))
.arg(var.value.s32v[1], 11, 10, QLatin1Char(' '))
.arg(var.value.s32v[2], 11, 10, QLatin1Char(' '))
.arg(var.value.s32v[3], 11, 10, QLatin1Char(' '));
text += QFormatStr("hex | %1 %2 %3 %4")
.arg(Formatter::HexFormat(var.value.u32v[0], 4))
.arg(Formatter::HexFormat(var.value.u32v[1], 4))
.arg(Formatter::HexFormat(var.value.u32v[2], 4))
.arg(Formatter::HexFormat(var.value.u32v[3], 4));
text += lit("</pre>");
QToolTip::showText(m_TooltipPos, text);
}
void ShaderViewer::hideVariableTooltip()
{
QToolTip::hideText();
m_TooltipVarIndex = -1;
m_TooltipVarPath = QString();
}
bool ShaderViewer::isSourceDebugging()
{
return !m_DisassemblyFrame->isVisible();
}
ShaderEncoding ShaderViewer::currentEncoding()
{
int idx = ui->encoding->currentIndex();
if(idx >= 0 && idx < m_Encodings.count())
return m_Encodings[idx];
return ShaderEncoding::Unknown;
}
void ShaderViewer::on_findReplace_clicked()
{
if(m_FindReplace->isVisible())
{
ToolWindowManager::raiseToolWindow(m_FindReplace);
}
else
{
ui->docking->moveToolWindow(
m_FindReplace, ToolWindowManager::AreaReference(ToolWindowManager::NewFloatingArea));
ui->docking->setToolWindowProperties(m_FindReplace, ToolWindowManager::HideOnClose);
}
ui->docking->areaOf(m_FindReplace)->parentWidget()->activateWindow();
m_FindReplace->takeFocus();
}
void ShaderViewer::PopulateCompileTools()
{
ShaderEncoding encoding = currentEncoding();
rdcarray<ShaderEncoding> accepted = m_Ctx.TargetShaderEncodings();
QStringList strs;
strs.clear();
for(const ShaderProcessingTool &tool : m_Ctx.Config().ShaderProcessors)
{
// skip tools that can't accept our inputs, or doesn't produce a supported output
if(tool.input != encoding || accepted.indexOf(tool.output) < 0)
continue;
strs << tool.name;
}
// if we can pass in the shader source as-is, add a built-in option
if(accepted.indexOf(encoding) >= 0)
strs << tr("Builtin");
ui->compileTool->clear();
ui->compileTool->addItems(strs);
// pick the first option as highest priority
ui->compileTool->setCurrentIndex(0);
// fill out parameters
PopulateCompileToolParameters();
if(strs.isEmpty())
{
ShowErrors(tr("No compilation tool found that takes %1 as input and produces compatible output")
.arg(ToQStr(encoding)));
}
}
void ShaderViewer::PopulateCompileToolParameters()
{
ShaderEncoding encoding = currentEncoding();
rdcarray<ShaderEncoding> accepted = m_Ctx.TargetShaderEncodings();
ui->toolCommandLine->clear();
if(accepted.indexOf(encoding) >= 0 &&
ui->compileTool->currentIndex() == ui->compileTool->count() - 1)
{
// if we're using the last Builtin tool, there are no default parameters
}
else
{
for(const ShaderProcessingTool &tool : m_Ctx.Config().ShaderProcessors)
{
if(QString(tool.name) == ui->compileTool->currentText())
{
ui->toolCommandLine->setPlainText(tool.DefaultArguments());
ui->toolCommandLine->setEnabled(true);
break;
}
}
}
for(int i = 0; i < m_Flags.flags.count(); i++)
{
ShaderCompileFlag &flag = m_Flags.flags[i];
if(flag.name == "@cmdline")
{
// append command line from saved flags, so any specified options override the defaults if
// they're specified twice
ui->toolCommandLine->setPlainText(ui->toolCommandLine->toPlainText() +
lit(" %1").arg(flag.value));
break;
}
}
}
bool ShaderViewer::ProcessIncludeDirectives(QString &source, const rdcstrpairs &files)
{
// try and match up #includes against the files that we have. This isn't always
// possible as fxc only seems to include the source for files if something in
// that file was included in the compiled output. So you might end up with
// dangling #includes - we just have to ignore them
int offs = source.indexOf(lit("#include"));
while(offs >= 0)
{
// search back to ensure this is a valid #include (ie. not in a comment).
// Must only see whitespace before, then a newline.
int ws = qMax(0, offs - 1);
while(ws >= 0 && (source[ws] == QLatin1Char(' ') || source[ws] == QLatin1Char('\t')))
ws--;
// not valid? jump to next.
if(ws > 0 && source[ws] != QLatin1Char('\n'))
{
offs = source.indexOf(lit("#include"), offs + 1);
continue;
}
int start = ws + 1;
bool tail = true;
int lineEnd = source.indexOf(QLatin1Char('\n'), start + 1);
if(lineEnd == -1)
{
lineEnd = source.length();
tail = false;
}
ws = offs + sizeof("#include") - 1;
while(source[ws] == QLatin1Char(' ') || source[ws] == QLatin1Char('\t'))
ws++;
QString line = source.mid(offs, lineEnd - offs + 1);
if(source[ws] != QLatin1Char('<') && source[ws] != QLatin1Char('"'))
{
ShowErrors(tr("Invalid #include directive found:\r\n") + line);
return false;
}
// find matching char, either <> or "";
int end =
source.indexOf(source[ws] == QLatin1Char('"') ? QLatin1Char('"') : QLatin1Char('>'), ws + 1);
if(end == -1)
{
ShowErrors(tr("Invalid #include directive found:\r\n") + line);
return false;
}
QString fname = source.mid(ws + 1, end - ws - 1);
QString fileText;
// look for exact match first
for(int i = 0; i < files.count(); i++)
{
if(QString(files[i].first) == fname)
{
fileText = files[i].second;
break;
}
}
if(fileText.isEmpty())
{
QString search = QFileInfo(fname).fileName();
// if not, try and find the same filename (this is not proper include handling!)
for(const rdcstrpair &kv : files)
{
if(QFileInfo(kv.first).fileName().compare(search, Qt::CaseInsensitive) == 0)
{
fileText = kv.second;
break;
}
}
if(fileText.isEmpty())
fileText = QFormatStr("// Can't find file %1\n").arg(fname);
}
source = source.left(offs) + lit("\n\n") + fileText + lit("\n\n") +
(tail ? source.mid(lineEnd + 1) : QString());
// need to start searching from the beginning - wasteful but allows nested includes to
// work
offs = source.indexOf(lit("#include"));
}
for(const rdcstrpair &kv : files)
{
if(kv.first == "@cmdline")
source = QString(kv.second) + lit("\n\n") + source;
}
return true;
}
void ShaderViewer::on_resetEdits_clicked()
{
QMessageBox::StandardButton res = RDDialog::question(
this, tr("Are you sure?"), tr("Are you sure you want to reset all edits and restore the "
"shader source back to the original?"),
QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
if(res != QMessageBox::Yes)
return;
for(ScintillaEdit *s : m_Scintillas)
{
QWidget *w = (QWidget *)s;
s->selectAll();
s->replaceSel(w->property("origText").toString().toUtf8().data());
}
m_RevertCallback(&m_Ctx, this, m_EditingShader);
m_Modified = false;
m_Saved = false;
updateEditState();
}
void ShaderViewer::on_unrefresh_clicked()
{
m_RevertCallback(&m_Ctx, this, m_EditingShader);
m_Modified = true;
m_Saved = false;
updateEditState();
}
void ShaderViewer::on_refresh_clicked()
{
if(m_Trace)
{
m_Ctx.GetPipelineViewer()->SaveShaderFile(m_ShaderDetails);
return;
}
ShaderEncoding encoding = currentEncoding();
// if we don't have any compile tools - even the 'builtin' one, this compilation is not going to
// succeed.
if(ui->compileTool->count() == 0 && !m_CustomShader)
{
ShowErrors(tr("No compilation tool found that takes %1 as input and produces compatible output")
.arg(ToQStr(encoding)));
}
else if(m_SaveCallback)
{
rdcstrpairs files;
for(ScintillaEdit *s : m_Scintillas)
{
QWidget *w = (QWidget *)s;
files.push_back(
{w->property("filename").toString(), QString::fromUtf8(s->getText(s->textLength() + 1))});
}
if(files.isEmpty())
return;
QString source = files[0].second;
if(encoding == ShaderEncoding::HLSL || encoding == ShaderEncoding::GLSL)
{
bool success = ProcessIncludeDirectives(source, files);
if(!success)
return;
}
m_Saved = true;
bytebuf shaderBytes(source.toUtf8());
rdcarray<ShaderEncoding> accepted = m_Ctx.TargetShaderEncodings();
if(m_CustomShader || (accepted.indexOf(encoding) >= 0 &&
ui->compileTool->currentIndex() == ui->compileTool->count() - 1))
{
// if using the builtin compiler, just pass through
}
else
{
for(const ShaderProcessingTool &tool : m_Ctx.Config().ShaderProcessors)
{
if(QString(tool.name) == ui->compileTool->currentText())
{
ShaderToolOutput out = tool.CompileShader(this, source, ui->entryFunc->text(), m_Stage,
ui->toolCommandLine->toPlainText());
ShowErrors(out.log);
if(out.result.isEmpty())
return;
encoding = tool.output;
shaderBytes = out.result;
break;
}
}
}
ShaderCompileFlags flags = m_Flags;
bool found = false;
for(ShaderCompileFlag &f : flags.flags)
{
if(f.name == "@cmdline")
{
f.value = ui->toolCommandLine->toPlainText();
found = true;
break;
}
}
if(!found)
flags.flags.push_back({"@cmdline", ui->toolCommandLine->toPlainText()});
m_Modified = false;
m_SaveCallback(&m_Ctx, this, m_EditingShader, m_Stage, encoding, flags, ui->entryFunc->text(),
shaderBytes);
}
}
void ShaderViewer::on_intView_clicked()
{
ui->intView->setChecked(true);
ui->floatView->setChecked(false);
updateDebugState();
}
void ShaderViewer::on_floatView_clicked()
{
ui->floatView->setChecked(true);
ui->intView->setChecked(false);
updateDebugState();
}
void ShaderViewer::on_debugToggle_clicked()
{
if(isSourceDebugging())
gotoDisassemblyDebugging();
else
gotoSourceDebugging();
updateDebugState();
}
void ShaderViewer::on_resources_sortByStep_clicked()
{
m_AccessedResourceView = AccessedResourceView::SortByStep;
ui->resources_sortByStep->setChecked(true);
ui->resources_sortByResource->setChecked(false);
updateAccessedResources();
}
void ShaderViewer::on_resources_sortByResource_clicked()
{
m_AccessedResourceView = AccessedResourceView::SortByResource;
ui->resources_sortByResource->setChecked(true);
ui->resources_sortByStep->setChecked(false);
updateAccessedResources();
}
ScintillaEdit *ShaderViewer::currentScintilla()
{
ScintillaEdit *cur = qobject_cast<ScintillaEdit *>(QApplication::focusWidget());
if(cur == NULL)
{
for(ScintillaEdit *s : m_Scintillas)
{
if(s->isVisible())
{
cur = s;
break;
}
}
}
return cur;
}
ScintillaEdit *ShaderViewer::nextScintilla(ScintillaEdit *cur)
{
for(int i = 0; i < m_Scintillas.count(); i++)
{
if(m_Scintillas[i] == cur)
{
if(i + 1 < m_Scintillas.count())
return m_Scintillas[i + 1];
return m_Scintillas[0];
}
}
if(!m_Scintillas.isEmpty())
return m_Scintillas[0];
return NULL;
}
void ShaderViewer::find(bool down)
{
ScintillaEdit *cur = currentScintilla();
if(!cur)
return;
QString find = m_FindReplace->findText();
sptr_t flags = 0;
if(m_FindReplace->matchCase())
flags |= SCFIND_MATCHCASE;
if(m_FindReplace->matchWord())
flags |= SCFIND_WHOLEWORD;
if(m_FindReplace->regexp())
flags |= SCFIND_REGEXP | SCFIND_POSIX;
FindReplace::SearchContext context = m_FindReplace->context();
QString findHash = QFormatStr("%1%2%3%4").arg(find).arg(flags).arg((int)context).arg(down);
if(findHash != m_FindState.hash)
{
m_FindState.hash = findHash;
m_FindState.start = 0;
m_FindState.end = cur->length();
m_FindState.offset = cur->currentPos();
if(down && cur->selectionStart() == m_FindState.offset &&
cur->selectionEnd() - m_FindState.offset == find.length())
m_FindState.offset += find.length();
}
int start = m_FindState.start + m_FindState.offset;
int end = m_FindState.end;
if(!down)
end = m_FindState.start;
QPair<int, int> result = cur->findText(flags, find.toUtf8().data(), start, end);
m_FindState.prevResult = result;
if(result.first == -1)
{
sptr_t maxOffset = down ? 0 : m_FindState.end;
// if we're at offset 0 searching down, there are no results. Same for offset max and searching
// up
if(m_FindState.offset == maxOffset)
return;
// otherwise, we can wrap the search around
if(context == FindReplace::AllFiles)
{
cur = nextScintilla(cur);
ToolWindowManager::raiseToolWindow(cur);
cur->activateWindow();
cur->QWidget::setFocus();
}
m_FindState.offset = maxOffset;
start = m_FindState.start + m_FindState.offset;
end = m_FindState.end;
if(!down)
end = m_FindState.start;
result = cur->findText(flags, find.toUtf8().data(), start, end);
m_FindState.prevResult = result;
if(result.first == -1)
return;
}
cur->setSelection(result.first, result.second);
ensureLineScrolled(cur, cur->lineFromPosition(result.first));
if(down)
m_FindState.offset = result.second - m_FindState.start;
else
m_FindState.offset = result.first - m_FindState.start;
}
void ShaderViewer::performFind()
{
find(m_FindReplace->direction() == FindReplace::Down);
}
void ShaderViewer::performFindAll()
{
ScintillaEdit *cur = currentScintilla();
if(!cur)
return;
QString find = m_FindReplace->findText();
sptr_t flags = 0;
QString results = tr("Find all \"%1\"").arg(find);
if(m_FindReplace->matchCase())
{
flags |= SCFIND_MATCHCASE;
results += tr(", Match case");
}
if(m_FindReplace->matchWord())
{
flags |= SCFIND_WHOLEWORD;
results += tr(", Match whole word");
}
if(m_FindReplace->regexp())
{
flags |= SCFIND_REGEXP | SCFIND_POSIX;
results += tr(", with Regular Expressions");
}
FindReplace::SearchContext context = m_FindReplace->context();
if(context == FindReplace::File)
results += tr(", in current file\n");
else
results += tr(", in all files\n");
// trash the find state for any incremental finds
m_FindState = FindState();
QList<ScintillaEdit *> scintillas = m_Scintillas;
if(context == FindReplace::File)
scintillas = {cur};
QList<QPair<int, int>> resultList;
m_FindAllResults.clear();
QByteArray findUtf8 = find.toUtf8();
if(findUtf8.isEmpty())
return;
for(ScintillaEdit *s : scintillas)
{
sptr_t start = 0;
sptr_t end = s->length();
s->setIndicatorCurrent(INDICATOR_FINDRESULT);
s->indicatorClearRange(start, end);
QPair<int, int> result;
do
{
result = s->findText(flags, findUtf8.data(), start, end);
if(result.first >= 0)
{
int line = s->lineFromPosition(result.first);
sptr_t lineStart = s->positionFromLine(line);
sptr_t lineEnd = s->lineEndPosition(line);
s->indicatorFillRange(result.first, result.second - result.first);
QString lineText = QString::fromUtf8(s->textRange(lineStart, lineEnd));
results += QFormatStr(" %1(%2): ").arg(s->windowTitle()).arg(line + 1, 4);
int startPos = results.length();
results += lineText;
results += lit("\n");
resultList.push_back(
qMakePair(result.first - lineStart + startPos, result.second - lineStart + startPos));
m_FindAllResults.push_back({s, result.first});
}
start = result.second;
} while(result.first >= 0);
}
results += tr("Matching lines: %1").arg(resultList.count());
m_FindResults->setReadOnly(false);
m_FindResults->setText(results.toUtf8().data());
m_FindResults->setIndicatorCurrent(INDICATOR_FINDALLHIGHLIGHT);
m_FindResults->indicatorClearRange(0, m_FindResults->length());
m_FindResults->setIndicatorCurrent(INDICATOR_FINDRESULT);
for(QPair<int, int> r : resultList)
m_FindResults->indicatorFillRange(r.first, r.second - r.first);
m_FindResults->setReadOnly(true);
if(m_FindResults->isVisible())
{
ToolWindowManager::raiseToolWindow(m_FindResults);
}
else
{
ui->docking->moveToolWindow(m_FindResults,
ToolWindowManager::AreaReference(ToolWindowManager::BottomOf,
ui->docking->areaOf(cur), 0.2f));
ui->docking->setToolWindowProperties(
m_FindResults, ToolWindowManager::HideOnClose | ToolWindowManager::DisallowFloatWindow);
}
}
void ShaderViewer::resultsDoubleClick(int position, int line)
{
if(line >= 1 && line - 1 < m_FindAllResults.count())
{
m_FindResults->setIndicatorCurrent(INDICATOR_FINDALLHIGHLIGHT);
m_FindResults->indicatorClearRange(0, m_FindResults->length());
sptr_t start = m_FindResults->positionFromLine(line);
sptr_t length = m_FindResults->lineLength(line);
m_FindResults->indicatorFillRange(start, length);
m_FindResults->setSelection(position, position);
ScintillaEdit *s = m_FindAllResults[line - 1].first;
int resultPos = m_FindAllResults[line - 1].second;
ToolWindowManager::raiseToolWindow(s);
s->activateWindow();
s->QWidget::setFocus();
s->clearSelections();
s->setSelection(resultPos, resultPos);
s->scrollCaret();
}
}
void ShaderViewer::performReplace()
{
ScintillaEdit *cur = currentScintilla();
if(!cur)
return;
QString find = m_FindReplace->findText();
if(find.isEmpty())
return;
sptr_t flags = 0;
if(m_FindReplace->matchCase())
flags |= SCFIND_MATCHCASE;
if(m_FindReplace->matchWord())
flags |= SCFIND_WHOLEWORD;
if(m_FindReplace->regexp())
flags |= SCFIND_REGEXP | SCFIND_POSIX;
FindReplace::SearchContext context = m_FindReplace->context();
QString findHash = QFormatStr("%1%2%3").arg(find).arg(flags).arg((int)context);
// if we didn't have a valid previous find, just do a find and bail
if(findHash != m_FindState.hash)
{
performFind();
return;
}
if(m_FindState.prevResult.first == -1)
return;
cur->setTargetRange(m_FindState.prevResult.first, m_FindState.prevResult.second);
FindState save = m_FindState;
QString replaceText = m_FindReplace->replaceText();
// otherwise we have a valid previous find. Do the replace now
// note this will invalidate the find state (as most user operations would), so we save/restore
// the state
if(m_FindReplace->regexp())
cur->replaceTargetRE(-1, replaceText.toUtf8().data());
else
cur->replaceTarget(-1, replaceText.toUtf8().data());
m_FindState = save;
// adjust the offset if we replaced text and it went up or down in size
m_FindState.offset += (replaceText.count() - find.count());
// move to the next result
performFind();
}
void ShaderViewer::performReplaceAll()
{
ScintillaEdit *cur = currentScintilla();
if(!cur)
return;
QString find = m_FindReplace->findText();
QString replace = m_FindReplace->replaceText();
if(find.isEmpty())
return;
sptr_t flags = 0;
if(m_FindReplace->matchCase())
flags |= SCFIND_MATCHCASE;
if(m_FindReplace->matchWord())
flags |= SCFIND_WHOLEWORD;
if(m_FindReplace->regexp())
flags |= SCFIND_REGEXP | SCFIND_POSIX;
FindReplace::SearchContext context = m_FindReplace->context();
(void)context;
// trash the find state for any incremental finds
m_FindState = FindState();
QList<ScintillaEdit *> scintillas = m_Scintillas;
if(context == FindReplace::File)
scintillas = {cur};
int numReplacements = 1;
for(ScintillaEdit *s : scintillas)
{
sptr_t start = 0;
sptr_t end = s->length();
QPair<int, int> result;
QByteArray findUtf8 = find.toUtf8();
QByteArray replaceUtf8 = replace.toUtf8();
do
{
result = s->findText(flags, findUtf8.data(), start, end);
if(result.first >= 0)
{
s->setTargetRange(result.first, result.second);
if(m_FindReplace->regexp())
s->replaceTargetRE(-1, replaceUtf8.data());
else
s->replaceTarget(-1, replaceUtf8.data());
numReplacements++;
}
start = result.second + (replaceUtf8.count() - findUtf8.count());
} while(result.first >= 0);
}
RDDialog::information(
this, tr("Replace all"),
tr("%1 replacements made in %2 files").arg(numReplacements).arg(scintillas.count()));
}
|