All files / engine/Source/Scene Primitive.js

90.93% Statements 823/905
85.23% Branches 358/420
90.16% Functions 55/61
90.85% Lines 815/897

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 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505                                                                                                                                                                                                                                                                                                                    787x                             787x                       787x 787x 787x                                         787x 787x 787x                                       787x 787x                   787x   787x 787x 787x 787x 787x 787x                     787x                       787x         787x     787x           1x                         786x   786x   786x 786x 786x 786x   786x 786x 786x 786x 786x 786x 786x 786x   786x 786x 786x   786x 786x 786x   786x 786x 786x 786x   786x   786x 786x   786x 786x 786x 786x 786x     786x 786x   786x 786x   786x 786x 786x 786x 786x 786x 786x 786x 786x 786x 786x     1x                         644x                               2x                               637x                               2860x                               1002x                               1255x                                                         1146x           656x   656x 656x     656x 842x 738x 738x     738x 73x   73x             1x 1x       738x 737x         656x     1x 1x 1x     872x 872x 222x 650x 146x 504x 3x 501x 501x         656x 656x     656x 656x       656x 656x   656x 656x 656x     656x 656x           656x 737x 737x   737x 737x               656x 125x                                                     125x 125x 125x 125x 125x     656x 2x         2x     656x             656x 656x   656x 713x 713x   713x 809x 809x 809x 809x 809x     713x       713x 435x     713x 713x   713x 713x 713x 713x 713x 713x   713x     656x 656x 656x   656x         37x 4x   33x   37x                 34x 34x 34x 134x 37x         34x 28x 28x 4x   24x       34x                 571x                 1x   1x             633x 633x 633x   633x 715x   715x         715x 82x     715x   712x 660x   660x                                           52x               3x       3x         3x 3x   3x           3x       3x             633x         1x 695x 520x     175x         175x           175x     1x             633x       204x     429x 79x       350x                   350x 350x 350x 344x         6x         350x       567x   567x             567x       567x     1x 62x 62x       62x     1x 559x 557x     2x 2x 2x         2x 2x 2x 2x   2x 2x 2x 2x   2x 2x       2x     1x         633x     511x     122x         122x               122x 120x                                       2x       122x                                 122x       567x 4x       563x 563x 563x 265x       298x   298x   298x 298x   298x   298x 298x   298x 298x   298x 201x   201x 201x     298x 57x 57x       241x 119x 119x         241x             241x               298x 298x 298x 298x 298x 298x   298x     298x       8x       8x         8x       8x       8x                 8x                         567x     567x                                   1x         1x               471x   471x 128x     128x   128x 128x 128x 142x 142x     142x                   142x             128x 1x 1x 3x         128x   128x 142x 142x 142x 142x 142x 142x 142x 142x 142x             142x 141x 141x   141x 141x 141x 141x 141x 141x         142x                   128x   128x   127x 127x     1x   343x 114x 114x       114x 114x   114x                                     114x 114x   114x     114x 114x 114x 114x       114x 114x 114x 114x   114x       111x 111x   3x                   528x     528x 528x 528x         528x 528x 571x 571x     571x 34x   537x     571x 571x     528x   528x 528x   528x                       527x 527x 527x       527x 527x 527x 527x   527x 524x 524x   3x         620x 620x 618x 618x       2x 2x 2x 2x 2x 2x 2x 2x   2x   2x 2x 2x         2x 2x   2x 2x 2x   2x 2x   2x 2x         2x             2x 2x 2x   2x     2x     2x     2x 2x 2x   2x     2x       2x 2x 2x 2x             2x           2x     1x 1x 1x 1x     635x     635x       516x     119x 119x 119x 119x 119x 119x   119x 119x   119x 119x 119x   119x 131x 131x       131x 131x 131x             131x 131x   131x       131x 131x   131x 129x       129x       129x       129x 129x     131x     119x     1x 1x   3720x 3720x         3718x     2x   2x 2x   2x 2x 2x   2x 2x 2x     2x       2x 2x 2x                                                                                         2x       635x 635x 635x 635x   635x 635x 635x 691x   691x                   691x 47x   644x     644x   644x 591x 591x 591x 591x 591x 591x 591x   591x     591x 591x         635x 635x   635x 631x     635x 635x       554x     554x 26x 26x       26x   26x 26x   528x 528x     554x 554x 8x     554x 8x 8x 8x 8x                   8x 8x           559x   559x   559x     559x 559x 559x         559x 559x 559x 559x 559x 559x   559x             559x   559x 8x     8x 8x         8x 8x 8x 8x 8x   8x 8x 8x   8x             8x       1x 1x       567x 567x 567x 567x                                       567x 567x   567x 3x                                         567x                         559x     559x 8x               559x   559x 559x 559x   559x 559x 559x     613x 29x 29x 26x         29x 29x 29x 29x 29x   29x     613x 613x 608x         613x 613x 613x 613x 613x   613x 8x                                 8x   8x 8x 8x         8x 8x 8x 8x 8x     613x       1x                   2903x 578x 578x 578x 632x 632x 632x         632x 578x       578x                     2903x 2903x                                                     2794x       2x           2792x     2792x 2696x 96x 45x 51x       51x         2792x 2792x 2792x 2792x 2792x 2792x 2792x   2792x 2792x   2792x 4531x 4531x 4531x 4531x 4531x 4531x 4531x 4531x   4531x 4526x   5x     4531x                                   1x 5544x                 6x     5538x 1x       5537x 1x           5536x 2x     5534x 5534x 656x   5534x 5534x         5534x     5534x       999x 471x   528x       5533x 635x 635x 635x     5533x 2446x     3087x 3085x   3087x 620x       3087x 3087x 3087x 3087x   3087x 620x 620x 620x 620x 2467x 5x 5x     3087x 3087x       3087x 8x 8x 8x 8x 3079x         3087x 3087x 620x 620x     3087x 263x     3087x   3087x 620x 620x     3087x 625x 625x     3087x 625x 625x                         3087x 3087x                       1x 1x   2x                     2x 2x             2x       287x 227x       227x 227x 227x       227x 100x   127x   227x                     287x   69x           6x         63x 63x         63x             1x     118x   76x 76x 75x 75x 75x 75x             75x 75x             76x     118x               118x                                           1x   200x 3x   197x 1x           196x 196x 75x     121x 121x 121x 121x 121x 130x 130x 118x 118x       121x 3x     118x 118x 118x 118x   118x 287x 287x 287x             118x 118x 118x   118x 118x 118x                           1x 1640x                                       1x       706x 706x   706x 706x 706x 621x   706x   706x 706x 706x 653x   706x   706x         706x 706x 706x   706x       642x 642x   642x 626x             626x        
import BoundingSphere from "../Core/BoundingSphere.js";
import Cartesian2 from "../Core/Cartesian2.js";
import Cartesian3 from "../Core/Cartesian3.js";
import Cartesian4 from "../Core/Cartesian4.js";
import Cartographic from "../Core/Cartographic.js";
import clone from "../Core/clone.js";
import Color from "../Core/Color.js";
import combine from "../Core/combine.js";
import ComponentDatatype from "../Core/ComponentDatatype.js";
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import destroyObject from "../Core/destroyObject.js";
import DeveloperError from "../Core/DeveloperError.js";
import EncodedCartesian3 from "../Core/EncodedCartesian3.js";
import FeatureDetection from "../Core/FeatureDetection.js";
import Geometry from "../Core/Geometry.js";
import GeometryAttribute from "../Core/GeometryAttribute.js";
import GeometryAttributes from "../Core/GeometryAttributes.js";
import GeometryOffsetAttribute from "../Core/GeometryOffsetAttribute.js";
import Intersect from "../Core/Intersect.js";
import Matrix4 from "../Core/Matrix4.js";
import Plane from "../Core/Plane.js";
import RuntimeError from "../Core/RuntimeError.js";
import subdivideArray from "../Core/subdivideArray.js";
import TaskProcessor from "../Core/TaskProcessor.js";
import BufferUsage from "../Renderer/BufferUsage.js";
import ContextLimits from "../Renderer/ContextLimits.js";
import DrawCommand from "../Renderer/DrawCommand.js";
import Pass from "../Renderer/Pass.js";
import RenderState from "../Renderer/RenderState.js";
import ShaderProgram from "../Renderer/ShaderProgram.js";
import ShaderSource from "../Renderer/ShaderSource.js";
import VertexArray from "../Renderer/VertexArray.js";
import BatchTable from "./BatchTable.js";
import CullFace from "./CullFace.js";
import DepthFunction from "./DepthFunction.js";
import PrimitivePipeline from "./PrimitivePipeline.js";
import PrimitiveState from "./PrimitiveState.js";
import SceneMode from "./SceneMode.js";
import ShadowMode from "./ShadowMode.js";
 
