All files / engine/Source/Scene GltfLoader.js

95.54% Statements 1029/1077
86.65% Branches 448/517
97.16% Functions 103/106
95.43% Lines 1004/1052

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 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990                                                                                                                                1x                   1x                                                                                                                                                                                                                                                         1755x                               1755x     1755x     1755x   1755x 1755x 1755x 1755x 1755x 1755x 1755x 1755x 1755x 1755x 1755x 1755x 1755x 1755x 1755x 1755x         1755x 1755x   1755x 1755x 1755x 1755x 1755x 1755x         1755x     1755x 1755x 1755x 1755x 1755x 1755x 1755x 1755x 1755x 1755x 1755x 1755x   1755x         1755x     1755x     1x 1x 1x     1x                                                   1726x                           27343x 27343x                               8315x                           207x                 1755x 1755x   1755x 1755x           1755x 1755x   1751x         2x     1749x 1749x   1749x   4x       4x 4x 4x         1727x 1x     1727x                   1727x     1725x 1725x   1725x     1203x 1203x     1725x                   1x 1755x       1755x 1755x       10x 10x 10x       3688x 3688x 3688x 15630x 15629x 7031x 7031x   15629x     3687x 3687x 247x 247x 90x     247x     3687x 3687x                                   3687x   1722x             1721x 1721x 1825x 1825x 1825x       11x           11x 11x   11x 11x   4x         11x 11x 143x 143x 10x         11x 11x 4x               1x 4122x 211x     3911x 3688x     3910x       1721x 1721x     3910x   1721x     1721x   1721x 1721x     2189x             1x 4121x 1752x     2369x 4x     2365x 2365x 2365x 1715x 1715x 336x 336x     1715x     2365x 726x     1639x 1639x 1639x                 1x   4128x     4128x       1727x   1722x     5x       4128x 5x 5x 5x 5x       4123x 4123x   1x 1x 1x     4122x       4122x 4122x 4122x   1x 1x       4121x 4121x 4121x           4121x 1050x     3071x                           5260x 5260x 5260x   5260x                               5260x                       1788x                         1788x       852x             852x   852x       1011x 1011x 1011x 1011x 1011x 1011x 1011x 1011x   1011x   999x 999x               12x         12x 12x 12x 12x   12x 2624x             2624x 7872x   2624x     12x                           852x 852x   852x 429x 15797x   423x 165x 4962x     258x   258x   258x 9601x       852x                     852x   852x 852x       852x           852x 852x       852x   852x 852x 852x 852x             852x   852x             23338x 7365x     15973x 2034x     13939x       5262x 1051x     4211x       2x   1x   1x                   1x             2x 2x     2x 2x 1x 1x     2x 2x 1x 1x     2x 2x               6x 6x 6x   6x 4x 4x     6x 6x 6x   6x 2x 2x 4x                 4x 4x         4x                                       6x       5262x 5262x 5262x   5262x 5262x 5262x 5262x 5262x 5262x 5262x 5262x 5262x 5262x 5262x 5262x 5262x   5262x 6x               5262x                     5262x       5262x 2x     5262x       5132x 5132x 5132x 1523x   3609x     1x                 5275x 5275x       969x     5275x   5275x 5275x 5275x 5275x   5275x           33x   33x   33x   33x                     88x 88x 88x   88x 88x     88x 2x       2x                         133x 133x   133x       133x 133x           133x 7x 7x 7x 7x 7x 7x 7x   7x 1147553x 1147553x 1147553x   1147553x 1147553x 1147553x 1147553x 1147553x 1147553x     7x         7x 7x                       5025x 4936x     5025x 159x 159x           159x       89x 89x                               5262x 5262x 5262x   5262x 5262x 5262x   5262x       5262x 5262x               5262x 2x     5260x                       5260x 5260x 5260x 5260x         5260x 5246x         88x           5158x 133x             5025x                     5260x                           5173x     5173x   5173x     5173x         5173x     5173x       5173x 5173x   5173x                     5173x 5173x   5173x                       5173x 5173x 5173x   5173x                   89x 89x   89x       89x         89x     89x       89x                 89x       89x   89x           89x   89x     89x     89x                                         1789x 1789x   1789x 1789x 1789x       1789x 1x     1788x 1788x   1788x     1788x       1788x       1788x 1788x   1788x                     1788x 1788x   1788x                   1788x 1788x 1788x 1788x       1788x 1785x 1785x 1785x     1788x 1788x 1788x   1788x       444x 444x           444x 1x     443x                   443x       443x 443x 443x 3x       3x     2x       1x 1x   443x       443x 336x 336x 34x       443x                                   7x   7x 7x 7x           7x 7x           7x 7x 7x   7x                                   1687x   1687x 1687x 301x           1687x 15x           1687x 1687x 1687x   1687x                 3x   3x 3x 3x   3x 3x           3x 3x   3x               3x   3x 3x 3x           3x 3x   3x                   3x   3x 3x 3x           3x 3x           3x 3x           3x 3x   3x                         1830x   1830x 1830x 1830x 1830x 1830x 1830x   1830x   1830x 7x           1823x 1687x           1823x 3x   1823x 3x   1823x 3x         1830x 19x             1830x 25x           1830x 18x           1830x 1830x 1830x 1830x   1830x         53x 53x 53x 53x 53x 53x 53x 53x                   3x 3x 3x 3x 3x 3x 3x             45x 45x 45x 45x 45x 45x 45x 45x 45x                   3x 3x 3x 3x     3x   3x 3x   3x 3x                   33x   33x 33x 33x 33x 33x   33x 33x                   33x 33x   63x     33x   33x                       1x 1x 1x 1x 1x 1x             1x 1x   1x                   14x     14x 14x 14x 14x   14x 26x     26x   26x           26x                     26x       26x     14x       1830x 1830x 1830x 1830x 7x     1823x                         1830x 1830x 1830x   1830x 1830x 1830x             1830x   1830x 1830x 1830x 4x 4x 4x               1830x 1830x 1830x   10x 10x     10x 10x           10x   5x 5x 5x       5x         10x             1830x   1830x 7x 7x     1830x 1830x   1830x 1830x 1830x 1830x 5160x     5160x 5160x           5160x 5160x 13x     5147x 1009x     5147x                       5147x 5147x       1830x   1830x 9x 14x                       1830x 1830x 1789x                 1789x 1788x 1788x               1830x 1830x 1830x 1830x     1830x 49x 1781x 3x                 1830x 26x 1804x 3x     1830x 1830x 1x       1829x   1829x       4x 4x 4x 4x                     49x       49x         49x 101x 101x     101x 33x           68x 38x       30x     101x                       3x   3x     3x 3x 2x 4x 4x   4x 4x 4x 4x     4x 2x             2x             4x         3x 3x 1x 1x 1x   1x 1x 1x 1x   1x                 1x             26x     26x   26x 16x     26x 10x             3x       1x   1x             35x   35x 35x 35x 35x 89x     89x 89x                         35x 35x 35x   35x 15x 20x 1x               35x           15x   15x 30x 30x     30x 15x       15x     30x                       1x   1x 1x 1x 2x 2x 2x 2x 2x     2x 1x             1x             2x                           2317x   2317x   2317x 2317x 2317x 2317x   2317x 2317x 2317x   2317x 36x 1x       35x     2316x 14x     2316x 2316x 1724x 1724x 1724x 1830x                       1723x 1723x       1723x         2315x                     1727x 1727x       1727x 2317x 2315x 2315x     1725x 2315x 2315x 427x 481x         1725x       14x   14x 113x   14x 14x 13x 13x   1x         14x       1725x     1725x 1711x     14x 14x 14x 14x     14x 14x 136x 136x 14x       14x                 88x                   88x 88x                                   410x 410x   410x 410x   410x 410x     410x 410x   410x       410x   410x     410x       410x   410x 410x   410x       410x   410x 410x 410x   410x       127x 127x   127x 410x 410x 410x     127x 410x     127x 127x   127x       1725x     1725x 1662x     63x 127x 127x 127x     63x       140x 140x   140x 140x   140x 140x 140x   140x       14x 14x 14x 14x       1725x 1725x 1725x 1711x   14x         1725x 1725x   1725x 1725x 1725x       1725x 1725x 1725x 1834x   1725x     1x                                   1727x 1727x 1727x 1727x 1727x   1727x             4x 4x 4x 4x     4x 4x     1727x 1725x 1725x 1725x 1725x   1725x 1725x 1725x 1725x 42x 62x   42x     1725x 1725x 1725x 1725x 1725x 1725x 1725x 1725x   1725x   4x         4x           1725x     1725x       88x           88x       1725x 1725x           1725x 1725x 1634x 1720x 1720x 1720x 1830x 1830x 124x 124x                               1725x 1725x       1725x 1396x     1725x       1725x 1725x 443x       1725x       3446x 3446x 852x       3446x       1725x 1725x 6995x       1725x       1725x 1725x 18x 18x 18x     1725x       1725x       73x 73x         1725x                         1x 1749x             1x 1725x 520x   1725x   1725x 1725x 1725x 1725x 1725x 1725x   1725x 1725x 1725x        
import ArticulationStageType from "../Core/ArticulationStageType.js";
import Cartesian2 from "../Core/Cartesian2.js";
import Cartesian3 from "../Core/Cartesian3.js";
import Cartesian4 from "../Core/Cartesian4.js";
import Check from "../Core/Check.js";
import ComponentDatatype from "../Core/ComponentDatatype.js";
import Credit from "../Core/Credit.js";
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import FeatureDetection from "../Core/FeatureDetection.js";
import InterpolationType from "../Core/InterpolationType.js";
import Matrix4 from "../Core/Matrix4.js";
import PrimitiveType from "../Core/PrimitiveType.js";
import Quaternion from "../Core/Quaternion.js";
import RuntimeError from "../Core/RuntimeError.js";
import Sampler from "../Renderer/Sampler.js";
import getAccessorByteStride from "./GltfPipeline/getAccessorByteStride.js";
import getComponentReader from "./GltfPipeline/getComponentReader.js";
import numberOfComponentsForType from "./GltfPipeline/numberOfComponentsForType.js";
import GltfStructuralMetadataLoader from "./GltfStructuralMetadataLoader.js";
import AttributeType from "./AttributeType.js";
import Axis from "./Axis.js";
import GltfLoaderUtil from "./GltfLoaderUtil.js";
import hasExtension from "./hasExtension.js";
import InstanceAttributeSemantic from "./InstanceAttributeSemantic.js";
import ModelComponents from "./ModelComponents.js";
import PrimitiveLoadPlan from "./PrimitiveLoadPlan.js";
import ResourceCache from "./ResourceCache.js";
import ResourceLoader from "./ResourceLoader.js";
import SupportedImageFormats from "./SupportedImageFormats.js";
import VertexAttributeSemantic from "./VertexAttributeSemantic.js";
import GltfGpmLoader from "./Model/Extensions/Gpm/GltfGpmLoader.js";
import GltfMeshPrimitiveGpmLoader from "./Model/Extensions/Gpm/GltfMeshPrimitiveGpmLoader.js";
import oneTimeWarning from "../Core/oneTimeWarning.js";
import addAllToArray from "../Core/addAllToArray.js";
import getMeshPrimitives from "./getMeshPrimitives.js";
 
const {
  Attribute,
  Indices,
  FeatureIdAttribute,
  FeatureIdTexture,
  FeatureIdImplicitRange,
  MorphTarget,
  Primitive,
  Instances,
  Skin,
  Node,
  AnimatedPropertyType,
  AnimationSampler,
  AnimationTarget,
  AnimationChannel,
  Animation,
  ArticulationStage,
  Articulation,
  Asset,
  Scene,
  Components,
  MetallicRoughness,
  SpecularGlossiness,
  Specular,
  Anisotropy,
  Clearcoat,
  Material,
} = ModelComponents;
 
/**
 * States of the glTF loading process. These states also apply to
 * asynchronous texture loading unless otherwise noted
 *
 * @enum {number}
 *
 * @private
 */
const GltfLoaderState = {
  /**
   * The initial state of the glTF loader before load() is called.
   *
   * @type {number}
   * @constant
   *
   * @private
   */
  NOT_LOADED: 0,
  /**
   * The state of the loader while waiting for the glTF JSON loader promise
   * to resolve.
   *
   * @type {number}
   * @constant
   *
   * @private
   */
  LOADING: 1,
  /**
   * The state of the loader once the glTF JSON is loaded but before
   * process() is called.
   *
   * @type {number}
   * @constant
   *
   * @private
   */
  LOADED: 2,
  /**
   * The state of the loader while parsing the glTF and creating GPU resources
   * as needed.
   *
   * @type {number}
   * @constant
   *
   * @private
   */
  PROCESSING: 3,
  /**
   * For some features like handling CESIUM_primitive_outlines, the geometry
   * must be modified after it is loaded. The post-processing state handles
   * any geometry modification (if needed).
   * <p>
   * This state is not used for asynchronous texture loading.
   * </p>
   *
   * @type {number}
   * @constant
   *
   * @private
   */
  POST_PROCESSING: 4,
  /**
   * Once the processing/post-processing states are finished, the loader
   * enters the processed state (sometimes from a promise chain). The next
   * call to process() will advance to the ready state.
   *
   * @type {number}
   * @constant
   *
   * @private
   */
  PROCESSED: 5,
  /**
   * When the loader reaches the ready state, the loaders' promise will be
   * resolved.
   *
   * @type {number}
   * @constant
   *
   * @private
   */
  READY: 6,
  /**
   * If an error occurs at any point, the loader switches to the failed state.
   *
   * @type {number}
   * @constant
   *
   * @private
   */
  FAILED: 7,
  /**
   * If unload() is called, the loader switches to the unloaded state.
   *
   * @type {number}
   * @constant
   *
   * @private
   */
  UNLOADED: 8,
};
 
