All files / Sources/Rendering/OpenGL/PolyDataMapper index.js

88.55% Statements 611/690
84.45% Branches 326/386
85.36% Functions 35/41
88.29% Lines 596/675

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                          1x       1x 1x 1x 1x 1x 1x 1x 1x             3742x 3742x 2187x     1555x         827x   827x 7438x 3719x 3719x 3719x   3719x 3719x             827x 26x 13x 13x       827x 100x 50x 50x 50x 50x       827x   827x 7358x 3679x       827x 3742x 3742x 820x 820x 4920x     3742x 3742x 3742x     827x 2631x 2631x 2631x     827x 2639x 2639x 2639x   2639x           2639x                 2639x 2620x                 2639x         2639x 2620x         2639x         2639x 2620x             2639x       14x 14x       14x     14x       14x         2639x       14x                   2625x         130x                     2495x                                                                 2495x       2495x               2639x           2639x 2639x 2639x     827x 2639x     2639x   2639x         2639x   2639x   2639x   19x                 19x     2617x                         2617x     2x 4x           2x           2x         2x 4x                         2x           2x           2x     1x 2x                     1x           1x             1x 2x                                                                                     1x           1x           1x         2639x     827x 2639x       2639x 2620x 2620x 2620x   2620x 2160x         2160x         2160x       2160x         2160x     2160x                     460x                               460x                               172x                 172x                     288x           288x                     288x                               2620x 2620x 2620x       827x   2639x   2639x 2639x 2639x     2639x     2639x 2620x         2620x               2620x       2620x         2620x         2620x         2620x           19x     19x           2639x 2639x 2639x     827x 2639x 136x 136x 136x   136x       136x                   136x 136x 136x 136x 6x 6x 2x     136x 130x         130x     136x 134x         134x       134x         134x       134x 4x                                                 4x                         2x         2x       2x         2x       2x                                                 2x                       136x 136x 136x       827x 2639x 2639x   2639x 12x 12x           12x                   12x         12x                     2639x 2639x     827x     6648x       6648x 6648x         6625x 6625x       12x 6613x       103x 6510x       6127x   6625x       383x 383x 383x           6648x 6648x         3663x   6648x     827x 2611x 2611x 2611x         2611x 951x   1660x       550x       550x           550x         550x           1660x   550x         550x                 1110x         1110x           1660x 1660x     827x 2639x 2639x 2639x 2639x 2639x 2639x 2639x 2639x   2639x 174x 174x         174x             174x       827x 4042x 4042x   4042x 4042x     4042x 4042x 4042x 4042x 4042x 4042x   4042x 3204x   838x     838x 516x   322x 309x         4042x     3981x 3981x 3981x 3984x 3984x 3984x 3984x 3984x 3981x       3984x           3x   3984x 1x         4042x 4042x       4042x 4042x       956x 956x 956x       4042x           11x                 4042x               2635x 2635x     1407x     827x   4042x 4042x             827x   4042x         4042x 550x     4042x             2639x       2639x 2639x                                 2639x         2160x                                 479x     2639x                                         2639x       136x                                 2503x   2639x       14x                                 2625x     2639x     4042x   15x 15x   15x 15x     15x     15x 12x 12x 12x     15x 29x 29x   29x 116x     15x 15x     4042x       254x       4042x 4042x 14x 14x 14x 14x 14x 14x           4042x 226x           4042x 4009x 4009x   4009x 3994x         4042x           4042x 4042x           4042x         827x   4042x     4042x 4039x     3x     3x   3x 3x 6x 6x 6x 6x 6x 6x 6x 6x   6x 6x   6x 6x 6x   6x   6x   6x     6x 6x 6x 6x 6x       6x       6x         3x 2x       1x 1x 1x   1x   1x 2x 2x 2x 2x 2x 2x 2x       2x       2x       2x       2x         2x           11232x 11232x 30457x 11232x   19225x       827x 4032x       4032x 4032x   4032x 4032x   4032x 4032x       4032x 4032x       4032x 10x 10x 10x 10x 10x 10x 10x 10x   4022x                 4032x 3971x                 4032x 3239x                   4032x 331x 145x   331x     4032x   68x       827x 4042x   4042x   4042x   4042x     4042x       4042x 4042x 4042x   4042x   4042x   4042x 4042x   4042x 4042x     4042x       4042x 61x     3981x 3981x 3981x 3981x     3981x                                                             827x 817x 817x 817x                                     827x 3742x 3742x   3742x 3742x 1640x 1640x     3742x 2187x   2187x         3742x       3742x 254x       3742x     827x 3641x     3641x     3641x     3641x             3641x 21846x 21846x 21846x   3983x       3983x       3941x 3941x           3941x               827x 3742x     3742x 254x       827x           3641x 3641x 3641x   3641x 3641x   3641x           3641x               3641x 3641x 3641x 3641x 3641x                 3641x 3641x 3641x     827x               827x   3742x 898x       827x     3655x 3655x           811x   2844x     827x 890x   890x       890x 890x   890x 890x 890x   890x               1x           890x     890x                     890x   890x 890x 884x       890x 130x 130x 130x       130x   130x 130x 130x 130x 130x   130x 130x 130x 130x             130x 130x 130x       890x       890x   817x 817x                           817x 817x           817x                 817x     817x 4902x 3268x                 3268x         1634x       258x                               1376x         817x 817x     817x     817x 817x       827x                           1x                                               827x     827x 827x         827x           827x 827x   827x 827x   827x 4962x 4962x 4962x             827x   827x 827x   827x 827x     827x         1x             1x  
import { mat3, mat4, vec3 } from 'gl-matrix';
 
import * as macro from 'vtk.js/Sources/macros';
import vtkHelper from 'vtk.js/Sources/Rendering/OpenGL/Helper';
import vtkMapper from 'vtk.js/Sources/Rendering/Core/Mapper';
import * as vtkMath from 'vtk.js/Sources/Common/Core/Math';
import vtkOpenGLTexture from 'vtk.js/Sources/Rendering/OpenGL/Texture';
import vtkProp from 'vtk.js/Sources/Rendering/Core/Prop';
import vtkProperty from 'vtk.js/Sources/Rendering/Core/Property';
import vtkShaderProgram from 'vtk.js/Sources/Rendering/OpenGL/ShaderProgram';
import vtkViewNode from 'vtk.js/Sources/Rendering/SceneGraph/ViewNode';
import vtkPolyDataVS from 'vtk.js/Sources/Rendering/OpenGL/glsl/vtkPolyDataVS.glsl';
import vtkPolyDataFS from 'vtk.js/Sources/Rendering/OpenGL/glsl/vtkPolyDataFS.glsl';
 
import vtkReplacementShaderMapper from 'vtk.js/Sources/Rendering/OpenGL/ReplacementShaderMapper';
 
import { registerOverride } from 'vtk.js/Sources/Rendering/OpenGL/ViewNodeFactory';
 
import { PassTypes } from 'vtk.js/Sources/Rendering/OpenGL/HardwareSelector/Constants';
import vtkDataSet from 'vtk.js/Sources/Common/DataModel/DataSet';
 
const { FieldAssociations } = vtkDataSet;
 
/* eslint-disable no-lonely-if */
 
const { primTypes } = vtkHelper;
const { Representation, Shading } = vtkProperty;
const { ScalarMode } = vtkMapper;
const { Filter, Wrap } = vtkOpenGLTexture;
const { vtkErrorMacro } = macro;
const StartEvent = { type: 'StartEvent' };
const EndEvent = { type: 'EndEvent' };
const { CoordinateSystem } = vtkProp;
 
// ----------------------------------------------------------------------------
// vtkOpenGLPolyDataMapper methods
// ----------------------------------------------------------------------------
 
function getPickState(renderer) {
  const selector = renderer.getSelector();
  if (selector) {
    return selector.getCurrentPass();
  }
 
  return PassTypes.MIN_KNOWN_PASS - 1;
}
 