/**
 * A primitive represents geometry in the {@link Scene}.  The geometry can be from a single {@link GeometryInstance}
 * as shown in example 1 below, or from an array of instances, even if the geometry is from different
 * geometry types, e.g., an {@link RectangleGeometry} and an {@link EllipsoidGeometry} as shown in Code Example 2.
 * <p>
 * A primitive combines geometry instances with an {@link Appearance} that describes the full shading, including
 * {@link Material} and {@link RenderState}.  Roughly, the geometry instance defines the structure and placement,
 * and the appearance defines the visual characteristics.  Decoupling geometry and appearance allows us to mix
 * and match most of them and add a new geometry or appearance independently of each other.
 * </p>
 * <p>
 * Combining multiple instances into one primitive is called batching, and significantly improves performance for static data.
 * Instances can be individually picked; {@link Scene#pick} returns their {@link GeometryInstance#id}.  Using
 * per-instance appearances like {@link PerInstanceColorAppearance}, each instance can also have a unique color.
 * </p>
 * <p>
 * {@link Geometry} can either be created and batched on a web worker or the main thread. The first two examples
 * show geometry that will be created on a web worker by using the descriptions of the geometry. The third example
 * shows how to create the geometry on the main thread by explicitly calling the <code>createGeometry</code> method.
 * </p>
 *
 * @alias Primitive
 * @constructor
 *
 * @param {object} [options] Object with the following properties:
 * @param {GeometryInstance[]|GeometryInstance} [options.geometryInstances] The geometry instances - or a single geometry instance - to render.
 * @param {Appearance} [options.appearance] The appearance used to render the primitive.
 * @param {Appearance} [options.depthFailAppearance] The appearance used to shade this primitive when it fails the depth test.
 * @param {boolean} [options.show=true] Determines if this primitive will be shown.
 * @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The 4x4 transformation matrix that transforms the primitive (all geometry instances) from model to world coordinates.
 * @param {boolean} [options.vertexCacheOptimize=false] When <code>true</code>, geometry vertices are optimized for the pre and post-vertex-shader caches.
 * @param {boolean} [options.interleave=false] When <code>true</code>, geometry vertex attributes are interleaved, which can slightly improve rendering performance but increases load time.
 * @param {boolean} [options.compressVertices=true] When <code>true</code>, the geometry vertices are compressed, which will save memory.
 * @param {boolean} [options.releaseGeometryInstances=true] When <code>true</code>, the primitive does not keep a reference to the input <code>geometryInstances</code> to save memory.
 * @param {boolean} [options.allowPicking=true] When <code>true</code>, each geometry instance will only be pickable with {@link Scene#pick}.  When <code>false</code>, GPU memory is saved.
 * @param {boolean} [options.cull=true] When <code>true</code>, the renderer frustum culls and horizon culls the primitive's commands based on their bounding volume.  Set this to <code>false</code> for a small performance gain if you are manually culling the primitive.
 * @param {boolean} [options.asynchronous=true] Determines if the primitive will be created asynchronously or block until ready.
 * @param {boolean} [options.debugShowBoundingVolume=false] For debugging only. Determines if this primitive's commands' bounding spheres are shown.
 * @param {ShadowMode} [options.shadows=ShadowMode.DISABLED] Determines whether this primitive casts or receives shadows from light sources.
 *
 * @example
 * // 1. Draw a translucent ellipse on the surface with a checkerboard pattern
 * const instance = new Cesium.GeometryInstance({
 *   geometry : new Cesium.EllipseGeometry({
 *       center : Cesium.Cartesian3.fromDegrees(-100.0, 20.0),
 *       semiMinorAxis : 500000.0,
 *       semiMajorAxis : 1000000.0,
 *       rotation : Cesium.Math.PI_OVER_FOUR,
 *       vertexFormat : Cesium.VertexFormat.POSITION_AND_ST
 *   }),
 *   id : 'object returned when this instance is picked and to get/set per-instance attributes'
 * });
 * scene.primitives.add(new Cesium.Primitive({
 *   geometryInstances : instance,
 *   appearance : new Cesium.EllipsoidSurfaceAppearance({
 *     material : Cesium.Material.fromType('Checkerboard')
 *   })
 * }));
 *
 * @example
 * // 2. Draw different instances each with a unique color
 * const rectangleInstance = new Cesium.GeometryInstance({
 *   geometry : new Cesium.RectangleGeometry({
 *     rectangle : Cesium.Rectangle.fromDegrees(-140.0, 30.0, -100.0, 40.0),
 *     vertexFormat : Cesium.PerInstanceColorAppearance.VERTEX_FORMAT
 *   }),
 *   id : 'rectangle',
 *   attributes : {
 *     color : new Cesium.ColorGeometryInstanceAttribute(0.0, 1.0, 1.0, 0.5)
 *   }
 * });
 * const ellipsoidInstance = new Cesium.GeometryInstance({
 *   geometry : new Cesium.EllipsoidGeometry({
 *     radii : new Cesium.Cartesian3(500000.0, 500000.0, 1000000.0),
 *     vertexFormat : Cesium.VertexFormat.POSITION_AND_NORMAL
 *   }),
 *   modelMatrix : Cesium.Matrix4.multiplyByTranslation(Cesium.Transforms.eastNorthUpToFixedFrame(
 *     Cesium.Cartesian3.fromDegrees(-95.59777, 40.03883)), new Cesium.Cartesian3(0.0, 0.0, 500000.0), new Cesium.Matrix4()),
 *   id : 'ellipsoid',
 *   attributes : {
 *     color : Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.AQUA)
 *   }
 * });
 * scene.primitives.add(new Cesium.Primitive({
 *   geometryInstances : [rectangleInstance, ellipsoidInstance],
 *   appearance : new Cesium.PerInstanceColorAppearance()
 * }));
 *
 * @example
 * // 3. Create the geometry on the main thread.
 * scene.primitives.add(new Cesium.Primitive({
 *   geometryInstances : new Cesium.GeometryInstance({
 *     geometry : Cesium.EllipsoidGeometry.createGeometry(new Cesium.EllipsoidGeometry({
 *       radii : new Cesium.Cartesian3(500000.0, 500000.0, 1000000.0),
 *       vertexFormat : Cesium.VertexFormat.POSITION_AND_NORMAL
 *     })),
 *     modelMatrix : Cesium.Matrix4.multiplyByTranslation(Cesium.Transforms.eastNorthUpToFixedFrame(
 *       Cesium.Cartesian3.fromDegrees(-95.59777, 40.03883)), new Cesium.Cartesian3(0.0, 0.0, 500000.0), new Cesium.Matrix4()),
 *     id : 'ellipsoid',
 *     attributes : {
 *       color : Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.AQUA)
 *     }
 *   }),
 *   appearance : new Cesium.PerInstanceColorAppearance(),
 *   asynchronous : false
 * }));
 *
 * @see GeometryInstance
 * @see Appearance
 * @see ClassificationPrimitive
 * @see GroundPrimitive
 */
function Primitive(options) {
  options = options ?? Frozen.EMPTY_OBJECT;
 
  /**
   * The geometry instances rendered with this primitive.  This may
   * be <code>undefined</code> if <code>options.releaseGeometryInstances</code>
   * is <code>true</code> when the primitive is constructed.
   * <p>
   * Changing this property after the primitive is rendered has no effect.
   * </p>
   *
   * @readonly
   * @type GeometryInstance[]|GeometryInstance
   *
   * @default undefined
   */
  this.geometryInstances = options.geometryInstances;
 
  /**
   * The {@link Appearance} used to shade this primitive. Each geometry
   * instance is shaded with the same appearance.  Some appearances, like
   * {@link PerInstanceColorAppearance} allow giving each instance unique
   * properties.
   *
   * @type Appearance
   *
   * @default undefined
   */
  this.appearance = options.appearance;
  this._appearance = undefined;
  this._material = undefined;
 
  /**
   * The {@link Appearance} used to shade this primitive when it fails the depth test. Each geometry
   * instance is shaded with the same appearance.  Some appearances, like
   * {@link PerInstanceColorAppearance} allow giving each instance unique
   * properties.
   *
   * <p>
   * When using an appearance that requires a color attribute, like PerInstanceColorAppearance,
   * add a depthFailColor per-instance attribute instead.
   * </p>
   *
   * <p>
   * Requires the EXT_frag_depth WebGL extension to render properly. If the extension is not supported,
   * there may be artifacts.
   * </p>
   * @type Appearance
   *
   * @default undefined
   */
  this.depthFailAppearance = options.depthFailAppearance;
  this._depthFailAppearance = undefined;
  this._depthFailMaterial = undefined;
 
  /**
   * The 4x4 transformation matrix that transforms the primitive (all geometry instances) from model to world coordinates.
   * When this is the identity matrix, the primitive is drawn in world coordinates, i.e., Earth's WGS84 coordinates.
   * Local reference frames can be used by providing a different transformation matrix, like that returned
   * by {@link Transforms.eastNorthUpToFixedFrame}.
   *
   * <p>
   * This property is only supported in 3D mode.
   * </p>
   *
   * @type Matrix4
   *
   * @default Matrix4.IDENTITY
   *
   * @example
   * const origin = Cesium.Cartesian3.fromDegrees(-95.0, 40.0, 200000.0);
   * p.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(origin);
   */
  this.modelMatrix = Matrix4.clone(options.modelMatrix ?? Matrix4.IDENTITY);
  this._modelMatrix = new Matrix4();
 
  /**
   * Determines if the primitive will be shown.  This affects all geometry
   * instances in the primitive.
   *
   * @type {boolean}
   *
   * @default true
   */
  this.show = options.show ?? true;
 
  this._vertexCacheOptimize = options.vertexCacheOptimize ?? false;
  this._interleave = options.interleave ?? false;
  this._releaseGeometryInstances = options.releaseGeometryInstances ?? true;
  this._allowPicking = options.allowPicking ?? true;
  this._asynchronous = options.asynchronous ?? true;
  this._compressVertices = options.compressVertices ?? true;
 
  /**
   * When <code>true</code>, the renderer frustum culls and horizon culls the primitive's commands
   * based on their bounding volume.  Set this to <code>false</code> for a small performance gain
   * if you are manually culling the primitive.
   *
   * @type {boolean}
   *
   * @default true
   */
  this.cull = options.cull ?? true;
 
  /**
   * This property is for debugging only; it is not for production use nor is it optimized.
   * <p>
   * Draws the bounding sphere for each draw command in the primitive.
   * </p>
   *
   * @type {boolean}
   *
   * @default false
   */
  this.debugShowBoundingVolume = options.debugShowBoundingVolume ?? false;
 
  /**
   * @private
   */
  this.rtcCenter = options.rtcCenter;
 
  //>>includeStart('debug', pragmas.debug);
  if (
    defined(this.rtcCenter) &&
    (!defined(this.geometryInstances) ||
      (Array.isArray(this.geometryInstances) &&
        this.geometryInstances.length !== 1))
  ) {
    throw new DeveloperError(
      "Relative-to-center rendering only supports one geometry instance.",
    );
  }
  //>>includeEnd('debug');
 
  /**
   * Determines whether this primitive casts or receives shadows from light sources.
   *
   * @type {ShadowMode}
   *
   * @default ShadowMode.DISABLED
   */
  this.shadows = options.shadows ?? ShadowMode.DISABLED;
 
  this._translucent = undefined;
 
  this._state = PrimitiveState.READY;
  this._geometries = [];
  this._error = undefined;
  this._numberOfInstances = 0;
 
  this._boundingSpheres = [];
  this._boundingSphereWC = [];
  this._boundingSphereCV = [];
  this._boundingSphere2D = [];
  this._boundingSphereMorph = [];
  this._perInstanceAttributeCache = new Map();
  this._instanceIds = [];
  this._lastPerInstanceAttributeIndex = 0;
 
  this._va = [];
  this._attributeLocations = undefined;
  this._primitiveType = undefined;
 
  this._frontFaceRS = undefined;
  this._backFaceRS = undefined;
  this._sp = undefined;
 
  this._depthFailAppearance = undefined;
  this._spDepthFail = undefined;
  this._frontFaceDepthFailRS = undefined;
  this._backFaceDepthFailRS = undefined;
 
  this._pickIds = [];
 
  this._colorCommands = [];
  this._pickCommands = [];
 
  this._createBoundingVolumeFunction = options._createBoundingVolumeFunction;
  this._createRenderStatesFunction = options._createRenderStatesFunction;
  this._createShaderProgramFunction = options._createShaderProgramFunction;
  this._createCommandsFunction = options._createCommandsFunction;
  this._updateAndQueueCommandsFunction =
    options._updateAndQueueCommandsFunction;
 
  this._createPickOffsets = options._createPickOffsets;
  this._pickOffsets = undefined;
 
  this._createGeometryResults = undefined;
  this._ready = false;
 
  this._batchTable = undefined;
  this._batchTableAttributeIndices = undefined;
  this._offsetInstanceExtend = undefined;
  this._batchTableOffsetAttribute2DIndex = undefined;
  this._batchTableOffsetsUpdated = false;
  this._instanceBoundingSpheres = undefined;
  this._instanceBoundingSpheresCV = undefined;
  this._tempBoundingSpheres = undefined;
  this._recomputeBoundingSpheres = false;
  this._batchTableBoundingSpheresUpdated = false;
  this._batchTableBoundingSphereAttributeIndices = undefined;
}
 