/**
 * Loads a glTF model.
 * <p>
 * Implements the {@link ResourceLoader} interface.
 * </p>
 *
 * @alias GltfLoader
 * @constructor
 * @augments ResourceLoader
 *
 * @param {object} options Object with the following properties:
 * @param {Resource} options.gltfResource The {@link Resource} containing the glTF. This is often the path of the .gltf or .glb file, but may also be the path of the .b3dm, .i3dm, or .cmpt file containing the embedded glb. .cmpt resources should have a URI fragment indicating the index of the inner content to which the glb belongs in order to individually identify the glb in the cache, e.g. http://example.com/tile.cmpt#index=2.
 * @param {Resource} [options.baseResource] The {@link Resource} that paths in the glTF JSON are relative to.
 * @param {Uint8Array} [options.typedArray] The typed array containing the glTF contents, e.g. from a .b3dm, .i3dm, or .cmpt file.
 * @param {object} [options.gltfJson] A parsed glTF JSON file instead of passing it in as a typed array.
 * @param {boolean} [options.releaseGltfJson=false] When true, the glTF JSON is released once the glTF is loaded. This is especially useful for cases like 3D Tiles, where each .gltf model is unique and caching the glTF JSON is not effective.
 * @param {boolean} [options.asynchronous=true] Determines if WebGL resource creation will be spread out over several frames or block until all WebGL resources are created.
 * @param {boolean} [options.incrementallyLoadTextures=true] Determine if textures may continue to stream in after the glTF is loaded.
 * @param {Axis} [options.upAxis=Axis.Y] The up-axis of the glTF model.
 * @param {Axis} [options.forwardAxis=Axis.Z] The forward-axis of the glTF model.
 * @param {boolean} [options.loadAttributesAsTypedArray=false] Load all attributes and indices as typed arrays instead of GPU buffers. If the attributes are interleaved in the glTF they will be de-interleaved in the typed array.
 * @param {boolean} [options.loadAttributesFor2D=false] If <code>true</code>, load the positions buffer and any instanced attribute buffers as typed arrays for accurately projecting models to 2D.
 * @param {boolean} [options.enablePick=false]  If <code>true</code>, load the positions buffer, any instanced attribute buffers, and index buffer as typed arrays for CPU-enabled picking in WebGL1.
 * @param {boolean} [options.loadIndicesForWireframe=false] If <code>true</code>, load the index buffer as both a buffer and typed array. The latter is useful for creating wireframe indices in WebGL1.
 * @param {boolean} [options.loadPrimitiveOutline=true] If <code>true</code>, load outlines from the {@link https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/CESIUM_primitive_outline|CESIUM_primitive_outline} extension. This can be set false to avoid post-processing geometry at load time.
 * @param {boolean} [options.loadForClassification=false] If <code>true</code> and if the model has feature IDs, load the feature IDs and indices as typed arrays. This is useful for batching features for classification.
 * @param {boolean} [options.renameBatchIdSemantic=false] If <code>true</code>, rename _BATCHID or BATCHID to _FEATURE_ID_0. This is used for .b3dm models
 * @private
 */
function GltfLoader(options) {
  options = options ?? Frozen.EMPTY_OBJECT;
  const {
    gltfResource,
    typedArray,
    releaseGltfJson = false,
    asynchronous = true,
    incrementallyLoadTextures = true,
    upAxis = Axis.Y,
    forwardAxis = Axis.Z,
    loadAttributesAsTypedArray = false,
    loadAttributesFor2D = false,
    enablePick = false,
    loadIndicesForWireframe = false,
    loadPrimitiveOutline = true,
    loadForClassification = false,
    renameBatchIdSemantic = false,
  } = options;
 
  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.object("options.gltfResource", gltfResource);
  //>>includeEnd('debug');
 
  const { baseResource = gltfResource.clone() } = options;
 
  this._gltfJson = options.gltfJson;
  this._gltfResource = gltfResource;
  this._baseResource = baseResource;
  this._typedArray = typedArray;
  this._releaseGltfJson = releaseGltfJson;
  this._asynchronous = asynchronous;
  this._incrementallyLoadTextures = incrementallyLoadTextures;
  this._upAxis = upAxis;
  this._forwardAxis = forwardAxis;
  this._loadAttributesAsTypedArray = loadAttributesAsTypedArray;
  this._loadAttributesFor2D = loadAttributesFor2D;
  this._enablePick = enablePick;
  this._loadIndicesForWireframe = loadIndicesForWireframe;
  this._loadPrimitiveOutline = loadPrimitiveOutline;
  this._loadForClassification = loadForClassification;
  this._renameBatchIdSemantic = renameBatchIdSemantic;
 
  // When loading EXT_feature_metadata, the feature tables and textures
  // are now stored as arrays like the newer EXT_structural_metadata extension.
  // This requires sorting the dictionary keys for a consistent ordering.
  this._sortedPropertyTableIds = undefined;
  this._sortedFeatureTextureIds = undefined;
 
  this._gltfJsonLoader = undefined;
  this._state = GltfLoaderState.NOT_LOADED;
  this._textureState = GltfLoaderState.NOT_LOADED;
  this._promise = undefined;
  this._processError = undefined;
  this._textureErrors = [];
 
  // Information about whether to load primitives as typed arrays or buffers,
  // and whether post-processing is needed after loading (e.g. for
  // generating outlines)
  this._primitiveLoadPlans = [];
 
  // Loaders that need to be processed before the glTF becomes ready
  this._loaderPromises = [];
  this._textureLoaders = [];
  this._texturesPromises = [];
  this._textureCallbacks = [];
  this._bufferViewLoaders = [];
  this._geometryLoaders = [];
  this._geometryCallbacks = [];
  this._structuralMetadataLoader = undefined;
  this._meshPrimitiveGpmLoader = undefined;
  this._loadResourcesPromise = undefined;
  this._resourcesLoaded = false;
  this._texturesLoaded = false;
 
  this._supportedImageFormats = undefined;
 
  // In some cases where geometry post-processing is needed (like generating
  // outlines) new attributes are added that may have GPU resources attached.
  // The GltfLoader will own the resources and store them here.
  this._postProcessBuffers = [];
 
  // Loaded results
  this._components = undefined;
}
 
Eif (defined(Object.create)) {
  GltfLoader.prototype = Object.create(ResourceLoader.prototype);
  GltfLoader.prototype.constructor = GltfLoader;
}
 
Object.defineProperties(GltfLoader.prototype, {
  /**
   * The cache key of the resource.
   *
   * @memberof GltfLoader.prototype
   *
   * @type {string}
   * @readonly
   * @private
   */
  cacheKey: {
    get: function () {
      return undefined;
    },
  },
  /**
   * The loaded components.
   *
   * @memberof GltfLoader.prototype
   *
   * @type {ModelComponents.Components}
   * @readonly
   * @private
   */
  components: {
    get: function () {
      return this._components;
    },
  },
  /**
   * The loaded glTF json.
   *
   * @memberof GltfLoader.prototype
   *
   * @type {object}
   * @readonly
   * @private
   */
  gltfJson: {
    get: function () {
      Eif (defined(this._gltfJsonLoader)) {
        return this._gltfJsonLoader.gltf;
      }
      return this._gltfJson;
    },
  },
  /**
   * Returns true if textures are loaded separately from the other glTF resources.
   *
   * @memberof GltfLoader.prototype
   *
   * @type {boolean}
   * @readonly
   * @private
   */
  incrementallyLoadTextures: {
    get: function () {
      return this._incrementallyLoadTextures;
    },
  },
  /**
   * true if textures are loaded, useful when incrementallyLoadTextures is true
   *
   * @memberof GltfLoader.prototype
   *
   * @type {boolean}
   * @readonly
   * @private
   */
  texturesLoaded: {
    get: function () {
      return this._texturesLoaded;
    },
  },
});
 
/**
 * Loads the gltf object
 */
async function loadGltfJson(loader) {
  loader._state = GltfLoaderState.LOADING;
  loader._textureState = GltfLoaderState.LOADING;
 
  try {
    const gltfJsonLoader = ResourceCache.getGltfJsonLoader({
      gltfResource: loader._gltfResource,
      baseResource: loader._baseResource,
      typedArray: loader._typedArray,
      gltfJson: loader._gltfJson,
    });
    loader._gltfJsonLoader = gltfJsonLoader;
    await gltfJsonLoader.load();
 
    if (
      loader.isDestroyed() ||
      loader.isUnloaded() ||
      gltfJsonLoader.isDestroyed()
    ) {
      return;
    }
 
    loader._state = GltfLoaderState.LOADED;
    loader._textureState = GltfLoaderState.LOADED;
 
    return loader;
  } catch (error) {
    Iif (loader.isDestroyed()) {
      return;
    }
 
    loader._state = GltfLoaderState.FAILED;
    loader._textureState = GltfLoaderState.FAILED;
    handleError(loader, error);
  }
}
 
async function loadResources(loader, frameState) {
  if (!FeatureDetection.supportsWebP.initialized) {
    await FeatureDetection.supportsWebP.initialize();
  }
 
  loader._supportedImageFormats = new SupportedImageFormats({
    webp: FeatureDetection.supportsWebP(),
    basis: frameState.context.supportsBasis,
  });
 
  // Loaders that create GPU resources need to be processed every frame until they become
  // ready since the JobScheduler is not able to execute all jobs in a single
  // frame. Any promise failures are collected, and will be handled synchronously in process().
  // Also note that it's fine to call process before a loader is ready to process or
  // after it has failed; nothing will happen.
  const promise = parse(loader, frameState);
 
  // All resource loaders have been created, so we can begin processing
  loader._state = GltfLoaderState.PROCESSING;
  loader._textureState = GltfLoaderState.PROCESSING;
 
  if (defined(loader._gltfJsonLoader) && loader._releaseGltfJson) {
    // Check that the glTF JSON loader is still defined before trying to unload it.
    // It can be unloaded if the glTF loader is destroyed.
    ResourceCache.unload(loader._gltfJsonLoader);
    loader._gltfJsonLoader = undefined;
  }
 
  return promise;
}
 
/**
 * Loads the resource.
 * @returns {Promise.<GltfLoader>} A promise which resolves to the loader when the resource loading is completed.
 * @exception {RuntimeError} Unsupported glTF version
 * @exception {RuntimeError} Unsupported glTF Extension
 * @private
 */
GltfLoader.prototype.load = async function () {
  Iif (defined(this._promise)) {
    return this._promise;
  }
 
  this._promise = loadGltfJson(this);
  return this._promise;
};
 
function handleError(gltfLoader, error) {
  gltfLoader.unload();
  const errorMessage = "Failed to load glTF";
  throw gltfLoader.getError(errorMessage, error);
}
 
function processLoaders(loader, frameState) {
  let ready = true;
  const geometryLoaders = loader._geometryLoaders;
  for (let i = 0; i < geometryLoaders.length; ++i) {
    const geometryReady = geometryLoaders[i].process(frameState);
    if (geometryReady && defined(loader._geometryCallbacks[i])) {
      loader._geometryCallbacks[i]();
      loader._geometryCallbacks[i] = undefined;
    }
    ready = ready && geometryReady;
  }
 
  const structuralMetadataLoader = loader._structuralMetadataLoader;
  if (defined(structuralMetadataLoader)) {
    const metadataReady = structuralMetadataLoader.process(frameState);
    if (metadataReady) {
      loader._components.structuralMetadata =
        structuralMetadataLoader.structuralMetadata;
    }
    ready = ready && metadataReady;
  }
 
  const meshPrimitiveGpmLoader = loader._meshPrimitiveGpmLoader;
  Iif (defined(meshPrimitiveGpmLoader)) {
    const metadataReady = meshPrimitiveGpmLoader.process(frameState);
    if (metadataReady) {
      if (defined(loader._components.structuralMetadata)) {
        oneTimeWarning(
          "structural-metadata-gpm",
          "The model defines both the 'EXT_structural_metadata' extension and the " +
            "'NGA_gpm_local' extension. The data from the 'EXT_structural_metadata' " +
            "extension will be replaced with the data from the 'NGA_gpm_local' extension, " +
            "and will no longer be available for styling and picking.",
        );
      }
      loader._components.structuralMetadata =
        meshPrimitiveGpmLoader.structuralMetadata;
    }
    ready = ready && metadataReady;
  }
 
  if (ready) {
    // Geometry requires further processing
    loader._state = GltfLoaderState.POST_PROCESSING;
  }
}
 