function vtkOpenGLPolyDataMapper(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkOpenGLPolyDataMapper');
 
  publicAPI.buildPass = (prepass) => {
    if (prepass) {
      model.currentRenderPass = null;
      model.openGLActor = publicAPI.getFirstAncestorOfType('vtkOpenGLActor');
      model._openGLRenderer =
        model.openGLActor.getFirstAncestorOfType('vtkOpenGLRenderer');
      model._openGLRenderWindow = model._openGLRenderer.getParent();
      model.openGLCamera = model._openGLRenderer.getViewNodeFor(
        model._openGLRenderer.getRenderable().getActiveCamera()
      );
    }
  };
 
  // Renders myself
  publicAPI.translucentPass = (prepass, renderPass) => {
    if (prepass) {
      model.currentRenderPass = renderPass;
      publicAPI.render();
    }
  };
 
  publicAPI.zBufferPass = (prepass) => {
    if (prepass) {
      model.haveSeenDepthRequest = true;
      model.renderDepth = true;
      publicAPI.render();
      model.renderDepth = false;
    }
  };
 
  publicAPI.opaqueZBufferPass = (prepass) => publicAPI.zBufferPass(prepass);
 
  publicAPI.opaquePass = (prepass) => {
    if (prepass) {
      publicAPI.render();
    }
  };
 
  publicAPI.render = () => {
    const ctx = model._openGLRenderWindow.getContext();
    if (model.context !== ctx) {
      model.context = ctx;
      for (let i = primTypes.Start; i < primTypes.End; i++) {
        model.primitives[i].setOpenGLRenderWindow(model._openGLRenderWindow);
      }
    }
    const actor = model.openGLActor.getRenderable();
    const ren = model._openGLRenderer.getRenderable();
    publicAPI.renderPiece(ren, actor);
  };
 
  publicAPI.getShaderTemplate = (shaders, ren, actor) => {
    shaders.Vertex = vtkPolyDataVS;
    shaders.Fragment = vtkPolyDataFS;
    shaders.Geometry = '';
  };
 
  publicAPI.replaceShaderColor = (shaders, ren, actor) => {
    let VSSource = shaders.Vertex;
    let GSSource = shaders.Geometry;
    let FSSource = shaders.Fragment;
 
    const lastLightComplexity = model.lastBoundBO.getReferenceByName(
      'lastLightComplexity'
    );
 
    // create the material/color property declarations, and VS implementation
    // these are always defined
    let colorDec = [
      'uniform float ambient;',
      'uniform float diffuse;',
      'uniform float specular;',
      'uniform float opacityUniform; // the fragment opacity',
      'uniform vec3 ambientColorUniform;',
      'uniform vec3 diffuseColorUniform;',
    ];
    // add more for specular
    if (lastLightComplexity) {
      colorDec = colorDec.concat([
        'uniform vec3 specularColorUniform;',
        'uniform float specularPowerUniform;',
      ]);
    }
 
    // now handle the more complex fragment shader implementation
    // the following are always defined variables.  We start
    // by assigning a default value from the uniform
    let colorImpl = [
      'vec3 ambientColor;',
      '  vec3 diffuseColor;',
      '  float opacity;',
    ];
    if (lastLightComplexity) {
      colorImpl = colorImpl.concat([
        '  vec3 specularColor;',
        '  float specularPower;',
      ]);
    }
    colorImpl = colorImpl.concat([
      '  ambientColor = ambientColorUniform;',
      '  diffuseColor = diffuseColorUniform;',
      '  opacity = opacityUniform;',
    ]);
    if (lastLightComplexity) {
      colorImpl = colorImpl.concat([
        '  specularColor = specularColorUniform;',
        '  specularPower = specularPowerUniform;',
      ]);
    }
 
    // add scalar vertex coloring
    if (
      model.lastBoundBO.getCABO().getColorComponents() !== 0 &&
      !model.drawingEdges
    ) {
      colorDec = colorDec.concat(['varying vec4 vertexColorVSOutput;']);
      VSSource = vtkShaderProgram.substitute(VSSource, '//VTK::Color::Dec', [
        'attribute vec4 scalarColor;',
        'varying vec4 vertexColorVSOutput;',
      ]).result;
      VSSource = vtkShaderProgram.substitute(VSSource, '//VTK::Color::Impl', [
        'vertexColorVSOutput =  scalarColor;',
      ]).result;
      GSSource = vtkShaderProgram.substitute(GSSource, '//VTK::Color::Dec', [
        'in vec4 vertexColorVSOutput[];',
        'out vec4 vertexColorGSOutput;',
      ]).result;
      GSSource = vtkShaderProgram.substitute(GSSource, '//VTK::Color::Impl', [
        'vertexColorGSOutput = vertexColorVSOutput[i];',
      ]).result;
    }
 
    if (
      model.lastBoundBO.getCABO().getColorComponents() !== 0 &&
      !model.drawingEdges
    ) {
      FSSource = vtkShaderProgram.substitute(
        FSSource,
        '//VTK::Color::Impl',
        colorImpl.concat([
          '  diffuseColor = vertexColorVSOutput.rgb;',
          '  ambientColor = vertexColorVSOutput.rgb;',
          '  opacity = opacity*vertexColorVSOutput.a;',
        ])
      ).result;
    } else {
      if (
        model.renderable.getInterpolateScalarsBeforeMapping() &&
        model.renderable.getColorCoordinates() &&
        !model.drawingEdges
      ) {
        FSSource = vtkShaderProgram.substitute(
          FSSource,
          '//VTK::Color::Impl',
          colorImpl.concat([
            '  vec4 texColor = texture2D(texture1, tcoordVCVSOutput.st);',
            '  diffuseColor = texColor.rgb;',
            '  ambientColor = texColor.rgb;',
            '  opacity = opacity*texColor.a;',
          ])
        ).result;
      } else {
        Iif (actor.getBackfaceProperty() && !model.drawingEdges) {
          colorDec = colorDec.concat([
            'uniform float opacityUniformBF; // the fragment opacity',
            'uniform float ambientIntensityBF; // the material ambient',
            'uniform float diffuseIntensityBF; // the material diffuse',
            'uniform vec3 ambientColorUniformBF; // ambient material color',
            'uniform vec3 diffuseColorUniformBF; // diffuse material color',
          ]);
 
          if (lastLightComplexity) {
            colorDec = colorDec.concat([
              'uniform float specularIntensityBF; // the material specular intensity',
              'uniform vec3 specularColorUniformBF; // intensity weighted color',
              'uniform float specularPowerUniformBF;',
            ]);
            colorImpl = colorImpl.concat([
              'if (gl_FrontFacing == false) {',
              '  ambientColor = ambientIntensityBF * ambientColorUniformBF;',
              '  diffuseColor = diffuseIntensityBF * diffuseColorUniformBF;',
              '  specularColor = specularIntensityBF * specularColorUniformBF;',
              '  specularPower = specularPowerUniformBF;',
              '  opacity = opacityUniformBF; }',
            ]);
          } else {
            colorImpl = colorImpl.concat([
              'if (gl_FrontFacing == false) {',
              '  ambientColor = ambientIntensityBF * ambientColorUniformBF;',
              '  diffuseColor = diffuseIntensityBF * diffuseColorUniformBF;',
              '  opacity = opacityUniformBF; }',
            ]);
          }
        }
 
        Iif (model.haveCellScalars && !model.drawingEdges) {
          colorDec = colorDec.concat(['uniform samplerBuffer texture1;']);
        }
 
        FSSource = vtkShaderProgram.substitute(
          FSSource,
          '//VTK::Color::Impl',
          colorImpl
        ).result;
      }
    }
 
    FSSource = vtkShaderProgram.substitute(
      FSSource,
      '//VTK::Color::Dec',
      colorDec
    ).result;
 
    shaders.Vertex = VSSource;
    shaders.Geometry = GSSource;
    shaders.Fragment = FSSource;
  };
 
  publicAPI.replaceShaderLight = (shaders, ren, actor) => {
    let FSSource = shaders.Fragment;
 
    // check for shadow maps
    const shadowFactor = '';
 
    const lastLightComplexity = model.lastBoundBO.getReferenceByName(
      'lastLightComplexity'
    );
 
    const lastLightCount =
      model.lastBoundBO.getReferenceByName('lastLightCount');
 
    let sstring = [];
 
    switch (lastLightComplexity) {
      case 0: // no lighting or RENDER_VALUES
        FSSource = vtkShaderProgram.substitute(
          FSSource,
          '//VTK::Light::Impl',
          [
            '  gl_FragData[0] = vec4(ambientColor * ambient + diffuseColor * diffuse, opacity);',
            '  //VTK::Light::Impl',
          ],
          false
        ).result;
        break;
 
      case 1: // headlight
        FSSource = vtkShaderProgram.substitute(
          FSSource,
          '//VTK::Light::Impl',
          [
            '  float df = max(0.0, normalVCVSOutput.z);',
            '  float sf = pow(df, specularPower);',
            '  vec3 diffuseL = df * diffuseColor;',
            '  vec3 specularL = sf * specularColor;',
            '  gl_FragData[0] = vec4(ambientColor * ambient + diffuseL * diffuse + specularL * specular, opacity);',
            '  //VTK::Light::Impl',
          ],
          false
        ).result;
        break;
 
      case 2: // light kit
        for (let lc = 0; lc < lastLightCount; ++lc) {
          sstring = sstring.concat([
            `uniform vec3 lightColor${lc};`,
            `uniform vec3 lightDirectionVC${lc}; // normalized`,
            `uniform vec3 lightHalfAngleVC${lc}; // normalized`,
          ]);
        }
        FSSource = vtkShaderProgram.substitute(
          FSSource,
          '//VTK::Light::Dec',
          sstring
        ).result;
 
        sstring = [
          'vec3 diffuseL = vec3(0,0,0);',
          '  vec3 specularL = vec3(0,0,0);',
          '  float df;',
        ];
        for (let lc = 0; lc < lastLightCount; ++lc) {
          sstring = sstring.concat([
            `  df = max(0.0, dot(normalVCVSOutput, -lightDirectionVC${lc}));`,
            `  diffuseL += ((df${shadowFactor}) * lightColor${lc});`,
            `  if (dot(normalVCVSOutput, lightDirectionVC${lc}) < 0.0)`,
            '    {',
            `    float sf = sign(df)*pow(max(1e-5,
                                              dot(reflect(lightDirectionVC${lc},normalVCVSOutput),
                                                  normalize(-vertexVC.xyz))),
                                         specularPower);`,
            `    specularL += (sf${shadowFactor} * lightColor${lc});`,
            '    }',
          ]);
        }
        sstring = sstring.concat([
          '  diffuseL = diffuseL * diffuseColor;',
          '  specularL = specularL * specularColor;',
          '  gl_FragData[0] = vec4(ambientColor * ambient + diffuseL * diffuse + specularL * specular, opacity);',
          '  //VTK::Light::Impl',
        ]);
        FSSource = vtkShaderProgram.substitute(
          FSSource,
          '//VTK::Light::Impl',
          sstring,
          false
        ).result;
        break;
 
      case 3: // positional
        for (let lc = 0; lc < lastLightCount; ++lc) {
          sstring = sstring.concat([
            `uniform vec3 lightColor${lc};`,
            `uniform vec3 lightDirectionVC${lc}; // normalized`,
            `uniform vec3 lightHalfAngleVC${lc}; // normalized`,
            `uniform vec3 lightPositionVC${lc};`,
            `uniform vec3 lightAttenuation${lc};`,
            `uniform float lightConeAngle${lc};`,
            `uniform float lightExponent${lc};`,
            `uniform int lightPositional${lc};`,
          ]);
        }
        FSSource = vtkShaderProgram.substitute(
          FSSource,
          '//VTK::Light::Dec',
          sstring
        ).result;
 
        sstring = [
          'vec3 diffuseL = vec3(0,0,0);',
          '  vec3 specularL = vec3(0,0,0);',
          '  vec3 vertLightDirectionVC;',
          '  float attenuation;',
          '  float df;',
        ];
        for (let lc = 0; lc < lastLightCount; ++lc) {
          sstring = sstring.concat([
            '  attenuation = 1.0;',
            `  if (lightPositional${lc} == 0)`,
            '    {',
            `      vertLightDirectionVC = lightDirectionVC${lc};`,
            '    }',
            '  else',
            '    {',
            `    vertLightDirectionVC = vertexVC.xyz - lightPositionVC${lc};`,
            '    float distanceVC = length(vertLightDirectionVC);',
            '    vertLightDirectionVC = normalize(vertLightDirectionVC);',
            '    attenuation = 1.0 /',
            `      (lightAttenuation${lc}.x`,
            `       + lightAttenuation${lc}.y * distanceVC`,
            `       + lightAttenuation${lc}.z * distanceVC * distanceVC);`,
            '    // per OpenGL standard cone angle is 90 or less for a spot light',
            `    if (lightConeAngle${lc} <= 90.0)`,
            '      {',
            `      float coneDot = dot(vertLightDirectionVC, lightDirectionVC${lc});`,
            '      // if inside the cone',
            `      if (coneDot >= cos(radians(lightConeAngle${lc})))`,
            '        {',
            `        attenuation = attenuation * pow(coneDot, lightExponent${lc});`,
            '        }',
            '      else',
            '        {',
            '        attenuation = 0.0;',
            '        }',
            '      }',
            '    }',
            '    df = max(0.0, attenuation*dot(normalVCVSOutput, -vertLightDirectionVC));',
            `    diffuseL += ((df${shadowFactor}) * lightColor${lc});`,
            '    if (dot(normalVCVSOutput, vertLightDirectionVC) < 0.0)',
            '      {',
            `      float sf = sign(df)*attenuation*pow(max(1e-5,
                                                           dot(reflect(lightDirectionVC${lc},
                                                                       normalVCVSOutput),
                                                               normalize(-vertexVC.xyz))),
                                                       specularPower);`,
            `    specularL += ((sf${shadowFactor}) * lightColor${lc});`,
            '    }',
          ]);
        }
        sstring = sstring.concat([
          '  diffuseL = diffuseL * diffuseColor;',
          '  specularL = specularL * specularColor;',
          '  gl_FragData[0] = vec4(ambientColor * ambient + diffuseL * diffuse + specularL * specular, opacity);',
          '  //VTK::Light::Impl',
        ]);
        FSSource = vtkShaderProgram.substitute(
          FSSource,
          '//VTK::Light::Impl',
          sstring,
          false
        ).result;
        break;
      default:
        vtkErrorMacro('bad light complexity');
    }
 
    shaders.Fragment = FSSource;
  };
 
  publicAPI.replaceShaderNormal = (shaders, ren, actor) => {
    const lastLightComplexity = model.lastBoundBO.getReferenceByName(
      'lastLightComplexity'
    );
 
    if (lastLightComplexity > 0) {
      let VSSource = shaders.Vertex;
      let GSSource = shaders.Geometry;
      let FSSource = shaders.Fragment;
 
      if (model.lastBoundBO.getCABO().getNormalOffset()) {
        VSSource = vtkShaderProgram.substitute(VSSource, '//VTK::Normal::Dec', [
          'attribute vec3 normalMC;',
          'uniform mat3 normalMatrix;',
          'varying vec3 normalVCVSOutput;',
        ]).result;
        VSSource = vtkShaderProgram.substitute(
          VSSource,
          '//VTK::Normal::Impl',
          ['normalVCVSOutput = normalMatrix * normalMC;']
        ).result;
        GSSource = vtkShaderProgram.substitute(GSSource, '//VTK::Normal::Dec', [
          'in vec3 normalVCVSOutput[];',
          'out vec3 normalVCGSOutput;',
        ]).result;
        GSSource = vtkShaderProgram.substitute(
          GSSource,
          '//VTK::Normal::Impl',
          ['normalVCGSOutput = normalVCVSOutput[i];']
        ).result;
        FSSource = vtkShaderProgram.substitute(FSSource, '//VTK::Normal::Dec', [
          'varying vec3 normalVCVSOutput;',
        ]).result;
        FSSource = vtkShaderProgram.substitute(
          FSSource,
          '//VTK::Normal::Impl',
          [
            'vec3 normalVCVSOutput = normalize(normalVCVSOutput);',
            //  if (!gl_FrontFacing) does not work in intel hd4000 mac
            //  if (int(gl_FrontFacing) == 0) does not work on mesa
            '  if (gl_FrontFacing == false) { normalVCVSOutput = -normalVCVSOutput; }',
          ]
        ).result;
      } else {
        Iif (model.haveCellNormals) {
          FSSource = vtkShaderProgram.substitute(
            FSSource,
            '//VTK::Normal::Dec',
            ['uniform mat3 normalMatrix;', 'uniform samplerBuffer textureN;']
          ).result;
          FSSource = vtkShaderProgram.substitute(
            FSSource,
            '//VTK::Normal::Impl',
            [
              'vec3 normalVCVSOutput = normalize(normalMatrix *',
              '    texelFetchBuffer(textureN, gl_PrimitiveID + PrimitiveIDOffset).xyz);',
              '  if (gl_FrontFacing == false) { normalVCVSOutput = -normalVCVSOutput; }',
            ]
          ).result;
        } else {
          if (
            model.lastBoundBO.getOpenGLMode(
              actor.getProperty().getRepresentation()
            ) === model.context.LINES
          ) {
            // generate a normal for lines, it will be perpendicular to the line
            // and maximally aligned with the camera view direction
            // no clue if this is the best way to do this.
            // the code below has been optimized a bit so what follows is
            // an explanation of the basic approach. Compute the gradient of the line
            // with respect to x and y, the the larger of the two
            // cross that with the camera view direction. That gives a vector
            // orthogonal to the camera view and the line. Note that the line and the camera
            // view are probably not orthogonal. Which is why when we cross result that with
            // the line gradient again we get a reasonable normal. It will be othogonal to
            // the line (which is a plane but maximally aligned with the camera view.
            FSSource = vtkShaderProgram.substitute(
              FSSource,
              '//VTK::UniformFlow::Impl',
              [
                '  vec3 fdx = dFdx(vertexVC.xyz);',
                '  vec3 fdy = dFdy(vertexVC.xyz);',
                '  //VTK::UniformFlow::Impl',
              ] // For further replacements
            ).result;
            FSSource = vtkShaderProgram.substitute(
              FSSource,
              '//VTK::Normal::Impl',
              [
                'vec3 normalVCVSOutput;',
                '  if (abs(fdx.x) > 0.0)',
                '    { fdx = normalize(fdx); normalVCVSOutput = normalize(cross(vec3(fdx.y, -fdx.x, 0.0), fdx)); }',
                '  else { fdy = normalize(fdy); normalVCVSOutput = normalize(cross(vec3(fdy.y, -fdy.x, 0.0), fdy));}',
              ]
            ).result;
          } else {
            FSSource = vtkShaderProgram.substitute(
              FSSource,
              '//VTK::Normal::Dec',
              ['uniform int cameraParallel;']
            ).result;
 
            FSSource = vtkShaderProgram.substitute(
              FSSource,
              '//VTK::UniformFlow::Impl',
              [
                // '  vec3 fdx = vec3(dFdx(vertexVC.x),dFdx(vertexVC.y),dFdx(vertexVC.z));',
                // '  vec3 fdy = vec3(dFdy(vertexVC.x),dFdy(vertexVC.y),dFdy(vertexVC.z));',
                '  vec3 fdx = dFdx(vertexVC.xyz);',
                '  vec3 fdy = dFdy(vertexVC.xyz);',
                '  //VTK::UniformFlow::Impl',
              ] // For further replacements
            ).result;
            FSSource = vtkShaderProgram.substitute(
              FSSource,
              '//VTK::Normal::Impl',
              [
                '  fdx = normalize(fdx);',
                '  fdy = normalize(fdy);',
                '  vec3 normalVCVSOutput = normalize(cross(fdx,fdy));',
                // the code below is faster, but does not work on some devices
                // 'vec3 normalVC = normalize(cross(dFdx(vertexVC.xyz), dFdy(vertexVC.xyz)));',
                '  if (cameraParallel == 1 && normalVCVSOutput.z < 0.0) { normalVCVSOutput = -1.0*normalVCVSOutput; }',
                '  if (cameraParallel == 0 && dot(normalVCVSOutput,vertexVC.xyz) > 0.0) { normalVCVSOutput = -1.0*normalVCVSOutput; }',
              ]
            ).result;
          }
        }
      }
      shaders.Vertex = VSSource;
      shaders.Geometry = GSSource;
      shaders.Fragment = FSSource;
    }
  };
 
  publicAPI.replaceShaderPositionVC = (shaders, ren, actor) => {
    // replace common shader code
    model.lastBoundBO.replaceShaderPositionVC(shaders, ren, actor);
 
    let VSSource = shaders.Vertex;
    let GSSource = shaders.Geometry;
    let FSSource = shaders.Fragment;
 
    // do we need the vertex in the shader in View Coordinates
    const lastLightComplexity = model.lastBoundBO.getReferenceByName(
      'lastLightComplexity'
    );
    if (lastLightComplexity > 0) {
      VSSource = vtkShaderProgram.substitute(
        VSSource,
        '//VTK::PositionVC::Dec',
        ['varying vec4 vertexVCVSOutput;']
      ).result;
      VSSource = vtkShaderProgram.substitute(
        VSSource,
        '//VTK::PositionVC::Impl',
        [
          'vertexVCVSOutput = MCVCMatrix * vertexMC;',
          '  gl_Position = MCPCMatrix * vertexMC;',
        ]
      ).result;
      VSSource = vtkShaderProgram.substitute(VSSource, '//VTK::Camera::Dec', [
        'uniform mat4 MCPCMatrix;',
        'uniform mat4 MCVCMatrix;',
      ]).result;
      GSSource = vtkShaderProgram.substitute(
        GSSource,
        '//VTK::PositionVC::Dec',
        ['in vec4 vertexVCVSOutput[];', 'out vec4 vertexVCGSOutput;']
      ).result;
      GSSource = vtkShaderProgram.substitute(
        GSSource,
        '//VTK::PositionVC::Impl',
        ['vertexVCGSOutput = vertexVCVSOutput[i];']
      ).result;
      FSSource = vtkShaderProgram.substitute(
        FSSource,
        '//VTK::PositionVC::Dec',
        ['varying vec4 vertexVCVSOutput;']
      ).result;
      FSSource = vtkShaderProgram.substitute(
        FSSource,
        '//VTK::PositionVC::Impl',
        ['vec4 vertexVC = vertexVCVSOutput;']
      ).result;
    } else {
      VSSource = vtkShaderProgram.substitute(VSSource, '//VTK::Camera::Dec', [
        'uniform mat4 MCPCMatrix;',
      ]).result;
      VSSource = vtkShaderProgram.substitute(
        VSSource,
        '//VTK::PositionVC::Impl',
        ['  gl_Position = MCPCMatrix * vertexMC;']
      ).result;
    }
    shaders.Vertex = VSSource;
    shaders.Geometry = GSSource;
    shaders.Fragment = FSSource;
  };
 
  publicAPI.replaceShaderTCoord = (shaders, ren, actor) => {
    if (model.lastBoundBO.getCABO().getTCoordOffset()) {
      let VSSource = shaders.Vertex;
      let GSSource = shaders.Geometry;
      let FSSource = shaders.Fragment;
 
      Iif (model.drawingEdges) {
        return;
      }
 
      VSSource = vtkShaderProgram.substitute(
        VSSource,
        '//VTK::TCoord::Impl',
        'tcoordVCVSOutput = tcoordMC;'
      ).result;
 
      // we only handle the first texture by default
      // additional textures are activated and we set the uniform
      // for the texture unit they are assigned to, but you have to
      // add in the shader code to do something with them
      const tus = model.openGLActor.getActiveTextures();
      let tNumComp = 2;
      let tcdim = 2;
      if (tus && tus.length > 0) {
        tNumComp = tus[0].getComponents();
        if (tus[0].getTarget() === model.context.TEXTURE_CUBE_MAP) {
          tcdim = 3;
        }
      }
      if (model.renderable.getColorTextureMap()) {
        tNumComp = model.renderable
          .getColorTextureMap()
          .getPointData()
          .getScalars()
          .getNumberOfComponents();
        tcdim = 2;
      }
 
      if (tcdim === 2) {
        VSSource = vtkShaderProgram.substitute(
          VSSource,
          '//VTK::TCoord::Dec',
          'attribute vec2 tcoordMC; varying vec2 tcoordVCVSOutput;'
        ).result;
        GSSource = vtkShaderProgram.substitute(GSSource, '//VTK::TCoord::Dec', [
          'in vec2 tcoordVCVSOutput[];',
          'out vec2 tcoordVCGSOutput;',
        ]).result;
        GSSource = vtkShaderProgram.substitute(
          GSSource,
          '//VTK::TCoord::Impl',
          'tcoordVCGSOutput = tcoordVCVSOutput[i];'
        ).result;
        FSSource = vtkShaderProgram.substitute(FSSource, '//VTK::TCoord::Dec', [
          'varying vec2 tcoordVCVSOutput;',
          'uniform sampler2D texture1;',
        ]).result;
        if (tus && tus.length >= 1) {
          switch (tNumComp) {
            case 1:
              FSSource = vtkShaderProgram.substitute(
                FSSource,
                '//VTK::TCoord::Impl',
                [
                  '  vec4 tcolor = texture2D(texture1, tcoordVCVSOutput);',
                  '  ambientColor = ambientColor*tcolor.r;',
                  '  diffuseColor = diffuseColor*tcolor.r;',
                ]
              ).result;
              break;
            case 2:
              FSSource = vtkShaderProgram.substitute(
                FSSource,
                '//VTK::TCoord::Impl',
                [
                  '  vec4 tcolor = texture2D(texture1, tcoordVCVSOutput);',
                  '  ambientColor = ambientColor*tcolor.r;',
                  '  diffuseColor = diffuseColor*tcolor.r;',
                  '  opacity = opacity * tcolor.g;',
                ]
              ).result;
              break;
            default:
              FSSource = vtkShaderProgram.substitute(
                FSSource,
                '//VTK::TCoord::Impl',
                [
                  '  vec4 tcolor = texture2D(texture1, tcoordVCVSOutput);',
                  '  ambientColor = ambientColor*tcolor.rgb;',
                  '  diffuseColor = diffuseColor*tcolor.rgb;',
                  '  opacity = opacity * tcolor.a;',
                ]
              ).result;
          }
        }
      } else {
        VSSource = vtkShaderProgram.substitute(
          VSSource,
          '//VTK::TCoord::Dec',
          'attribute vec3 tcoordMC; varying vec3 tcoordVCVSOutput;'
        ).result;
        GSSource = vtkShaderProgram.substitute(GSSource, '//VTK::TCoord::Dec', [
          'in vec3 tcoordVCVSOutput[];',
          'out vec3 tcoordVCGSOutput;',
        ]).result;
        GSSource = vtkShaderProgram.substitute(
          GSSource,
          '//VTK::TCoord::Impl',
          'tcoordVCGSOutput = tcoordVCVSOutput[i];'
        ).result;
        FSSource = vtkShaderProgram.substitute(FSSource, '//VTK::TCoord::Dec', [
          'varying vec3 tcoordVCVSOutput;',
          'uniform samplerCube texture1;',
        ]).result;
        switch (tNumComp) {
          case 1:
            FSSource = vtkShaderProgram.substitute(
              FSSource,
              '//VTK::TCoord::Impl',
              [
                '  vec4 tcolor = textureCube(texture1, tcoordVCVSOutput);',
                '  ambientColor = ambientColor*tcolor.r;',
                '  diffuseColor = diffuseColor*tcolor.r;',
              ]
            ).result;
            break;
          case 2:
            FSSource = vtkShaderProgram.substitute(
              FSSource,
              '//VTK::TCoord::Impl',
              [
                '  vec4 tcolor = textureCube(texture1, tcoordVCVSOutput);',
                '  ambientColor = ambientColor*tcolor.r;',
                '  diffuseColor = diffuseColor*tcolor.r;',
                '  opacity = opacity * tcolor.g;',
              ]
            ).result;
            break;
          default:
            FSSource = vtkShaderProgram.substitute(
              FSSource,
              '//VTK::TCoord::Impl',
              [
                '  vec4 tcolor = textureCube(texture1, tcoordVCVSOutput);',
                '  ambientColor = ambientColor*tcolor.rgb;',
                '  diffuseColor = diffuseColor*tcolor.rgb;',
                '  opacity = opacity * tcolor.a;',
              ]
            ).result;
        }
      }
      shaders.Vertex = VSSource;
      shaders.Geometry = GSSource;
      shaders.Fragment = FSSource;
    }
  };
 
  publicAPI.replaceShaderClip = (shaders, ren, actor) => {
    let VSSource = shaders.Vertex;
    let FSSource = shaders.Fragment;
 
    if (model.renderable.getNumberOfClippingPlanes()) {
      const numClipPlanes = model.renderable.getNumberOfClippingPlanes();
      VSSource = vtkShaderProgram.substitute(VSSource, '//VTK::Clip::Dec', [
        'uniform int numClipPlanes;',
        `uniform vec4 clipPlanes[${numClipPlanes}];`,
        `varying float clipDistancesVSOutput[${numClipPlanes}];`,
      ]).result;
 
      VSSource = vtkShaderProgram.substitute(VSSource, '//VTK::Clip::Impl', [
        `for (int planeNum = 0; planeNum < ${numClipPlanes}; planeNum++)`,
        '    {',
        '    if (planeNum >= numClipPlanes)',
        '        {',
        '        break;',
        '        }',
        '    clipDistancesVSOutput[planeNum] = dot(clipPlanes[planeNum], vertexMC);',
        '    }',
      ]).result;
      FSSource = vtkShaderProgram.substitute(FSSource, '//VTK::Clip::Dec', [
        'uniform int numClipPlanes;',
        `varying float clipDistancesVSOutput[${numClipPlanes}];`,
      ]).result;
 
      FSSource = vtkShaderProgram.substitute(FSSource, '//VTK::Clip::Impl', [
        `for (int planeNum = 0; planeNum < ${numClipPlanes}; planeNum++)`,
        '    {',
        '    if (planeNum >= numClipPlanes)',
        '        {',
        '        break;',
        '        }',
        '    if (clipDistancesVSOutput[planeNum] < 0.0) discard;',
        '    }',
      ]).result;
    }
    shaders.Vertex = VSSource;
    shaders.Fragment = FSSource;
  };
 
  publicAPI.getCoincidentParameters = (ren, actor) => {
    // 1. ResolveCoincidentTopology is On and non zero for this primitive
    // type
    let cp = {
      factor: 0.0,
      offset: 0.0,
    };
    const prop = actor.getProperty();
    if (
      model.renderable.getResolveCoincidentTopology() ||
      (prop.getEdgeVisibility() &&
        prop.getRepresentation() === Representation.SURFACE)
    ) {
      const primType = model.lastBoundBO.getPrimitiveType();
      if (
        primType === primTypes.Points ||
        prop.getRepresentation() === Representation.POINTS
      ) {
        cp = model.renderable.getCoincidentTopologyPointOffsetParameter();
      } else if (
        primType === primTypes.Lines ||
        prop.getRepresentation() === Representation.WIREFRAME
      ) {
        cp = model.renderable.getCoincidentTopologyLineOffsetParameters();
      } else if (
        primType === primTypes.Tris ||
        primType === primTypes.TriStrips
      ) {
        cp = model.renderable.getCoincidentTopologyPolygonOffsetParameters();
      }
      if (
        primType === primTypes.TrisEdges ||
        primType === primTypes.TriStripsEdges
      ) {
        cp = model.renderable.getCoincidentTopologyPolygonOffsetParameters();
        cp.factor /= 2.0;
        cp.offset /= 2.0;
      }
    }
 
    // hardware picking always offset due to saved zbuffer
    // This gets you above the saved surface depth buffer.
    const selector = model._openGLRenderer.getSelector();
    if (
      selector &&
      selector.getFieldAssociation() ===
        FieldAssociations.FIELD_ASSOCIATION_POINTS
    ) {
      cp.offset -= 2.0;
    }
    return cp;
  };
 
  publicAPI.replaceShaderPicking = (shaders, ren, actor) => {
    let FSSource = shaders.Fragment;
    let VSSource = shaders.Vertex;
    FSSource = vtkShaderProgram.substitute(FSSource, '//VTK::Picking::Dec', [
      'uniform int picking;',
      '//VTK::Picking::Dec',
    ]).result;
 
    if (!model._openGLRenderer.getSelector()) {
      return;
    }
    if (
      model.lastSelectionState === PassTypes.ID_LOW24 ||
      model.lastSelectionState === PassTypes.ID_HIGH24
    ) {
      VSSource = vtkShaderProgram.substitute(VSSource, '//VTK::Picking::Dec', [
        'flat out int vertexIDVSOutput;\n',
        'uniform int VertexIDOffset;\n',
      ]).result;
      VSSource = vtkShaderProgram.substitute(
        VSSource,
        '//VTK::Picking::Impl',
        '  vertexIDVSOutput = gl_VertexID + VertexIDOffset;\n'
      ).result;
 
      FSSource = vtkShaderProgram.substitute(
        FSSource,
        '//VTK::Picking::Dec',
        'flat in int vertexIDVSOutput;\n'
      ).result;
      FSSource = vtkShaderProgram.substitute(FSSource, '//VTK::Picking::Impl', [
        '  int idx = vertexIDVSOutput;',
        '//VTK::Picking::Impl',
      ]).result;
    }
 
    switch (model.lastSelectionState) {
      case PassTypes.ID_LOW24:
        FSSource = vtkShaderProgram.substitute(
          FSSource,
          '//VTK::Picking::Impl',
          '  gl_FragData[0] = vec4(float(idx%256)/255.0, float((idx/256)%256)/255.0, float((idx/65536)%256)/255.0, 1.0);'
        ).result;
        break;
      case PassTypes.ID_HIGH24:
        FSSource = vtkShaderProgram.substitute(
          FSSource,
          '//VTK::Picking::Impl',
          '  gl_FragData[0] = vec4(float(idx)/255.0, 0.0, 0.0, 1.0);'
        ).result;
        break;
      default:
        FSSource = vtkShaderProgram.substitute(
          FSSource,
          '//VTK::Picking::Dec',
          'uniform vec3 mapperIndex;'
        ).result;
        FSSource = vtkShaderProgram.substitute(
          FSSource,
          '//VTK::Picking::Impl',
          '  gl_FragData[0] = picking != 0 ? vec4(mapperIndex,1.0) : gl_FragData[0];'
        ).result;
    }
    shaders.Fragment = FSSource;
    shaders.Vertex = VSSource;
  };
 
  publicAPI.replaceShaderValues = (shaders, ren, actor) => {
    publicAPI.replaceShaderColor(shaders, ren, actor);
    publicAPI.replaceShaderNormal(shaders, ren, actor);
    publicAPI.replaceShaderLight(shaders, ren, actor);
    publicAPI.replaceShaderTCoord(shaders, ren, actor);
    publicAPI.replaceShaderPicking(shaders, ren, actor);
    publicAPI.replaceShaderClip(shaders, ren, actor);
    publicAPI.replaceShaderCoincidentOffset(shaders, ren, actor);
    publicAPI.replaceShaderPositionVC(shaders, ren, actor);
 
    if (model.haveSeenDepthRequest) {
      let FSSource = shaders.Fragment;
      FSSource = vtkShaderProgram.substitute(
        FSSource,
        '//VTK::ZBuffer::Dec',
        'uniform int depthRequest;'
      ).result;
      FSSource = vtkShaderProgram.substitute(FSSource, '//VTK::ZBuffer::Impl', [
        'if (depthRequest == 1) {',
        'float iz = floor(gl_FragCoord.z*65535.0 + 0.1);',
        'float rf = floor(iz/256.0)/255.0;',
        'float gf = mod(iz,256.0)/255.0;',
        'gl_FragData[0] = vec4(rf, gf, 0.0, 1.0); }',
      ]).result;
      shaders.Fragment = FSSource;
    }
  };
 
  publicAPI.getNeedToRebuildShaders = (cellBO, ren, actor) => {
    let lightComplexity = 0;
    let numberOfLights = 0;
 
    const primType = cellBO.getPrimitiveType();
    const poly = model.currentInput;
 
    // different algo from C++ as of 5/2019
    let needLighting = false;
    const pointNormals = poly.getPointData().getNormals();
    const cellNormals = poly.getCellData().getNormals();
    const flat = actor.getProperty().getInterpolation() === Shading.FLAT;
    const representation = actor.getProperty().getRepresentation();
    const mode = cellBO.getOpenGLMode(representation, primType);
    // 1) all surfaces need lighting
    if (mode === model.context.TRIANGLES) {
      needLighting = true;
      // 2) all cell normals without point normals need lighting
    } else Iif (cellNormals && !pointNormals) {
      needLighting = true;
      // 3) Phong + pointNormals need lighting
    } else if (!flat && pointNormals) {
      needLighting = true;
      // 4) Phong Lines need lighting
    } else if (!flat && mode === model.context.LINES) {
      needLighting = true;
    }
    // 5) everything else is unlit
 
    // do we need lighting?
    if (actor.getProperty().getLighting() && needLighting) {
      // consider the lighting complexity to determine which case applies
      // simple headlight, Light Kit, the whole feature set of VTK
      lightComplexity = 0;
      const lights = ren.getLightsByReference();
      for (let index = 0; index < lights.length; ++index) {
        const light = lights[index];
        const status = light.getSwitch();
        if (status > 0) {
          numberOfLights++;
          if (lightComplexity === 0) {
            lightComplexity = 1;
          }
        }
 
        if (
          lightComplexity === 1 &&
          (numberOfLights > 1 ||
            light.getIntensity() !== 1.0 ||
            !light.lightTypeIsHeadLight())
        ) {
          lightComplexity = 2;
        }
        if (lightComplexity < 3 && light.getPositional()) {
          lightComplexity = 3;
        }
      }
    }
 
    let needRebuild = false;
    const lastLightComplexity = model.lastBoundBO.getReferenceByName(
      'lastLightComplexity'
    );
    const lastLightCount =
      model.lastBoundBO.getReferenceByName('lastLightCount');
    if (
      lastLightComplexity !== lightComplexity ||
      lastLightCount !== numberOfLights
    ) {
      model.lastBoundBO.set({ lastLightComplexity: lightComplexity }, true);
      model.lastBoundBO.set({ lastLightCount: numberOfLights }, true);
      needRebuild = true;
    }
 
    // has the render pass shader replacement changed? Two options
    if (
      (!model.currentRenderPass && model.lastRenderPassShaderReplacement) ||
      (model.currentRenderPass &&
        model.currentRenderPass.getShaderReplacement() !==
          model.lastRenderPassShaderReplacement)
    ) {
      needRebuild = true;
    }
 
    // has something changed that would require us to recreate the shader?
    // candidates are
    // property modified (representation interpolation and lighting)
    // input modified
    // light complexity changed
    // render pass shader replacement changed
    if (
      model.lastHaveSeenDepthRequest !== model.haveSeenDepthRequest ||
      cellBO.getShaderSourceTime().getMTime() < model.renderable.getMTime() ||
      cellBO.getShaderSourceTime().getMTime() < model.currentInput.getMTime() ||
      cellBO.getShaderSourceTime().getMTime() <
        model.selectionStateChanged.getMTime() ||
      needRebuild
    ) {
      model.lastHaveSeenDepthRequest = model.haveSeenDepthRequest;
      return true;
    }
 
    return false;
  };
 
  publicAPI.invokeShaderCallbacks = (cellBO, ren, actor) => {
    const listCallbacks =
      model.renderable.getViewSpecificProperties().ShadersCallbacks;
    Iif (listCallbacks) {
      listCallbacks.forEach((object) => {
        object.callback(object.userData, cellBO, ren, actor);
      });
    }
  };
 
  publicAPI.setMapperShaderParameters = (cellBO, ren, actor) => {
    // Now to update the VAO too, if necessary.
    Iif (cellBO.getProgram().isUniformUsed('PrimitiveIDOffset')) {
      cellBO
        .getProgram()
        .setUniformi('PrimitiveIDOffset', model.primitiveIDOffset);
    }
    if (cellBO.getProgram().isUniformUsed('VertexIDOffset')) {
      cellBO.getProgram().setUniformi('VertexIDOffset', model.vertexIDOffset);
    }
 
    if (
      cellBO.getCABO().getElementCount() &&
      (model.VBOBuildTime.getMTime() >
        cellBO.getAttributeUpdateTime().getMTime() ||
        cellBO.getShaderSourceTime().getMTime() >
          cellBO.getAttributeUpdateTime().getMTime())
    ) {
      const lastLightComplexity = model.lastBoundBO.getReferenceByName(
        'lastLightComplexity'
      );
 
      if (cellBO.getProgram().isAttributeUsed('vertexMC')) {
        Iif (
          !cellBO
            .getVAO()
            .addAttributeArray(
              cellBO.getProgram(),
              cellBO.getCABO(),
              'vertexMC',
              cellBO.getCABO().getVertexOffset(),
              cellBO.getCABO().getStride(),
              model.context.FLOAT,
              3,
              false
            )
        ) {
          vtkErrorMacro('Error setting vertexMC in shader VAO.');
        }
      }
      if (
        cellBO.getProgram().isAttributeUsed('normalMC') &&
        cellBO.getCABO().getNormalOffset() &&
        lastLightComplexity > 0
      ) {
        Iif (
          !cellBO
            .getVAO()
            .addAttributeArray(
              cellBO.getProgram(),
              cellBO.getCABO(),
              'normalMC',
              cellBO.getCABO().getNormalOffset(),
              cellBO.getCABO().getStride(),
              model.context.FLOAT,
              3,
              false
            )
        ) {
          vtkErrorMacro('Error setting normalMC in shader VAO.');
        }
      } else {
        cellBO.getVAO().removeAttributeArray('normalMC');
      }
 
      model.renderable.getCustomShaderAttributes().forEach((attrName, idx) => {
        if (cellBO.getProgram().isAttributeUsed(`${attrName}MC`)) {
          if (
            !cellBO
              .getVAO()
              .addAttributeArray(
                cellBO.getProgram(),
                cellBO.getCABO(),
                `${attrName}MC`,
                cellBO.getCABO().getCustomData()[idx].offset,
                cellBO.getCABO().getStride(),
                model.context.FLOAT,
                cellBO.getCABO().getCustomData()[idx].components,
                false
              )
          ) {
            vtkErrorMacro(`Error setting ${attrName}MC in shader VAO.`);
          }
        }
      });
 
      if (
        cellBO.getProgram().isAttributeUsed('tcoordMC') &&
        cellBO.getCABO().getTCoordOffset()
      ) {
        Iif (
          !cellBO
            .getVAO()
            .addAttributeArray(
              cellBO.getProgram(),
              cellBO.getCABO(),
              'tcoordMC',
              cellBO.getCABO().getTCoordOffset(),
              cellBO.getCABO().getStride(),
              model.context.FLOAT,
              cellBO.getCABO().getTCoordComponents(),
              false
            )
        ) {
          vtkErrorMacro('Error setting tcoordMC in shader VAO.');
        }
      } else {
        cellBO.getVAO().removeAttributeArray('tcoordMC');
      }
      if (
        cellBO.getProgram().isAttributeUsed('scalarColor') &&
        cellBO.getCABO().getColorComponents()
      ) {
        Iif (
          !cellBO
            .getVAO()
            .addAttributeArray(
              cellBO.getProgram(),
              cellBO.getCABO().getColorBO(),
              'scalarColor',
              cellBO.getCABO().getColorOffset(),
              cellBO.getCABO().getColorBOStride(),
              model.context.UNSIGNED_BYTE,
              4,
              true
            )
        ) {
          vtkErrorMacro('Error setting scalarColor in shader VAO.');
        }
      } else {
        cellBO.getVAO().removeAttributeArray('scalarColor');
      }
 
      cellBO.getAttributeUpdateTime().modified();
    }
 
    if (model.renderable.getNumberOfClippingPlanes()) {
      // add all the clipping planes
      const numClipPlanes = model.renderable.getNumberOfClippingPlanes();
      const planeEquations = [];
 
      const shiftScaleEnabled = cellBO.getCABO().getCoordShiftAndScaleEnabled();
      const inverseShiftScaleMatrix = shiftScaleEnabled
        ? cellBO.getCABO().getInverseShiftAndScaleMatrix()
        : null;
      const mat = inverseShiftScaleMatrix
        ? mat4.copy(model.tmpMat4, actor.getMatrix())
        : actor.getMatrix();
      if (inverseShiftScaleMatrix) {
        mat4.transpose(mat, mat);
        mat4.multiply(mat, mat, inverseShiftScaleMatrix);
        mat4.transpose(mat, mat);
      }
 
      for (let i = 0; i < numClipPlanes; i++) {
        const planeEquation = [];
        model.renderable.getClippingPlaneInDataCoords(mat, i, planeEquation);
 
        for (let j = 0; j < 4; j++) {
          planeEquations.push(planeEquation[j]);
        }
      }
      cellBO.getProgram().setUniformi('numClipPlanes', numClipPlanes);
      cellBO.getProgram().setUniform4fv('clipPlanes', planeEquations);
    }
 
    if (
      model.internalColorTexture &&
      cellBO.getProgram().isUniformUsed('texture1')
    ) {
      cellBO
        .getProgram()
        .setUniformi('texture1', model.internalColorTexture.getTextureUnit());
    }
    const tus = model.openGLActor.getActiveTextures();
    if (tus) {
      for (let index = 0; index < tus.length; ++index) {
        const tex = tus[index];
        const texUnit = tex.getTextureUnit();
        const tname = `texture${texUnit + 1}`;
        if (cellBO.getProgram().isUniformUsed(tname)) {
          cellBO.getProgram().setUniformi(tname, texUnit);
        }
      }
    }
 
    // handle depth requests
    if (model.haveSeenDepthRequest) {
      cellBO
        .getProgram()
        .setUniformi('depthRequest', model.renderDepth ? 1 : 0);
    }
 
    // handle coincident
    if (cellBO.getProgram().isUniformUsed('coffset')) {
      const cp = publicAPI.getCoincidentParameters(ren, actor);
      cellBO.getProgram().setUniformf('coffset', cp.offset);
      // cfactor isn't always used when coffset is.
      if (cellBO.getProgram().isUniformUsed('cfactor')) {
        cellBO.getProgram().setUniformf('cfactor', cp.factor);
      }
    }
 
    // handle wide lines
    cellBO.setMapperShaderParameters(
      ren,
      actor,
      model._openGLRenderer.getTiledSizeAndOrigin()
    );
 
    const selector = model._openGLRenderer.getSelector();
    cellBO
      .getProgram()
      .setUniform3fArray(
        'mapperIndex',
        selector ? selector.getPropColorValue() : [0.0, 0.0, 0.0]
      );
    cellBO
      .getProgram()
      .setUniformi('picking', selector ? selector.getCurrentPass() + 1 : 0);
  };
 
  publicAPI.setLightingShaderParameters = (cellBO, ren, actor) => {
    // for unlit and headlight there are no lighting parameters
    const lastLightComplexity = model.lastBoundBO.getReferenceByName(
      'lastLightComplexity'
    );
    if (lastLightComplexity < 2) {
      return;
    }
 
    const program = cellBO.getProgram();
 
    // bind some light settings
    let numberOfLights = 0;
 
    const lights = ren.getLightsByReference();
    for (let index = 0; index < lights.length; ++index) {
      const light = lights[index];
      const status = light.getSwitch();
      if (status > 0.0) {
        const dColor = light.getColorByReference();
        const intensity = light.getIntensity();
        model.lightColor[0] = dColor[0] * intensity;
        model.lightColor[1] = dColor[1] * intensity;
        model.lightColor[2] = dColor[2] * intensity;
        // get required info from light
        const ld = light.getDirection();
        const transform = ren.getActiveCamera().getViewMatrix();
 
        const newLightDirection = [...ld];
        if (light.lightTypeIsSceneLight()) {
          newLightDirection[0] =
            transform[0] * ld[0] + transform[1] * ld[1] + transform[2] * ld[2];
          newLightDirection[1] =
            transform[4] * ld[0] + transform[5] * ld[1] + transform[6] * ld[2];
          newLightDirection[2] =
            transform[8] * ld[0] + transform[9] * ld[1] + transform[10] * ld[2];
          vtkMath.normalize(newLightDirection);
        }
 
        model.lightDirection[0] = newLightDirection[0];
        model.lightDirection[1] = newLightDirection[1];
        model.lightDirection[2] = newLightDirection[2];
        vtkMath.normalize(model.lightDirection);
        program.setUniform3fArray(
          `lightColor${numberOfLights}`,
          model.lightColor
        );
        program.setUniform3fArray(
          `lightDirectionVC${numberOfLights}`,
          model.lightDirection
        );
        numberOfLights++;
      }
    }
 
    // we are done unless we have positional lights
    if (lastLightComplexity < 3) {
      return;
    }
 
    // for lightkit case there are some parameters to set
    const cam = ren.getActiveCamera();
    const viewTF = cam.getViewMatrix();
    mat4.transpose(viewTF, viewTF);
 
    numberOfLights = 0;
 
    for (let index = 0; index < lights.length; ++index) {
      const light = lights[index];
      const status = light.getSwitch();
      if (status > 0.0) {
        const lp = light.getTransformedPosition();
        const np = new Float64Array(3);
        vec3.transformMat4(np, lp, viewTF);
        program.setUniform3fArray(
          `lightAttenuation${numberOfLights}`,
          light.getAttenuationValuesByReference()
        );
        program.setUniformi(
          `lightPositional${numberOfLights}`,
          light.getPositional()
        );
        program.setUniformf(
          `lightExponent${numberOfLights}`,
          light.getExponent()
        );
        program.setUniformf(
          `lightConeAngle${numberOfLights}`,
          light.getConeAngle()
        );
        program.setUniform3fArray(`lightPositionVC${numberOfLights}`, [
          np[0],
          np[1],
          np[2],
        ]);
        numberOfLights++;
      }
    }
  };
 
  function safeMatrixMultiply(matrixArray, matrixType, tmpMat) {
    matrixType.identity(tmpMat);
    return matrixArray.reduce((res, matrix, index) => {
      if (index === 0) {
        return matrix ? matrixType.copy(res, matrix) : matrixType.identity(res);
      }
      return matrix ? matrixType.multiply(res, res, matrix) : res;
    }, tmpMat);
  }
 
  publicAPI.setCameraShaderParameters = (cellBO, ren, actor) => {
    const program = cellBO.getProgram();
 
    // [WMVP]C == {world, model, view, projection} coordinates
    // E.g., WCPC == world to projection coordinate transformation
    const keyMats = model.openGLCamera.getKeyMatrices(ren);
    const cam = ren.getActiveCamera();
 
    const camm = model.openGLCamera.getKeyMatrixTime().getMTime();
    const progm = program.getLastCameraMTime();
 
    const shiftScaleEnabled = cellBO.getCABO().getCoordShiftAndScaleEnabled();
    const inverseShiftScaleMatrix = shiftScaleEnabled
      ? cellBO.getCABO().getInverseShiftAndScaleMatrix()
      : null;
 
    const actorIsIdentity = actor.getIsIdentity();
    const actMats = actorIsIdentity
      ? { mcwc: null, normalMatrix: null }
      : model.openGLActor.getKeyMatrices();
 
    if (actor.getCoordinateSystem() === CoordinateSystem.DISPLAY) {
      const size = model._openGLRenderer.getTiledSizeAndOrigin();
      mat4.identity(model.tmpMat4);
      model.tmpMat4[0] = 2.0 / size.usize;
      model.tmpMat4[12] = -1.0;
      model.tmpMat4[5] = 2.0 / size.vsize;
      model.tmpMat4[13] = -1.0;
      mat4.multiply(model.tmpMat4, model.tmpMat4, inverseShiftScaleMatrix);
      program.setUniformMatrix('MCPCMatrix', model.tmpMat4);
    } else {
      program.setUniformMatrix(
        'MCPCMatrix',
        safeMatrixMultiply(
          [keyMats.wcpc, actMats.mcwc, inverseShiftScaleMatrix],
          mat4,
          model.tmpMat4
        )
      );
    }
    if (program.isUniformUsed('MCVCMatrix')) {
      program.setUniformMatrix(
        'MCVCMatrix',
        safeMatrixMultiply(
          [keyMats.wcvc, actMats.mcwc, inverseShiftScaleMatrix],
          mat4,
          model.tmpMat4
        )
      );
    }
    if (program.isUniformUsed('normalMatrix')) {
      program.setUniformMatrix3x3(
        'normalMatrix',
        safeMatrixMultiply(
          [keyMats.normalMatrix, actMats.normalMatrix],
          mat3,
          model.tmpMat3
        )
      );
    }
 
    if (progm !== camm) {
      if (program.isUniformUsed('cameraParallel')) {
        program.setUniformi('cameraParallel', cam.getParallelProjection());
      }
      program.setLastCameraMTime(camm);
    }
 
    if (!actorIsIdentity) {
      // reset the cam mtime as actor modified the shader values
      program.setLastCameraMTime(0);
    }
  };
 
  publicAPI.setPropertyShaderParameters = (cellBO, ren, actor) => {
    const program = cellBO.getProgram();
 
    let ppty = actor.getProperty();
 
    let opacity = ppty.getOpacity();
 
    let aColor = model.drawingEdges
      ? ppty.getEdgeColorByReference()
      : ppty.getAmbientColorByReference();
    let dColor = model.drawingEdges
      ? ppty.getEdgeColorByReference()
      : ppty.getDiffuseColorByReference();
 
    let aIntensity = model.drawingEdges ? 1.0 : ppty.getAmbient();
    let dIntensity = model.drawingEdges ? 0.0 : ppty.getDiffuse();
    let sIntensity = model.drawingEdges ? 0.0 : ppty.getSpecular();
 
    const specularPower = ppty.getSpecularPower();
 
    program.setUniformf('opacityUniform', opacity);
 
    program.setUniform3fArray('ambientColorUniform', aColor);
    program.setUniform3fArray('diffuseColorUniform', dColor);
 
    program.setUniformf('ambient', aIntensity);
    program.setUniformf('diffuse', dIntensity);
 
    // we are done unless we have lighting
    const lastLightComplexity = model.lastBoundBO.getReferenceByName(
      'lastLightComplexity'
    );
 
    if (lastLightComplexity < 1) {
      return;
    }
 
    let sColor = ppty.getSpecularColorByReference();
    program.setUniform3fArray('specularColorUniform', sColor);
    program.setUniformf('specularPowerUniform', specularPower);
    program.setUniformf('specular', sIntensity);
 
    // now set the backface properties if we have them
    Iif (program.isUniformUsed('ambientIntensityBF')) {
      ppty = actor.getBackfaceProperty();
 
      opacity = ppty.getOpacity();
 
      aColor = ppty.getAmbientColor();
      aIntensity = ppty.getAmbient();
 
      dColor = ppty.getDiffuseColor();
      dIntensity = ppty.getDiffuse();
 
      sColor = ppty.getSpecularColor();
      sIntensity = ppty.getSpecular();
 
      program.setUniformf('ambientIntensityBF', aIntensity);
      program.setUniformf('diffuseIntensityBF', dIntensity);
      program.setUniformf('opacityUniformBF', opacity);
      program.setUniform3fArray('ambientColorUniformBF', aColor);
      program.setUniform3fArray('diffuseColorUniformBF', dColor);
 
      // we are done unless we have lighting
      if (lastLightComplexity < 1) {
        return;
      }
 
      program.setUniformf('specularIntensityBF', sIntensity);
      program.setUniform3fArray('specularColorUniformBF', sColor);
      program.setUniformf('specularPowerUniformBF', specularPower);
    }
  };
 
  publicAPI.updateMaximumPointCellIds = (ren, actor) => {
    const selector = model._openGLRenderer.getSelector();
    if (!selector) {
      return;
    }
 
    if (model.selectionWebGLIdsToVTKIds?.points?.length) {
      const length = model.selectionWebGLIdsToVTKIds.points.length;
      selector.setMaximumPointId(length - 1);
    }
 
    if (model.selectionWebGLIdsToVTKIds?.cells?.length) {
      const length = model.selectionWebGLIdsToVTKIds.cells.length;
      selector.setMaximumCellId(length - 1);
    }
 
    const fieldAssociation = selector.getFieldAssociation();
    if (fieldAssociation === FieldAssociations.FIELD_ASSOCIATION_POINTS) {
      model.pointPicking = true;
    }
  };
 
  publicAPI.renderPieceStart = (ren, actor) => {
    model.primitiveIDOffset = 0;
    model.vertexIDOffset = 0;
 
    const picking = getPickState(model._openGLRenderer);
    if (model.lastSelectionState !== picking) {
      model.selectionStateChanged.modified();
      model.lastSelectionState = picking;
    }
 
    if (model._openGLRenderer.getSelector()) {
      switch (picking) {
        default:
          model._openGLRenderer.getSelector().renderProp(actor);
      }
    }
 
    // make sure the BOs are up to date
    publicAPI.updateBufferObjects(ren, actor);
 
    // If we are coloring by texture, then load the texture map.
    // Use Map as indicator, because texture hangs around.
    if (model.renderable.getColorTextureMap()) {
      model.internalColorTexture.activate();
    }
 
    // Bind the OpenGL, this is shared between the different primitive/cell types.
    model.lastBoundBO = null;
  };
 
  publicAPI.renderPieceDraw = (ren, actor) => {
    const representation = actor.getProperty().getRepresentation();
 
    const drawSurfaceWithEdges =
      actor.getProperty().getEdgeVisibility() &&
      representation === Representation.SURFACE;
 
    const selector = model._openGLRenderer.getSelector();
    // If we are picking points, we need to tell it to the helper
    const pointPicking =
      selector &&
      selector.getFieldAssociation() ===
        FieldAssociations.FIELD_ASSOCIATION_POINTS &&
      (model.lastSelectionState === PassTypes.ID_LOW24 ||
        model.lastSelectionState === PassTypes.ID_HIGH24);
 
    // for every primitive type
    for (let i = primTypes.Start; i < primTypes.End; i++) {
      model.primitives[i].setPointPicking(pointPicking);
      const cabo = model.primitives[i].getCABO();
      if (cabo.getElementCount()) {
        // are we drawing edges
        model.drawingEdges =
          drawSurfaceWithEdges &&
          (i === primTypes.TrisEdges || i === primTypes.TriStripsEdges);
        // don't draw edges when rendering depth or rendering for picking
        if (
          !model.drawingEdges ||
          !(model.renderDepth || model.lastSelectionState >= 0)
        ) {
          model.lastBoundBO = model.primitives[i];
          model.primitiveIDOffset += model.primitives[i].drawArrays(
            ren,
            actor,
            representation,
            publicAPI
          );
          model.vertexIDOffset += model.primitives[i]
            .getCABO()
            .getElementCount();
        }
      }
    }
  };
 
  publicAPI.renderPieceFinish = (ren, actor) => {
    Iif (model.LastBoundBO) {
      model.LastBoundBO.getVAO().release();
    }
    if (model.renderable.getColorTextureMap()) {
      model.internalColorTexture.deactivate();
    }
  };
 
  publicAPI.renderPiece = (ren, actor) => {
    // Make sure that we have been properly initialized.
    // if (ren.getRenderWindow().checkAbortStatus()) {
    //   return;
    // }
 
    publicAPI.invokeEvent(StartEvent);
    if (!model.renderable.getStatic()) {
      model.renderable.update();
    }
    model.currentInput = model.renderable.getInputData();
    publicAPI.invokeEvent(EndEvent);
 
    Iif (!model.currentInput) {
      vtkErrorMacro('No input!');
      return;
    }
 
    // if there are no points then we are done
    Iif (
      !model.currentInput.getPoints ||
      !model.currentInput.getPoints().getNumberOfValues()
    ) {
      return;
    }
 
    // apply faceCulling
    const gl = model.context;
    const backfaceCulling = actor.getProperty().getBackfaceCulling();
    const frontfaceCulling = actor.getProperty().getFrontfaceCulling();
    if (!backfaceCulling && !frontfaceCulling) {
      model._openGLRenderWindow.disableCullFace();
    } else Eif (frontfaceCulling) {
      model._openGLRenderWindow.enableCullFace();
      gl.cullFace(gl.FRONT);
    } else {
      model._openGLRenderWindow.enableCullFace();
      gl.cullFace(gl.BACK);
    }
 
    publicAPI.renderPieceStart(ren, actor);
    publicAPI.renderPieceDraw(ren, actor);
    publicAPI.renderPieceFinish(ren, actor);
  };
 
  publicAPI.computeBounds = (ren, actor) => {
    if (!publicAPI.getInput()) {
      vtkMath.uninitializeBounds(model.bounds);
      return;
    }
    model.bounds = publicAPI.getInput().getBounds();
  };
 
  publicAPI.updateBufferObjects = (ren, actor) => {
    // Rebuild buffers if needed
    if (publicAPI.getNeedToRebuildBufferObjects(ren, actor)) {
      publicAPI.buildBufferObjects(ren, actor);
    }
  };
 
  publicAPI.getNeedToRebuildBufferObjects = (ren, actor) => {
    // first do a coarse check
    // Note that the actor's mtime includes it's properties mtime
    const vmtime = model.VBOBuildTime.getMTime();
    if (
      vmtime < publicAPI.getMTime() ||
      vmtime < model.renderable.getMTime() ||
      vmtime < actor.getMTime() ||
      vmtime < model.currentInput.getMTime()
    ) {
      return true;
    }
    return false;
  };
 
  publicAPI.buildBufferObjects = (ren, actor) => {
    const poly = model.currentInput;
 
    Iif (poly === null) {
      return;
    }
 
    model.renderable.mapScalars(poly, 1.0);
    const c = model.renderable.getColorMapColors();
 
    model.haveCellScalars = false;
    const scalarMode = model.renderable.getScalarMode();
    if (model.renderable.getScalarVisibility()) {
      // We must figure out how the scalars should be mapped to the polydata.
      if (
        (scalarMode === ScalarMode.USE_CELL_DATA ||
          scalarMode === ScalarMode.USE_CELL_FIELD_DATA ||
          scalarMode === ScalarMode.USE_FIELD_DATA ||
          !poly.getPointData().getScalars()) &&
        scalarMode !== ScalarMode.USE_POINT_FIELD_DATA &&
        c
      ) {
        model.haveCellScalars = true;
      }
    }
 
    // Do we have normals?
    let n =
      actor.getProperty().getInterpolation() !== Shading.FLAT
        ? poly.getPointData().getNormals()
        : null;
    Iif (n === null && poly.getCellData().getNormals()) {
      model.haveCellNormals = true;
      n = poly.getCellData().getNormals();
    }
 
    // rebuild the VBO if the data has changed we create a string for the VBO what
    // can change the VBO? points normals tcoords colors so what can change those?
    // the input data is clearly one as it can change all four items tcoords may
    // haveTextures or not colors may change based on quite a few mapping
    // parameters in the mapper
 
    const representation = actor.getProperty().getRepresentation();
 
    let tcoords = poly.getPointData().getTCoords();
    if (!model.openGLActor.getActiveTextures()) {
      tcoords = null;
    }
 
    // handle color mapping via texture
    if (model.renderable.getColorCoordinates()) {
      tcoords = model.renderable.getColorCoordinates();
      if (!model.internalColorTexture) {
        model.internalColorTexture = vtkOpenGLTexture.newInstance({
          resizable: true,
        });
      }
      const tex = model.internalColorTexture;
      // the following 4 lines allow for NPOT textures
      tex.setMinificationFilter(Filter.NEAREST);
      tex.setMagnificationFilter(Filter.NEAREST);
      tex.setWrapS(Wrap.CLAMP_TO_EDGE);
      tex.setWrapT(Wrap.CLAMP_TO_EDGE);
      tex.setOpenGLRenderWindow(model._openGLRenderWindow);
 
      const input = model.renderable.getColorTextureMap();
      const ext = input.getExtent();
      const inScalars = input.getPointData().getScalars();
      tex.create2DFromRaw(
        ext[1] - ext[0] + 1,
        ext[3] - ext[2] + 1,
        inScalars.getNumberOfComponents(),
        inScalars.getDataType(),
        inScalars.getData()
      );
      tex.activate();
      tex.sendParameters();
      tex.deactivate();
    }
 
    const toString =
      `${poly.getMTime()}A${representation}B${poly.getMTime()}` +
      `C${n ? n.getMTime() : 1}D${c ? c.getMTime() : 1}` +
      `E${actor.getProperty().getEdgeVisibility()}` +
      `F${tcoords ? tcoords.getMTime() : 1}`;
    if (model.VBOBuildString !== toString) {
      // Build the VBOs
      const points = poly.getPoints();
      const options = {
        points,
        normals: n,
        tcoords,
        colors: c,
        cellOffset: 0,
        vertexOffset: 0, // Used to keep track of vertex ids across primitives for selection
        haveCellScalars: model.haveCellScalars,
        haveCellNormals: model.haveCellNormals,
        customAttributes: model.renderable
          .getCustomShaderAttributes()
          .map((arrayName) => poly.getPointData().getArrayByName(arrayName)),
      };
 
      if (model.renderable.getPopulateSelectionSettings()) {
        model.selectionWebGLIdsToVTKIds = {
          points: null,
          cells: null,
        };
      }
 
      const primitives = [
        { inRep: 'verts', cells: poly.getVerts() },
        { inRep: 'lines', cells: poly.getLines() },
        { inRep: 'polys', cells: poly.getPolys() },
        { inRep: 'strips', cells: poly.getStrips() },
        { inRep: 'polys', cells: poly.getPolys() },
        { inRep: 'strips', cells: poly.getStrips() },
      ];
      const drawSurfaceWithEdges =
        actor.getProperty().getEdgeVisibility() &&
        representation === Representation.SURFACE;
 
      for (let i = primTypes.Start; i < primTypes.End; i++) {
        if (i !== primTypes.TrisEdges && i !== primTypes.TriStripsEdges) {
          options.cellOffset += model.primitives[i]
            .getCABO()
            .createVBO(
              primitives[i].cells,
              primitives[i].inRep,
              representation,
              options,
              model.selectionWebGLIdsToVTKIds
            );
          options.vertexOffset += model.primitives[i]
            .getCABO()
            .getElementCount();
        } else {
          // if we have edge visibility build the edge VBOs
          if (drawSurfaceWithEdges) {
            // VBOs for edges in "surface with edges" are the last to be built,
            // they are not used when picking with a hardware selector so they
            // don't need selectionWebGLIdsToVTKIds and don't update cellOffset and vertexOffset
            model.primitives[i]
              .getCABO()
              .createVBO(
                primitives[i].cells,
                primitives[i].inRep,
                Representation.WIREFRAME,
                {
                  ...options,
                  tcoords: null,
                  colors: null,
                  haveCellScalars: false,
                  haveCellNormals: false,
                }
              );
          } else {
            // otherwise free them
            model.primitives[i].releaseGraphicsResources();
          }
        }
      }
 
      if (model.renderable.getPopulateSelectionSettings()) {
        model.renderable.setSelectionWebGLIdsToVTKIds(
          model.selectionWebGLIdsToVTKIds
        );
        publicAPI.updateMaximumPointCellIds();
      }
 
      model.VBOBuildTime.modified();
      model.VBOBuildString = toString;
    }
  };
 
  publicAPI.getAllocatedGPUMemoryInBytes = () => {
    let memUsed = 0;
    model.primitives.forEach((prim) => {
      memUsed += prim.getAllocatedGPUMemoryInBytes();
    });
    // Return in MB
    return memUsed;
  };
}
 
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
 