Object.defineProperties(Primitive.prototype, {
  /**
   * When <code>true</code>, geometry vertices are optimized for the pre and post-vertex-shader caches.
   *
   * @memberof Primitive.prototype
   *
   * @type {boolean}
   * @readonly
   *
   * @default true
   */
  vertexCacheOptimize: {
    get: function () {
      return this._vertexCacheOptimize;
    },
  },
 
  /**
   * Determines if geometry vertex attributes are interleaved, which can slightly improve rendering performance.
   *
   * @memberof Primitive.prototype
   *
   * @type {boolean}
   * @readonly
   *
   * @default false
   */
  interleave: {
    get: function () {
      return this._interleave;
    },
  },
 
  /**
   * When <code>true</code>, the primitive does not keep a reference to the input <code>geometryInstances</code> to save memory.
   *
   * @memberof Primitive.prototype
   *
   * @type {boolean}
   * @readonly
   *
   * @default true
   */
  releaseGeometryInstances: {
    get: function () {
      return this._releaseGeometryInstances;
    },
  },
 
  /**
   * When <code>true</code>, each geometry instance will only be pickable with {@link Scene#pick}.  When <code>false</code>, GPU memory is saved.         *
   *
   * @memberof Primitive.prototype
   *
   * @type {boolean}
   * @readonly
   *
   * @default true
   */
  allowPicking: {
    get: function () {
      return this._allowPicking;
    },
  },
 
  /**
   * Determines if the geometry instances will be created and batched on a web worker.
   *
   * @memberof Primitive.prototype
   *
   * @type {boolean}
   * @readonly
   *
   * @default true
   */
  asynchronous: {
    get: function () {
      return this._asynchronous;
    },
  },
 
  /**
   * When <code>true</code>, geometry vertices are compressed, which will save memory.
   *
   * @memberof Primitive.prototype
   *
   * @type {boolean}
   * @readonly
   *
   * @default true
   */
  compressVertices: {
    get: function () {
      return this._compressVertices;
    },
  },
 
  /**
   * Determines if the primitive is complete and ready to render.  If this property is
   * true, the primitive will be rendered the next time that {@link Primitive#update}
   * is called.
   *
   * @memberof Primitive.prototype
   *
   * @type {boolean}
   * @readonly
   *
   * @example
   * // Wait for a primitive to become ready before accessing attributes
   * const removeListener = scene.postRender.addEventListener(() => {
   *   if (!frustumPrimitive.ready) {
   *     return;
   *   }
   *
   *   const attributes = primitive.getGeometryInstanceAttributes('an id');
   *   attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.AQUA);
   *
   *   removeListener();
   * });
   */
  ready: {
    get: function () {
      return this._ready;
    },
  },
});
 
function getCommonPerInstanceAttributeNames(instances) {
  const length = instances.length;
 
  const attributesInAllInstances = [];
  const attributes0 = instances[0].attributes;
  let name;
 
  for (name in attributes0) {
    if (attributes0.hasOwnProperty(name) && defined(attributes0[name])) {
      const attribute = attributes0[name];
      let inAllInstances = true;
 
      // Does this same attribute exist in all instances?
      for (let i = 1; i < length; ++i) {
        const otherAttribute = instances[i].attributes[name];
 
        if (
          !defined(otherAttribute) ||
          attribute.componentDatatype !== otherAttribute.componentDatatype ||
          attribute.componentsPerAttribute !==
            otherAttribute.componentsPerAttribute ||
          attribute.normalize !== otherAttribute.normalize
        ) {
          inAllInstances = false;
          break;
        }
      }
 
      if (inAllInstances) {
        attributesInAllInstances.push(name);
      }
    }
  }
 
  return attributesInAllInstances;
}
 
const scratchGetAttributeCartesian2 = new Cartesian2();
const scratchGetAttributeCartesian3 = new Cartesian3();
const scratchGetAttributeCartesian4 = new Cartesian4();
 
function getAttributeValue(value) {
  const componentsPerAttribute = value.length;
  if (componentsPerAttribute === 1) {
    return value[0];
  } else if (componentsPerAttribute === 2) {
    return Cartesian2.unpack(value, 0, scratchGetAttributeCartesian2);
  } else if (componentsPerAttribute === 3) {
    return Cartesian3.unpack(value, 0, scratchGetAttributeCartesian3);
  } else Eif (componentsPerAttribute === 4) {
    return Cartesian4.unpack(value, 0, scratchGetAttributeCartesian4);
  }
}
 
function createBatchTable(primitive, context) {
  const geometryInstances = primitive.geometryInstances;
  const instances = Array.isArray(geometryInstances)
    ? geometryInstances
    : [geometryInstances];
  const numberOfInstances = instances.length;
  Iif (numberOfInstances === 0) {
    return;
  }
 
  const names = getCommonPerInstanceAttributeNames(instances);
  const length = names.length;
 
  const attributes = [];
  const attributeIndices = {};
  const boundingSphereAttributeIndices = {};
  let offset2DIndex;
 
  const firstInstance = instances[0];
  let instanceAttributes = firstInstance.attributes;
 
  let i;
  let name;
  let attribute;
 
  for (i = 0; i < length; ++i) {
    name = names[i];
    attribute = instanceAttributes[name];
 
    attributeIndices[name] = i;
    attributes.push({
      functionName: `czm_batchTable_${name}`,
      componentDatatype: attribute.componentDatatype,
      componentsPerAttribute: attribute.componentsPerAttribute,
      normalize: attribute.normalize,
    });
  }
 
  if (names.indexOf("distanceDisplayCondition") !== -1) {
    attributes.push(
      {
        functionName: "czm_batchTable_boundingSphereCenter3DHigh",
        componentDatatype: ComponentDatatype.FLOAT,
        componentsPerAttribute: 3,
      },
      {
        functionName: "czm_batchTable_boundingSphereCenter3DLow",
        componentDatatype: ComponentDatatype.FLOAT,
        componentsPerAttribute: 3,
      },
      {
        functionName: "czm_batchTable_boundingSphereCenter2DHigh",
        componentDatatype: ComponentDatatype.FLOAT,
        componentsPerAttribute: 3,
      },
      {
        functionName: "czm_batchTable_boundingSphereCenter2DLow",
        componentDatatype: ComponentDatatype.FLOAT,
        componentsPerAttribute: 3,
      },
      {
        functionName: "czm_batchTable_boundingSphereRadius",
        componentDatatype: ComponentDatatype.FLOAT,
        componentsPerAttribute: 1,
      },
    );
    boundingSphereAttributeIndices.center3DHigh = attributes.length - 5;
    boundingSphereAttributeIndices.center3DLow = attributes.length - 4;
    boundingSphereAttributeIndices.center2DHigh = attributes.length - 3;
    boundingSphereAttributeIndices.center2DLow = attributes.length - 2;
    boundingSphereAttributeIndices.radius = attributes.length - 1;
  }
 
  if (names.indexOf("offset") !== -1) {
    attributes.push({
      functionName: "czm_batchTable_offset2D",
      componentDatatype: ComponentDatatype.FLOAT,
      componentsPerAttribute: 3,
    });
    offset2DIndex = attributes.length - 1;
  }
 
  attributes.push({
    functionName: "czm_batchTable_pickColor",
    componentDatatype: ComponentDatatype.UNSIGNED_BYTE,
    componentsPerAttribute: 4,
    normalize: true,
  });
 
  const attributesLength = attributes.length;
  const batchTable = new BatchTable(context, attributes, numberOfInstances);
 
  for (i = 0; i < numberOfInstances; ++i) {
    const instance = instances[i];
    instanceAttributes = instance.attributes;
 
    for (let j = 0; j < length; ++j) {
      name = names[j];
      attribute = instanceAttributes[name];
      const value = getAttributeValue(attribute.value);
      const attributeIndex = attributeIndices[name];
      batchTable.setBatchedAttribute(i, attributeIndex, value);
    }
 
    const pickObject = {
      primitive: instance.pickPrimitive ?? primitive,
    };
 
    if (defined(instance.id)) {
      pickObject.id = instance.id;
    }
 
    const pickId = context.createPickId(pickObject);
    primitive._pickIds.push(pickId);
 
    const pickColor = pickId.color;
    const color = scratchGetAttributeCartesian4;
    color.x = Color.floatToByte(pickColor.red);
    color.y = Color.floatToByte(pickColor.green);
    color.z = Color.floatToByte(pickColor.blue);
    color.w = Color.floatToByte(pickColor.alpha);
 
    batchTable.setBatchedAttribute(i, attributesLength - 1, color);
  }
 
  primitive._batchTable = batchTable;
  primitive._batchTableAttributeIndices = attributeIndices;
  primitive._batchTableBoundingSphereAttributeIndices =
    boundingSphereAttributeIndices;
  primitive._batchTableOffsetAttribute2DIndex = offset2DIndex;
}
 
function cloneAttribute(attribute) {
  let clonedValues;
  if (Array.isArray(attribute.values)) {
    clonedValues = attribute.values.slice(0);
  } else {
    clonedValues = new attribute.values.constructor(attribute.values);
  }
  return new GeometryAttribute({
    componentDatatype: attribute.componentDatatype,
    componentsPerAttribute: attribute.componentsPerAttribute,
    normalize: attribute.normalize,
    values: clonedValues,
  });
}
 
function cloneGeometry(geometry) {
  const attributes = geometry.attributes;
  const newAttributes = new GeometryAttributes();
  for (const property in attributes) {
    if (attributes.hasOwnProperty(property) && defined(attributes[property])) {
      newAttributes[property] = cloneAttribute(attributes[property]);
    }
  }
 
  let indices;
  if (defined(geometry.indices)) {
    const sourceValues = geometry.indices;
    if (Array.isArray(sourceValues)) {
      indices = sourceValues.slice(0);
    } else {
      indices = new sourceValues.constructor(sourceValues);
    }
  }
 
  return new Geometry({
    attributes: newAttributes,
    indices: indices,
    primitiveType: geometry.primitiveType,
    boundingSphere: BoundingSphere.clone(geometry.boundingSphere),
  });
}
 
function cloneInstance(instance, geometry) {
  return {
    geometry: geometry,
    attributes: instance.attributes,
    modelMatrix: Matrix4.clone(instance.modelMatrix),
    pickPrimitive: instance.pickPrimitive,
    id: instance.id,
  };
}
 
const positionRegex = /in\s+vec(?:3|4)\s+(.*)3DHigh;/g;
 
Primitive._modifyShaderPosition = function (
  primitive,
  vertexShaderSource,
  scene3DOnly,
) {
  let match;
 
  let forwardDecl = "";
  let attributes = "";
  let computeFunctions = "";
 
  while ((match = positionRegex.exec(vertexShaderSource)) !== null) {
    const name = match[1];
 
    const functionName = `vec4 czm_compute${name[0].toUpperCase()}${name.substr(
      1,
    )}()`;
 
    // Don't forward-declare czm_computePosition because computePosition.glsl already does.
    if (functionName !== "vec4 czm_computePosition()") {
      forwardDecl += `${functionName};\n`;
    }
 
    if (!defined(primitive.rtcCenter)) {
      // Use GPU RTE
      if (!scene3DOnly) {
        attributes += `in vec3 ${name}2DHigh;\nin vec3 ${name}2DLow;\n`;
 
        computeFunctions +=
          `${functionName}\n` +
          `{\n` +
          `    vec4 p;\n` +
          `    if (czm_morphTime == 1.0)\n` +
          `    {\n` +
          `        p = czm_translateRelativeToEye(${name}3DHigh, ${name}3DLow);\n` +
          `    }\n` +
          `    else if (czm_morphTime == 0.0)\n` +
          `    {\n` +
          `        p = czm_translateRelativeToEye(${name}2DHigh.zxy, ${name}2DLow.zxy);\n` +
          `    }\n` +
          `    else\n` +
          `    {\n` +
          `        p = czm_columbusViewMorph(\n` +
          `                czm_translateRelativeToEye(${name}2DHigh.zxy, ${name}2DLow.zxy),\n` +
          `                czm_translateRelativeToEye(${name}3DHigh, ${name}3DLow),\n` +
          `                czm_morphTime);\n` +
          `    }\n` +
          `    return p;\n` +
          `}\n\n`;
      } else {
        computeFunctions +=
          `${functionName}\n` +
          `{\n` +
          `    return czm_translateRelativeToEye(${name}3DHigh, ${name}3DLow);\n` +
          `}\n\n`;
      }
    } else {
      // Use RTC
      vertexShaderSource = vertexShaderSource.replace(
        /in\s+vec(?:3|4)\s+position3DHigh;/g,
        "",
      );
      vertexShaderSource = vertexShaderSource.replace(
        /in\s+vec(?:3|4)\s+position3DLow;/g,
        "",
      );
 
      forwardDecl += "uniform mat4 u_modifiedModelView;\n";
      attributes += "in vec4 position;\n";
 
      computeFunctions +=
        `${functionName}\n` +
        `{\n` +
        `    return u_modifiedModelView * position;\n` +
        `}\n\n`;
 
      vertexShaderSource = vertexShaderSource.replace(
        /czm_modelViewRelativeToEye\s+\*\s+/g,
        "",
      );
      vertexShaderSource = vertexShaderSource.replace(
        /czm_modelViewProjectionRelativeToEye/g,
        "czm_projection",
      );
    }
  }
 
  return [forwardDecl, attributes, vertexShaderSource, computeFunctions].join(
    "\n",
  );
};
 