function postProcessGeometry(loader, context) {
  // Apply post-processing steps on geometry such as
  // updating attributes for rendering outlines.
  const loadPlans = loader._primitiveLoadPlans;
  for (let i = 0; i < loadPlans.length; i++) {
    const loadPlan = loadPlans[i];
    loadPlan.postProcess(context);
    if (loadPlan.needsOutlines || loadPlan.needsGaussianSplats) {
      // The glTF loader takes ownership of any buffers generated in the
      // post-process stage since they were created after the geometry loaders
      // finished. This way they can be destroyed when the loader is destroyed.
      gatherPostProcessBuffers(loader, loadPlan);
    }
  }
}
 
function gatherPostProcessBuffers(loader, primitiveLoadPlan) {
  const buffers = loader._postProcessBuffers;
  const primitive = primitiveLoadPlan.primitive;
 
  const outlineCoordinates = primitive.outlineCoordinates;
  if (defined(outlineCoordinates)) {
    // outline coordinates are always loaded as a buffer.
    buffers.push(outlineCoordinates.buffer);
  }
 
  // to do post-processing, all the attributes are loaded as typed arrays
  // so if a buffer exists, it was newly generated
  const attributes = primitive.attributes;
  for (let i = 0; i < attributes.length; i++) {
    const attribute = attributes[i];
    if (defined(attribute.buffer)) {
      buffers.push(attribute.buffer);
    }
  }
 
  // Similarly for the indices.
  const indices = primitive.indices;
  if (defined(indices) && defined(indices.buffer)) {
    buffers.push(indices.buffer);
  }
}
 
/**
 * Process loaders other than textures
 * @private
 */
GltfLoader.prototype._process = function (frameState) {
  if (this._state === GltfLoaderState.READY) {
    return true;
  }
 
  if (this._state === GltfLoaderState.PROCESSING) {
    processLoaders(this, frameState);
  }
 
  if (
    this._resourcesLoaded &&
    this._state === GltfLoaderState.POST_PROCESSING
  ) {
    postProcessGeometry(this, frameState.context);
    this._state = GltfLoaderState.PROCESSED;
  }
 
  if (this._resourcesLoaded && this._state === GltfLoaderState.PROCESSED) {
    // The buffer views can be unloaded once the data is copied.
    unloadBufferViewLoaders(this);
 
    // Similarly, if the glTF was loaded from a typed array, release the memory
    this._typedArray = undefined;
 
    this._state = GltfLoaderState.READY;
    return true;
  }
 
  return false;
};
 
/**
 * Process textures other than textures
 * @private
 */
GltfLoader.prototype._processTextures = function (frameState) {
  if (this._textureState === GltfLoaderState.READY) {
    return true;
  }
 
  if (this._textureState !== GltfLoaderState.PROCESSING) {
    return false;
  }
 
  let ready = true;
  const textureLoaders = this._textureLoaders;
  for (let i = 0; i < textureLoaders.length; ++i) {
    const textureReady = textureLoaders[i].process(frameState);
    if (textureReady && defined(this._textureCallbacks[i])) {
      this._textureCallbacks[i]();
      this._textureCallbacks[i] = undefined;
    }
 
    ready = ready && textureReady;
  }
 
  if (!ready) {
    return false;
  }
 
  this._textureState = GltfLoaderState.READY;
  this._texturesLoaded = true;
  return true;
};
 
/**
 * Processes the resource until it becomes ready.
 *
 * @param {FrameState} frameState The frame state.
 * @private
 */
GltfLoader.prototype.process = function (frameState) {
  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.object("frameState", frameState);
  //>>includeEnd('debug');
 
  if (
    this._state === GltfLoaderState.LOADED &&
    !defined(this._loadResourcesPromise)
  ) {
    this._loadResourcesPromise = loadResources(this, frameState)
      .then(() => {
        this._resourcesLoaded = true;
      })
      .catch((error) => {
        this._processError = error;
      });
  }
 
  if (defined(this._processError)) {
    this._state = GltfLoaderState.FAILED;
    const error = this._processError;
    this._processError = undefined;
    handleError(this, error);
  }
 
  // Pop the next error of the list in case there are multiple
  const textureError = this._textureErrors.pop();
  if (defined(textureError)) {
    // There shouldn't be the need to completely unload in this case. Just throw the error.
    const error = this.getError("Failed to load glTF texture", textureError);
    error.name = "TextureError";
    throw error;
  }
 
  Iif (this._state === GltfLoaderState.FAILED) {
    return false;
  }
 
  let ready = false;
  try {
    ready = this._process(frameState);
  } catch (error) {
    this._state = GltfLoaderState.FAILED;
    handleError(this, error);
  }
 
  // Since textures can be loaded independently and are handled through a separate promise, they are processed in their own function
  let texturesReady = false;
  try {
    texturesReady = this._processTextures(frameState);
  } catch (error) {
    this._textureState = GltfLoaderState.FAILED;
    handleError(this, error);
  }
 
  if (this._incrementallyLoadTextures) {
    return ready;
  }
 
  return ready && texturesReady;
};
 
function getVertexBufferLoader(
  loader,
  accessorId,
  semantic,
  primitive,
  draco,
  spzExtension,
  loadBuffer,
  loadTypedArray,
  frameState,
) {
  const gltf = loader.gltfJson;
  const accessor = gltf.accessors[accessorId];
  const bufferViewId = accessor.bufferView;
 
  const vertexBufferLoader = ResourceCache.getVertexBufferLoader({
    gltf: gltf,
    gltfResource: loader._gltfResource,
    baseResource: loader._baseResource,
    frameState: frameState,
    bufferViewId: bufferViewId,
    primitive: primitive,
    draco: draco,
    spz: spzExtension,
    attributeSemantic: semantic,
    accessorId: accessorId,
    asynchronous: loader._asynchronous,
    loadBuffer: loadBuffer,
    loadTypedArray: loadTypedArray,
  });
 
  return vertexBufferLoader;
}
 
function getIndexBufferLoader(
  loader,
  accessorId,
  primitive,
  draco,
  loadBuffer,
  loadTypedArray,
  frameState,
) {
  const indexBufferLoader = ResourceCache.getIndexBufferLoader({
    gltf: loader.gltfJson,
    accessorId: accessorId,
    gltfResource: loader._gltfResource,
    baseResource: loader._baseResource,
    frameState: frameState,
    primitive: primitive,
    draco: draco,
    asynchronous: loader._asynchronous,
    loadBuffer: loadBuffer,
    loadTypedArray: loadTypedArray,
  });
 
  return indexBufferLoader;
}
 
function getBufferViewLoader(loader, bufferViewId) {
  const bufferViewLoader = ResourceCache.getBufferViewLoader({
    gltf: loader.gltfJson,
    bufferViewId: bufferViewId,
    gltfResource: loader._gltfResource,
    baseResource: loader._baseResource,
  });
 
  loader._bufferViewLoaders.push(bufferViewLoader);
 
  return bufferViewLoader;
}
 
function getPackedTypedArray(gltf, accessor, bufferViewTypedArray) {
  let byteOffset = accessor.byteOffset;
  const byteStride = getAccessorByteStride(gltf, accessor);
  const count = accessor.count;
  const componentCount = numberOfComponentsForType(accessor.type);
  const componentType = accessor.componentType;
  const componentByteLength = ComponentDatatype.getSizeInBytes(componentType);
  const defaultByteStride = componentByteLength * componentCount;
  const componentsLength = count * componentCount;
 
  if (byteStride === defaultByteStride) {
    // Copy the typed array and let the underlying ArrayBuffer be freed
    bufferViewTypedArray = new Uint8Array(bufferViewTypedArray);
    return ComponentDatatype.createArrayBufferView(
      componentType,
      bufferViewTypedArray.buffer,
      bufferViewTypedArray.byteOffset + byteOffset,
      componentsLength,
    );
  }
 
  const accessorTypedArray = ComponentDatatype.createTypedArray(
    componentType,
    componentsLength,
  );
 
  const dataView = new DataView(bufferViewTypedArray.buffer);
  const components = new Array(componentCount);
  const componentReader = getComponentReader(accessor.componentType);
  byteOffset = bufferViewTypedArray.byteOffset + byteOffset;
 
  for (let i = 0; i < count; ++i) {
    componentReader(
      dataView,
      byteOffset,
      componentCount,
      componentByteLength,
      components,
    );
    for (let j = 0; j < componentCount; ++j) {
      accessorTypedArray[i * componentCount + j] = components[j];
    }
    byteOffset += byteStride;
  }
 
  return accessorTypedArray;
}
 
function loadDefaultAccessorValues(accessor, values) {
  const accessorType = accessor.type;
  if (accessorType === AttributeType.SCALAR) {
    return values.fill(0);
  }
 
  const MathType = AttributeType.getMathType(accessorType);
  return values.fill(MathType.clone(MathType.ZERO));
}
 
function loadAccessorValues(accessor, typedArray, values, useQuaternion) {
  const accessorType = accessor.type;
  const accessorCount = accessor.count;
 
  if (accessorType === AttributeType.SCALAR) {
    for (let i = 0; i < accessorCount; i++) {
      values[i] = typedArray[i];
    }
  } else if (accessorType === AttributeType.VEC4 && useQuaternion) {
    for (let i = 0; i < accessorCount; i++) {
      values[i] = Quaternion.unpack(typedArray, i * 4);
    }
  } else {
    const MathType = AttributeType.getMathType(accessorType);
    const numberOfComponents =
      AttributeType.getNumberOfComponents(accessorType);
 
    for (let i = 0; i < accessorCount; i++) {
      values[i] = MathType.unpack(typedArray, i * numberOfComponents);
    }
  }
 
  return values;
}
 
async function loadAccessorBufferView(
  loader,
  bufferViewLoader,
  accessor,
  useQuaternion,
  values,
) {
  // Save a link to the gltfJson, which is removed after bufferViewLoader.load()
  const { gltfJson } = loader;
 
  await bufferViewLoader.load();
  Iif (loader.isDestroyed()) {
    return;
  }
 
  const typedArray = getPackedTypedArray(
    gltfJson,
    accessor,
    bufferViewLoader.typedArray,
  );
 
  useQuaternion = useQuaternion ?? false;
  loadAccessorValues(accessor, typedArray, values, useQuaternion);
}
 
function loadAccessor(loader, accessor, useQuaternion) {
  const values = new Array(accessor.count);
 
  const bufferViewId = accessor.bufferView;
  Eif (defined(bufferViewId)) {
    const bufferViewLoader = getBufferViewLoader(loader, bufferViewId);
    const promise = loadAccessorBufferView(
      loader,
      bufferViewLoader,
      accessor,
      useQuaternion,
      values,
    );
    loader._loaderPromises.push(promise);
 
    return values;
  }
 
  return loadDefaultAccessorValues(accessor, values);
}
 
function fromArray(MathType, values) {
  if (!defined(values)) {
    return undefined;
  }
 
  if (MathType === Number) {
    return values[0];
  }
 
  return MathType.unpack(values);
}
 
function getDefault(MathType) {
  if (MathType === Number) {
    return 0.0;
  }
 
  return new MathType(); // defaults to 0.0 for all types
}
 
function getQuantizationDivisor(componentDatatype) {
  switch (componentDatatype) {
    case ComponentDatatype.BYTE:
      return 127;
    case ComponentDatatype.UNSIGNED_BYTE:
      return 255;
    case ComponentDatatype.SHORT:
      return 32767;
    case ComponentDatatype.UNSIGNED_SHORT:
      return 65535;
    default:
      return 1.0;
  }
}
 
const minimumBoundsByType = {
  VEC2: new Cartesian2(-1.0, -1.0),
  VEC3: new Cartesian3(-1.0, -1.0, -1.0),
  VEC4: new Cartesian4(-1.0, -1.0, -1.0, -1.0),
};
 
function dequantizeMinMax(attribute, VectorType) {
  const divisor = getQuantizationDivisor(attribute.componentDatatype);
  const minimumBound = minimumBoundsByType[attribute.type];
 
  // dequantized = max(quantized / divisor, -1.0)
  let min = attribute.min;
  if (defined(min)) {
    min = VectorType.divideByScalar(min, divisor, min);
    min = VectorType.maximumByComponent(min, minimumBound, min);
  }
 
  let max = attribute.max;
  if (defined(max)) {
    max = VectorType.divideByScalar(max, divisor, max);
    max = VectorType.maximumByComponent(max, minimumBound, max);
  }
 
  attribute.min = min;
  attribute.max = max;
}
 
