Hash :
0cdbc781
Author :
Date :
2025-03-06T11:22:18
WGSL: Output samplers, including samplers from structs This output two WGSL variables for each GLSL sampler, including samplers in structs. This does not output the correct types for the WGSL variables, yet, nor does it generate texture access function calls. It also can't deal with arrays of samplers, which are not allowed in WGSL. Note that WGSL does not allow structs containing samplers to be arguments to a function, like Vulkan, nor does it allowed arrays of samplers at all, unlike Vulkan. This deals with the former problem the same way as Vulkan and Metal, by monomorphizing functions that take unsupported arguments. Bug: angleproject:389145696 Change-Id: I346688783dd2771c8fe6848b6783d948ed111783 Reviewed-on: https://chromium-review.googlesource.com/c/angle/angle/+/6253672 Reviewed-by: Geoff Lang <geofflang@chromium.org> Commit-Queue: Matthew Denton <mpdenton@chromium.org>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088
//
// Copyright 2024 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "compiler/translator/wgsl/TranslatorWGSL.h"
#include <iostream>
#include <variant>
#include "GLSLANG/ShaderLang.h"
#include "common/log_utils.h"
#include "common/span.h"
#include "compiler/translator/BaseTypes.h"
#include "compiler/translator/Common.h"
#include "compiler/translator/Diagnostics.h"
#include "compiler/translator/ImmutableString.h"
#include "compiler/translator/ImmutableStringBuilder.h"
#include "compiler/translator/InfoSink.h"
#include "compiler/translator/IntermNode.h"
#include "compiler/translator/Operator_autogen.h"
#include "compiler/translator/OutputTree.h"
#include "compiler/translator/StaticType.h"
#include "compiler/translator/SymbolUniqueId.h"
#include "compiler/translator/Types.h"
#include "compiler/translator/tree_ops/MonomorphizeUnsupportedFunctions.h"
#include "compiler/translator/tree_ops/RewriteArrayOfArrayOfOpaqueUniforms.h"
#include "compiler/translator/tree_ops/RewriteStructSamplers.h"
#include "compiler/translator/tree_ops/SeparateStructFromUniformDeclarations.h"
#include "compiler/translator/tree_util/BuiltIn_autogen.h"
#include "compiler/translator/tree_util/FindMain.h"
#include "compiler/translator/tree_util/IntermNode_util.h"
#include "compiler/translator/tree_util/IntermTraverse.h"
#include "compiler/translator/tree_util/RunAtTheEndOfShader.h"
#include "compiler/translator/wgsl/OutputUniformBlocks.h"
#include "compiler/translator/wgsl/RewritePipelineVariables.h"
#include "compiler/translator/wgsl/Utils.h"
namespace sh
{
namespace
{
constexpr bool kOutputTreeBeforeTranslation = false;
constexpr bool kOutputTranslatedShader = false;
struct VarDecl
{
const SymbolType symbolType = SymbolType::Empty;
const ImmutableString &symbolName;
const TType &type;
};
bool IsDefaultUniform(const TType &type)
{
return type.getQualifier() == EvqUniform && type.getInterfaceBlock() == nullptr &&
!IsOpaqueType(type.getBasicType());
}
// When emitting a list of statements, this determines whether a semicolon follows the statement.
bool RequiresSemicolonTerminator(TIntermNode &node)
{
if (node.getAsBlock())
{
return false;
}
if (node.getAsLoopNode())
{
return false;
}
if (node.getAsSwitchNode())
{
return false;
}
if (node.getAsIfElseNode())
{
return false;
}
if (node.getAsFunctionDefinition())
{
return false;
}
if (node.getAsCaseNode())
{
return false;
}
return true;
}
// For pretty formatting of the resulting WGSL text.
bool NewlinePad(TIntermNode &node)
{
if (node.getAsFunctionDefinition())
{
return true;
}
if (TIntermDeclaration *declNode = node.getAsDeclarationNode())
{
ASSERT(declNode->getChildCount() == 1);
TIntermNode &childNode = *declNode->getChildNode(0);
if (TIntermSymbol *symbolNode = childNode.getAsSymbolNode())
{
const TVariable &var = symbolNode->variable();
return var.getType().isStructSpecifier();
}
return false;
}
return false;
}
// A traverser that generates WGSL as it walks the AST.
class OutputWGSLTraverser : public TIntermTraverser
{
public:
OutputWGSLTraverser(TInfoSinkBase *sink,
RewritePipelineVarOutput *rewritePipelineVarOutput,
UniformBlockMetadata *uniformBlockMetadata,
WGSLGenerationMetadataForUniforms *arrayElementTypesInUniforms);
~OutputWGSLTraverser() override;
protected:
void visitSymbol(TIntermSymbol *node) override;
void visitConstantUnion(TIntermConstantUnion *node) override;
bool visitSwizzle(Visit visit, TIntermSwizzle *node) override;
bool visitBinary(Visit visit, TIntermBinary *node) override;
bool visitUnary(Visit visit, TIntermUnary *node) override;
bool visitTernary(Visit visit, TIntermTernary *node) override;
bool visitIfElse(Visit visit, TIntermIfElse *node) override;
bool visitSwitch(Visit visit, TIntermSwitch *node) override;
bool visitCase(Visit visit, TIntermCase *node) override;
void visitFunctionPrototype(TIntermFunctionPrototype *node) override;
bool visitFunctionDefinition(Visit visit, TIntermFunctionDefinition *node) override;
bool visitAggregate(Visit visit, TIntermAggregate *node) override;
bool visitBlock(Visit visit, TIntermBlock *node) override;
bool visitGlobalQualifierDeclaration(Visit visit,
TIntermGlobalQualifierDeclaration *node) override;
bool visitDeclaration(Visit visit, TIntermDeclaration *node) override;
bool visitLoop(Visit visit, TIntermLoop *node) override;
bool visitBranch(Visit visit, TIntermBranch *node) override;
void visitPreprocessorDirective(TIntermPreprocessorDirective *node) override;
private:
struct EmitVariableDeclarationConfig
{
EmitTypeConfig typeConfig;
bool isParameter = false;
bool disableStructSpecifier = false;
bool needsVar = false;
bool isGlobalScope = false;
};
void groupedTraverse(TIntermNode &node);
void emitNameOf(const VarDecl &decl);
void emitBareTypeName(const TType &type);
void emitType(const TType &type);
void emitSingleConstant(const TConstantUnion *const constUnion);
const TConstantUnion *emitConstantUnionArray(const TConstantUnion *const constUnion,
const size_t size);
const TConstantUnion *emitConstantUnion(const TType &type,
const TConstantUnion *constUnionBegin);
const TField &getDirectField(const TIntermTyped &fieldsNode, TIntermTyped &indexNode);
void emitIndentation();
void emitOpenBrace();
void emitCloseBrace();
bool emitBlock(angle::Span<TIntermNode *> nodes);
void emitFunctionSignature(const TFunction &func);
void emitFunctionReturn(const TFunction &func);
void emitFunctionParameter(const TFunction &func, const TVariable ¶m);
void emitStructDeclaration(const TType &type);
void emitVariableDeclaration(const VarDecl &decl,
const EmitVariableDeclarationConfig &evdConfig);
void emitArrayIndex(TIntermTyped &leftNode, TIntermTyped &rightNode);
void emitStructIndex(TIntermBinary *binaryNode);
void emitStructIndexNoUnwrapping(TIntermBinary *binaryNode);
bool emitForLoop(TIntermLoop *);
bool emitWhileLoop(TIntermLoop *);
bool emulateDoWhileLoop(TIntermLoop *);
TInfoSinkBase &mSink;
const RewritePipelineVarOutput *mRewritePipelineVarOutput;
const UniformBlockMetadata *mUniformBlockMetadata;
WGSLGenerationMetadataForUniforms *mWGSLGenerationMetadataForUniforms;
int mIndentLevel = -1;
int mLastIndentationPos = -1;
};
OutputWGSLTraverser::OutputWGSLTraverser(
TInfoSinkBase *sink,
RewritePipelineVarOutput *rewritePipelineVarOutput,
UniformBlockMetadata *uniformBlockMetadata,
WGSLGenerationMetadataForUniforms *wgslGenerationMetadataForUniforms)
: TIntermTraverser(true, false, false),
mSink(*sink),
mRewritePipelineVarOutput(rewritePipelineVarOutput),
mUniformBlockMetadata(uniformBlockMetadata),
mWGSLGenerationMetadataForUniforms(wgslGenerationMetadataForUniforms)
{}
OutputWGSLTraverser::~OutputWGSLTraverser() = default;
void OutputWGSLTraverser::groupedTraverse(TIntermNode &node)
{
// TODO(anglebug.com/42267100): to make generated code more readable, do not always
// emit parentheses like WGSL is some Lisp dialect.
const bool emitParens = true;
if (emitParens)
{
mSink << "(";
}
node.traverse(this);
if (emitParens)
{
mSink << ")";
}
}
void OutputWGSLTraverser::emitNameOf(const VarDecl &decl)
{
WriteNameOf(mSink, decl.symbolType, decl.symbolName);
}
void OutputWGSLTraverser::emitIndentation()
{
ASSERT(mIndentLevel >= 0);
if (mLastIndentationPos == mSink.size())
{
return; // Line is already indented.
}
for (int i = 0; i < mIndentLevel; ++i)
{
mSink << " ";
}
mLastIndentationPos = mSink.size();
}
void OutputWGSLTraverser::emitOpenBrace()
{
ASSERT(mIndentLevel >= 0);
emitIndentation();
mSink << "{\n";
++mIndentLevel;
}
void OutputWGSLTraverser::emitCloseBrace()
{
ASSERT(mIndentLevel >= 1);
--mIndentLevel;
emitIndentation();
mSink << "}";
}
void OutputWGSLTraverser::visitSymbol(TIntermSymbol *symbolNode)
{
const TVariable &var = symbolNode->variable();
const TType &type = var.getType();
ASSERT(var.symbolType() != SymbolType::Empty);
if (type.getBasicType() == TBasicType::EbtVoid)
{
UNREACHABLE();
}
else
{
// Accesses of pipeline variables should be rewritten as struct accesses.
if (mRewritePipelineVarOutput->IsInputVar(var.uniqueId()))
{
mSink << kBuiltinInputStructName << "." << var.name();
}
else if (mRewritePipelineVarOutput->IsOutputVar(var.uniqueId()))
{
mSink << kBuiltinOutputStructName << "." << var.name();
}
// Accesses of basic uniforms need to be converted to struct accesses.
else if (IsDefaultUniform(type))
{
mSink << kDefaultUniformBlockVarName << "." << var.name();
}
else
{
WriteNameOf(mSink, var);
}
if (var.symbolType() == SymbolType::BuiltIn)
{
ASSERT(mRewritePipelineVarOutput->IsInputVar(var.uniqueId()) ||
mRewritePipelineVarOutput->IsOutputVar(var.uniqueId()) ||
var.uniqueId() == BuiltInId::gl_DepthRange);
// TODO(anglebug.com/42267100): support gl_DepthRange.
// Match the name of the struct field in `mRewritePipelineVarOutput`.
mSink << "_";
}
}
}
void OutputWGSLTraverser::emitSingleConstant(const TConstantUnion *const constUnion)
{
switch (constUnion->getType())
{
case TBasicType::EbtBool:
{
mSink << (constUnion->getBConst() ? "true" : "false");
}
break;
case TBasicType::EbtFloat:
{
float value = constUnion->getFConst();
if (std::isnan(value))
{
UNIMPLEMENTED();
// TODO(anglebug.com/42267100): this is not a valid constant in WGPU.
// You can't even do something like bitcast<f32>(0xffffffffu).
// The WGSL compiler still complains. I think this is because
// WGSL supports implementations compiling with -ffastmath and
// therefore nans and infinities are assumed to not exist.
// See also https://github.com/gpuweb/gpuweb/issues/3749.
mSink << "NAN_INVALID";
}
else if (std::isinf(value))
{
UNIMPLEMENTED();
// see above.
mSink << "INFINITY_INVALID";
}
else
{
mSink << value << "f";
}
}
break;
case TBasicType::EbtInt:
{
mSink << constUnion->getIConst() << "i";
}
break;
case TBasicType::EbtUInt:
{
mSink << constUnion->getUConst() << "u";
}
break;
default:
{
UNIMPLEMENTED();
}
}
}
const TConstantUnion *OutputWGSLTraverser::emitConstantUnionArray(
const TConstantUnion *const constUnion,
const size_t size)
{
const TConstantUnion *constUnionIterated = constUnion;
for (size_t i = 0; i < size; i++, constUnionIterated++)
{
emitSingleConstant(constUnionIterated);
if (i != size - 1)
{
mSink << ", ";
}
}
return constUnionIterated;
}
const TConstantUnion *OutputWGSLTraverser::emitConstantUnion(const TType &type,
const TConstantUnion *constUnionBegin)
{
const TConstantUnion *constUnionCurr = constUnionBegin;
const TStructure *structure = type.getStruct();
if (structure)
{
emitType(type);
// Structs are constructed with parentheses in WGSL.
mSink << "(";
// Emit the constructor parameters. Both GLSL and WGSL require there to be the same number
// of parameters as struct fields.
const TFieldList &fields = structure->fields();
for (size_t i = 0; i < fields.size(); ++i)
{
const TType *fieldType = fields[i]->type();
constUnionCurr = emitConstantUnion(*fieldType, constUnionCurr);
if (i != fields.size() - 1)
{
mSink << ", ";
}
}
mSink << ")";
}
else
{
size_t size = type.getObjectSize();
// If the type's size is more than 1, the type needs to be written with parantheses. This
// applies for vectors, matrices, and arrays.
bool writeType = size > 1;
if (writeType)
{
emitType(type);
mSink << "(";
}
constUnionCurr = emitConstantUnionArray(constUnionCurr, size);
if (writeType)
{
mSink << ")";
}
}
return constUnionCurr;
}
void OutputWGSLTraverser::visitConstantUnion(TIntermConstantUnion *constValueNode)
{
emitConstantUnion(constValueNode->getType(), constValueNode->getConstantValue());
}
bool OutputWGSLTraverser::visitSwizzle(Visit, TIntermSwizzle *swizzleNode)
{
groupedTraverse(*swizzleNode->getOperand());
mSink << "." << swizzleNode->getOffsetsAsXYZW();
return false;
}
const char *GetOperatorString(TOperator op,
const TType &resultType,
const TType *argType0,
const TType *argType1,
const TType *argType2)
{
switch (op)
{
case TOperator::EOpComma:
// WGSL does not have a comma operator or any other way to implement "statement list as
// an expression", so nested expressions will have to be pulled out into statements.
UNIMPLEMENTED();
return "TODO_operator";
case TOperator::EOpAssign:
return "=";
case TOperator::EOpInitialize:
return "=";
// Compound assignments now exist: https://www.w3.org/TR/WGSL/#compound-assignment-sec
case TOperator::EOpAddAssign:
return "+=";
case TOperator::EOpSubAssign:
return "-=";
case TOperator::EOpMulAssign:
return "*=";
case TOperator::EOpDivAssign:
return "/=";
case TOperator::EOpIModAssign:
return "%=";
case TOperator::EOpBitShiftLeftAssign:
return "<<=";
case TOperator::EOpBitShiftRightAssign:
return ">>=";
case TOperator::EOpBitwiseAndAssign:
return "&=";
case TOperator::EOpBitwiseXorAssign:
return "^=";
case TOperator::EOpBitwiseOrAssign:
return "|=";
case TOperator::EOpAdd:
return "+";
case TOperator::EOpSub:
return "-";
case TOperator::EOpMul:
return "*";
case TOperator::EOpDiv:
return "/";
// TODO(anglebug.com/42267100): Works different from GLSL for negative numbers.
// https://github.com/gpuweb/gpuweb/discussions/2204#:~:text=not%20WGSL%3B%20etc.-,Inconsistent%20mod/%25%20operator,-At%20first%20glance
// GLSL does `x - y * floor(x/y)`, WGSL does x - y * trunc(x/y).
case TOperator::EOpIMod:
case TOperator::EOpMod:
return "%";
case TOperator::EOpBitShiftLeft:
return "<<";
case TOperator::EOpBitShiftRight:
return ">>";
case TOperator::EOpBitwiseAnd:
return "&";
case TOperator::EOpBitwiseXor:
return "^";
case TOperator::EOpBitwiseOr:
return "|";
case TOperator::EOpLessThan:
return "<";
case TOperator::EOpGreaterThan:
return ">";
case TOperator::EOpLessThanEqual:
return "<=";
case TOperator::EOpGreaterThanEqual:
return ">=";
// Component-wise comparisons are done with regular infix operators in WGSL:
// https://www.w3.org/TR/WGSL/#comparison-expr
case TOperator::EOpLessThanComponentWise:
return "<";
case TOperator::EOpLessThanEqualComponentWise:
return "<=";
case TOperator::EOpGreaterThanEqualComponentWise:
return ">=";
case TOperator::EOpGreaterThanComponentWise:
return ">";
case TOperator::EOpLogicalOr:
return "||";
// Logical XOR is only applied to boolean expressions so it's the same as "not equals".
// Neither short-circuits.
case TOperator::EOpLogicalXor:
return "!=";
case TOperator::EOpLogicalAnd:
return "&&";
case TOperator::EOpNegative:
return "-";
case TOperator::EOpPositive:
if (argType0->isMatrix())
{
return "";
}
return "+";
case TOperator::EOpLogicalNot:
return "!";
// Component-wise not done with normal prefix unary operator in WGSL:
// https://www.w3.org/TR/WGSL/#logical-expr
case TOperator::EOpNotComponentWise:
return "!";
case TOperator::EOpBitwiseNot:
return "~";
// TODO(anglebug.com/42267100): increment operations cannot be used as expressions in WGSL.
case TOperator::EOpPostIncrement:
return "++";
case TOperator::EOpPostDecrement:
return "--";
case TOperator::EOpPreIncrement:
case TOperator::EOpPreDecrement:
// TODO(anglebug.com/42267100): pre increments and decrements do not exist in WGSL.
UNIMPLEMENTED();
return "TODO_operator";
case TOperator::EOpVectorTimesScalarAssign:
return "*=";
case TOperator::EOpVectorTimesMatrixAssign:
return "*=";
case TOperator::EOpMatrixTimesScalarAssign:
return "*=";
case TOperator::EOpMatrixTimesMatrixAssign:
return "*=";
case TOperator::EOpVectorTimesScalar:
return "*";
case TOperator::EOpVectorTimesMatrix:
return "*";
case TOperator::EOpMatrixTimesVector:
return "*";
case TOperator::EOpMatrixTimesScalar:
return "*";
case TOperator::EOpMatrixTimesMatrix:
return "*";
case TOperator::EOpEqualComponentWise:
return "==";
case TOperator::EOpNotEqualComponentWise:
return "!=";
// TODO(anglebug.com/42267100): structs, matrices, and arrays are not comparable with WGSL's
// == or !=. Comparing vectors results in a component-wise comparison returning a boolean
// vector, which is different from GLSL (which use equal(vec, vec) for component-wise
// comparison)
case TOperator::EOpEqual:
if ((argType0->isVector() && argType1->isVector()) ||
(argType0->getStruct() && argType1->getStruct()) ||
(argType0->isArray() && argType1->isArray()) ||
(argType0->isMatrix() && argType1->isMatrix()))
{
UNIMPLEMENTED();
return "TODO_operator";
}
return "==";
case TOperator::EOpNotEqual:
if ((argType0->isVector() && argType1->isVector()) ||
(argType0->getStruct() && argType1->getStruct()) ||
(argType0->isArray() && argType1->isArray()) ||
(argType0->isMatrix() && argType1->isMatrix()))
{
UNIMPLEMENTED();
return "TODO_operator";
}
return "!=";
case TOperator::EOpKill:
case TOperator::EOpReturn:
case TOperator::EOpBreak:
case TOperator::EOpContinue:
// These should all be emitted in visitBranch().
UNREACHABLE();
return "UNREACHABLE_operator";
case TOperator::EOpRadians:
return "radians";
case TOperator::EOpDegrees:
return "degrees";
case TOperator::EOpAtan:
return argType1 == nullptr ? "atan" : "atan2";
case TOperator::EOpRefract:
return argType0->isVector() ? "refract" : "TODO_operator";
case TOperator::EOpDistance:
return "distance";
case TOperator::EOpLength:
return "length";
case TOperator::EOpDot:
return argType0->isVector() ? "dot" : "*";
case TOperator::EOpNormalize:
return argType0->isVector() ? "normalize" : "sign";
case TOperator::EOpFaceforward:
return argType0->isVector() ? "faceForward" : "TODO_Operator";
case TOperator::EOpReflect:
return argType0->isVector() ? "reflect" : "TODO_Operator";
case TOperator::EOpMatrixCompMult:
return "TODO_Operator";
case TOperator::EOpOuterProduct:
return "TODO_Operator";
case TOperator::EOpSign:
return "sign";
case TOperator::EOpAbs:
return "abs";
case TOperator::EOpAll:
return "all";
case TOperator::EOpAny:
return "any";
case TOperator::EOpSin:
return "sin";
case TOperator::EOpCos:
return "cos";
case TOperator::EOpTan:
return "tan";
case TOperator::EOpAsin:
return "asin";
case TOperator::EOpAcos:
return "acos";
case TOperator::EOpSinh:
return "sinh";
case TOperator::EOpCosh:
return "cosh";
case TOperator::EOpTanh:
return "tanh";
case TOperator::EOpAsinh:
return "asinh";
case TOperator::EOpAcosh:
return "acosh";
case TOperator::EOpAtanh:
return "atanh";
case TOperator::EOpFma:
return "fma";
// TODO(anglebug.com/42267100): Won't accept pow(vec<f32>, f32).
// https://github.com/gpuweb/gpuweb/discussions/2204#:~:text=Similarly%20pow(vec3%3Cf32%3E%2C%20f32)%20works%20in%20GLSL%20but%20not%20WGSL
case TOperator::EOpPow:
return "pow"; // GLSL's pow excludes negative x
case TOperator::EOpExp:
return "exp";
case TOperator::EOpExp2:
return "exp2";
case TOperator::EOpLog:
return "log";
case TOperator::EOpLog2:
return "log2";
case TOperator::EOpSqrt:
return "sqrt";
case TOperator::EOpFloor:
return "floor";
case TOperator::EOpTrunc:
return "trunc";
case TOperator::EOpCeil:
return "ceil";
case TOperator::EOpFract:
return "fract";
case TOperator::EOpMin:
return "min";
case TOperator::EOpMax:
return "max";
case TOperator::EOpRound:
return "round"; // TODO(anglebug.com/42267100): this is wrong and must round away from
// zero if there is a tie. This always rounds to the even number.
case TOperator::EOpRoundEven:
return "round";
// TODO(anglebug.com/42267100):
// https://github.com/gpuweb/gpuweb/discussions/2204#:~:text=clamp(vec2%3Cf32%3E%2C%20f32%2C%20f32)%20works%20in%20GLSL%20but%20not%20WGSL%3B%20etc.
// Need to expand clamp(vec<f32>, low : f32, high : f32) ->
// clamp(vec<f32>, vec<f32>(low), vec<f32>(high))
case TOperator::EOpClamp:
return "clamp";
case TOperator::EOpSaturate:
return "saturate";
case TOperator::EOpMix:
if (!argType1->isScalar() && argType2 && argType2->getBasicType() == EbtBool)
{
return "TODO_Operator";
}
return "mix";
case TOperator::EOpStep:
return "step";
case TOperator::EOpSmoothstep:
return "smoothstep";
case TOperator::EOpModf:
UNIMPLEMENTED(); // TODO(anglebug.com/42267100): in WGSL this returns a struct, GLSL it
// uses a return value and an outparam
return "modf";
case TOperator::EOpIsnan:
case TOperator::EOpIsinf:
UNIMPLEMENTED(); // TODO(anglebug.com/42267100): WGSL does not allow NaNs or infinity.
// What to do about shaders that require this?
// Implementations are allowed to assume overflow, infinities, and NaNs are not present
// at runtime, however. https://www.w3.org/TR/WGSL/#floating-point-evaluation
return "TODO_Operator";
case TOperator::EOpLdexp:
// TODO(anglebug.com/42267100): won't accept first arg vector, second arg scalar
return "ldexp";
case TOperator::EOpFrexp:
return "frexp"; // TODO(anglebug.com/42267100): returns a struct
case TOperator::EOpInversesqrt:
return "inverseSqrt";
case TOperator::EOpCross:
return "cross";
// TODO(anglebug.com/42267100): are these the same? dpdxCoarse() vs dpdxFine()?
case TOperator::EOpDFdx:
return "dpdx";
case TOperator::EOpDFdy:
return "dpdy";
case TOperator::EOpFwidth:
return "fwidth";
case TOperator::EOpTranspose:
return "transpose";
case TOperator::EOpDeterminant:
return "determinant";
case TOperator::EOpInverse:
return "TODO_Operator"; // No builtin invert().
// https://github.com/gpuweb/gpuweb/issues/4115
// TODO(anglebug.com/42267100): these interpolateAt*() are not builtin
case TOperator::EOpInterpolateAtCentroid:
return "TODO_Operator";
case TOperator::EOpInterpolateAtSample:
return "TODO_Operator";
case TOperator::EOpInterpolateAtOffset:
return "TODO_Operator";
case TOperator::EOpInterpolateAtCenter:
return "TODO_Operator";
case TOperator::EOpFloatBitsToInt:
case TOperator::EOpFloatBitsToUint:
case TOperator::EOpIntBitsToFloat:
case TOperator::EOpUintBitsToFloat:
{
#define BITCAST_SCALAR() \
do \
switch (resultType.getBasicType()) \
{ \
case TBasicType::EbtInt: \
return "bitcast<i32>"; \
case TBasicType::EbtUInt: \
return "bitcast<u32>"; \
case TBasicType::EbtFloat: \
return "bitcast<f32>"; \
default: \
UNIMPLEMENTED(); \
return "TOperator_TODO"; \
} \
while (false)
#define BITCAST_VECTOR(vecSize) \
do \
switch (resultType.getBasicType()) \
{ \
case TBasicType::EbtInt: \
return "bitcast<vec" vecSize "<i32>>"; \
case TBasicType::EbtUInt: \
return "bitcast<vec" vecSize "<u32>>"; \
case TBasicType::EbtFloat: \
return "bitcast<vec" vecSize "<f32>>"; \
default: \
UNIMPLEMENTED(); \
return "TOperator_TODO"; \
} \
while (false)
if (resultType.isScalar())
{
BITCAST_SCALAR();
}
else if (resultType.isVector())
{
switch (resultType.getNominalSize())
{
case 2:
BITCAST_VECTOR("2");
case 3:
BITCAST_VECTOR("3");
case 4:
BITCAST_VECTOR("4");
default:
UNREACHABLE();
return nullptr;
}
}
else
{
UNIMPLEMENTED();
return "TOperator_TODO";
}
#undef BITCAST_SCALAR
#undef BITCAST_VECTOR
}
case TOperator::EOpPackUnorm2x16:
return "pack2x16unorm";
case TOperator::EOpPackSnorm2x16:
return "pack2x16snorm";
case TOperator::EOpPackUnorm4x8:
return "pack4x8unorm";
case TOperator::EOpPackSnorm4x8:
return "pack4x8snorm";
case TOperator::EOpUnpackUnorm2x16:
return "unpack2x16unorm";
case TOperator::EOpUnpackSnorm2x16:
return "unpack2x16snorm";
case TOperator::EOpUnpackUnorm4x8:
return "unpack4x8unorm";
case TOperator::EOpUnpackSnorm4x8:
return "unpack4x8snorm";
case TOperator::EOpPackHalf2x16:
return "pack2x16float";
case TOperator::EOpUnpackHalf2x16:
return "unpack2x16float";
case TOperator::EOpBarrier:
UNREACHABLE();
return "TOperator_TODO";
case TOperator::EOpMemoryBarrier:
// TODO(anglebug.com/42267100): does this exist in WGPU? Device-scoped memory barrier?
// Maybe storageBarrier()?
UNREACHABLE();
return "TOperator_TODO";
case TOperator::EOpGroupMemoryBarrier:
return "workgroupBarrier";
case TOperator::EOpMemoryBarrierAtomicCounter:
case TOperator::EOpMemoryBarrierBuffer:
case TOperator::EOpMemoryBarrierShared:
UNREACHABLE();
return "TOperator_TODO";
case TOperator::EOpAtomicAdd:
return "atomicAdd";
case TOperator::EOpAtomicMin:
return "atomicMin";
case TOperator::EOpAtomicMax:
return "atomicMax";
case TOperator::EOpAtomicAnd:
return "atomicAnd";
case TOperator::EOpAtomicOr:
return "atomicOr";
case TOperator::EOpAtomicXor:
return "atomicXor";
case TOperator::EOpAtomicExchange:
return "atomicExchange";
case TOperator::EOpAtomicCompSwap:
return "atomicCompareExchangeWeak"; // TODO(anglebug.com/42267100): returns a struct.
case TOperator::EOpBitfieldExtract:
case TOperator::EOpBitfieldInsert:
case TOperator::EOpBitfieldReverse:
case TOperator::EOpBitCount:
case TOperator::EOpFindLSB:
case TOperator::EOpFindMSB:
case TOperator::EOpUaddCarry:
case TOperator::EOpUsubBorrow:
case TOperator::EOpUmulExtended:
case TOperator::EOpImulExtended:
case TOperator::EOpEmitVertex:
case TOperator::EOpEndPrimitive:
case TOperator::EOpArrayLength:
UNIMPLEMENTED();
return "TOperator_TODO";
case TOperator::EOpNull:
case TOperator::EOpConstruct:
case TOperator::EOpCallFunctionInAST:
case TOperator::EOpCallInternalRawFunction:
case TOperator::EOpIndexDirect:
case TOperator::EOpIndexIndirect:
case TOperator::EOpIndexDirectStruct:
case TOperator::EOpIndexDirectInterfaceBlock:
UNREACHABLE();
return nullptr;
default:
// Any other built-in function.
return nullptr;
}
}
bool IsSymbolicOperator(TOperator op,
const TType &resultType,
const TType *argType0,
const TType *argType1)
{
const char *operatorString = GetOperatorString(op, resultType, argType0, argType1, nullptr);
if (operatorString == nullptr)
{
return false;
}
return !std::isalnum(operatorString[0]);
}
const TField &OutputWGSLTraverser::getDirectField(const TIntermTyped &fieldsNode,
TIntermTyped &indexNode)
{
const TType &fieldsType = fieldsNode.getType();
const TFieldListCollection *fieldListCollection = fieldsType.getStruct();
if (fieldListCollection == nullptr)
{
fieldListCollection = fieldsType.getInterfaceBlock();
}
ASSERT(fieldListCollection);
const TIntermConstantUnion *indexNodeAsConstantUnion = indexNode.getAsConstantUnion();
ASSERT(indexNodeAsConstantUnion);
const TConstantUnion &index = *indexNodeAsConstantUnion->getConstantValue();
ASSERT(index.getType() == TBasicType::EbtInt);
const TFieldList &fieldList = fieldListCollection->fields();
const int indexVal = index.getIConst();
const TField &field = *fieldList[indexVal];
return field;
}
void OutputWGSLTraverser::emitArrayIndex(TIntermTyped &leftNode, TIntermTyped &rightNode)
{
TType leftType = leftNode.getType();
// Some arrays within the uniform address space have their element types wrapped in a struct
// when generating WGSL, so this unwraps the element (as an optimization of converting the
// entire array back to the unwrapped type).
bool needsUnwrapping = false;
bool isUniformMatrixNeedingConversion = false;
TIntermBinary *leftNodeBinary = leftNode.getAsBinaryNode();
if (leftNodeBinary && leftNodeBinary->getOp() == TOperator::EOpIndexDirectStruct)
{
const TStructure *structure = leftNodeBinary->getLeft()->getType().getStruct();
bool isInUniformAddressSpace =
mUniformBlockMetadata->structsInUniformAddressSpace.count(structure->uniqueId().get());
needsUnwrapping =
structure && ElementTypeNeedsUniformWrapperStruct(isInUniformAddressSpace, &leftType);
isUniformMatrixNeedingConversion = isInUniformAddressSpace && IsMatCx2(&leftType);
ASSERT(!needsUnwrapping || !isUniformMatrixNeedingConversion);
}
// Emit the left side, which should be of type array.
if (needsUnwrapping || isUniformMatrixNeedingConversion)
{
if (isUniformMatrixNeedingConversion)
{
// If this array index expression is yielding an std140 matCx2 (i.e.
// array<ANGLE_wrapped_vec2, C>), just convert the entire expression to a WGSL matCx2,
// instead of converting the entire array of std140 matCx2s into an array of WGSL
// matCx2s and then indexing into it.
TType baseType = leftType;
baseType.toArrayBaseType();
mSink << MakeMatCx2ConversionFunctionName(&baseType) << "(";
// Make sure the conversion function referenced here is actually generated in the
// resulting WGSL.
mWGSLGenerationMetadataForUniforms->outputMatCx2Conversion.insert(baseType);
}
emitStructIndexNoUnwrapping(leftNodeBinary);
}
else
{
groupedTraverse(leftNode);
}
mSink << "[";
const TConstantUnion *constIndex = rightNode.getConstantValue();
// If the array index is a constant that we can statically verify is within array
// bounds, just emit that constant.
if (!leftType.isUnsizedArray() && constIndex != nullptr && constIndex->getType() == EbtInt &&
constIndex->getIConst() >= 0 &&
constIndex->getIConst() < static_cast<int>(leftType.isArray()
? leftType.getOutermostArraySize()
: leftType.getNominalSize()))
{
emitSingleConstant(constIndex);
}
else
{
// If the array index is not a constant within the bounds of the array, clamp the
// index.
mSink << "clamp(";
groupedTraverse(rightNode);
mSink << ", 0, ";
// Now find the array size and clamp it.
if (leftType.isUnsizedArray())
{
// TODO(anglebug.com/42267100): This is a bug to traverse the `leftNode` a
// second time if `leftNode` has side effects (and could also have performance
// implications). This should be stored in a temporary variable. This might also
// be a bug in the MSL shader compiler.
mSink << "arrayLength(&";
groupedTraverse(leftNode);
mSink << ")";
}
else
{
uint32_t maxSize;
if (leftType.isArray())
{
maxSize = leftType.getOutermostArraySize() - 1;
}
else
{
maxSize = leftType.getNominalSize() - 1;
}
mSink << maxSize;
}
// End the clamp() function.
mSink << ")";
}
// End the array index operation.
mSink << "]";
if (needsUnwrapping)
{
mSink << "." << kWrappedStructFieldName;
}
else if (isUniformMatrixNeedingConversion)
{
// Close conversion function call
mSink << ")";
}
}
void OutputWGSLTraverser::emitStructIndex(TIntermBinary *binaryNode)
{
ASSERT(binaryNode->getOp() == TOperator::EOpIndexDirectStruct);
TIntermTyped &leftNode = *binaryNode->getLeft();
const TType *binaryNodeType = &binaryNode->getType();
const TStructure *structure = leftNode.getType().getStruct();
ASSERT(structure);
bool isInUniformAddressSpace =
mUniformBlockMetadata->structsInUniformAddressSpace.count(structure->uniqueId().get());
bool isUniformMatrixNeedingConversion = isInUniformAddressSpace && IsMatCx2(binaryNodeType);
bool needsUnwrapping =
ElementTypeNeedsUniformWrapperStruct(isInUniformAddressSpace, binaryNodeType);
if (needsUnwrapping)
{
ASSERT(!isUniformMatrixNeedingConversion);
mSink << MakeUnwrappingArrayConversionFunctionName(&binaryNode->getType()) << "(";
// Make sure the conversion function referenced here is actually generated in the resulting
// WGSL.
mWGSLGenerationMetadataForUniforms->arrayElementTypesThatNeedUnwrappingConversions.insert(
*binaryNodeType);
}
else if (isUniformMatrixNeedingConversion)
{
mSink << MakeMatCx2ConversionFunctionName(binaryNodeType) << "(";
// Make sure the conversion function referenced here is actually generated in the resulting
// WGSL.
mWGSLGenerationMetadataForUniforms->outputMatCx2Conversion.insert(*binaryNodeType);
}
emitStructIndexNoUnwrapping(binaryNode);
if (needsUnwrapping || isUniformMatrixNeedingConversion)
{
mSink << ")";
}
}
void OutputWGSLTraverser::emitStructIndexNoUnwrapping(TIntermBinary *binaryNode)
{
ASSERT(binaryNode->getOp() == TOperator::EOpIndexDirectStruct);
TIntermTyped &leftNode = *binaryNode->getLeft();
TIntermTyped &rightNode = *binaryNode->getRight();
groupedTraverse(leftNode);
mSink << ".";
WriteNameOf(mSink, getDirectField(leftNode, rightNode));
}
bool OutputWGSLTraverser::visitBinary(Visit, TIntermBinary *binaryNode)
{
const TOperator op = binaryNode->getOp();
TIntermTyped &leftNode = *binaryNode->getLeft();
TIntermTyped &rightNode = *binaryNode->getRight();
switch (op)
{
case TOperator::EOpIndexDirectStruct:
case TOperator::EOpIndexDirectInterfaceBlock:
emitStructIndex(binaryNode);
break;
case TOperator::EOpIndexDirect:
case TOperator::EOpIndexIndirect:
emitArrayIndex(leftNode, rightNode);
break;
default:
{
const TType &resultType = binaryNode->getType();
const TType &leftType = leftNode.getType();
const TType &rightType = rightNode.getType();
// x * y, x ^ y, etc.
if (IsSymbolicOperator(op, resultType, &leftType, &rightType))
{
groupedTraverse(leftNode);
if (op != TOperator::EOpComma)
{
mSink << " ";
}
mSink << GetOperatorString(op, resultType, &leftType, &rightType, nullptr) << " ";
groupedTraverse(rightNode);
}
// E.g. builtin function calls
else
{
mSink << GetOperatorString(op, resultType, &leftType, &rightType, nullptr) << "(";
leftNode.traverse(this);
mSink << ", ";
rightNode.traverse(this);
mSink << ")";
}
}
}
return false;
}
bool IsPostfix(TOperator op)
{
switch (op)
{
case TOperator::EOpPostIncrement:
case TOperator::EOpPostDecrement:
return true;
default:
return false;
}
}
bool OutputWGSLTraverser::visitUnary(Visit, TIntermUnary *unaryNode)
{
const TOperator op = unaryNode->getOp();
const TType &resultType = unaryNode->getType();
TIntermTyped &arg = *unaryNode->getOperand();
const TType &argType = arg.getType();
const char *name = GetOperatorString(op, resultType, &argType, nullptr, nullptr);
// Examples: -x, ~x, ~x
if (IsSymbolicOperator(op, resultType, &argType, nullptr))
{
const bool postfix = IsPostfix(op);
if (!postfix)
{
mSink << name;
}
groupedTraverse(arg);
if (postfix)
{
mSink << name;
}
}
else
{
mSink << name << "(";
arg.traverse(this);
mSink << ")";
}
return false;
}
bool OutputWGSLTraverser::visitTernary(Visit, TIntermTernary *conditionalNode)
{
// WGSL does not have a ternary. https://github.com/gpuweb/gpuweb/issues/3747
// The select() builtin is not short circuiting. Maybe we can get if () {} else {} as an
// expression, which would also solve the comma operator problem.
// TODO(anglebug.com/42267100): as mentioned above this is not correct if the operands have side
// effects. Even if they don't have side effects it could have performance implications.
// It also doesn't work with all types that ternaries do, e.g. arrays or structs.
mSink << "select(";
groupedTraverse(*conditionalNode->getFalseExpression());
mSink << ", ";
groupedTraverse(*conditionalNode->getTrueExpression());
mSink << ", ";
groupedTraverse(*conditionalNode->getCondition());
mSink << ")";
return false;
}
bool OutputWGSLTraverser::visitIfElse(Visit, TIntermIfElse *ifThenElseNode)
{
TIntermTyped &condNode = *ifThenElseNode->getCondition();
TIntermBlock *thenNode = ifThenElseNode->getTrueBlock();
TIntermBlock *elseNode = ifThenElseNode->getFalseBlock();
mSink << "if (";
condNode.traverse(this);
mSink << ")";
if (thenNode)
{
mSink << "\n";
thenNode->traverse(this);
}
else
{
mSink << " {}";
}
if (elseNode)
{
mSink << "\n";
emitIndentation();
mSink << "else\n";
elseNode->traverse(this);
}
return false;
}
bool OutputWGSLTraverser::visitSwitch(Visit, TIntermSwitch *switchNode)
{
TIntermBlock &stmtList = *switchNode->getStatementList();
emitIndentation();
mSink << "switch ";
switchNode->getInit()->traverse(this);
mSink << "\n";
emitOpenBrace();
// TODO(anglebug.com/42267100): Case statements that fall through need to combined into a single
// case statement with multiple labels.
const size_t stmtCount = stmtList.getChildCount();
bool inCaseList = false;
size_t currStmt = 0;
while (currStmt < stmtCount)
{
TIntermNode &stmtNode = *stmtList.getChildNode(currStmt);
TIntermCase *caseNode = stmtNode.getAsCaseNode();
if (caseNode)
{
if (inCaseList)
{
mSink << ", ";
}
else
{
emitIndentation();
mSink << "case ";
inCaseList = true;
}
caseNode->traverse(this);
// Process the next statement.
currStmt++;
}
else
{
// The current statement is not a case statement, end the current case list and emit all
// the code until the next case statement. WGSL requires braces around the case
// statement's code.
ASSERT(inCaseList);
inCaseList = false;
mSink << ":\n";
// Count the statements until the next case (or the end of the switch) and emit them as
// a block. This assumes that the current statement list will never fallthrough to the
// next case statement.
size_t nextCaseStmt = currStmt + 1;
for (;
nextCaseStmt < stmtCount && !stmtList.getChildNode(nextCaseStmt)->getAsCaseNode();
nextCaseStmt++)
{
}
angle::Span<TIntermNode *> stmtListView(&stmtList.getSequence()->at(currStmt),
nextCaseStmt - currStmt);
emitBlock(stmtListView);
mSink << "\n";
// Skip to the next case statement.
currStmt = nextCaseStmt;
}
}
emitCloseBrace();
return false;
}
bool OutputWGSLTraverser::visitCase(Visit, TIntermCase *caseNode)
{
// "case" will have been emitted in the visitSwitch() override.
if (caseNode->hasCondition())
{
TIntermTyped *condExpr = caseNode->getCondition();
condExpr->traverse(this);
}
else
{
mSink << "default";
}
return false;
}
void OutputWGSLTraverser::emitFunctionReturn(const TFunction &func)
{
const TType &returnType = func.getReturnType();
if (returnType.getBasicType() == EbtVoid)
{
return;
}
mSink << " -> ";
emitType(returnType);
}
// TODO(anglebug.com/42267100): Function overloads are not supported in WGSL, so function names
// should either be emitted mangled or overloaded functions should be renamed in the AST as a
// pre-pass. As of Apr 2024, WGSL function overloads are "not coming soon"
// (https://github.com/gpuweb/gpuweb/issues/876).
void OutputWGSLTraverser::emitFunctionSignature(const TFunction &func)
{
mSink << "fn ";
WriteNameOf(mSink, func);
mSink << "(";
bool emitComma = false;
const size_t paramCount = func.getParamCount();
for (size_t i = 0; i < paramCount; ++i)
{
if (emitComma)
{
mSink << ", ";
}
emitComma = true;
const TVariable ¶m = *func.getParam(i);
emitFunctionParameter(func, param);
}
mSink << ")";
emitFunctionReturn(func);
}
void OutputWGSLTraverser::emitFunctionParameter(const TFunction &func, const TVariable ¶m)
{
// TODO(anglebug.com/42267100): function parameters are immutable and will need to be renamed if
// they are mutated.
EmitVariableDeclarationConfig evdConfig;
evdConfig.isParameter = true;
emitVariableDeclaration({param.symbolType(), param.name(), param.getType()}, evdConfig);
}
void OutputWGSLTraverser::visitFunctionPrototype(TIntermFunctionPrototype *funcProtoNode)
{
const TFunction &func = *funcProtoNode->getFunction();
emitIndentation();
// TODO(anglebug.com/42267100): output correct signature for main() if main() is declared as a
// function prototype, or perhaps just emit nothing.
emitFunctionSignature(func);
}
bool OutputWGSLTraverser::visitFunctionDefinition(Visit, TIntermFunctionDefinition *funcDefNode)
{
const TFunction &func = *funcDefNode->getFunction();
TIntermBlock &body = *funcDefNode->getBody();
emitIndentation();
emitFunctionSignature(func);
mSink << "\n";
body.traverse(this);
return false;
}
bool OutputWGSLTraverser::visitAggregate(Visit, TIntermAggregate *aggregateNode)
{
const TIntermSequence &args = *aggregateNode->getSequence();
auto emitArgList = [&]() {
mSink << "(";
bool emitComma = false;
for (TIntermNode *arg : args)
{
if (emitComma)
{
mSink << ", ";
}
emitComma = true;
arg->traverse(this);
}
mSink << ")";
};
const TType &retType = aggregateNode->getType();
if (aggregateNode->isConstructor())
{
emitType(retType);
emitArgList();
return false;
}
else
{
const TOperator op = aggregateNode->getOp();
switch (op)
{
case TOperator::EOpCallFunctionInAST:
WriteNameOf(mSink, *aggregateNode->getFunction());
emitArgList();
return false;
default:
// Do not allow raw function calls, i.e. calls to functions
// not present in the AST.
ASSERT(op != TOperator::EOpCallInternalRawFunction);
auto getArgType = [&](size_t index) -> const TType * {
if (index < args.size())
{
TIntermTyped *arg = args[index]->getAsTyped();
ASSERT(arg);
return &arg->getType();
}
return nullptr;
};
const TType *argType0 = getArgType(0);
const TType *argType1 = getArgType(1);
const TType *argType2 = getArgType(2);
const char *opName = GetOperatorString(op, retType, argType0, argType1, argType2);
if (IsSymbolicOperator(op, retType, argType0, argType1))
{
switch (args.size())
{
case 1:
{
TIntermNode &operandNode = *aggregateNode->getChildNode(0);
if (IsPostfix(op))
{
mSink << opName;
groupedTraverse(operandNode);
}
else
{
groupedTraverse(operandNode);
mSink << opName;
}
return false;
}
case 2:
{
// symbolic operators with 2 args are emitted with infix notation.
TIntermNode &leftNode = *aggregateNode->getChildNode(0);
TIntermNode &rightNode = *aggregateNode->getChildNode(1);
groupedTraverse(leftNode);
mSink << " " << opName << " ";
groupedTraverse(rightNode);
return false;
}
default:
UNREACHABLE();
return false;
}
}
else
{
// If the operator is not symbolic then it is a builtin that uses function call
// syntax: builtin(arg1, arg2, ..);
mSink << (opName == nullptr ? "TODO_Operator" : opName);
emitArgList();
return false;
}
}
}
}
bool OutputWGSLTraverser::emitBlock(angle::Span<TIntermNode *> nodes)
{
ASSERT(mIndentLevel >= -1);
const bool isGlobalScope = mIndentLevel == -1;
if (isGlobalScope)
{
++mIndentLevel;
}
else
{
emitOpenBrace();
}
TIntermNode *prevStmtNode = nullptr;
const size_t stmtCount = nodes.size();
for (size_t i = 0; i < stmtCount; ++i)
{
TIntermNode &stmtNode = *nodes[i];
if (isGlobalScope && prevStmtNode && (NewlinePad(*prevStmtNode) || NewlinePad(stmtNode)))
{
mSink << "\n";
}
const bool isCase = stmtNode.getAsCaseNode();
mIndentLevel -= isCase;
emitIndentation();
mIndentLevel += isCase;
stmtNode.traverse(this);
if (RequiresSemicolonTerminator(stmtNode))
{
mSink << ";";
}
mSink << "\n";
prevStmtNode = &stmtNode;
}
if (isGlobalScope)
{
ASSERT(mIndentLevel == 0);
--mIndentLevel;
}
else
{
emitCloseBrace();
}
return false;
}
bool OutputWGSLTraverser::visitBlock(Visit, TIntermBlock *blockNode)
{
return emitBlock(
angle::Span(blockNode->getSequence()->data(), blockNode->getSequence()->size()));
}
bool OutputWGSLTraverser::visitGlobalQualifierDeclaration(Visit,
TIntermGlobalQualifierDeclaration *)
{
return false;
}
void OutputWGSLTraverser::emitStructDeclaration(const TType &type)
{
ASSERT(type.getBasicType() == TBasicType::EbtStruct);
ASSERT(type.isStructSpecifier());
mSink << "struct ";
emitBareTypeName(type);
mSink << "\n";
emitOpenBrace();
const TStructure &structure = *type.getStruct();
bool isInUniformAddressSpace =
mUniformBlockMetadata->structsInUniformAddressSpace.count(structure.uniqueId().get()) != 0;
bool alignTo16InUniformAddressSpace = true;
for (const TField *field : structure.fields())
{
const TType *fieldType = field->type();
emitIndentation();
// If this struct is used in the uniform address space, it must obey the uniform address
// space's layout constaints (https://www.w3.org/TR/WGSL/#address-space-layout-constraints).
// WGSL's address space layout constraints nearly match std140, and the places they don't
// are handled elsewhere.
if (isInUniformAddressSpace)
{
// Here, the field must be aligned to 16 if:
// 1. The field is a struct or array (note that matCx2 is represented as an array of
// vec2)
// 2. The previous field is a struct
// 3. The field is the first in the struct (for convenience).
if (field->type()->getStruct() || fieldType->isArray() || IsMatCx2(fieldType))
{
alignTo16InUniformAddressSpace = true;
}
if (alignTo16InUniformAddressSpace)
{
mSink << "@align(16) ";
}
// If this field is a struct, the next member should be aligned to 16.
alignTo16InUniformAddressSpace = fieldType->getStruct();
// If the field is an array whose stride is not aligned to 16, the element type must be
// emitted with a wrapper struct. Record that the wrapper struct needs to be emitted.
// Note that if the array element type is already of struct type, it doesn't need
// another wrapper struct, it will automatically be aligned to 16 because its first
// member is aligned to 16 (implemented above).
if (ElementTypeNeedsUniformWrapperStruct(/*inUniformAddressSpace=*/true, fieldType))
{
TType innerType = *fieldType;
innerType.toArrayElementType();
// Multidimensional arrays not currently supported in uniforms in the WebGPU backend
ASSERT(!innerType.isArray());
mWGSLGenerationMetadataForUniforms->arrayElementTypesInUniforms.insert(innerType);
}
}
// TODO(anglebug.com/42267100): emit qualifiers.
EmitVariableDeclarationConfig evdConfig;
evdConfig.typeConfig.addressSpace =
isInUniformAddressSpace ? WgslAddressSpace::Uniform : WgslAddressSpace::NonUniform;
evdConfig.disableStructSpecifier = true;
emitVariableDeclaration({field->symbolType(), field->name(), *fieldType}, evdConfig);
mSink << ",\n";
}
emitCloseBrace();
}
void OutputWGSLTraverser::emitVariableDeclaration(const VarDecl &decl,
const EmitVariableDeclarationConfig &evdConfig)
{
const TBasicType basicType = decl.type.getBasicType();
if (decl.type.getQualifier() == EvqUniform)
{
// Uniforms are declared in a pre-pass, and don't need to be outputted here.
return;
}
if (basicType == TBasicType::EbtStruct && decl.type.isStructSpecifier() &&
!evdConfig.disableStructSpecifier)
{
// TODO(anglebug.com/42267100): in WGSL structs probably can't be declared in
// function parameters or in uniform declarations or in variable declarations, or
// anonymously either within other structs or within a variable declaration. Handle
// these with the same AST pre-passes as other shader translators.
ASSERT(!evdConfig.isParameter);
emitStructDeclaration(decl.type);
if (decl.symbolType != SymbolType::Empty)
{
mSink << " ";
emitNameOf(decl);
}
return;
}
ASSERT(basicType == TBasicType::EbtStruct || decl.symbolType != SymbolType::Empty ||
evdConfig.isParameter);
if (evdConfig.needsVar)
{
// "const" and "let" probably don't need to be ever emitted because they are more for
// readability, and the GLSL compiler constant folds most (all?) the consts anyway.
mSink << "var";
// TODO(anglebug.com/42267100): <workgroup> or <storage>?
if (evdConfig.isGlobalScope)
{
if (decl.type.getQualifier() == EvqUniform)
{
ASSERT(IsOpaqueType(decl.type.getBasicType()));
mSink << "<uniform>";
}
else
{
mSink << "<private>";
}
}
mSink << " ";
}
else
{
ASSERT(!evdConfig.isGlobalScope);
}
if (decl.symbolType != SymbolType::Empty)
{
emitNameOf(decl);
}
mSink << " : ";
WriteWgslType(mSink, decl.type, evdConfig.typeConfig);
}
bool OutputWGSLTraverser::visitDeclaration(Visit, TIntermDeclaration *declNode)
{
ASSERT(declNode->getChildCount() == 1);
TIntermNode &node = *declNode->getChildNode(0);
EmitVariableDeclarationConfig evdConfig;
evdConfig.needsVar = true;
evdConfig.isGlobalScope = mIndentLevel == 0;
if (TIntermSymbol *symbolNode = node.getAsSymbolNode())
{
const TVariable &var = symbolNode->variable();
if (mRewritePipelineVarOutput->IsInputVar(var.uniqueId()) ||
mRewritePipelineVarOutput->IsOutputVar(var.uniqueId()))
{
// Some variables, like shader inputs/outputs/builtins, are declared in the WGSL source
// outside of the traverser.
return false;
}
emitVariableDeclaration({var.symbolType(), var.name(), var.getType()}, evdConfig);
}
else if (TIntermBinary *initNode = node.getAsBinaryNode())
{
ASSERT(initNode->getOp() == TOperator::EOpInitialize);
TIntermSymbol *leftSymbolNode = initNode->getLeft()->getAsSymbolNode();
TIntermTyped *valueNode = initNode->getRight()->getAsTyped();
ASSERT(leftSymbolNode && valueNode);
const TVariable &var = leftSymbolNode->variable();
if (mRewritePipelineVarOutput->IsInputVar(var.uniqueId()) ||
mRewritePipelineVarOutput->IsOutputVar(var.uniqueId()))
{
// Some variables, like shader inputs/outputs/builtins, are declared in the WGSL source
// outside of the traverser.
return false;
}
emitVariableDeclaration({var.symbolType(), var.name(), var.getType()}, evdConfig);
mSink << " = ";
groupedTraverse(*valueNode);
}
else
{
UNREACHABLE();
}
return false;
}
bool OutputWGSLTraverser::visitLoop(Visit, TIntermLoop *loopNode)
{
const TLoopType loopType = loopNode->getType();
switch (loopType)
{
case TLoopType::ELoopFor:
return emitForLoop(loopNode);
case TLoopType::ELoopWhile:
return emitWhileLoop(loopNode);
case TLoopType::ELoopDoWhile:
return emulateDoWhileLoop(loopNode);
}
}
bool OutputWGSLTraverser::emitForLoop(TIntermLoop *loopNode)
{
ASSERT(loopNode->getType() == TLoopType::ELoopFor);
TIntermNode *initNode = loopNode->getInit();
TIntermTyped *condNode = loopNode->getCondition();
TIntermTyped *exprNode = loopNode->getExpression();
mSink << "for (";
if (initNode)
{
initNode->traverse(this);
}
else
{
mSink << " ";
}
mSink << "; ";
if (condNode)
{
condNode->traverse(this);
}
mSink << "; ";
if (exprNode)
{
exprNode->traverse(this);
}
mSink << ")\n";
loopNode->getBody()->traverse(this);
return false;
}
bool OutputWGSLTraverser::emitWhileLoop(TIntermLoop *loopNode)
{
ASSERT(loopNode->getType() == TLoopType::ELoopWhile);
TIntermNode *initNode = loopNode->getInit();
TIntermTyped *condNode = loopNode->getCondition();
TIntermTyped *exprNode = loopNode->getExpression();
ASSERT(condNode);
ASSERT(!initNode && !exprNode);
emitIndentation();
mSink << "while (";
condNode->traverse(this);
mSink << ")\n";
loopNode->getBody()->traverse(this);
return false;
}
bool OutputWGSLTraverser::emulateDoWhileLoop(TIntermLoop *loopNode)
{
ASSERT(loopNode->getType() == TLoopType::ELoopDoWhile);
TIntermNode *initNode = loopNode->getInit();
TIntermTyped *condNode = loopNode->getCondition();
TIntermTyped *exprNode = loopNode->getExpression();
ASSERT(condNode);
ASSERT(!initNode && !exprNode);
emitIndentation();
// Write an infinite loop.
mSink << "loop {\n";
mIndentLevel++;
loopNode->getBody()->traverse(this);
mSink << "\n";
emitIndentation();
// At the end of the loop, break if the loop condition dos not still hold.
mSink << "if (!(";
condNode->traverse(this);
mSink << ") { break; }\n";
mIndentLevel--;
emitIndentation();
mSink << "}";
return false;
}
bool OutputWGSLTraverser::visitBranch(Visit, TIntermBranch *branchNode)
{
const TOperator flowOp = branchNode->getFlowOp();
TIntermTyped *exprNode = branchNode->getExpression();
emitIndentation();
switch (flowOp)
{
case TOperator::EOpKill:
{
ASSERT(exprNode == nullptr);
mSink << "discard";
}
break;
case TOperator::EOpReturn:
{
mSink << "return";
if (exprNode)
{
mSink << " ";
exprNode->traverse(this);
}
}
break;
case TOperator::EOpBreak:
{
ASSERT(exprNode == nullptr);
mSink << "break";
}
break;
case TOperator::EOpContinue:
{
ASSERT(exprNode == nullptr);
mSink << "continue";
}
break;
default:
{
UNREACHABLE();
}
}
return false;
}
void OutputWGSLTraverser::visitPreprocessorDirective(TIntermPreprocessorDirective *node)
{
// No preprocessor directives expected at this point.
UNREACHABLE();
}
void OutputWGSLTraverser::emitBareTypeName(const TType &type)
{
WriteWgslBareTypeName(mSink, type, {});
}
void OutputWGSLTraverser::emitType(const TType &type)
{
WriteWgslType(mSink, type, {});
}
} // namespace
TranslatorWGSL::TranslatorWGSL(sh::GLenum type, ShShaderSpec spec, ShShaderOutput output)
: TCompiler(type, spec, output)
{}
bool TranslatorWGSL::preTranslateTreeModifications(TIntermBlock *root)
{
int aggregateTypesUsedForUniforms = 0;
for (const auto &uniform : getUniforms())
{
if (uniform.isStruct() || uniform.isArrayOfArrays())
{
++aggregateTypesUsedForUniforms;
}
}
// Samplers are legal as function parameters, but samplers within structs or arrays are not
// allowed in WGSL
// (https://www.w3.org/TR/WGSL/#function-call-expr:~:text=A%20function%20parameter,a%20sampler%20type).
// TODO(anglebug.com/389145696): handle arrays of samplers here.
// If there are any function calls that take array-of-array of opaque uniform parameters, or
// other opaque uniforms that need special handling in WebGPU, monomorphize the functions by
// removing said parameters and replacing them in the function body with the call arguments.
//
// This dramatically simplifies future transformations w.r.t to samplers in structs, array of
// arrays of opaque types, atomic counters etc.
UnsupportedFunctionArgsBitSet args{UnsupportedFunctionArgs::StructContainingSamplers,
UnsupportedFunctionArgs::ArrayOfArrayOfSamplerOrImage,
UnsupportedFunctionArgs::AtomicCounter,
UnsupportedFunctionArgs::Image};
if (!MonomorphizeUnsupportedFunctions(this, root, &getSymbolTable(), args))
{
return false;
}
if (aggregateTypesUsedForUniforms > 0)
{
if (!SeparateStructFromUniformDeclarations(this, root, &getSymbolTable()))
{
return false;
}
int removedUniformsCount;
// Requires MonomorphizeUnsupportedFunctions() to have been run already.
if (!RewriteStructSamplers(this, root, &getSymbolTable(), &removedUniformsCount))
{
return false;
}
}
// Replace array of array of opaque uniforms with a flattened array. This is run after
// MonomorphizeUnsupportedFunctions and RewriteStructSamplers so that it's not possible for an
// array of array of opaque type to be partially subscripted and passed to a function.
// TODO(anglebug.com/389145696): Even single-level arrays of samplers are not allowed in WGSL.
if (!RewriteArrayOfArrayOfOpaqueUniforms(this, root, &getSymbolTable()))
{
return false;
}
return true;
}
bool TranslatorWGSL::translate(TIntermBlock *root,
const ShCompileOptions &compileOptions,
PerformanceDiagnostics *perfDiagnostics)
{
if (kOutputTreeBeforeTranslation)
{
OutputTree(root, getInfoSink().info);
std::cout << getInfoSink().info.c_str();
}
if (!preTranslateTreeModifications(root))
{
return false;
}
enableValidateNoMoreTransformations();
RewritePipelineVarOutput rewritePipelineVarOutput(getShaderType());
WGSLGenerationMetadataForUniforms wgslGenerationMetadataForUniforms;
// WGSL's main() will need to take parameters or return values if any glsl (input/output)
// builtin variables are used.
if (!GenerateMainFunctionAndIOStructs(*this, *root, rewritePipelineVarOutput))
{
return false;
}
TInfoSinkBase &sink = getInfoSink().obj;
// Start writing the output structs that will be referred to by the `traverser`'s output.'
if (!rewritePipelineVarOutput.OutputStructs(sink))
{
return false;
}
if (!OutputUniformBlocksAndSamplers(this, root))
{
return false;
}
UniformBlockMetadata uniformBlockMetadata;
if (!RecordUniformBlockMetadata(root, uniformBlockMetadata))
{
return false;
}
// Generate the body of the WGSL including the GLSL main() function.
TInfoSinkBase traverserOutput;
OutputWGSLTraverser traverser(&traverserOutput, &rewritePipelineVarOutput,
&uniformBlockMetadata, &wgslGenerationMetadataForUniforms);
root->traverse(&traverser);
sink << "\n";
OutputUniformWrapperStructsAndConversions(sink, wgslGenerationMetadataForUniforms);
// The traverser output needs to be in the code after uniform wrapper structs are emitted above,
// since the traverser code references the wrapper struct types.
sink << traverserOutput.str();
// Write the actual WGSL main function, wgslMain(), which calls the GLSL main function.
if (!rewritePipelineVarOutput.OutputMainFunction(sink))
{
return false;
}
if (kOutputTranslatedShader)
{
std::cout << sink.str();
}
return true;
}
bool TranslatorWGSL::shouldFlattenPragmaStdglInvariantAll()
{
// Not neccesary for WGSL transformation.
return false;
}
} // namespace sh