Primitive._appendShowToShader = function (primitive, vertexShaderSource) {
  if (!defined(primitive._batchTableAttributeIndices.show)) {
    return vertexShaderSource;
  }
 
  const renamedVS = ShaderSource.replaceMain(
    vertexShaderSource,
    "czm_non_show_main",
  );
  const showMain =
    "void main() \n" +
    "{ \n" +
    "    czm_non_show_main(); \n" +
    "    gl_Position *= czm_batchTable_show(batchId); \n" +
    "}";
 
  return `${renamedVS}\n${showMain}`;
};
 
Primitive._updateColorAttribute = function (
  primitive,
  vertexShaderSource,
  isDepthFail,
) {
  // some appearances have a color attribute for per vertex color.
  // only remove if color is a per instance attribute.
  if (
    !defined(primitive._batchTableAttributeIndices.color) &&
    !defined(primitive._batchTableAttributeIndices.depthFailColor)
  ) {
    return vertexShaderSource;
  }
 
  if (vertexShaderSource.search(/in\s+vec4\s+color;/g) === -1) {
    return vertexShaderSource;
  }
 
  //>>includeStart('debug', pragmas.debug);
  Iif (
    isDepthFail &&
    !defined(primitive._batchTableAttributeIndices.depthFailColor)
  ) {
    throw new DeveloperError(
      "A depthFailColor per-instance attribute is required when using a depth fail appearance that uses a color attribute.",
    );
  }
  //>>includeEnd('debug');
 
  let modifiedVS = vertexShaderSource;
  modifiedVS = modifiedVS.replace(/in\s+vec4\s+color;/g, "");
  if (!isDepthFail) {
    modifiedVS = modifiedVS.replace(
      /(\b)color(\b)/g,
      "$1czm_batchTable_color(batchId)$2",
    );
  } else {
    modifiedVS = modifiedVS.replace(
      /(\b)color(\b)/g,
      "$1czm_batchTable_depthFailColor(batchId)$2",
    );
  }
  return modifiedVS;
};
 
function appendPickToVertexShader(source) {
  const renamedVS = ShaderSource.replaceMain(source, "czm_non_pick_main");
  const pickMain =
    "out vec4 v_pickColor; \n" +
    "void main() \n" +
    "{ \n" +
    "    czm_non_pick_main(); \n" +
    "    v_pickColor = czm_batchTable_pickColor(batchId); \n" +
    "}";
 
  return `${renamedVS}\n${pickMain}`;
}
 
function appendPickToFragmentShader(source) {
  return `in vec4 v_pickColor;\n${source}`;
}
 
Primitive._updatePickColorAttribute = function (source) {
  let vsPick = source.replace(/in\s+vec4\s+pickColor;/g, "");
  vsPick = vsPick.replace(
    /(\b)pickColor(\b)/g,
    "$1czm_batchTable_pickColor(batchId)$2",
  );
  return vsPick;
};
 
Primitive._appendOffsetToShader = function (primitive, vertexShaderSource) {
  if (!defined(primitive._batchTableAttributeIndices.offset)) {
    return vertexShaderSource;
  }
 
  let attr = "in float batchId;\n";
  attr += "in float applyOffset;";
  let modifiedShader = vertexShaderSource.replace(
    /in\s+float\s+batchId;/g,
    attr,
  );
 
  let str = "vec4 $1 = czm_computePosition();\n";
  str += "    if (czm_sceneMode == czm_sceneMode3D)\n";
  str += "    {\n";
  str +=
    "        $1 = $1 + vec4(czm_batchTable_offset(batchId) * applyOffset, 0.0);";
  str += "    }\n";
  str += "    else\n";
  str += "    {\n";
  str +=
    "        $1 = $1 + vec4(czm_batchTable_offset2D(batchId) * applyOffset, 0.0);";
  str += "    }\n";
  modifiedShader = modifiedShader.replace(
    /vec4\s+([A-Za-z0-9_]+)\s+=\s+czm_computePosition\(\);/g,
    str,
  );
  return modifiedShader;
};
 
Primitive._appendDistanceDisplayConditionToShader = function (
  primitive,
  vertexShaderSource,
  scene3DOnly,
) {
  if (
    !defined(primitive._batchTableAttributeIndices.distanceDisplayCondition)
  ) {
    return vertexShaderSource;
  }
 
  const renamedVS = ShaderSource.replaceMain(
    vertexShaderSource,
    "czm_non_distanceDisplayCondition_main",
  );
  let distanceDisplayConditionMain =
    "void main() \n" +
    "{ \n" +
    "    czm_non_distanceDisplayCondition_main(); \n" +
    "    vec2 distanceDisplayCondition = czm_batchTable_distanceDisplayCondition(batchId);\n" +
    "    vec3 boundingSphereCenter3DHigh = czm_batchTable_boundingSphereCenter3DHigh(batchId);\n" +
    "    vec3 boundingSphereCenter3DLow = czm_batchTable_boundingSphereCenter3DLow(batchId);\n" +
    "    float boundingSphereRadius = czm_batchTable_boundingSphereRadius(batchId);\n";
 
  if (!scene3DOnly) {
    distanceDisplayConditionMain +=
      "    vec3 boundingSphereCenter2DHigh = czm_batchTable_boundingSphereCenter2DHigh(batchId);\n" +
      "    vec3 boundingSphereCenter2DLow = czm_batchTable_boundingSphereCenter2DLow(batchId);\n" +
      "    vec4 centerRTE;\n" +
      "    if (czm_morphTime == 1.0)\n" +
      "    {\n" +
      "        centerRTE = czm_translateRelativeToEye(boundingSphereCenter3DHigh, boundingSphereCenter3DLow);\n" +
      "    }\n" +
      "    else if (czm_morphTime == 0.0)\n" +
      "    {\n" +
      "        centerRTE = czm_translateRelativeToEye(boundingSphereCenter2DHigh.zxy, boundingSphereCenter2DLow.zxy);\n" +
      "    }\n" +
      "    else\n" +
      "    {\n" +
      "        centerRTE = czm_columbusViewMorph(\n" +
      "                czm_translateRelativeToEye(boundingSphereCenter2DHigh.zxy, boundingSphereCenter2DLow.zxy),\n" +
      "                czm_translateRelativeToEye(boundingSphereCenter3DHigh, boundingSphereCenter3DLow),\n" +
      "                czm_morphTime);\n" +
      "    }\n";
  } else {
    distanceDisplayConditionMain +=
      "    vec4 centerRTE = czm_translateRelativeToEye(boundingSphereCenter3DHigh, boundingSphereCenter3DLow);\n";
  }
 
  distanceDisplayConditionMain +=
    "    float radiusSq = boundingSphereRadius * boundingSphereRadius; \n" +
    "    float distanceSq; \n" +
    "    if (czm_sceneMode == czm_sceneMode2D) \n" +
    "    { \n" +
    "        distanceSq = czm_eyeHeight2D.y - radiusSq; \n" +
    "    } \n" +
    "    else \n" +
    "    { \n" +
    "        distanceSq = dot(centerRTE.xyz, centerRTE.xyz) - radiusSq; \n" +
    "    } \n" +
    "    distanceSq = max(distanceSq, 0.0); \n" +
    "    float nearSq = distanceDisplayCondition.x * distanceDisplayCondition.x; \n" +
    "    float farSq = distanceDisplayCondition.y * distanceDisplayCondition.y; \n" +
    "    float show = (distanceSq >= nearSq && distanceSq <= farSq) ? 1.0 : 0.0; \n" +
    "    gl_Position *= show; \n" +
    "}";
  return `${renamedVS}\n${distanceDisplayConditionMain}`;
};
 
function modifyForEncodedNormals(primitive, vertexShaderSource) {
  if (!primitive.compressVertices) {
    return vertexShaderSource;
  }
 
  const containsNormal =
    vertexShaderSource.search(/in\s+vec3\s+normal;/g) !== -1;
  const containsSt = vertexShaderSource.search(/in\s+vec2\s+st;/g) !== -1;
  if (!containsNormal && !containsSt) {
    return vertexShaderSource;
  }
 
  const containsTangent =
    vertexShaderSource.search(/in\s+vec3\s+tangent;/g) !== -1;
  const containsBitangent =
    vertexShaderSource.search(/in\s+vec3\s+bitangent;/g) !== -1;
 
  let numComponents = containsSt && containsNormal ? 2.0 : 1.0;
  numComponents += containsTangent || containsBitangent ? 1 : 0;
 
  const type = numComponents > 1 ? `vec${numComponents}` : "float";
 
  const attributeName = "compressedAttributes";
  const attributeDecl = `in ${type} ${attributeName};`;
 
  let globalDecl = "";
  let decode = "";
 
  if (containsSt) {
    globalDecl += "vec2 st;\n";
    const stComponent =
      numComponents > 1 ? `${attributeName}.x` : attributeName;
    decode += `    st = czm_decompressTextureCoordinates(${stComponent});\n`;
  }
 
  if (containsNormal && containsTangent && containsBitangent) {
    globalDecl += "vec3 normal;\n" + "vec3 tangent;\n" + "vec3 bitangent;\n";
    decode += `    czm_octDecode(${attributeName}.${
      containsSt ? "yz" : "xy"
    }, normal, tangent, bitangent);\n`;
  } else {
    if (containsNormal) {
      globalDecl += "vec3 normal;\n";
      decode += `    normal = czm_octDecode(${attributeName}${
        numComponents > 1 ? `.${containsSt ? "y" : "x"}` : ""
      });\n`;
    }
 
    Iif (containsTangent) {
      globalDecl += "vec3 tangent;\n";
      decode += `    tangent = czm_octDecode(${attributeName}.${
        containsSt && containsNormal ? "z" : "y"
      });\n`;
    }
 
    Iif (containsBitangent) {
      globalDecl += "vec3 bitangent;\n";
      decode += `    bitangent = czm_octDecode(${attributeName}.${
        containsSt && containsNormal ? "z" : "y"
      });\n`;
    }
  }
 
  let modifiedVS = vertexShaderSource;
  modifiedVS = modifiedVS.replace(/in\s+vec3\s+normal;/g, "");
  modifiedVS = modifiedVS.replace(/in\s+vec2\s+st;/g, "");
  modifiedVS = modifiedVS.replace(/in\s+vec3\s+tangent;/g, "");
  modifiedVS = modifiedVS.replace(/in\s+vec3\s+bitangent;/g, "");
  modifiedVS = ShaderSource.replaceMain(modifiedVS, "czm_non_compressed_main");
  const compressedMain =
    `${"void main() \n" + "{ \n"}${decode}    czm_non_compressed_main(); \n` +
    `}`;
 
  return [attributeDecl, globalDecl, modifiedVS, compressedMain].join("\n");
}
 