function setQuantizationFromWeb3dQuantizedAttributes(
  extension,
  attribute,
  MathType,
) {
  const decodeMatrix = extension.decodeMatrix;
  const decodedMin = fromArray(MathType, extension.decodedMin);
  const decodedMax = fromArray(MathType, extension.decodedMax);
 
  if (defined(decodedMin) && defined(decodedMax)) {
    attribute.min = decodedMin;
    attribute.max = decodedMax;
  }
 
  const quantization = new ModelComponents.Quantization();
  quantization.componentDatatype = attribute.componentDatatype;
  quantization.type = attribute.type;
 
  if (decodeMatrix.length === 4) {
    quantization.quantizedVolumeOffset = decodeMatrix[2];
    quantization.quantizedVolumeStepSize = decodeMatrix[0];
  } else Iif (decodeMatrix.length === 9) {
    quantization.quantizedVolumeOffset = new Cartesian2(
      decodeMatrix[6],
      decodeMatrix[7],
    );
    quantization.quantizedVolumeStepSize = new Cartesian2(
      decodeMatrix[0],
      decodeMatrix[4],
    );
  } else if (decodeMatrix.length === 16) {
    quantization.quantizedVolumeOffset = new Cartesian3(
      decodeMatrix[12],
      decodeMatrix[13],
      decodeMatrix[14],
    );
    quantization.quantizedVolumeStepSize = new Cartesian3(
      decodeMatrix[0],
      decodeMatrix[5],
      decodeMatrix[10],
    );
  } else Eif (decodeMatrix.length === 25) {
    quantization.quantizedVolumeOffset = new Cartesian4(
      decodeMatrix[20],
      decodeMatrix[21],
      decodeMatrix[22],
      decodeMatrix[23],
    );
    quantization.quantizedVolumeStepSize = new Cartesian4(
      decodeMatrix[0],
      decodeMatrix[6],
      decodeMatrix[12],
      decodeMatrix[18],
    );
  }
 
  attribute.quantization = quantization;
}
 
function createAttribute(gltf, accessorId, name, semantic, setIndex) {
  const accessor = gltf.accessors[accessorId];
  const MathType = AttributeType.getMathType(accessor.type);
  const normalized = accessor.normalized ?? false;
 
  const attribute = new Attribute();
  attribute.name = name;
  attribute.semantic = semantic;
  attribute.setIndex = setIndex;
  attribute.constant = getDefault(MathType);
  attribute.componentDatatype = accessor.componentType;
  attribute.normalized = normalized;
  attribute.count = accessor.count;
  attribute.type = accessor.type;
  attribute.min = fromArray(MathType, accessor.min);
  attribute.max = fromArray(MathType, accessor.max);
  attribute.byteOffset = accessor.byteOffset;
  attribute.byteStride = getAccessorByteStride(gltf, accessor);
 
  if (hasExtension(accessor, "WEB3D_quantized_attributes")) {
    setQuantizationFromWeb3dQuantizedAttributes(
      accessor.extensions.WEB3D_quantized_attributes,
      attribute,
      MathType,
    );
  }
 
  const isQuantizable =
    attribute.semantic === VertexAttributeSemantic.POSITION ||
    attribute.semantic === VertexAttributeSemantic.NORMAL ||
    attribute.semantic === VertexAttributeSemantic.TANGENT ||
    attribute.semantic === VertexAttributeSemantic.TEXCOORD ||
    attribute.semantic === VertexAttributeSemantic.FEATURE_ID ||
    attribute.semantic === VertexAttributeSemantic.SCALE ||
    attribute.semantic === VertexAttributeSemantic.ROTATION;
 
  // In the glTF 2.0 spec, min and max are not affected by the normalized flag.
  // However, for KHR_mesh_quantization, min and max must be dequantized for
  // normalized values, else the bounding sphere will be computed incorrectly.
  const hasKhrMeshQuantization = gltf.extensionsRequired?.includes(
    "KHR_mesh_quantization",
  );
 
  if (hasKhrMeshQuantization && normalized && isQuantizable) {
    dequantizeMinMax(attribute, MathType);
  }
 
  return attribute;
}
 
function getSetIndex(gltfSemantic) {
  const setIndexRegex = /^\w+_(\d+)$/;
  const setIndexMatch = setIndexRegex.exec(gltfSemantic);
  if (setIndexMatch !== null) {
    return parseInt(setIndexMatch[1]);
  }
  return undefined;
}
 
const scratchSemanticInfo = {
  gltfSemantic: undefined,
  renamedSemantic: undefined,
  modelSemantic: undefined,
};
 
function getSemanticInfo(loader, semanticType, gltfSemantic) {
  // For .b3dm, rename _BATCHID (or the legacy BATCHID) to _FEATURE_ID_0
  // in the generated model components for compatibility with EXT_mesh_features
  let renamedSemantic = gltfSemantic;
  if (
    loader._renameBatchIdSemantic &&
    (gltfSemantic === "_BATCHID" || gltfSemantic === "BATCHID")
  ) {
    renamedSemantic = "_FEATURE_ID_0";
  }
 
  const modelSemantic = semanticType.fromGltfSemantic(renamedSemantic);
 
  const semanticInfo = scratchSemanticInfo;
  semanticInfo.gltfSemantic = gltfSemantic;
  semanticInfo.renamedSemantic = renamedSemantic;
  semanticInfo.modelSemantic = modelSemantic;
 
  return semanticInfo;
}
 
function isClassificationAttribute(attributeSemantic) {
  // Classification models only use the position, texcoord, and feature ID attributes.
  const isPositionAttribute =
    attributeSemantic === VertexAttributeSemantic.POSITION;
  const isFeatureIdAttribute =
    attributeSemantic === VertexAttributeSemantic.FEATURE_ID;
  const isTexcoordAttribute =
    attributeSemantic === VertexAttributeSemantic.TEXCOORD;
 
  return isPositionAttribute || isFeatureIdAttribute || isTexcoordAttribute;
}
 
function finalizeDracoAttribute(
  attribute,
  vertexBufferLoader,
  loadBuffer,
  loadTypedArray,
) {
  // The accessor's byteOffset and byteStride should be ignored for draco.
  // Each attribute is tightly packed in its own buffer after decode.
  attribute.byteOffset = 0;
  attribute.byteStride = undefined;
  attribute.quantization = vertexBufferLoader.quantization;
 
  Eif (loadBuffer) {
    attribute.buffer = vertexBufferLoader.buffer;
  }
 
  if (loadTypedArray) {
    const componentDatatype = defined(vertexBufferLoader.quantization)
      ? vertexBufferLoader.quantization.componentDatatype
      : attribute.componentDatatype;
 
    attribute.typedArray = ComponentDatatype.createArrayBufferView(
      componentDatatype,
      vertexBufferLoader.typedArray.buffer,
    );
  }
}
 
function finalizeSpzAttribute(
  attribute,
  vertexBufferLoader,
  loadBuffer,
  loadTypedArray,
) {
  attribute.byteOffset = 0;
  attribute.byteStride = undefined;
 
  Iif (loadBuffer) {
    attribute.buffer = vertexBufferLoader.buffer;
  }
 
  Eif (loadTypedArray && defined(vertexBufferLoader.typedArray)) {
    attribute.typedArray = ComponentDatatype.createArrayBufferView(
      attribute.componentDatatype,
      vertexBufferLoader.typedArray.buffer,
    );
  }
 
  if (attribute.semantic === VertexAttributeSemantic.POSITION) {
    const findMinMaxXY = (flatArray) => {
      let minX = Infinity;
      let maxX = -Infinity;
      let minY = Infinity;
      let maxY = -Infinity;
      let minZ = Infinity;
      let maxZ = -Infinity;
 
      for (let i = 0; i < flatArray.length; i += 3) {
        const x = flatArray[i];
        const y = flatArray[i + 1];
        const z = flatArray[i + 2];
 
        minX = Math.min(minX, x);
        maxX = Math.max(maxX, x);
        minY = Math.min(minY, y);
        maxY = Math.max(maxY, y);
        minZ = Math.min(minZ, z);
        maxZ = Math.max(maxZ, z);
      }
 
      return [
        new Cartesian3(minX, minY, minZ),
        new Cartesian3(maxX, maxY, maxZ),
      ];
    };
    const buffer = attribute.typedArray;
    [attribute.min, attribute.max] = findMinMaxXY(buffer);
  }
}
 
function finalizeAttribute(
  gltf,
  accessor,
  attribute,
  vertexBufferLoader,
  loadBuffer,
  loadTypedArray,
) {
  if (loadBuffer) {
    attribute.buffer = vertexBufferLoader.buffer;
  }
 
  if (loadTypedArray) {
    const bufferViewTypedArray = vertexBufferLoader.typedArray;
    attribute.typedArray = getPackedTypedArray(
      gltf,
      accessor,
      bufferViewTypedArray,
    );
 
    if (!loadBuffer) {
      // If the buffer isn't loaded, then the accessor's byteOffset and
      // byteStride should be ignored, since values are only available in a
      // tightly packed typed array
      attribute.byteOffset = 0;
      attribute.byteStride = undefined;
    }
  }
}
 
function loadAttribute(
  loader,
  accessorId,
  semanticInfo,
  primitive,
  draco,
  spz,
  loadBuffer,
  loadTypedArray,
  frameState,
) {
  const gltf = loader.gltfJson;
  const accessor = gltf.accessors[accessorId];
  const bufferViewId = accessor.bufferView;
 
  const gltfSemantic = semanticInfo.gltfSemantic;
  const renamedSemantic = semanticInfo.renamedSemantic;
  const modelSemantic = semanticInfo.modelSemantic;
 
  const setIndex = defined(modelSemantic)
    ? getSetIndex(renamedSemantic)
    : undefined;
 
  const name = gltfSemantic;
  const attribute = createAttribute(
    gltf,
    accessorId,
    name,
    modelSemantic,
    setIndex,
  );
 
  if (!defined(draco) && !defined(bufferViewId) && !defined(spz)) {
    return attribute;
  }
 
  const vertexBufferLoader = getVertexBufferLoader(
    loader,
    accessorId,
    gltfSemantic,
    primitive,
    draco,
    spz,
    loadBuffer,
    loadTypedArray,
    frameState,
  );
 
  const index = loader._geometryLoaders.length;
  loader._geometryLoaders.push(vertexBufferLoader);
  const promise = vertexBufferLoader.load();
  loader._loaderPromises.push(promise);
 
  // This can only execute once vertexBufferLoader.process() has run and returns true
  // Save this finish callback by the loader index so it can be called
  // in process().
  loader._geometryCallbacks[index] = () => {
    if (
      defined(draco) &&
      defined(draco.attributes) &&
      defined(draco.attributes[gltfSemantic])
    ) {
      finalizeDracoAttribute(
        attribute,
        vertexBufferLoader,
        loadBuffer,
        loadTypedArray,
      );
    } else if (defined(spz)) {
      finalizeSpzAttribute(
        attribute,
        vertexBufferLoader,
        loadBuffer,
        loadTypedArray,
      );
    } else {
      finalizeAttribute(
        gltf,
        accessor,
        attribute,
        vertexBufferLoader,
        loadBuffer,
        loadTypedArray,
      );
    }
  };
 
  return attribute;
}
 
function loadVertexAttribute(
  loader,
  accessorId,
  semanticInfo,
  primitive,
  draco,
  spz,
  hasInstances,
  needsPostProcessing,
  frameState,
) {
  const modelSemantic = semanticInfo.modelSemantic;
 
  const isPositionAttribute =
    modelSemantic === VertexAttributeSemantic.POSITION;
  const isFeatureIdAttribute =
    modelSemantic === VertexAttributeSemantic.FEATURE_ID;
 
  const loadTypedArrayFor2D =
    isPositionAttribute &&
    !hasInstances &&
    loader._loadAttributesFor2D &&
    !frameState.scene3DOnly;
  const loadTypedArrayForPicking =
    isPositionAttribute && loader._enablePick && !frameState.context.webgl2;
 
  const loadTypedArrayForClassification =
    loader._loadForClassification && isFeatureIdAttribute;
 
  // Whether the final output should be a buffer or typed array
  // after loading and post-processing.
  const outputTypedArrayOnly = loader._loadAttributesAsTypedArray;
  const outputBuffer = !outputTypedArrayOnly;
  const outputTypedArray =
    outputTypedArrayOnly ||
    loadTypedArrayFor2D ||
    loadTypedArrayForPicking ||
    loadTypedArrayForClassification;
 
  // Determine what to load right now:
  //
  // - If post-processing is needed, load a packed typed array for
  //   further processing, and defer the buffer loading until later.
  // - On the other hand, if post-processing is not needed,
  //   set the load flags directly
  const loadBuffer = needsPostProcessing ? false : outputBuffer;
  const loadTypedArray = needsPostProcessing ? true : outputTypedArray;
 
  const attribute = loadAttribute(
    loader,
    accessorId,
    semanticInfo,
    primitive,
    draco,
    spz,
    loadBuffer,
    loadTypedArray,
    frameState,
  );
 
  const attributePlan = new PrimitiveLoadPlan.AttributeLoadPlan(attribute);
  attributePlan.loadBuffer = outputBuffer;
  attributePlan.loadTypedArray = outputTypedArray;
 
  return attributePlan;
}
 