const DEFAULT_VALUES = {
  context: null,
  VBOBuildTime: 0,
  VBOBuildString: null,
  primitives: null,
  primTypes: null,
  shaderRebuildString: null,
  tmpMat4: null,
  ambientColor: [], // used internally
  diffuseColor: [], // used internally
  specularColor: [], // used internally
  lightColor: [], // used internally
  lightDirection: [], // used internally
  lastHaveSeenDepthRequest: false,
  haveSeenDepthRequest: false,
  lastSelectionState: PassTypes.MIN_KNOWN_PASS - 1,
  selectionStateChanged: null,
  selectionWebGLIdsToVTKIds: null,
  pointPicking: false,
};
 
// ----------------------------------------------------------------------------
 
export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);
 
  // Inheritance
  vtkViewNode.extend(publicAPI, model, initialValues);
  vtkReplacementShaderMapper.implementReplaceShaderCoincidentOffset(
    publicAPI,
    model,
    initialValues
  );
  vtkReplacementShaderMapper.implementBuildShadersWithReplacements(
    publicAPI,
    model,
    initialValues
  );
 
  model.primitives = [];
  model.primTypes = primTypes;
 
  model.tmpMat3 = mat3.identity(new Float64Array(9));
  model.tmpMat4 = mat4.identity(new Float64Array(16));
 
  for (let i = primTypes.Start; i < primTypes.End; i++) {
    model.primitives[i] = vtkHelper.newInstance();
    model.primitives[i].setPrimitiveType(i);
    model.primitives[i].set(
      { lastLightComplexity: 0, lastLightCount: 0, lastSelectionPass: false },
      true
    );
  }
 
  // Build VTK API
  macro.setGet(publicAPI, model, ['context']);
 
  model.VBOBuildTime = {};
  macro.obj(model.VBOBuildTime, { mtime: 0 });
 
  model.selectionStateChanged = {};
  macro.obj(model.selectionStateChanged, { mtime: 0 });
 
  // Object methods
  vtkOpenGLPolyDataMapper(publicAPI, model);
}
 
// ----------------------------------------------------------------------------
 
export const newInstance = macro.newInstance(extend, 'vtkOpenGLPolyDataMapper');
 
// ----------------------------------------------------------------------------
 
export default { newInstance, extend };
 
// Register ourself to OpenGL backend if imported
registerOverride('vtkMapper', newInstance);