function depthClampVS(vertexShaderSource) {
  let modifiedVS = ShaderSource.replaceMain(
    vertexShaderSource,
    "czm_non_depth_clamp_main",
  );
  modifiedVS +=
    "void main() {\n" +
    "    czm_non_depth_clamp_main();\n" +
    "    gl_Position = czm_depthClamp(gl_Position);" +
    "}\n";
  return modifiedVS;
}
 
function depthClampFS(fragmentShaderSource) {
  let modifiedFS = ShaderSource.replaceMain(
    fragmentShaderSource,
    "czm_non_depth_clamp_main",
  );
  modifiedFS +=
    "void main() {\n" +
    "    czm_non_depth_clamp_main();\n" +
    "    #if defined(LOG_DEPTH)\n" +
    "        czm_writeLogDepth();\n" +
    "    #else\n" +
    "        czm_writeDepthClamp();\n" +
    "    #endif\n" +
    "}\n";
  return modifiedFS;
}
 
function validateShaderMatching(shaderProgram, attributeLocations) {
  // For a VAO and shader program to be compatible, the VAO must have
  // all active attribute in the shader program.  The VAO may have
  // extra attributes with the only concern being a potential
  // performance hit due to extra memory bandwidth and cache pollution.
  // The shader source could have extra attributes that are not used,
  // but there is no guarantee they will be optimized out.
  //
  // Here, we validate that the VAO has all attributes required
  // to match the shader program.
  const shaderAttributes = shaderProgram.vertexAttributes;
 
  //>>includeStart('debug', pragmas.debug);
  for (const name in shaderAttributes) {
    if (shaderAttributes.hasOwnProperty(name)) {
      if (!defined(attributeLocations[name])) {
        throw new DeveloperError(
          `Appearance/Geometry mismatch.  The appearance requires vertex shader attribute input '${name}', which was not computed as part of the Geometry.  Use the appearance's vertexFormat property when constructing the geometry.`,
        );
      }
    }
  }
  //>>includeEnd('debug');
}
 
function getUniformFunction(uniforms, name) {
  return function () {
    return uniforms[name];
  };
}
 
const numberOfCreationWorkers = Math.max(
  FeatureDetection.hardwareConcurrency - 1,
  1,
);
let createGeometryTaskProcessors;
const combineGeometryTaskProcessor = new TaskProcessor("combineGeometry");
 
function loadAsynchronous(primitive, frameState) {
  let instances;
  let geometry;
  let i;
  let j;
 
  const instanceIds = primitive._instanceIds;
 
  if (primitive._state === PrimitiveState.READY) {
    instances = Array.isArray(primitive.geometryInstances)
      ? primitive.geometryInstances
      : [primitive.geometryInstances];
    const length = (primitive._numberOfInstances = instances.length);
 
    const promises = [];
    let subTasks = [];
    for (i = 0; i < length; ++i) {
      geometry = instances[i].geometry;
      instanceIds.push(instances[i].id);
 
      //>>includeStart('debug', pragmas.debug);
      Iif (
        (defined(geometry._workerName) && defined(geometry._workerPath)) ||
        (!defined(geometry._workerName) && !defined(geometry._workerPath))
      ) {
        throw new DeveloperError(
          "Must define either _workerName or _workerPath for asynchronous geometry.",
        );
      }
      //>>includeEnd('debug');
 
      subTasks.push({
        moduleName: geometry._workerName,
        modulePath: geometry._workerPath,
        geometry: geometry,
      });
    }
 
    if (!defined(createGeometryTaskProcessors)) {
      createGeometryTaskProcessors = new Array(numberOfCreationWorkers);
      for (i = 0; i < numberOfCreationWorkers; i++) {
        createGeometryTaskProcessors[i] = new TaskProcessor("createGeometry");
      }
    }
 
    let subTask;
    subTasks = subdivideArray(subTasks, numberOfCreationWorkers);
 
    for (i = 0; i < subTasks.length; i++) {
      let packedLength = 0;
      const workerSubTasks = subTasks[i];
      const workerSubTasksLength = workerSubTasks.length;
      for (j = 0; j < workerSubTasksLength; ++j) {
        subTask = workerSubTasks[j];
        geometry = subTask.geometry;
        Eif (defined(geometry.constructor.pack)) {
          subTask.offset = packedLength;
          packedLength +=
            geometry.constructor.packedLength ?? geometry.packedLength;
        }
      }
 
      let subTaskTransferableObjects;
 
      if (packedLength > 0) {
        const array = new Float64Array(packedLength);
        subTaskTransferableObjects = [array.buffer];
 
        for (j = 0; j < workerSubTasksLength; ++j) {
          subTask = workerSubTasks[j];
          geometry = subTask.geometry;
          Eif (defined(geometry.constructor.pack)) {
            geometry.constructor.pack(geometry, array, subTask.offset);
            subTask.geometry = array;
          }
        }
      }
 
      promises.push(
        createGeometryTaskProcessors[i].scheduleTask(
          {
            subTasks: subTasks[i],
          },
          subTaskTransferableObjects,
        ),
      );
    }
 
    primitive._state = PrimitiveState.CREATING;
 
    Promise.all(promises)
      .then(function (results) {
        primitive._createGeometryResults = results;
        primitive._state = PrimitiveState.CREATED;
      })
      .catch(function (error) {
        setReady(primitive, frameState, PrimitiveState.FAILED, error);
      });
  } else if (primitive._state === PrimitiveState.CREATED) {
    const transferableObjects = [];
    instances = Array.isArray(primitive.geometryInstances)
      ? primitive.geometryInstances
      : [primitive.geometryInstances];
 
    const scene3DOnly = frameState.scene3DOnly;
    const projection = frameState.mapProjection;
 
    const promise = combineGeometryTaskProcessor.scheduleTask(
      PrimitivePipeline.packCombineGeometryParameters(
        {
          createGeometryResults: primitive._createGeometryResults,
          instances: instances,
          ellipsoid: projection.ellipsoid,
          projection: projection,
          elementIndexUintSupported: frameState.context.elementIndexUint,
          scene3DOnly: scene3DOnly,
          vertexCacheOptimize: primitive.vertexCacheOptimize,
          compressVertices: primitive.compressVertices,
          modelMatrix: primitive.modelMatrix,
          createPickOffsets: primitive._createPickOffsets,
        },
        transferableObjects,
      ),
      transferableObjects,
    );
 
    primitive._createGeometryResults = undefined;
    primitive._state = PrimitiveState.COMBINING;
 
    Promise.resolve(promise)
      .then(function (packedResult) {
        const result =
          PrimitivePipeline.unpackCombineGeometryResults(packedResult);
        primitive._geometries = result.geometries;
        primitive._attributeLocations = result.attributeLocations;
        primitive.modelMatrix = Matrix4.clone(
          result.modelMatrix,
          primitive.modelMatrix,
        );
        primitive._pickOffsets = result.pickOffsets;
        primitive._offsetInstanceExtend = result.offsetInstanceExtend;
        primitive._instanceBoundingSpheres = result.boundingSpheres;
        primitive._instanceBoundingSpheresCV = result.boundingSpheresCV;
 
        if (
          defined(primitive._geometries) &&
          primitive._geometries.length > 0
        ) {
          primitive._recomputeBoundingSpheres = true;
          primitive._state = PrimitiveState.COMBINED;
        } else {
          setReady(primitive, frameState, PrimitiveState.FAILED, undefined);
        }
      })
      .catch(function (error) {
        setReady(primitive, frameState, PrimitiveState.FAILED, error);
      });
  }
}
 
function loadSynchronous(primitive, frameState) {
  const instances = Array.isArray(primitive.geometryInstances)
    ? primitive.geometryInstances
    : [primitive.geometryInstances];
  const length = (primitive._numberOfInstances = instances.length);
  const clonedInstances = new Array(length);
  const instanceIds = primitive._instanceIds;
 
  let instance;
  let i;
 
  let geometryIndex = 0;
  for (i = 0; i < length; i++) {
    instance = instances[i];
    const geometry = instance.geometry;
 
    let createdGeometry;
    if (defined(geometry.attributes) && defined(geometry.primitiveType)) {
      createdGeometry = cloneGeometry(geometry);
    } else {
      createdGeometry = geometry.constructor.createGeometry(geometry);
    }
 
    clonedInstances[geometryIndex++] = cloneInstance(instance, createdGeometry);
    instanceIds.push(instance.id);
  }
 
  clonedInstances.length = geometryIndex;
 
  const scene3DOnly = frameState.scene3DOnly;
  const projection = frameState.mapProjection;
 
  const result = PrimitivePipeline.combineGeometry({
    instances: clonedInstances,
    ellipsoid: projection.ellipsoid,
    projection: projection,
    elementIndexUintSupported: frameState.context.elementIndexUint,
    scene3DOnly: scene3DOnly,
    vertexCacheOptimize: primitive.vertexCacheOptimize,
    compressVertices: primitive.compressVertices,
    modelMatrix: primitive.modelMatrix,
    createPickOffsets: primitive._createPickOffsets,
  });
 
  primitive._geometries = result.geometries;
  primitive._attributeLocations = result.attributeLocations;
  primitive.modelMatrix = Matrix4.clone(
    result.modelMatrix,
    primitive.modelMatrix,
  );
  primitive._pickOffsets = result.pickOffsets;
  primitive._offsetInstanceExtend = result.offsetInstanceExtend;
  primitive._instanceBoundingSpheres = result.boundingSpheres;
  primitive._instanceBoundingSpheresCV = result.boundingSpheresCV;
 
  if (defined(primitive._geometries) && primitive._geometries.length > 0) {
    primitive._recomputeBoundingSpheres = true;
    primitive._state = PrimitiveState.COMBINED;
  } else {
    setReady(primitive, frameState, PrimitiveState.FAILED, undefined);
  }
}
 
function recomputeBoundingSpheres(primitive, frameState) {
  const offsetIndex = primitive._batchTableAttributeIndices.offset;
  if (!primitive._recomputeBoundingSpheres || !defined(offsetIndex)) {
    primitive._recomputeBoundingSpheres = false;
    return;
  }
 
  let i;
  const offsetInstanceExtend = primitive._offsetInstanceExtend;
  const boundingSpheres = primitive._instanceBoundingSpheres;
  const length = boundingSpheres.length;
  let newBoundingSpheres = primitive._tempBoundingSpheres;
  Eif (!defined(newBoundingSpheres)) {
    newBoundingSpheres = new Array(length);
    for (i = 0; i < length; i++) {
      newBoundingSpheres[i] = new BoundingSphere();
    }
    primitive._tempBoundingSpheres = newBoundingSpheres;
  }
  for (i = 0; i < length; ++i) {
    let newBS = newBoundingSpheres[i];
    const offset = primitive._batchTable.getBatchedAttribute(
      i,
      offsetIndex,
      new Cartesian3(),
    );
    newBS = boundingSpheres[i].clone(newBS);
    transformBoundingSphere(newBS, offset, offsetInstanceExtend[i]);
  }
  const combinedBS = [];
  const combinedWestBS = [];
  const combinedEastBS = [];
 
  for (i = 0; i < length; ++i) {
    const bs = newBoundingSpheres[i];
 
    const minX = bs.center.x - bs.radius;
    if (
      minX > 0 ||
      BoundingSphere.intersectPlane(bs, Plane.ORIGIN_ZX_PLANE) !==
        Intersect.INTERSECTING
    ) {
      combinedBS.push(bs);
    } else E{
      combinedWestBS.push(bs);
      combinedEastBS.push(bs);
    }
  }
 
  let resultBS1 = combinedBS[0];
  let resultBS2 = combinedEastBS[0];
  let resultBS3 = combinedWestBS[0];
 
  for (i = 1; i < combinedBS.length; i++) {
    resultBS1 = BoundingSphere.union(resultBS1, combinedBS[i]);
  }
  for (i = 1; i < combinedEastBS.length; i++) {
    resultBS2 = BoundingSphere.union(resultBS2, combinedEastBS[i]);
  }
  for (i = 1; i < combinedWestBS.length; i++) {
    resultBS3 = BoundingSphere.union(resultBS3, combinedWestBS[i]);
  }
  const result = [];
  Eif (defined(resultBS1)) {
    result.push(resultBS1);
  }
  Iif (defined(resultBS2)) {
    result.push(resultBS2);
  }
  Iif (defined(resultBS3)) {
    result.push(resultBS3);
  }
 
  for (i = 0; i < result.length; i++) {
    const boundingSphere = result[i].clone(primitive._boundingSpheres[i]);
    primitive._boundingSpheres[i] = boundingSphere;
    primitive._boundingSphereCV[i] = BoundingSphere.projectTo2D(
      boundingSphere,
      frameState.mapProjection,
      primitive._boundingSphereCV[i],
    );
  }
 
  Primitive._updateBoundingVolumes(
    primitive,
    frameState,
    primitive.modelMatrix,
    true,
  );
  primitive._recomputeBoundingSpheres = false;
}
 