function loadInstancedAttribute(
  loader,
  accessorId,
  attributes,
  gltfSemantic,
  frameState,
) {
  const accessors = loader.gltfJson.accessors;
  const hasRotation = defined(attributes.ROTATION);
  const hasTranslationMinMax =
    defined(attributes.TRANSLATION) &&
    defined(accessors[attributes.TRANSLATION].min) &&
    defined(accessors[attributes.TRANSLATION].max);
 
  const semanticInfo = getSemanticInfo(
    loader,
    InstanceAttributeSemantic,
    gltfSemantic,
  );
  const modelSemantic = semanticInfo.modelSemantic;
 
  const isTransformAttribute =
    modelSemantic === InstanceAttributeSemantic.TRANSLATION ||
    modelSemantic === InstanceAttributeSemantic.ROTATION ||
    modelSemantic === InstanceAttributeSemantic.SCALE;
  const isTranslationAttribute =
    modelSemantic === InstanceAttributeSemantic.TRANSLATION;
 
  // Load the attributes as typed arrays only if:
  // - loadAttributesAsTypedArray is true
  // - the instances have rotations. This only applies to the transform attributes,
  //   since The instance matrices are computed on the CPU. This avoids the
  //   expensive quaternion -> rotation matrix conversion in the shader.
  // - GPU instancing is not supported.
  const loadAsTypedArrayOnly =
    loader._loadAttributesAsTypedArray ||
    (hasRotation && isTransformAttribute) ||
    !frameState.context.instancedArrays;
  const loadTypedArrayForPicking =
    loader._enablePick && !frameState.context.webgl2;
 
  const loadBuffer = !loadAsTypedArrayOnly;
 
  // Load the translations as a typed array in addition to the buffer if
  // - the accessor does not have a min and max. The values will be used
  //   for computing an accurate bounding volume.
  // - the model will be projected to 2D.
  const loadFor2D = loader._loadAttributesFor2D && !frameState.scene3DOnly;
  const loadTranslationAsTypedArray =
    isTranslationAttribute &&
    (!hasTranslationMinMax || loadFor2D || loadTypedArrayForPicking);
 
  const loadTypedArray = loadAsTypedArrayOnly || loadTranslationAsTypedArray;
 
  // Don't pass in primitive or draco object since instanced attributes can't be draco compressed
  return loadAttribute(
    loader,
    accessorId,
    semanticInfo,
    undefined,
    undefined,
    undefined,
    loadBuffer,
    loadTypedArray,
    frameState,
  );
}
 
function loadIndices(
  loader,
  accessorId,
  primitive,
  hasFeatureIds,
  needsPostProcessing,
  frameState,
) {
  const accessor = loader.gltfJson.accessors[accessorId];
  const bufferViewId = accessor.bufferView;
  // Infer compression / extensions directly from the glTF primitive instead of passing in flags
  const extensions = primitive.extensions ?? Frozen.EMPTY_OBJECT;
  const draco = extensions.KHR_draco_mesh_compression;
  const hasEdgeVisibility = defined(
    extensions.EXT_mesh_primitive_edge_visibility,
  );
 
  if (!defined(draco) && !defined(bufferViewId)) {
    return undefined;
  }
 
  const indices = new Indices();
  indices.count = accessor.count;
 
  const loadAttributesAsTypedArray = loader._loadAttributesAsTypedArray;
  // Load the index buffer as a typed array to generate wireframes or pick in WebGL1.
  const loadForCpuOperations =
    (loader._loadIndicesForWireframe || loader._enablePick) &&
    !frameState.context.webgl2;
 
  // Load the index buffer as a typed array to batch features together for classification.
  const loadForClassification = loader._loadForClassification && hasFeatureIds;
 
  // Whether the final output should be a buffer or typed array
  // after loading and post-processing.
  const outputTypedArrayOnly = loadAttributesAsTypedArray;
  const outputBuffer = !outputTypedArrayOnly;
  const outputTypedArray =
    loadAttributesAsTypedArray ||
    loadForCpuOperations ||
    loadForClassification ||
    hasEdgeVisibility;
 
  // Determine what to load right now:
  //
  // - If post-processing is needed, load a packed typed array for
  //   further processing, and defer the buffer loading until later.
  // - On the other hand, if post-processing is not needed, set the load
  //   flags directly
  const loadBuffer = needsPostProcessing ? false : outputBuffer;
  const loadTypedArray = needsPostProcessing ? true : outputTypedArray;
 
  const indexBufferLoader = getIndexBufferLoader(
    loader,
    accessorId,
    primitive,
    draco,
    loadBuffer,
    loadTypedArray,
    frameState,
  );
 
  const index = loader._geometryLoaders.length;
  loader._geometryLoaders.push(indexBufferLoader);
  const promise = indexBufferLoader.load();
  loader._loaderPromises.push(promise);
  // This can only execute once indexBufferLoader.process() has run and returns true
  // Save this finish callback by the loader index so it can be called
  // in process().
  loader._geometryCallbacks[index] = () => {
    indices.indexDatatype = indexBufferLoader.indexDatatype;
    indices.buffer = indexBufferLoader.buffer;
    indices.typedArray = indexBufferLoader.typedArray;
  };
 
  const indicesPlan = new PrimitiveLoadPlan.IndicesLoadPlan(indices);
  indicesPlan.loadBuffer = outputBuffer;
  indicesPlan.loadTypedArray = outputTypedArray;
 
  return indicesPlan;
}
 
function loadTexture(loader, textureInfo, frameState, samplerOverride) {
  const gltf = loader.gltfJson;
  const imageId = GltfLoaderUtil.getImageIdFromTexture({
    gltf: gltf,
    textureId: textureInfo.index,
    supportedImageFormats: loader._supportedImageFormats,
  });
 
  if (!defined(imageId)) {
    return undefined;
  }
 
  const textureLoader = ResourceCache.getTextureLoader({
    gltf: gltf,
    textureInfo: textureInfo,
    gltfResource: loader._gltfResource,
    baseResource: loader._baseResource,
    supportedImageFormats: loader._supportedImageFormats,
    frameState: frameState,
    asynchronous: loader._asynchronous,
  });
 
  const textureReader = GltfLoaderUtil.createModelTextureReader({
    textureInfo: textureInfo,
  });
 
  const index = loader._textureLoaders.length;
  loader._textureLoaders.push(textureLoader);
  const promise = textureLoader.load().catch((error) => {
    Iif (loader.isDestroyed()) {
      return;
    }
 
    if (!loader._incrementallyLoadTextures) {
      // If incrementallyLoadTextures is false, throw the error to ensure the loader state
      // immediately is set to have failed
      throw error;
    }
 
    // Otherwise, save the error so it can be thrown next
    loader._textureState = GltfLoaderState.FAILED;
    loader._textureErrors.push(error);
  });
  loader._texturesPromises.push(promise);
  // This can only execute once textureLoader.process() has run and returns true
  // Save this finish callback by the loader index so it can be called
  // in process().
  loader._textureCallbacks[index] = () => {
    textureReader.texture = textureLoader.texture;
    if (defined(samplerOverride)) {
      textureReader.texture.sampler = samplerOverride;
    }
  };
 
  return textureReader;
}
 
/**
 * Load textures and parse factors for the KHR_materials_pbrSpecularGlossiness extension
 * @param {GltfLoader} loader
 * @param {object} specularGlossinessInfo The contents of the KHR_materials_pbrSpecularGlossiness extension in the parsed glTF JSON
 * @param {FrameState} frameState
 * @returns {ModelComponents.SpecularGlossiness}
 * @private
 */
function loadSpecularGlossiness(loader, specularGlossinessInfo, frameState) {
  const {
    diffuseTexture,
    specularGlossinessTexture,
    diffuseFactor,
    specularFactor,
    glossinessFactor,
  } = specularGlossinessInfo;
 
  const specularGlossiness = new SpecularGlossiness();
  Eif (defined(diffuseTexture)) {
    specularGlossiness.diffuseTexture = loadTexture(
      loader,
      diffuseTexture,
      frameState,
    );
  }
  Eif (defined(specularGlossinessTexture)) {
    specularGlossiness.specularGlossinessTexture = loadTexture(
      loader,
      specularGlossinessTexture,
      frameState,
    );
  }
  specularGlossiness.diffuseFactor = fromArray(Cartesian4, diffuseFactor);
  specularGlossiness.specularFactor = fromArray(Cartesian3, specularFactor);
  specularGlossiness.glossinessFactor = glossinessFactor;
 
  return specularGlossiness;
}
 
/**
 * Load textures and parse factors for a metallic-roughness PBR model in a glTF material
 * @param {GltfLoader} loader
 * @param {object} metallicRoughnessInfo The contents of a pbrMetallicRoughness property in the parsed glTF JSON
 * @param {FrameState} frameState
 * @returns {ModelComponents.MetallicRoughness}
 * @private
 */
function loadMetallicRoughness(loader, metallicRoughnessInfo, frameState) {
  const {
    baseColorTexture,
    metallicRoughnessTexture,
    baseColorFactor,
    metallicFactor,
    roughnessFactor,
  } = metallicRoughnessInfo;
 
  const metallicRoughness = new MetallicRoughness();
  if (defined(baseColorTexture)) {
    metallicRoughness.baseColorTexture = loadTexture(
      loader,
      baseColorTexture,
      frameState,
    );
  }
  if (defined(metallicRoughnessTexture)) {
    metallicRoughness.metallicRoughnessTexture = loadTexture(
      loader,
      metallicRoughnessTexture,
      frameState,
    );
  }
  metallicRoughness.baseColorFactor = fromArray(Cartesian4, baseColorFactor);
  metallicRoughness.metallicFactor = metallicFactor;
  metallicRoughness.roughnessFactor = roughnessFactor;
 
  return metallicRoughness;
}
 
function loadSpecular(loader, specularInfo, frameState) {
  const {
    specularFactor,
    specularTexture,
    specularColorFactor,
    specularColorTexture,
  } = specularInfo;
 
  const specular = new Specular();
  Eif (defined(specularTexture)) {
    specular.specularTexture = loadTexture(loader, specularTexture, frameState);
  }
  Eif (defined(specularColorTexture)) {
    specular.specularColorTexture = loadTexture(
      loader,
      specularColorTexture,
      frameState,
    );
  }
  specular.specularFactor = specularFactor;
  specular.specularColorFactor = fromArray(Cartesian3, specularColorFactor);
 
  return specular;
}
 
function loadAnisotropy(loader, anisotropyInfo, frameState) {
  const {
    anisotropyStrength = Anisotropy.DEFAULT_ANISOTROPY_STRENGTH,
    anisotropyRotation = Anisotropy.DEFAULT_ANISOTROPY_ROTATION,
    anisotropyTexture,
  } = anisotropyInfo;
 
  const anisotropy = new Anisotropy();
  Eif (defined(anisotropyTexture)) {
    anisotropy.anisotropyTexture = loadTexture(
      loader,
      anisotropyTexture,
      frameState,
    );
  }
  anisotropy.anisotropyStrength = anisotropyStrength;
  anisotropy.anisotropyRotation = anisotropyRotation;
 
  return anisotropy;
}
 
function loadClearcoat(loader, clearcoatInfo, frameState) {
  const {
    clearcoatFactor = Clearcoat.DEFAULT_CLEARCOAT_FACTOR,
    clearcoatTexture,
    clearcoatRoughnessFactor = Clearcoat.DEFAULT_CLEARCOAT_ROUGHNESS_FACTOR,
    clearcoatRoughnessTexture,
    clearcoatNormalTexture,
  } = clearcoatInfo;
 
  const clearcoat = new Clearcoat();
  Eif (defined(clearcoatTexture)) {
    clearcoat.clearcoatTexture = loadTexture(
      loader,
      clearcoatTexture,
      frameState,
    );
  }
  Eif (defined(clearcoatRoughnessTexture)) {
    clearcoat.clearcoatRoughnessTexture = loadTexture(
      loader,
      clearcoatRoughnessTexture,
      frameState,
    );
  }
  Eif (defined(clearcoatNormalTexture)) {
    clearcoat.clearcoatNormalTexture = loadTexture(
      loader,
      clearcoatNormalTexture,
      frameState,
    );
  }
  clearcoat.clearcoatFactor = clearcoatFactor;
  clearcoat.clearcoatRoughnessFactor = clearcoatRoughnessFactor;
 
  return clearcoat;
}
 
/**
 * Load textures and parse factors and flags for a glTF material
 *
 * @param {GltfLoader} loader
 * @param {object} gltfMaterial An entry from the <code>.materials</code> array in the glTF JSON
 * @param {FrameState} frameState
 * @returns {ModelComponents.Material}
 * @private
 */