const scratchBoundingSphereCenterEncoded = new EncodedCartesian3();
const scratchBoundingSphereCartographic = new Cartographic();
const scratchBoundingSphereCenter2D = new Cartesian3();
const scratchBoundingSphere = new BoundingSphere();
 
function updateBatchTableBoundingSpheres(primitive, frameState) {
  const hasDistanceDisplayCondition = defined(
    primitive._batchTableAttributeIndices.distanceDisplayCondition,
  );
  if (
    !hasDistanceDisplayCondition ||
    primitive._batchTableBoundingSpheresUpdated
  ) {
    return;
  }
 
  const indices = primitive._batchTableBoundingSphereAttributeIndices;
  const center3DHighIndex = indices.center3DHigh;
  const center3DLowIndex = indices.center3DLow;
  const center2DHighIndex = indices.center2DHigh;
  const center2DLowIndex = indices.center2DLow;
  const radiusIndex = indices.radius;
 
  const projection = frameState.mapProjection;
  const ellipsoid = projection.ellipsoid;
 
  const batchTable = primitive._batchTable;
  const boundingSpheres = primitive._instanceBoundingSpheres;
  const length = boundingSpheres.length;
 
  for (let i = 0; i < length; ++i) {
    let boundingSphere = boundingSpheres[i];
    Iif (!defined(boundingSphere)) {
      continue;
    }
 
    const modelMatrix = primitive.modelMatrix;
    Eif (defined(modelMatrix)) {
      boundingSphere = BoundingSphere.transform(
        boundingSphere,
        modelMatrix,
        scratchBoundingSphere,
      );
    }
 
    const center = boundingSphere.center;
    const radius = boundingSphere.radius;
 
    let encodedCenter = EncodedCartesian3.fromCartesian(
      center,
      scratchBoundingSphereCenterEncoded,
    );
    batchTable.setBatchedAttribute(i, center3DHighIndex, encodedCenter.high);
    batchTable.setBatchedAttribute(i, center3DLowIndex, encodedCenter.low);
 
    if (!frameState.scene3DOnly) {
      const cartographic = ellipsoid.cartesianToCartographic(
        center,
        scratchBoundingSphereCartographic,
      );
      const center2D = projection.project(
        cartographic,
        scratchBoundingSphereCenter2D,
      );
      encodedCenter = EncodedCartesian3.fromCartesian(
        center2D,
        scratchBoundingSphereCenterEncoded,
      );
      batchTable.setBatchedAttribute(i, center2DHighIndex, encodedCenter.high);
      batchTable.setBatchedAttribute(i, center2DLowIndex, encodedCenter.low);
    }
 
    batchTable.setBatchedAttribute(i, radiusIndex, radius);
  }
 
  primitive._batchTableBoundingSpheresUpdated = true;
}
 
const offsetScratchCartesian = new Cartesian3();
const offsetCenterScratch = new Cartesian3();
function updateBatchTableOffsets(primitive, frameState) {
  const hasOffset = defined(primitive._batchTableAttributeIndices.offset);
  if (
    !hasOffset ||
    primitive._batchTableOffsetsUpdated ||
    frameState.scene3DOnly
  ) {
    return;
  }
 
  const index2D = primitive._batchTableOffsetAttribute2DIndex;
 
  const projection = frameState.mapProjection;
  const ellipsoid = projection.ellipsoid;
 
  const batchTable = primitive._batchTable;
  const boundingSpheres = primitive._instanceBoundingSpheres;
  const length = boundingSpheres.length;
 
  for (let i = 0; i < length; ++i) {
    let boundingSphere = boundingSpheres[i];
    Iif (!defined(boundingSphere)) {
      continue;
    }
    const offset = batchTable.getBatchedAttribute(
      i,
      primitive._batchTableAttributeIndices.offset,
    );
    Eif (Cartesian3.equals(offset, Cartesian3.ZERO)) {
      batchTable.setBatchedAttribute(i, index2D, Cartesian3.ZERO);
      continue;
    }
 
    const modelMatrix = primitive.modelMatrix;
    if (defined(modelMatrix)) {
      boundingSphere = BoundingSphere.transform(
        boundingSphere,
        modelMatrix,
        scratchBoundingSphere,
      );
    }
 
    let center = boundingSphere.center;
    center = ellipsoid.scaleToGeodeticSurface(center, offsetCenterScratch);
    let cartographic = ellipsoid.cartesianToCartographic(
      center,
      scratchBoundingSphereCartographic,
    );
    const center2D = projection.project(
      cartographic,
      scratchBoundingSphereCenter2D,
    );
 
    const newPoint = Cartesian3.add(offset, center, offsetScratchCartesian);
    cartographic = ellipsoid.cartesianToCartographic(newPoint, cartographic);
 
    const newPointProjected = projection.project(
      cartographic,
      offsetScratchCartesian,
    );
 
    const newVector = Cartesian3.subtract(
      newPointProjected,
      center2D,
      offsetScratchCartesian,
    );
 
    const x = newVector.x;
    newVector.x = newVector.z;
    newVector.z = newVector.y;
    newVector.y = x;
 
    batchTable.setBatchedAttribute(i, index2D, newVector);
  }
 
  primitive._batchTableOffsetsUpdated = true;
}
 
function createVertexArray(primitive, frameState) {
  const attributeLocations = primitive._attributeLocations;
  const geometries = primitive._geometries;
  const scene3DOnly = frameState.scene3DOnly;
  const context = frameState.context;
 
  const va = [];
  const length = geometries.length;
  for (let i = 0; i < length; ++i) {
    const geometry = geometries[i];
 
    va.push(
      VertexArray.fromGeometry({
        context: context,
        geometry: geometry,
        attributeLocations: attributeLocations,
        bufferUsage: BufferUsage.STATIC_DRAW,
        interleave: primitive._interleave,
      }),
    );
 
    if (defined(primitive._createBoundingVolumeFunction)) {
      primitive._createBoundingVolumeFunction(frameState, geometry);
    } else {
      primitive._boundingSpheres.push(
        BoundingSphere.clone(geometry.boundingSphere),
      );
      primitive._boundingSphereWC.push(new BoundingSphere());
 
      if (!scene3DOnly) {
        const center = geometry.boundingSphereCV.center;
        const x = center.x;
        const y = center.y;
        const z = center.z;
        center.x = z;
        center.y = x;
        center.z = y;
 
        primitive._boundingSphereCV.push(
          BoundingSphere.clone(geometry.boundingSphereCV),
        );
        primitive._boundingSphere2D.push(new BoundingSphere());
        primitive._boundingSphereMorph.push(new BoundingSphere());
      }
    }
  }
 
  primitive._va = va;
  primitive._primitiveType = geometries[0].primitiveType;
 
  if (primitive.releaseGeometryInstances) {
    primitive.geometryInstances = undefined;
  }
 
  primitive._geometries = undefined;
  setReady(primitive, frameState, PrimitiveState.COMPLETE, undefined);
}
 
function createRenderStates(primitive, context, appearance, twoPasses) {
  let renderState = appearance.getRenderState();
  let rs;
 
  if (twoPasses) {
    rs = clone(renderState, false);
    rs.cull = {
      enabled: true,
      face: CullFace.BACK,
    };
    primitive._frontFaceRS = RenderState.fromCache(rs);
 
    rs.cull.face = CullFace.FRONT;
    primitive._backFaceRS = RenderState.fromCache(rs);
  } else {
    primitive._frontFaceRS = RenderState.fromCache(renderState);
    primitive._backFaceRS = primitive._frontFaceRS;
  }
 
  rs = clone(renderState, false);
  if (defined(primitive._depthFailAppearance)) {
    rs.depthTest.enabled = false;
  }
 
  if (defined(primitive._depthFailAppearance)) {
    renderState = primitive._depthFailAppearance.getRenderState();
    rs = clone(renderState, false);
    rs.depthTest.func = DepthFunction.GREATER;
    Iif (twoPasses) {
      rs.cull = {
        enabled: true,
        face: CullFace.BACK,
      };
      primitive._frontFaceDepthFailRS = RenderState.fromCache(rs);
 
      rs.cull.face = CullFace.FRONT;
      primitive._backFaceDepthFailRS = RenderState.fromCache(rs);
    } else {
      primitive._frontFaceDepthFailRS = RenderState.fromCache(rs);
      primitive._backFaceDepthFailRS = primitive._frontFaceRS;
    }
  }
}
 
function createShaderProgram(primitive, frameState, appearance) {
  const context = frameState.context;
 
  const attributeLocations = primitive._attributeLocations;
 
  let vs = primitive._batchTable.getVertexShaderCallback()(
    appearance.vertexShaderSource,
  );
  vs = Primitive._appendOffsetToShader(primitive, vs);
  vs = Primitive._appendShowToShader(primitive, vs);
  vs = Primitive._appendDistanceDisplayConditionToShader(
    primitive,
    vs,
    frameState.scene3DOnly,
  );
  vs = appendPickToVertexShader(vs);
  vs = Primitive._updateColorAttribute(primitive, vs, false);
  vs = modifyForEncodedNormals(primitive, vs);
  vs = Primitive._modifyShaderPosition(primitive, vs, frameState.scene3DOnly);
  let fs = appearance.getFragmentShaderSource();
  fs = appendPickToFragmentShader(fs);
 
  primitive._sp = ShaderProgram.replaceCache({
    context: context,
    shaderProgram: primitive._sp,
    vertexShaderSource: vs,
    fragmentShaderSource: fs,
    attributeLocations: attributeLocations,
  });
  validateShaderMatching(primitive._sp, attributeLocations);
 
  if (defined(primitive._depthFailAppearance)) {
    vs = primitive._batchTable.getVertexShaderCallback()(
      primitive._depthFailAppearance.vertexShaderSource,
    );
    vs = Primitive._appendShowToShader(primitive, vs);
    vs = Primitive._appendDistanceDisplayConditionToShader(
      primitive,
      vs,
      frameState.scene3DOnly,
    );
    vs = appendPickToVertexShader(vs);
    vs = Primitive._updateColorAttribute(primitive, vs, true);
    vs = modifyForEncodedNormals(primitive, vs);
    vs = Primitive._modifyShaderPosition(primitive, vs, frameState.scene3DOnly);
    vs = depthClampVS(vs);
 
    fs = primitive._depthFailAppearance.getFragmentShaderSource();
    fs = appendPickToFragmentShader(fs);
    fs = depthClampFS(fs);
 
    primitive._spDepthFail = ShaderProgram.replaceCache({
      context: context,
      shaderProgram: primitive._spDepthFail,
      vertexShaderSource: vs,
      fragmentShaderSource: fs,
      attributeLocations: attributeLocations,
    });
    validateShaderMatching(primitive._spDepthFail, attributeLocations);
  }
}
 