function loadMaterial(loader, gltfMaterial, frameState) {
  const material = new Material();
 
  const extensions = gltfMaterial.extensions ?? Frozen.EMPTY_OBJECT;
  const pbrSpecularGlossiness = extensions.KHR_materials_pbrSpecularGlossiness;
  const pbrSpecular = extensions.KHR_materials_specular;
  const pbrAnisotropy = extensions.KHR_materials_anisotropy;
  const pbrClearcoat = extensions.KHR_materials_clearcoat;
  const pbrMetallicRoughness = gltfMaterial.pbrMetallicRoughness;
 
  material.unlit = defined(extensions.KHR_materials_unlit);
 
  if (defined(pbrSpecularGlossiness)) {
    material.specularGlossiness = loadSpecularGlossiness(
      loader,
      pbrSpecularGlossiness,
      frameState,
    );
  } else {
    if (defined(pbrMetallicRoughness)) {
      material.metallicRoughness = loadMetallicRoughness(
        loader,
        pbrMetallicRoughness,
        frameState,
      );
    }
    if (defined(pbrSpecular) && !material.unlit) {
      material.specular = loadSpecular(loader, pbrSpecular, frameState);
    }
    if (defined(pbrAnisotropy) && !material.unlit) {
      material.anisotropy = loadAnisotropy(loader, pbrAnisotropy, frameState);
    }
    if (defined(pbrClearcoat) && !material.unlit) {
      material.clearcoat = loadClearcoat(loader, pbrClearcoat, frameState);
    }
  }
 
  // Top level textures
  if (defined(gltfMaterial.emissiveTexture)) {
    material.emissiveTexture = loadTexture(
      loader,
      gltfMaterial.emissiveTexture,
      frameState,
    );
  }
  // Normals aren't used for classification, so don't load the normal texture.
  if (defined(gltfMaterial.normalTexture) && !loader._loadForClassification) {
    material.normalTexture = loadTexture(
      loader,
      gltfMaterial.normalTexture,
      frameState,
    );
  }
  if (defined(gltfMaterial.occlusionTexture)) {
    material.occlusionTexture = loadTexture(
      loader,
      gltfMaterial.occlusionTexture,
      frameState,
    );
  }
  material.emissiveFactor = fromArray(Cartesian3, gltfMaterial.emissiveFactor);
  material.alphaMode = gltfMaterial.alphaMode;
  material.alphaCutoff = gltfMaterial.alphaCutoff;
  material.doubleSided = gltfMaterial.doubleSided;
 
  return material;
}
 
// for EXT_mesh_features
function loadFeatureIdAttribute(featureIds, positionalLabel) {
  const featureIdAttribute = new FeatureIdAttribute();
  featureIdAttribute.featureCount = featureIds.featureCount;
  featureIdAttribute.nullFeatureId = featureIds.nullFeatureId;
  featureIdAttribute.propertyTableId = featureIds.propertyTable;
  featureIdAttribute.setIndex = featureIds.attribute;
  featureIdAttribute.label = featureIds.label;
  featureIdAttribute.positionalLabel = positionalLabel;
  return featureIdAttribute;
}
 
// for backwards compatibility with EXT_feature_metadata
function loadFeatureIdAttributeLegacy(
  gltfFeatureIdAttribute,
  featureTableId,
  featureCount,
  positionalLabel,
) {
  const featureIdAttribute = new FeatureIdAttribute();
  const featureIds = gltfFeatureIdAttribute.featureIds;
  featureIdAttribute.featureCount = featureCount;
  featureIdAttribute.propertyTableId = featureTableId;
  featureIdAttribute.setIndex = getSetIndex(featureIds.attribute);
  featureIdAttribute.positionalLabel = positionalLabel;
  return featureIdAttribute;
}
 
// implicit ranges do not exist in EXT_mesh_features and EXT_instance_features,
// but both default to the vertex/instance ID which is like
// an implicit range of {offset: 0, repeat: 1}
function loadDefaultFeatureIds(featureIds, positionalLabel) {
  const featureIdRange = new FeatureIdImplicitRange();
  featureIdRange.propertyTableId = featureIds.propertyTable;
  featureIdRange.featureCount = featureIds.featureCount;
  featureIdRange.nullFeatureId = featureIds.nullFeatureId;
  featureIdRange.label = featureIds.label;
  featureIdRange.positionalLabel = positionalLabel;
  featureIdRange.offset = 0;
  featureIdRange.repeat = 1;
  return featureIdRange;
}
 
// for backwards compatibility with EXT_feature_metadata
function loadFeatureIdImplicitRangeLegacy(
  gltfFeatureIdAttribute,
  featureTableId,
  featureCount,
  positionalLabel,
) {
  const featureIdRange = new FeatureIdImplicitRange();
  const featureIds = gltfFeatureIdAttribute.featureIds;
  featureIdRange.propertyTableId = featureTableId;
  featureIdRange.featureCount = featureCount;
 
  // constant/divisor was renamed to offset/repeat
  featureIdRange.offset = featureIds.constant ?? 0;
  // The default is now undefined
  const divisor = featureIds.divisor ?? 0;
  featureIdRange.repeat = divisor === 0 ? undefined : divisor;
 
  featureIdRange.positionalLabel = positionalLabel;
  return featureIdRange;
}
 
// for EXT_mesh_features
function loadFeatureIdTexture(
  loader,
  gltfFeatureIdTexture,
  frameState,
  positionalLabel,
) {
  const featureIdTexture = new FeatureIdTexture();
 
  featureIdTexture.featureCount = gltfFeatureIdTexture.featureCount;
  featureIdTexture.nullFeatureId = gltfFeatureIdTexture.nullFeatureId;
  featureIdTexture.propertyTableId = gltfFeatureIdTexture.propertyTable;
  featureIdTexture.label = gltfFeatureIdTexture.label;
  featureIdTexture.positionalLabel = positionalLabel;
 
  const textureInfo = gltfFeatureIdTexture.texture;
  featureIdTexture.textureReader = loadTexture(
    loader,
    textureInfo,
    frameState,
    Sampler.NEAREST, // Feature ID textures require nearest sampling
  );
 
  // Though the new channel index is more future-proof, this implementation
  // only supports RGBA textures. At least for now, the string representation
  // is more useful for generating shader code.
  const channels = defined(textureInfo.channels) ? textureInfo.channels : [0];
  const channelString = channels
    .map(function (channelIndex) {
      return "rgba".charAt(channelIndex);
    })
    .join("");
  featureIdTexture.textureReader.channels = channelString;
 
  return featureIdTexture;
}
 
// for backwards compatibility with EXT_feature_metadata
function loadFeatureIdTextureLegacy(
  loader,
  gltfFeatureIdTexture,
  featureTableId,
  frameState,
  featureCount,
  positionalLabel,
) {
  const featureIdTexture = new FeatureIdTexture();
  const featureIds = gltfFeatureIdTexture.featureIds;
  const textureInfo = featureIds.texture;
  featureIdTexture.featureCount = featureCount;
  featureIdTexture.propertyTableId = featureTableId;
  featureIdTexture.textureReader = loadTexture(
    loader,
    textureInfo,
    frameState,
    Sampler.NEAREST, // Feature ID textures require nearest sampling
  );
 
  featureIdTexture.textureReader.channels = featureIds.channels;
  featureIdTexture.positionalLabel = positionalLabel;
 
  return featureIdTexture;
}
 
function loadMorphTarget(
  loader,
  target,
  needsPostProcessing,
  primitiveLoadPlan,
  frameState,
) {
  const morphTarget = new MorphTarget();
 
  // Don't pass in primitive or draco object since morph targets can't be draco compressed
  const primitive = undefined;
  const draco = undefined;
  const spz = undefined;
  const hasInstances = false;
 
  for (const semantic in target) {
    Iif (!target.hasOwnProperty(semantic)) {
      continue;
    }
    const accessorId = target[semantic];
 
    const semanticInfo = getSemanticInfo(
      loader,
      VertexAttributeSemantic,
      semantic,
    );
 
    const attributePlan = loadVertexAttribute(
      loader,
      accessorId,
      semanticInfo,
      primitive,
      draco,
      spz,
      hasInstances,
      needsPostProcessing,
      frameState,
    );
    morphTarget.attributes.push(attributePlan.attribute);
 
    // The load plan doesn't need to distinguish morph target attributes from
    // regular attributes
    primitiveLoadPlan.attributePlans.push(attributePlan);
  }
 
  return morphTarget;
}
 
function fetchSpzExtensionFrom(extensions) {
  const gaussianSplatting = extensions?.KHR_gaussian_splatting;
  const gsExtensions = gaussianSplatting?.extensions;
  const spz = gsExtensions?.KHR_gaussian_splatting_compression_spz_2;
  if (defined(spz)) {
    return spz;
  }
 
  return undefined;
}
 
/**
 * Load resources associated with a mesh primitive for a glTF node
 * @param {GltfLoader} loader
 * @param {object} gltfPrimitive One of the primitives in a mesh
 * @param {boolean} hasInstances True if the node using this mesh has instances
 * @param {FrameState} frameState
 * @returns {ModelComponents.Primitive}
 * @private
 */
function loadPrimitive(loader, gltfPrimitive, hasInstances, frameState) {
  const primitive = new Primitive();
  const primitivePlan = new PrimitiveLoadPlan(primitive);
  loader._primitiveLoadPlans.push(primitivePlan);
 
  const materialId = gltfPrimitive.material;
  Eif (defined(materialId)) {
    primitive.material = loadMaterial(
      loader,
      loader.gltfJson.materials[materialId],
      frameState,
    );
  }
 
  const extensions = gltfPrimitive.extensions ?? Frozen.EMPTY_OBJECT;
 
  let needsPostProcessing = false;
  const outlineExtension = extensions.CESIUM_primitive_outline;
  if (loader._loadPrimitiveOutline && defined(outlineExtension)) {
    needsPostProcessing = true;
    primitivePlan.needsOutlines = true;
    primitivePlan.outlineIndices = loadPrimitiveOutline(
      loader,
      outlineExtension,
      primitivePlan,
    );
  }
 
  // Edge Visibility
  const edgeVisibilityExtension = extensions.EXT_mesh_primitive_edge_visibility;
  const hasEdgeVisibility = defined(edgeVisibilityExtension);
  if (hasEdgeVisibility) {
    const visibilityAccessor =
      loader.gltfJson.accessors[edgeVisibilityExtension.visibility];
    Iif (!defined(visibilityAccessor)) {
      throw new RuntimeError("Edge visibility accessor not found!");
    }
    const visibilityValues = loadAccessor(loader, visibilityAccessor);
    primitive.edgeVisibility = {
      visibility: visibilityValues,
      material: edgeVisibilityExtension.material,
    };
 
    // Load silhouette normals
    if (defined(edgeVisibilityExtension.silhouetteNormals)) {
      const silhouetteNormalsAccessor =
        loader.gltfJson.accessors[edgeVisibilityExtension.silhouetteNormals];
      Eif (defined(silhouetteNormalsAccessor)) {
        const silhouetteNormalsValues = loadAccessor(
          loader,
          silhouetteNormalsAccessor,
        );
        primitive.edgeVisibility.silhouetteNormals = silhouetteNormalsValues;
      }
    }
 
    // Load line strings
    Iif (defined(edgeVisibilityExtension.lineStrings)) {
      primitivePlan.edgeVisibility.lineStrings =
        edgeVisibilityExtension.lineStrings;
    }
  }
 
  //support the latest glTF spec and the legacy extension
  const spzExtension = fetchSpzExtensionFrom(extensions);
 
  if (defined(spzExtension)) {
    needsPostProcessing = true;
    primitivePlan.needsGaussianSplats = true;
  }
 
  const loadForClassification = loader._loadForClassification;
  const draco = extensions.KHR_draco_mesh_compression;
 
  let hasFeatureIds = false;
  const attributes = gltfPrimitive.attributes;
  Eif (defined(attributes)) {
    for (const semantic in attributes) {
      Iif (!attributes.hasOwnProperty(semantic)) {
        continue;
      }
      const accessorId = attributes[semantic];
      const semanticInfo = getSemanticInfo(
        loader,
        VertexAttributeSemantic,
        semantic,
      );
 
      const modelSemantic = semanticInfo.modelSemantic;
      if (loadForClassification && !isClassificationAttribute(modelSemantic)) {
        continue;
      }
 
      if (modelSemantic === VertexAttributeSemantic.FEATURE_ID) {
        hasFeatureIds = true;
      }
 
      const attributePlan = loadVertexAttribute(
        loader,
        accessorId,
        semanticInfo,
        gltfPrimitive,
        draco,
        spzExtension,
        hasInstances,
        needsPostProcessing,
        frameState,
      );
 
      primitivePlan.attributePlans.push(attributePlan);
      primitive.attributes.push(attributePlan.attribute);
    }
  }
 
  const targets = gltfPrimitive.targets;
  // Morph targets are disabled for classification models.
  if (defined(targets) && !loadForClassification) {
    for (let i = 0; i < targets.length; ++i) {
      primitive.morphTargets.push(
        loadMorphTarget(
          loader,
          targets[i],
          needsPostProcessing,
          primitivePlan,
          frameState,
        ),
      );
    }
  }
 
  const indices = gltfPrimitive.indices;
  if (defined(indices)) {
    const indicesPlan = loadIndices(
      loader,
      indices,
      gltfPrimitive,
      hasFeatureIds,
      needsPostProcessing,
      frameState,
    );
 
    if (defined(indicesPlan)) {
      primitivePlan.indicesPlan = indicesPlan;
      primitive.indices = indicesPlan.indices;
    }
  }
 
  // With the latest revision, feature IDs are defined in EXT_mesh_features
  // while EXT_structural_metadata is for defining property textures and
  // property mappings. In the legacy EXT_feature_metadata, these concepts
  // were all in one extension.
  const structuralMetadata = extensions.EXT_structural_metadata;
  const meshFeatures = extensions.EXT_mesh_features;
  const featureMetadataLegacy = extensions.EXT_feature_metadata;
  const hasFeatureMetadataLegacy = defined(featureMetadataLegacy);
 
  // Load feature Ids
  if (defined(meshFeatures)) {
    loadPrimitiveFeatures(loader, primitive, meshFeatures, frameState);
  } else if (hasFeatureMetadataLegacy) {
    loadPrimitiveFeaturesLegacy(
      loader,
      primitive,
      featureMetadataLegacy,
      frameState,
    );
  }
 
  // Load structural metadata
  if (defined(structuralMetadata)) {
    loadPrimitiveMetadata(primitive, structuralMetadata);
  } else if (hasFeatureMetadataLegacy) {
    loadPrimitiveMetadataLegacy(loader, primitive, featureMetadataLegacy);
  }
 
  const primitiveType = gltfPrimitive.mode;
  if (loadForClassification && primitiveType !== PrimitiveType.TRIANGLES) {
    throw new RuntimeError(
      "Only triangle meshes can be used for classification.",
    );
  }
  primitive.primitiveType = primitiveType;
 
  return primitive;
}
 