const modifiedModelViewScratch = new Matrix4();
const rtcScratch = new Cartesian3();
 
function getUniforms(primitive, appearance, material, frameState) {
  // Create uniform map by combining uniforms from the appearance and material if either have uniforms.
  const materialUniformMap = defined(material) ? material._uniforms : undefined;
  const appearanceUniformMap = {};
  const appearanceUniforms = appearance.uniforms;
  Iif (defined(appearanceUniforms)) {
    // Convert to uniform map of functions for the renderer
    for (const name in appearanceUniforms) {
      if (appearanceUniforms.hasOwnProperty(name)) {
        //>>includeStart('debug', pragmas.debug);
        if (defined(materialUniformMap) && defined(materialUniformMap[name])) {
          // Later, we could rename uniforms behind-the-scenes if needed.
          throw new DeveloperError(
            `Appearance and material have a uniform with the same name: ${name}`,
          );
        }
        //>>includeEnd('debug');
 
        appearanceUniformMap[name] = getUniformFunction(
          appearanceUniforms,
          name,
        );
      }
    }
  }
  let uniforms = combine(appearanceUniformMap, materialUniformMap);
  uniforms = primitive._batchTable.getUniformMapCallback()(uniforms);
 
  if (defined(primitive.rtcCenter)) {
    uniforms.u_modifiedModelView = function () {
      const viewMatrix = frameState.context.uniformState.view;
      Matrix4.multiply(
        viewMatrix,
        primitive._modelMatrix,
        modifiedModelViewScratch,
      );
      Matrix4.multiplyByPoint(
        modifiedModelViewScratch,
        primitive.rtcCenter,
        rtcScratch,
      );
      Matrix4.setTranslation(
        modifiedModelViewScratch,
        rtcScratch,
        modifiedModelViewScratch,
      );
      return modifiedModelViewScratch;
    };
  }
 
  return uniforms;
}
 
function createCommands(
  primitive,
  appearance,
  material,
  translucent,
  twoPasses,
  colorCommands,
  pickCommands,
  frameState,
) {
  const uniforms = getUniforms(primitive, appearance, material, frameState);
 
  let depthFailUniforms;
  if (defined(primitive._depthFailAppearance)) {
    depthFailUniforms = getUniforms(
      primitive,
      primitive._depthFailAppearance,
      primitive._depthFailAppearance.material,
      frameState,
    );
  }
 
  const pass = translucent ? Pass.TRANSLUCENT : Pass.OPAQUE;
 
  let multiplier = twoPasses ? 2 : 1;
  multiplier *= defined(primitive._depthFailAppearance) ? 2 : 1;
  colorCommands.length = primitive._va.length * multiplier;
 
  const length = colorCommands.length;
  let vaIndex = 0;
  for (let i = 0; i < length; ++i) {
    let colorCommand;
 
    if (twoPasses) {
      colorCommand = colorCommands[i];
      if (!defined(colorCommand)) {
        colorCommand = colorCommands[i] = new DrawCommand({
          owner: primitive,
          primitiveType: primitive._primitiveType,
        });
      }
      colorCommand.vertexArray = primitive._va[vaIndex];
      colorCommand.renderState = primitive._backFaceRS;
      colorCommand.shaderProgram = primitive._sp;
      colorCommand.uniformMap = uniforms;
      colorCommand.pass = pass;
 
      ++i;
    }
 
    colorCommand = colorCommands[i];
    if (!defined(colorCommand)) {
      colorCommand = colorCommands[i] = new DrawCommand({
        owner: primitive,
        primitiveType: primitive._primitiveType,
      });
    }
    colorCommand.vertexArray = primitive._va[vaIndex];
    colorCommand.renderState = primitive._frontFaceRS;
    colorCommand.shaderProgram = primitive._sp;
    colorCommand.uniformMap = uniforms;
    colorCommand.pass = pass;
 
    if (defined(primitive._depthFailAppearance)) {
      Iif (twoPasses) {
        ++i;
 
        colorCommand = colorCommands[i];
        if (!defined(colorCommand)) {
          colorCommand = colorCommands[i] = new DrawCommand({
            owner: primitive,
            primitiveType: primitive._primitiveType,
          });
        }
        colorCommand.vertexArray = primitive._va[vaIndex];
        colorCommand.renderState = primitive._backFaceDepthFailRS;
        colorCommand.shaderProgram = primitive._spDepthFail;
        colorCommand.uniformMap = depthFailUniforms;
        colorCommand.pass = pass;
      }
 
      ++i;
 
      colorCommand = colorCommands[i];
      Eif (!defined(colorCommand)) {
        colorCommand = colorCommands[i] = new DrawCommand({
          owner: primitive,
          primitiveType: primitive._primitiveType,
        });
      }
      colorCommand.vertexArray = primitive._va[vaIndex];
      colorCommand.renderState = primitive._frontFaceDepthFailRS;
      colorCommand.shaderProgram = primitive._spDepthFail;
      colorCommand.uniformMap = depthFailUniforms;
      colorCommand.pass = pass;
    }
 
    ++vaIndex;
  }
}
 
Primitive._updateBoundingVolumes = function (
  primitive,
  frameState,
  modelMatrix,
  forceUpdate,
) {
  let i;
  let length;
  let boundingSphere;
 
  if (forceUpdate || !Matrix4.equals(modelMatrix, primitive._modelMatrix)) {
    Matrix4.clone(modelMatrix, primitive._modelMatrix);
    length = primitive._boundingSpheres.length;
    for (i = 0; i < length; ++i) {
      boundingSphere = primitive._boundingSpheres[i];
      Eif (defined(boundingSphere)) {
        primitive._boundingSphereWC[i] = BoundingSphere.transform(
          boundingSphere,
          modelMatrix,
          primitive._boundingSphereWC[i],
        );
        if (!frameState.scene3DOnly) {
          primitive._boundingSphere2D[i] = BoundingSphere.clone(
            primitive._boundingSphereCV[i],
            primitive._boundingSphere2D[i],
          );
          primitive._boundingSphereMorph[i] = BoundingSphere.union(
            primitive._boundingSphereWC[i],
            primitive._boundingSphereCV[i],
          );
        }
      }
    }
  }
 
  // Update bounding volumes for primitives that are sized in pixels.
  // The pixel size in meters varies based on the distance from the camera.
  const pixelSize = primitive.appearance.pixelSize;
  Iif (defined(pixelSize)) {
    length = primitive._boundingSpheres.length;
    for (i = 0; i < length; ++i) {
      boundingSphere = primitive._boundingSpheres[i];
      const boundingSphereWC = primitive._boundingSphereWC[i];
      const pixelSizeInMeters = frameState.camera.getPixelSize(
        boundingSphere,
        frameState.context.drawingBufferWidth,
        frameState.context.drawingBufferHeight,
      );
      const sizeInMeters = pixelSizeInMeters * pixelSize;
      boundingSphereWC.radius = boundingSphere.radius + sizeInMeters;
    }
  }
};
 
function updateAndQueueCommands(
  primitive,
  frameState,
  colorCommands,
  pickCommands,
  modelMatrix,
  cull,
  debugShowBoundingVolume,
  twoPasses,
) {
  //>>includeStart('debug', pragmas.debug);
  if (
    frameState.mode !== SceneMode.SCENE3D &&
    !Matrix4.equals(modelMatrix, Matrix4.IDENTITY)
  ) {
    throw new DeveloperError(
      "Primitive.modelMatrix is only supported in 3D mode.",
    );
  }
  //>>includeEnd('debug');
 
  Primitive._updateBoundingVolumes(primitive, frameState, modelMatrix);
 
  let boundingSpheres;
  if (frameState.mode === SceneMode.SCENE3D) {
    boundingSpheres = primitive._boundingSphereWC;
  } else if (frameState.mode === SceneMode.COLUMBUS_VIEW) {
    boundingSpheres = primitive._boundingSphereCV;
  } else if (
    frameState.mode === SceneMode.SCENE2D &&
    defined(primitive._boundingSphere2D)
  ) {
    boundingSpheres = primitive._boundingSphere2D;
  } else Eif (defined(primitive._boundingSphereMorph)) {
    boundingSpheres = primitive._boundingSphereMorph;
  }
 
  const commandList = frameState.commandList;
  const passes = frameState.passes;
  Eif (passes.render || passes.pick) {
    const allowPicking = primitive.allowPicking;
    const castShadows = ShadowMode.castShadows(primitive.shadows);
    const receiveShadows = ShadowMode.receiveShadows(primitive.shadows);
    const colorLength = colorCommands.length;
 
    let factor = twoPasses ? 2 : 1;
    factor *= defined(primitive._depthFailAppearance) ? 2 : 1;
 
    for (let j = 0; j < colorLength; ++j) {
      const sphereIndex = Math.floor(j / factor);
      const colorCommand = colorCommands[j];
      colorCommand.modelMatrix = modelMatrix;
      colorCommand.boundingVolume = boundingSpheres[sphereIndex];
      colorCommand.cull = cull;
      colorCommand.debugShowBoundingVolume = debugShowBoundingVolume;
      colorCommand.castShadows = castShadows;
      colorCommand.receiveShadows = receiveShadows;
 
      if (allowPicking) {
        colorCommand.pickId = "v_pickColor";
      } else {
        colorCommand.pickId = undefined;
      }
 
      commandList.push(colorCommand);
    }
  }
}
 
/**
 * Called when {@link Viewer} or {@link CesiumWidget} render the scene to
 * get the draw commands needed to render this primitive.
 * <p>
 * Do not call this function directly.  This is documented just to
 * list the exceptions that may be propagated when the scene is rendered:
 * </p>
 *
 * @exception {DeveloperError} All instance geometries must have the same primitiveType.
 * @exception {DeveloperError} Appearance and material have a uniform with the same name.
 * @exception {DeveloperError} Primitive.modelMatrix is only supported in 3D mode.
 * @exception {RuntimeError} Vertex texture fetch support is required to render primitives with per-instance attributes. The maximum number of vertex texture image units must be greater than zero.
 */
Primitive.prototype.update = function (frameState) {
  if (
    (!defined(this.geometryInstances) && this._va.length === 0) ||
    (defined(this.geometryInstances) &&
      Array.isArray(this.geometryInstances) &&
      this.geometryInstances.length === 0) ||
    !defined(this.appearance) ||
    (frameState.mode !== SceneMode.SCENE3D && frameState.scene3DOnly) ||
    (!frameState.passes.render && !frameState.passes.pick)
  ) {
    return;
  }
 
  if (defined(this._error)) {
    throw this._error;
  }
 
  //>>includeStart('debug', pragmas.debug);
  if (defined(this.rtcCenter) && !frameState.scene3DOnly) {
    throw new DeveloperError(
      "RTC rendering is only available for 3D only scenes.",
    );
  }
  //>>includeEnd('debug');
 
  if (this._state === PrimitiveState.FAILED) {
    return;
  }
 
  const context = frameState.context;
  if (!defined(this._batchTable)) {
    createBatchTable(this, context);
  }
  Eif (this._batchTable.attributes.length > 0) {
    Iif (ContextLimits.maximumVertexTextureImageUnits === 0) {
      throw new RuntimeError(
        "Vertex texture fetch support is required to render primitives with per-instance attributes. The maximum number of vertex texture image units must be greater than zero.",
      );
    }
    this._batchTable.update(frameState);
  }
 
  if (
    this._state !== PrimitiveState.COMPLETE &&
    this._state !== PrimitiveState.COMBINED
  ) {
    if (this.asynchronous) {
      loadAsynchronous(this, frameState);
    } else {
      loadSynchronous(this, frameState);
    }
  }
 
  if (this._state === PrimitiveState.COMBINED) {
    updateBatchTableBoundingSpheres(this, frameState);
    updateBatchTableOffsets(this, frameState);
    createVertexArray(this, frameState);
  }
 
  if (!this.show || this._state !== PrimitiveState.COMPLETE) {
    return;
  }
 
  if (!this._batchTableOffsetsUpdated) {
    updateBatchTableOffsets(this, frameState);
  }
  if (this._recomputeBoundingSpheres) {
    recomputeBoundingSpheres(this, frameState);
  }
 
  // Create or recreate render state and shader program if appearance/material changed
  const appearance = this.appearance;
  const material = appearance.material;
  let createRS = false;
  let createSP = false;
 
  if (this._appearance !== appearance) {
    this._appearance = appearance;
    this._material = material;
    createRS = true;
    createSP = true;
  } else if (this._material !== material) {
    this._material = material;
    createSP = true;
  }
 
  const depthFailAppearance = this.depthFailAppearance;
  const depthFailMaterial = defined(depthFailAppearance)
    ? depthFailAppearance.material
    : undefined;
 
  if (this._depthFailAppearance !== depthFailAppearance) {
    this._depthFailAppearance = depthFailAppearance;
    this._depthFailMaterial = depthFailMaterial;
    createRS = true;
    createSP = true;
  } else Iif (this._depthFailMaterial !== depthFailMaterial) {
    this._depthFailMaterial = depthFailMaterial;
    createSP = true;
  }
 
  const translucent = this._appearance.isTranslucent();
  if (this._translucent !== translucent) {
    this._translucent = translucent;
    createRS = true;
  }
 
  if (defined(this._material)) {
    this._material.update(context);
  }
 
  const twoPasses = appearance.closed && translucent;
 
  if (createRS) {
    const rsFunc = this._createRenderStatesFunction ?? createRenderStates;
    rsFunc(this, context, appearance, twoPasses);
  }
 
  if (createSP) {
    const spFunc = this._createShaderProgramFunction ?? createShaderProgram;
    spFunc(this, frameState, appearance);
  }
 
  if (createRS || createSP) {
    const commandFunc = this._createCommandsFunction ?? createCommands;
    commandFunc(
      this,
      appearance,
      material,
      translucent,
      twoPasses,
      this._colorCommands,
      this._pickCommands,
      frameState,
    );
  }
 
  const updateAndQueueCommandsFunc =
    this._updateAndQueueCommandsFunction ?? updateAndQueueCommands;
  updateAndQueueCommandsFunc(
    this,
    frameState,
    this._colorCommands,
    this._pickCommands,
    this.modelMatrix,
    this.cull,
    this.debugShowBoundingVolume,
    twoPasses,
  );
};
 
const offsetBoundingSphereScratch1 = new BoundingSphere();
const offsetBoundingSphereScratch2 = new BoundingSphere();
function transformBoundingSphere(boundingSphere, offset, offsetAttribute) {
  Iif (offsetAttribute === GeometryOffsetAttribute.TOP) {
    const origBS = BoundingSphere.clone(
      boundingSphere,
      offsetBoundingSphereScratch1,
    );
    const offsetBS = BoundingSphere.clone(
      boundingSphere,
      offsetBoundingSphereScratch2,
    );
    offsetBS.center = Cartesian3.add(offsetBS.center, offset, offsetBS.center);
    boundingSphere = BoundingSphere.union(origBS, offsetBS, boundingSphere);
  } else Eif (offsetAttribute === GeometryOffsetAttribute.ALL) {
    boundingSphere.center = Cartesian3.add(
      boundingSphere.center,
      offset,
      boundingSphere.center,
    );
  }
 
  return boundingSphere;
}
 
function createGetFunction(batchTable, instanceIndex, attributeIndex) {
  return function () {
    const attributeValue = batchTable.getBatchedAttribute(
      instanceIndex,
      attributeIndex,
    );
    const attribute = batchTable.attributes[attributeIndex];
    const componentsPerAttribute = attribute.componentsPerAttribute;
    const value = ComponentDatatype.createTypedArray(
      attribute.componentDatatype,
      componentsPerAttribute,
    );
    if (defined(attributeValue.constructor.pack)) {
      attributeValue.constructor.pack(attributeValue, value, 0);
    } else {
      value[0] = attributeValue;
    }
    return value;
  };
}
 
function createSetFunction(
  batchTable,
  instanceIndex,
  attributeIndex,
  primitive,
  name,
) {
  return function (value) {
    //>>includeStart('debug', pragmas.debug);
    if (
      !defined(value) ||
      !defined(value.length) ||
      value.length < 1 ||
      value.length > 4
    ) {
      throw new DeveloperError(
        "value must be and array with length between 1 and 4.",
      );
    }
    //>>includeEnd('debug');
    const attributeValue = getAttributeValue(value);
    batchTable.setBatchedAttribute(
      instanceIndex,
      attributeIndex,
      attributeValue,
    );
    Iif (name === "offset") {
      primitive._recomputeBoundingSpheres = true;
      primitive._batchTableOffsetsUpdated = false;
    }
  };
}
 
const offsetScratch = new Cartesian3();
 
function createBoundingSphereProperties(primitive, properties, index) {
  properties.boundingSphere = {
    get: function () {
      let boundingSphere = primitive._instanceBoundingSpheres[index];
      if (defined(boundingSphere)) {
        boundingSphere = boundingSphere.clone();
        const modelMatrix = primitive.modelMatrix;
        const offset = properties.offset;
        Iif (defined(offset)) {
          transformBoundingSphere(
            boundingSphere,
            Cartesian3.fromArray(offset.get(), 0, offsetScratch),
            primitive._offsetInstanceExtend[index],
          );
        }
        Eif (defined(modelMatrix)) {
          boundingSphere = BoundingSphere.transform(
            boundingSphere,
            modelMatrix,
          );
        }
      }
 
      return boundingSphere;
    },
  };
  properties.boundingSphereCV = {
    get: function () {
      return primitive._instanceBoundingSpheresCV[index];
    },
  };
}
 
function createPickIdProperty(primitive, properties, index) {
  properties.pickId = {
    get: function () {
      return primitive._pickIds[index];
    },
  };
}
 
/**
 * Returns the modifiable per-instance attributes for a {@link GeometryInstance}.
 *
 * @param {*} id The id of the {@link GeometryInstance}.
 * @returns {object} The typed array in the attribute's format or undefined if the is no instance with id.
 *
 * @exception {DeveloperError} must call update before calling getGeometryInstanceAttributes.
 *
 * @example
 * const attributes = primitive.getGeometryInstanceAttributes('an id');
 * attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.AQUA);
 * attributes.show = Cesium.ShowGeometryInstanceAttribute.toValue(true);
 * attributes.distanceDisplayCondition = Cesium.DistanceDisplayConditionGeometryInstanceAttribute.toValue(100.0, 10000.0);
 * attributes.offset = Cesium.OffsetGeometryInstanceAttribute.toValue(Cartesian3.IDENTITY);
 */
Primitive.prototype.getGeometryInstanceAttributes = function (id) {
  //>>includeStart('debug', pragmas.debug);
  if (!defined(id)) {
    throw new DeveloperError("id is required");
  }
  if (!defined(this._batchTable)) {
    throw new DeveloperError(
      "must call update before calling getGeometryInstanceAttributes",
    );
  }
  //>>includeEnd('debug');
 
  let attributes = this._perInstanceAttributeCache.get(id);
  if (defined(attributes)) {
    return attributes;
  }
 
  let index = -1;
  const lastIndex = this._lastPerInstanceAttributeIndex;
  const ids = this._instanceIds;
  const length = ids.length;
  for (let i = 0; i < length; ++i) {
    const curIndex = (lastIndex + i) % length;
    if (id === ids[curIndex]) {
      index = curIndex;
      break;
    }
  }
 
  if (index === -1) {
    return undefined;
  }
 
  const batchTable = this._batchTable;
  const perInstanceAttributeIndices = this._batchTableAttributeIndices;
  attributes = {};
  const properties = {};
 
  for (const name in perInstanceAttributeIndices) {
    Eif (perInstanceAttributeIndices.hasOwnProperty(name)) {
      const attributeIndex = perInstanceAttributeIndices[name];
      properties[name] = {
        get: createGetFunction(batchTable, index, attributeIndex),
        set: createSetFunction(batchTable, index, attributeIndex, this, name),
      };
    }
  }
 
  createBoundingSphereProperties(this, properties, index);
  createPickIdProperty(this, properties, index);
  Object.defineProperties(attributes, properties);
 
  this._lastPerInstanceAttributeIndex = index;
  this._perInstanceAttributeCache.set(id, attributes);
  return attributes;
};
 
/**
 * Returns true if this object was destroyed; otherwise, false.
 * <p>
 * If this object was destroyed, it should not be used; calling any function other than
 * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
 * </p>
 *
 * @returns {boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
 *
 * @see Primitive#destroy
 */
Primitive.prototype.isDestroyed = function () {
  return false;
};
 
/**
 * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
 * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
 * <p>
 * Once an object is destroyed, it should not be used; calling any function other than
 * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
 * assign the return value (<code>undefined</code>) to the object as done in the example.
 * </p>
 *
 * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
 *
 *
 * @example
 * e = e && e.destroy();
 *
 * @see Primitive#isDestroyed
 */
Primitive.prototype.destroy = function () {
  let length;
  let i;
 
  this._sp = this._sp && this._sp.destroy();
  this._spDepthFail = this._spDepthFail && this._spDepthFail.destroy();
 
  const va = this._va;
  length = va.length;
  for (i = 0; i < length; ++i) {
    va[i].destroy();
  }
  this._va = undefined;
 
  const pickIds = this._pickIds;
  length = pickIds.length;
  for (i = 0; i < length; ++i) {
    pickIds[i].destroy();
  }
  this._pickIds = undefined;
 
  this._batchTable = this._batchTable && this._batchTable.destroy();
 
  //These objects may be fairly large and reference other large objects (like Entities)
  //We explicitly set them to undefined here so that the memory can be freed
  //even if a reference to the destroyed Primitive has been kept around.
  this._instanceIds = undefined;
  this._perInstanceAttributeCache = undefined;
  this._attributeLocations = undefined;
 
  return destroyObject(this);
};
 
function setReady(primitive, frameState, state, error) {
  primitive._error = error;
  primitive._state = state;
 
  frameState.afterRender.push(function () {
    primitive._ready =
      primitive._state === PrimitiveState.COMPLETE ||
      primitive._state === PrimitiveState.FAILED;
 
    // Returning 'true' here will ensure that another rendering pass is
    // triggered after the primitive actually became ready, to make sure
    // that it is in fact rendered even in "request render mode"
    return true;
  });
}
export default Primitive;