function loadPrimitiveOutline(loader, outlineExtension) {
  const accessorId = outlineExtension.indices;
  const accessor = loader.gltfJson.accessors[accessorId];
  const useQuaternion = false;
  return loadAccessor(loader, accessor, useQuaternion);
}
 
// For EXT_mesh_features
function loadPrimitiveFeatures(
  loader,
  primitive,
  meshFeaturesExtension,
  frameState,
) {
  let featureIdsArray;
  if (
    defined(meshFeaturesExtension) &&
    defined(meshFeaturesExtension.featureIds)
  ) {
    featureIdsArray = meshFeaturesExtension.featureIds;
  } else E{
    featureIdsArray = [];
  }
 
  for (let i = 0; i < featureIdsArray.length; i++) {
    const featureIds = featureIdsArray[i];
    const label = `featureId_${i}`;
 
    let featureIdComponent;
    if (defined(featureIds.texture)) {
      featureIdComponent = loadFeatureIdTexture(
        loader,
        featureIds,
        frameState,
        label,
      );
    } else if (defined(featureIds.attribute)) {
      featureIdComponent = loadFeatureIdAttribute(featureIds, label);
    } else {
      // default to vertex ID, in other words an implicit range with
      // offset: 0, repeat: 1
      featureIdComponent = loadDefaultFeatureIds(featureIds, label);
    }
 
    primitive.featureIds.push(featureIdComponent);
  }
}
 
// For EXT_feature_metadata
function loadPrimitiveFeaturesLegacy(
  loader,
  primitive,
  metadataExtension,
  frameState,
) {
  // For looking up the featureCount for each set of feature IDs
  const { featureTables } = loader.gltfJson.extensions.EXT_feature_metadata;
 
  let nextFeatureIdIndex = 0;
 
  // Feature ID Attributes
  const featureIdAttributes = metadataExtension.featureIdAttributes;
  if (defined(featureIdAttributes)) {
    for (let i = 0; i < featureIdAttributes.length; ++i) {
      const featureIdAttribute = featureIdAttributes[i];
      const featureTableId = featureIdAttribute.featureTable;
      const propertyTableId =
        loader._sortedPropertyTableIds.indexOf(featureTableId);
      const featureCount = featureTables[featureTableId].count;
      const label = `featureId_${nextFeatureIdIndex}`;
      nextFeatureIdIndex++;
 
      let featureIdComponent;
      if (defined(featureIdAttribute.featureIds.attribute)) {
        featureIdComponent = loadFeatureIdAttributeLegacy(
          featureIdAttribute,
          propertyTableId,
          featureCount,
          label,
        );
      } else {
        featureIdComponent = loadFeatureIdImplicitRangeLegacy(
          featureIdAttribute,
          propertyTableId,
          featureCount,
          label,
        );
      }
      primitive.featureIds.push(featureIdComponent);
    }
  }
 
  // Feature ID Textures
  const featureIdTextures = metadataExtension.featureIdTextures;
  if (defined(featureIdTextures)) {
    for (let i = 0; i < featureIdTextures.length; ++i) {
      const featureIdTexture = featureIdTextures[i];
      const featureTableId = featureIdTexture.featureTable;
      const propertyTableId =
        loader._sortedPropertyTableIds.indexOf(featureTableId);
      const featureCount = featureTables[featureTableId].count;
      const featureIdLabel = `featureId_${nextFeatureIdIndex}`;
      nextFeatureIdIndex++;
 
      const featureIdComponent = loadFeatureIdTextureLegacy(
        loader,
        featureIdTexture,
        propertyTableId,
        frameState,
        featureCount,
        featureIdLabel,
      );
      // Feature ID textures are added after feature ID attributes in the list
      primitive.featureIds.push(featureIdComponent);
    }
  }
}
 
// For primitive-level EXT_structural_metadata
function loadPrimitiveMetadata(primitive, structuralMetadataExtension) {
  Iif (!defined(structuralMetadataExtension)) {
    return;
  }
  const { propertyTextures, propertyAttributes } = structuralMetadataExtension;
 
  if (defined(propertyTextures)) {
    primitive.propertyTextureIds = propertyTextures;
  }
 
  if (defined(propertyAttributes)) {
    primitive.propertyAttributeIds = propertyAttributes;
  }
}
 
// For EXT_feature_metadata
function loadPrimitiveMetadataLegacy(loader, primitive, metadataExtension) {
  // Feature Textures
  if (defined(metadataExtension.featureTextures)) {
    // feature textures are now identified by an integer index. To convert the
    // string IDs to integers, find their place in the sorted list of feature
    // table names
    primitive.propertyTextureIds = metadataExtension.featureTextures.map(
      function (id) {
        return loader._sortedFeatureTextureIds.indexOf(id);
      },
    );
  }
}
 
function loadInstances(loader, nodeExtensions, frameState) {
  const instancingExtension = nodeExtensions.EXT_mesh_gpu_instancing;
 
  const instances = new Instances();
  const attributes = instancingExtension.attributes;
  Eif (defined(attributes)) {
    for (const semantic in attributes) {
      Iif (!attributes.hasOwnProperty(semantic)) {
        continue;
      }
      const accessorId = attributes[semantic];
      instances.attributes.push(
        loadInstancedAttribute(
          loader,
          accessorId,
          attributes,
          semantic,
          frameState,
        ),
      );
    }
  }
 
  const instancingExtExtensions =
    instancingExtension.extensions ?? Frozen.EMPTY_OBJECT;
  const instanceFeatures = nodeExtensions.EXT_instance_features;
  const featureMetadataLegacy = instancingExtExtensions.EXT_feature_metadata;
 
  if (defined(instanceFeatures)) {
    loadInstanceFeatures(instances, instanceFeatures);
  } else if (defined(featureMetadataLegacy)) {
    loadInstanceFeaturesLegacy(
      loader.gltfJson,
      instances,
      featureMetadataLegacy,
      loader._sortedPropertyTableIds,
    );
  }
 
  return instances;
}
 
// For EXT_mesh_features
function loadInstanceFeatures(instances, instanceFeaturesExtension) {
  // feature IDs are required in EXT_instance_features
  const featureIdsArray = instanceFeaturesExtension.featureIds;
 
  for (let i = 0; i < featureIdsArray.length; i++) {
    const featureIds = featureIdsArray[i];
    const label = `instanceFeatureId_${i}`;
 
    let featureIdComponent;
    if (defined(featureIds.attribute)) {
      featureIdComponent = loadFeatureIdAttribute(featureIds, label);
    } else {
      // in EXT_instance_features, the default is to assign IDs by instance
      // ID. This can be expressed with offset: 0, repeat: 1
      featureIdComponent = loadDefaultFeatureIds(featureIds, label);
    }
 
    instances.featureIds.push(featureIdComponent);
  }
}
 
// For backwards-compatibility with EXT_feature_metadata
function loadInstanceFeaturesLegacy(
  gltf,
  instances,
  metadataExtension,
  sortedPropertyTableIds,
) {
  // For looking up the featureCount for each set of feature IDs
  const featureTables = gltf.extensions.EXT_feature_metadata.featureTables;
 
  const featureIdAttributes = metadataExtension.featureIdAttributes;
  Eif (defined(featureIdAttributes)) {
    for (let i = 0; i < featureIdAttributes.length; ++i) {
      const featureIdAttribute = featureIdAttributes[i];
      const featureTableId = featureIdAttribute.featureTable;
      const propertyTableId = sortedPropertyTableIds.indexOf(featureTableId);
      const featureCount = featureTables[featureTableId].count;
      const label = `instanceFeatureId_${i}`;
 
      let featureIdComponent;
      if (defined(featureIdAttribute.featureIds.attribute)) {
        featureIdComponent = loadFeatureIdAttributeLegacy(
          featureIdAttribute,
          propertyTableId,
          featureCount,
          label,
        );
      } else {
        featureIdComponent = loadFeatureIdImplicitRangeLegacy(
          featureIdAttribute,
          propertyTableId,
          featureCount,
          label,
        );
      }
      instances.featureIds.push(featureIdComponent);
    }
  }
}
 
/**
 * Load resources associated with one node from a glTF JSON
 * @param {GltfLoader} loader
 * @param {object} gltfNode An entry from the <code>.nodes</code> array in the glTF JSON
 * @param {FrameState} frameState
 * @returns {ModelComponents.Node}
 * @private
 */
function loadNode(loader, gltfNode, frameState) {
  const node = new Node();
 
  node.name = gltfNode.name;
 
  node.matrix = fromArray(Matrix4, gltfNode.matrix);
  node.translation = fromArray(Cartesian3, gltfNode.translation);
  node.rotation = fromArray(Quaternion, gltfNode.rotation);
  node.scale = fromArray(Cartesian3, gltfNode.scale);
 
  const nodeExtensions = gltfNode.extensions ?? Frozen.EMPTY_OBJECT;
  const instancingExtension = nodeExtensions.EXT_mesh_gpu_instancing;
  const articulationsExtension = nodeExtensions.AGI_articulations;
 
  if (defined(instancingExtension)) {
    if (loader._loadForClassification) {
      throw new RuntimeError(
        "Models with the EXT_mesh_gpu_instancing extension cannot be used for classification.",
      );
    }
    node.instances = loadInstances(loader, nodeExtensions, frameState);
  }
 
  if (defined(articulationsExtension)) {
    node.articulationName = articulationsExtension.articulationName;
  }
 
  const meshId = gltfNode.mesh;
  if (defined(meshId)) {
    const mesh = loader.gltfJson.meshes[meshId];
    const primitives = getMeshPrimitives(mesh);
    for (let i = 0; i < primitives.length; ++i) {
      node.primitives.push(
        loadPrimitive(
          loader,
          primitives[i],
          defined(node.instances),
          frameState,
        ),
      );
    }
 
    // If the node has no weights array, it will look for the weights array provided
    // by the mesh. If both are undefined, it will default to an array of zero weights.
    const morphWeights = gltfNode.weights ?? mesh.weights;
    const targets = node.primitives[0].morphTargets;
 
    // Since meshes are not stored as separate components, the mesh weights will still
    // be stored at the node level.
    node.morphWeights = defined(morphWeights)
      ? morphWeights.slice()
      : new Array(targets.length).fill(0.0);
  }
 
  return node;
}
 
/**
 * Load resources associated with the nodes in a glTF JSON
 * @param {GltfLoader} loader
 * @param {FrameState} frameState
 * @returns {ModelComponents.Node[]}
 * @private
 */
function loadNodes(loader, frameState) {
  const nodeJsons = loader.gltfJson.nodes;
  Iif (!defined(nodeJsons)) {
    return [];
  }
 
  const loadedNodes = nodeJsons.map(function (nodeJson, i) {
    const node = loadNode(loader, nodeJson, frameState);
    node.index = i;
    return node;
  });
 
  for (let i = 0; i < loadedNodes.length; ++i) {
    const childrenNodeIds = nodeJsons[i].children;
    if (defined(childrenNodeIds)) {
      for (let j = 0; j < childrenNodeIds.length; ++j) {
        loadedNodes[i].children.push(loadedNodes[childrenNodeIds[j]]);
      }
    }
  }
 
  return loadedNodes;
}
 
function loadSkin(loader, gltfSkin, nodes) {
  const skin = new Skin();
 
  const jointIds = gltfSkin.joints;
  skin.joints = jointIds.map((jointId) => nodes[jointId]);
 
  const inverseBindMatricesAccessorId = gltfSkin.inverseBindMatrices;
  if (defined(inverseBindMatricesAccessorId)) {
    const accessor = loader.gltfJson.accessors[inverseBindMatricesAccessorId];
    skin.inverseBindMatrices = loadAccessor(loader, accessor);
  } else {
    skin.inverseBindMatrices = new Array(jointIds.length).fill(
      Matrix4.IDENTITY,
    );
  }
 
  return skin;
}
 
function loadSkins(loader, nodes) {
  const skinJsons = loader.gltfJson.skins;
 
  // Skins are disabled for classification models.
  if (loader._loadForClassification || !defined(skinJsons)) {
    return [];
  }
 
  const loadedSkins = skinJsons.map(function (skinJson, i) {
    const skin = loadSkin(loader, skinJson, nodes);
    skin.index = i;
    return skin;
  });
 
  const nodeJsons = loader.gltfJson.nodes;
  for (let i = 0; i < nodes.length; ++i) {
    const skinId = nodeJsons[i].skin;
    if (defined(skinId)) {
      nodes[i].skin = loadedSkins[skinId];
    }
  }
 
  return loadedSkins;
}
 
async function loadStructuralMetadata(
  loader,
  extension,
  extensionLegacy,
  frameState,
) {
  const structuralMetadataLoader = new GltfStructuralMetadataLoader({
    gltf: loader.gltfJson,
    extension: extension,
    extensionLegacy: extensionLegacy,
    gltfResource: loader._gltfResource,
    baseResource: loader._baseResource,
    supportedImageFormats: loader._supportedImageFormats,
    frameState: frameState,
    asynchronous: loader._asynchronous,
  });
  loader._structuralMetadataLoader = structuralMetadataLoader;
  return structuralMetadataLoader.load();
}
 
async function loadMeshPrimitiveGpm(loader, gltf, extension, frameState) {
  const meshPrimitiveGpmLoader = new GltfMeshPrimitiveGpmLoader({
    gltf: gltf,
    extension: extension,
    gltfResource: loader._gltfResource,
    baseResource: loader._baseResource,
    supportedImageFormats: loader._supportedImageFormats,
    frameState: frameState,
    asynchronous: loader._asynchronous,
  });
  loader._meshPrimitiveGpmLoader = meshPrimitiveGpmLoader;
  return meshPrimitiveGpmLoader.load();
}
 
function loadAnimationSampler(loader, gltfSampler) {
  const animationSampler = new AnimationSampler();
  const accessors = loader.gltfJson.accessors;
 
  const inputAccessor = accessors[gltfSampler.input];
  animationSampler.input = loadAccessor(loader, inputAccessor);
 
  const gltfInterpolation = gltfSampler.interpolation;
  animationSampler.interpolation =
    InterpolationType[gltfInterpolation] ?? InterpolationType.LINEAR;
 
  const outputAccessor = accessors[gltfSampler.output];
  animationSampler.output = loadAccessor(loader, outputAccessor, true);
 
  return animationSampler;
}
 
function loadAnimationTarget(gltfTarget, nodes) {
  const animationTarget = new AnimationTarget();
 
  const nodeIndex = gltfTarget.node;
  // If the node isn't defined, the animation channel should be ignored.
  // It's easiest to signal this by returning undefined.
  Iif (!defined(nodeIndex)) {
    return undefined;
  }
 
  animationTarget.node = nodes[nodeIndex];
 
  const path = gltfTarget.path.toUpperCase();
  animationTarget.path = AnimatedPropertyType[path];
 
  return animationTarget;
}
 
function loadAnimationChannel(gltfChannel, samplers, nodes) {
  const animationChannel = new AnimationChannel();
 
  const samplerIndex = gltfChannel.sampler;
  animationChannel.sampler = samplers[samplerIndex];
  animationChannel.target = loadAnimationTarget(gltfChannel.target, nodes);
 
  return animationChannel;
}
 
function loadAnimation(loader, animationJson, nodes) {
  const animation = new Animation();
  animation.name = animationJson.name;
 
  const samplers = animationJson.samplers.map(function (samplerJson, i) {
    const sampler = loadAnimationSampler(loader, samplerJson);
    sampler.index = i;
    return sampler;
  });
 
  const channels = animationJson.channels.map(function (channelJson) {
    return loadAnimationChannel(channelJson, samplers, nodes);
  });
 
  animation.samplers = samplers;
  animation.channels = channels;
 
  return animation;
}
 
function loadAnimations(loader, nodes) {
  const animationJsons = loader.gltfJson.animations;
 
  // Animations are disabled for classification models.
  if (loader._loadForClassification || !defined(animationJsons)) {
    return [];
  }
 
  const animations = animationJsons.map(function (animationJson, i) {
    const animation = loadAnimation(loader, animationJson, nodes);
    animation.index = i;
    return animation;
  });
 
  return animations;
}
 
function loadArticulationStage(gltfStage) {
  const stage = new ArticulationStage();
  stage.name = gltfStage.name;
 
  const type = gltfStage.type.toUpperCase();
  stage.type = ArticulationStageType[type];
 
  stage.minimumValue = gltfStage.minimumValue;
  stage.maximumValue = gltfStage.maximumValue;
  stage.initialValue = gltfStage.initialValue;
 
  return stage;
}
 
function loadArticulation(articulationJson) {
  const articulation = new Articulation();
  articulation.name = articulationJson.name;
  articulation.stages = articulationJson.stages.map(loadArticulationStage);
  return articulation;
}
 
function loadArticulations(gltf) {
  const extensions = gltf.extensions ?? Frozen.EMPTY_OBJECT;
  const articulationJsons = extensions.AGI_articulations?.articulations;
  if (!defined(articulationJsons)) {
    return [];
  }
  return articulationJsons.map(loadArticulation);
}
 
function getSceneNodeIds(gltf) {
  let nodesIds;
  Eif (defined(gltf.scenes) && defined(gltf.scene)) {
    nodesIds = gltf.scenes[gltf.scene].nodes;
  }
  nodesIds = nodesIds ?? gltf.nodes;
  nodesIds = defined(nodesIds) ? nodesIds : [];
  return nodesIds;
}
 
function loadScene(gltf, nodes) {
  const scene = new Scene();
  const sceneNodeIds = getSceneNodeIds(gltf);
  scene.nodes = sceneNodeIds.map(function (sceneNodeId) {
    return nodes[sceneNodeId];
  });
  return scene;
}
 
const scratchCenter = new Cartesian3();
 
/**
 * Parse the glTF which populates the loaders arrays. Loading promises will be created, and will
 * resolve once the loaders are ready (i.e. all external resources
 * have been fetched and all GPU resources have been created). Loaders that
 * create GPU resources need to be processed every frame until they become
 * ready since the JobScheduler is not able to execute all jobs in a single
 * frame. Any promise failures are collected, and will be handled synchronously in process().
 * Also note that it's fine to call process before a loader is ready to process or
 * after it has failed; nothing will happen.
 *
 * @param {GltfLoader} loader
 * @param {FrameState} frameState
 * @returns {Promise} A Promise that resolves when all loaders are ready
 * @private
 */
function parse(loader, frameState) {
  const gltf = loader.gltfJson;
  const extensions = gltf.extensions ?? Frozen.EMPTY_OBJECT;
  const structuralMetadataExtension = extensions.EXT_structural_metadata;
  const featureMetadataExtensionLegacy = extensions.EXT_feature_metadata;
  const cesiumRtcExtension = extensions.CESIUM_RTC;
 
  if (defined(featureMetadataExtensionLegacy)) {
    // If the old EXT_feature_metadata extension is present, sort the IDs of the
    // feature tables and feature textures so we don't have to do this once
    // per primitive.
    //
    // This must run before loadNodes so these IDs are available when
    // attributes are processed.
    const featureTables = featureMetadataExtensionLegacy.featureTables;
    const featureTextures = featureMetadataExtensionLegacy.featureTextures;
    const allPropertyTableIds = defined(featureTables) ? featureTables : [];
    const allFeatureTextureIds = defined(featureTextures)
      ? featureTextures
      : [];
    loader._sortedPropertyTableIds = Object.keys(allPropertyTableIds).sort();
    loader._sortedFeatureTextureIds = Object.keys(allFeatureTextureIds).sort();
  }
 
  const nodes = loadNodes(loader, frameState);
  const skins = loadSkins(loader, nodes);
  const animations = loadAnimations(loader, nodes);
  const articulations = loadArticulations(gltf);
  const scene = loadScene(gltf, nodes);
 
  const components = new Components();
  const asset = new Asset();
  const copyright = gltf.asset.copyright;
  if (defined(copyright)) {
    const credits = copyright.split(";").map(function (string) {
      return new Credit(string.trim());
    });
    asset.credits = credits;
  }
 
  components.asset = asset;
  components.scene = scene;
  components.nodes = nodes;
  components.skins = skins;
  components.animations = animations;
  components.articulations = articulations;
  components.upAxis = loader._upAxis;
  components.forwardAxis = loader._forwardAxis;
 
  if (defined(cesiumRtcExtension)) {
    // CESIUM_RTC is almost always WGS84 coordinates so no axis conversion needed
    const center = Cartesian3.fromArray(
      cesiumRtcExtension.center,
      0,
      scratchCenter,
    );
    components.transform = Matrix4.fromTranslation(
      center,
      components.transform,
    );
  }
 
  loader._components = components;
 
  // Load structural metadata (property tables and property textures)
  if (
    defined(structuralMetadataExtension) ||
    defined(featureMetadataExtensionLegacy)
  ) {
    const promise = loadStructuralMetadata(
      loader,
      structuralMetadataExtension,
      featureMetadataExtensionLegacy,
      frameState,
    );
    loader._loaderPromises.push(promise);
  }
 
  // Load NGA_gpm_local from root object
  const gpmExtension = extensions.NGA_gpm_local;
  Iif (defined(gpmExtension)) {
    const gltfGpmLocal = GltfGpmLoader.load(gpmExtension);
    loader._components.extensions["NGA_gpm_local"] = gltfGpmLocal;
  }
 
  // Load NGA_gpm_local from mesh primitives
  const meshes = gltf.meshes;
  if (defined(meshes)) {
    for (const mesh of meshes) {
      const primitives = mesh.primitives;
      Eif (defined(primitives)) {
        for (const primitive of primitives) {
          const primitiveExtensions = primitive.extensions;
          if (defined(primitiveExtensions)) {
            const meshPrimitiveGpmExtension = primitiveExtensions.NGA_gpm_local;
            Iif (defined(meshPrimitiveGpmExtension)) {
              const promise = loadMeshPrimitiveGpm(
                loader,
                gltf,
                meshPrimitiveGpmExtension,
                frameState,
              );
              loader._loaderPromises.push(promise);
            }
          }
        }
      }
    }
  }
 
  // Gather promises and handle any errors
  const readyPromises = [];
  addAllToArray(readyPromises, loader._loaderPromises);
 
  // When incrementallyLoadTextures is true, the errors are caught and thrown individually
  // since it doesn't affect the overall loader state
  if (!loader._incrementallyLoadTextures) {
    addAllToArray(readyPromises, loader._texturesPromises);
  }
 
  return Promise.all(readyPromises);
}
 
function unloadTextures(loader) {
  const textureLoaders = loader._textureLoaders;
  for (let i = 0; i < textureLoaders.length; ++i) {
    textureLoaders[i] =
      !textureLoaders[i].isDestroyed() &&
      ResourceCache.unload(textureLoaders[i]);
  }
  loader._textureLoaders.length = 0;
}
 
function unloadBufferViewLoaders(loader) {
  const bufferViewLoaders = loader._bufferViewLoaders;
  for (let i = 0; i < bufferViewLoaders.length; ++i) {
    bufferViewLoaders[i] =
      !bufferViewLoaders[i].isDestroyed() &&
      ResourceCache.unload(bufferViewLoaders[i]);
  }
  loader._bufferViewLoaders.length = 0;
}
 
function unloadGeometry(loader) {
  const geometryLoaders = loader._geometryLoaders;
  for (let i = 0; i < geometryLoaders.length; ++i) {
    geometryLoaders[i] =
      !geometryLoaders[i].isDestroyed() &&
      ResourceCache.unload(geometryLoaders[i]);
  }
  loader._geometryLoaders.length = 0;
}
 
function unloadGeneratedAttributes(loader) {
  const buffers = loader._postProcessBuffers;
  for (let i = 0; i < buffers.length; i++) {
    const buffer = buffers[i];
    Eif (!buffer.isDestroyed()) {
      buffer.destroy();
    }
  }
  buffers.length = 0;
}
 
function unloadStructuralMetadata(loader) {
  if (
    defined(loader._structuralMetadataLoader) &&
    !loader._structuralMetadataLoader.isDestroyed()
  ) {
    loader._structuralMetadataLoader.destroy();
    loader._structuralMetadataLoader = undefined;
  }
}
 
function unloadMeshPrimitiveGpm(loader) {
  Iif (
    defined(loader._meshPrimitiveGpmLoader) &&
    !loader._meshPrimitiveGpmLoader.isDestroyed()
  ) {
    loader._meshPrimitiveGpmLoader.destroy();
    loader._meshPrimitiveGpmLoader = undefined;
  }
}
 
/**
 * Returns whether the resource has been unloaded.
 * @private
 */
GltfLoader.prototype.isUnloaded = function () {
  return this._state === GltfLoaderState.UNLOADED;
};
 
/**
 * Unloads the resource.
 * @private
 */
GltfLoader.prototype.unload = function () {
  if (defined(this._gltfJsonLoader) && !this._gltfJsonLoader.isDestroyed()) {
    ResourceCache.unload(this._gltfJsonLoader);
  }
  this._gltfJsonLoader = undefined;
 
  unloadTextures(this);
  unloadBufferViewLoaders(this);
  unloadGeometry(this);
  unloadGeneratedAttributes(this);
  unloadStructuralMetadata(this);
  unloadMeshPrimitiveGpm(this);
 
  this._components = undefined;
  this._typedArray = undefined;
  this._state = GltfLoaderState.UNLOADED;
};
 
export default GltfLoader;