All files / engine/Source/DataSources KmlDataSource.js

93.96% Statements 1620/1724
81.93% Branches 789/963
94.65% Functions 124/131
93.91% Lines 1591/1694

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 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250                                                                                                                                                                1x                                                                                                               17x 17x 17x         1x 1x     1x           3x       1x   1x 1x 1x 1x   1x               1x 1x 1x               1x                       220x 220x 220x 220x 220x 220x   220x 220x     1x     86x         1x 84x         84x     1x 19x     1x   220x 220x 145x     220x     1x 84x 84x 75x     84x     1x 2x         2x 2x 2x 2x 2x 2x 2x       1x 408x 408x 408x 408x 408x 84x   324x   324x     1x 84x 84x     84x 75x 75x     9x     1x 86x 86x   86x 86x 324x 324x         88x     88x       2x 2x       322x         84x           41x 41x 41x 41x 41x       41x     41x 41x       29x 29x 29x 29x   29x     29x 29x       39x         39x 39x 39x 39x 39x 2x 2x 2x   2x         39x 2x     39x       39x 39x     39x 9x 9x 9x 9x 3x 3x 3x   6x       39x       10x 10x 10x 10x         17x 17x 17x       91x 91x 91x 91x 15x 15x 15x 14x 14x 14x 14x 12x 12x 12x 6x               546x 546x 62x 62x 62x 62x 61x               229x 229x 229x 25x         229x 229x 1x 1x         229x 229x 229x 229x   229x       65x                 244x 1x     243x 243x 1x     242x 242x 242x   242x 242x 242x   242x       60x 24x     36x 36x 1x     35x 35x 35x 35x 163x   35x       154x 106x     48x 48x 48x 48x           1857x 1462x   395x 395x       6584x 1185x   5399x 5399x 5399x 20509x 20509x       807x     4592x       444x     444x 444x 444x 444x 96x 96x       96x     444x       77x     77x 77x 77x 77x 602x 602x       97x     77x       580x 580x 105x 105x   475x       3246x 3246x 369x   2877x       407x 407x 71x 71x   336x       136x 1x       135x   11x 11x 11x 9x         2x 2x 2x 2x 1x             135x 125x         135x     1x                   59x 3x     56x       56x 56x 56x 56x   56x 51x     5x 3x 3x   2x 2x   5x 3x 3x   2x 2x   5x 3x 3x   2x 2x   5x 5x       144x 144x 89x   55x             217x 217x   217x 213x               4x 4x 4x           4x       227x 227x 216x       11x 11x       11x 11x       11x 8x 1x 1x 1x   8x 8x           3x 1x 1x           2x 1x 1x               11x       138x 138x 138x 138x           138x           138x       38x 38x 38x 38x       137x 137x 137x 137x 137x 137x 137x                   88x 88x 34x     54x 1x     1x 1x 1x 1x 1x   1x     54x   54x 6x         6x         6x 1x       5x 1x             6x   6x       6x   6x 6x 6x   6x       6x 6x                 6x     48x                   65x 65x 65x   65x 65x                 65x 1x     65x 65x 65x 65x   65x 65x 65x 65x 65x   65x 65x 65x 65x     65x 65x 65x   65x 1x         65x 11x 11x             65x       65x 12x 10x 2x 1x 1x 1x   12x     65x 12x 10x 2x 1x 1x 1x     12x     65x 12x                     86x 314x 314x 65x             249x 13x 13x 13x 13x   13x   13x   13x 236x 17x 17x 17x 17x   17x 17x 17x 1x         17x 1x         17x 1x         17x 1x         219x 16x 16x 16x 16x   16x   16x   16x   203x   2x     2x   2x       2x 2x         201x 1x         1x 1x                                 227x       227x 227x 227x 227x 913x 913x 73x       227x 73x 73x 71x                 2x 2x 3x 3x 3x 2x 2x                 2x 2x     1x                   227x 227x 13x 13x 2x 2x 2x       2x     13x 13x 1x   13x 13x       227x         2x 2x                                         222x 222x 222x 222x 87x 87x 87x 12x 12x 2x   12x 12x     12x 12x                       222x 222x 222x 222x 9x 9x 9x 7x 7x 7x 7x 7x 7x 7x 2x   7x 7x   7x 7x 6x 1x     6x 2x   6x   6x 6x     1x 1x                                       222x 222x 222x 222x 15x 15x         4x 4x 2x 2x       2x             222x       9x     9x 9x     9x             57x       44x     13x 3x     10x 8x     2x 1x       1x     1x 1x       1x                                               10x           6x     4x                     4x                 12x 1x     11x                 11x                     11x 11x 68x 68x   11x                 134x 134x 131x     131x   134x   134x 134x 108x     108x     134x 95x         39x 1x     134x 134x 20x 20x 18x     2x 2x       134x 4x 4x         14x 14x 14x 14x 14x     14x 14x 4x 4x                     48x         48x         48x         48x 48x 48x   48x 48x             48x 4x     48x                   19x         19x         19x         19x 19x         19x 19x   19x 19x 19x 19x 5x 5x 5x 5x   5x 1x 1x       5x 5x 1x     1x 4x         14x 2x 2x 2x 2x 2x 2x     2x         2x   12x 1x         12x             12x 12x 12x           12x 8x       19x                   23x         23x         23x         23x 23x 23x 23x         23x         23x   23x       23x 23x 1x     1x   23x   23x 8x 8x 15x 15x     23x 12x 12x         12x 2x         2x 2x         2x 2x 2x       12x     23x                   9x         9x         9x 9x 9x 9x 9x 9x   9x 1x           9x 9x 9x 9x 19x 19x 19x   9x 9x 9x 9x           9x   9x   9x 9x               9x 3x     9x                           10x 10x   10x 10x   10x                         10x               10x                                           5x         5x         5x 5x 5x 5x 5x 5x 8x 8x 8x 8x         8x         8x 8x   8x   8x 8x 8x 14x 14x 14x     8x         4x 2x                       4x 4x     8x                     8x     5x 5x 5x 5x 5x 2x 2x     5x     1x                                     1x 1x 1x 9x 9x 9x 2x 2x 2x 2x 2x 2x 2x                 2x         1x                   1x       1x       227x   227x 221x     6x 1x   6x 1x           6x 6x 6x 6x 6x 7x 7x 7x 7x                     6x       1x 1x                           227x 227x 227x   227x   227x 227x 227x   227x 2x 2x 2x       227x 40x 40x 40x 40x 40x         40x   40x 1x 1x 1x 4x 4x 4x 4x   4x 4x 2x   4x 2x         187x   5x 5x 2x   2x 6x 6x 6x   2x       227x   185x       42x       42x 42x 42x 31x       42x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x       42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x   42x 42x 42x 42x 42x 42x 42x 42x     42x       227x 227x 227x 227x   227x         227x 227x               227x 227x 227x   227x 227x 217x   227x   227x       243x 227x   16x     227x         227x     227x 227x 227x 227x 227x   227x 227x 227x 227x 227x 227x 227x 227x   227x 227x         227x   227x 227x               227x 227x 227x   227x 1x     227x             84x 84x       15x 15x 15x 15x                 176x 176x 176x   176x 176x 176x 622x 622x 622x     104x               104x       176x 72x 72x       1x                 3x 3x 3x   3x 3x 3x 3x 3x 17x 17x   7x 7x 7x                   3x       3x       1x 1x       3x 3x   3x   3x 3x   3x   3x 3x       230x 230x 2x 2x   2x   2x 2x 2x   2x 2x   2x         230x 230x 2x 2x   2x 2x 2x 2x   2x 2x   2x         2x   2x                   8x 8x 1x     7x 7x   7x 7x               7x       7x 7x   7x 7x 4x   4x         4x         4x           4x 4x 4x 4x 4x   4x                   4x                       4x   4x 4x   4x 4x 4x 4x 4x   4x 4x 1x 3x 3x           4x 4x 1x 3x 3x             4x 4x 4x 4x 4x   4x 4x 2x     2x 2x         4x     4x 4x 2x     2x 1x 1x 1x     4x       4x     7x                 16x 16x     16x   16x 16x       16x 16x 3x 3x 3x 3x 3x   13x 13x 13x   13x         13x 3x 3x 3x 3x   3x 3x   3x 3x   3x 3x   3x 3x   3x   3x 3x 1x 1x 1x         16x 16x             16x 6x 1x         6x 6x 6x 6x   6x 1x           6x 6x         6x   10x     16x           16x 1x   1x         1x                 15x         15x                     15x         15x                             1x                 1x           1x             26x 16x     10x 10x 2x     10x     1x 1x 1x 1x                                                         27x     27x   27x       6x 6x 6x 6x 6x             6x           6x 6x     6x                           6x       6x       6x       6x         6x 6x 6x 6x 6x       6x       6x       6x 6x 6x         6x 6x       6x       6x         6x 6x 6x 6x 6x 6x 6x       6x 6x     6x 6x   21x 21x 21x 21x   21x 21x 21x 21x 21x 21x 21x 21x   21x 21x 21x 21x 21x     27x 7x 7x   20x 20x     27x 27x 27x 27x 27x   27x       20x 20x   20x 20x   20x   20x 1x   20x 20x     20x 20x 20x       20x   2x 1x         18x 18x         18x 1x       1x   17x     17x       17x   17x 17x 17x   17x 3x     17x 17x                   19x           19x 19x   11x 11x 11x 11x 15x 15x 11x 11x     15x   11x     11x           11x 11x         6x         6x   6x 6x                       6x 6x 4x             4x               6x 1x 1x   1x 1x 5x   3x 1x           3x 1x 1x 1x 1x     1x 1x               2x         2x   2x 2x                 6x 4x         8x 8x     19x           220x 220x 220x                                       220x   220x   220x     220x 220x 212x       220x 205x     220x 220x 220x                   220x 220x 36x 36x 90x 90x 36x 36x         220x                   220x 220x 220x   220x 220x                       12x 12x 12x         12x 12x   12x 12x   12x 33x 33x 27x       15x 10x       10x     5x     12x           12x 10x   12x 12x 12x 2x   10x   10x                     233x 233x 233x 233x 233x   233x 233x 43x 43x 43x     43x 43x 43x             190x     233x   233x 196x     233x   224x 41x 41x 12x               29x         29x     29x         29x 29x             29x           2x         2x         2x   27x                       183x                     13x 13x 13x                                                                                                                                           212x 212x 212x   212x 212x 212x 212x 212x   212x 212x 212x 212x 212x 212x 212x               212x                   212x   212x                     212x     212x 212x 199x   212x     212x   212x   212x                     1x 187x 187x 187x     1x                 5x     1x 1x 1x                         4x                   193x                   1x                   3x                   2x                   2x                   4x                   2x                   5x     2x                                                           1x                   6x                         1x   211x 1x       210x 210x   210x 210x 210x   210x 210x       205x   205x 205x 205x 205x 205x       25x 1x 1x 1x       25x 4x 4x 4x     25x 25x 25x 25x 25x 25x 25x               205x 205x 26x 26x     205x 203x     205x 204x     205x   205x     5x 5x 5x 5x             1x 6x 7x 7x         242x 242x 31x 31x 6x 6x 2x   4x                         4x 4x         4x 4x         4x   4x 4x 4x                     4x     4x               4x 4x 4x 1x 1x   3x   1x 1x           1x 1x 1x 1x 1x     1x                                 4x 4x 4x     8x 8x 8x 8x 4x         4x 4x   4x 12x 12x 4x 4x     4x     4x 4x 8x 8x 4x 4x   8x   4x     4x     4x     4x   4x 4x 4x 4x 4x                   4x 4x 4x             1x               1x 251x 251x       251x 251x   251x     12x 12x 12x 8x 8x 8x       251x 251x 251x 251x                             2x 2x 2x 2x 2x     251x 251x 251x 251x 251x       251x 251x 251x 248x       1x   3x 1x 1x   2x 2x 2x 2x     2x         2x       251x 4x 4x 4x 4x   4x 4x 4x                 4x                                 4x     251x     251x 4x 4x     251x                                         229x                                         229x                         229x         229x         229x             229x       1x 1x      
import ArcType from "../Core/ArcType.js";
import AssociativeArray from "../Core/AssociativeArray.js";
import BoundingRectangle from "../Core/BoundingRectangle.js";
import buildModuleUrl from "../Core/buildModuleUrl.js";
import Cartesian2 from "../Core/Cartesian2.js";
import Cartesian3 from "../Core/Cartesian3.js";
import Cartographic from "../Core/Cartographic.js";
import ClockRange from "../Core/ClockRange.js";
import ClockStep from "../Core/ClockStep.js";
import clone from "../Core/clone.js";
import Color from "../Core/Color.js";
import createGuid from "../Core/createGuid.js";
import Credit from "../Core/Credit.js";
import Frozen from "../Core/Frozen.js";
import defer from "../Core/defer.js";
import defined from "../Core/defined.js";
import DeveloperError from "../Core/DeveloperError.js";
import Ellipsoid from "../Core/Ellipsoid.js";
import Event from "../Core/Event.js";
import getExtensionFromUri from "../Core/getExtensionFromUri.js";
import getFilenameFromUri from "../Core/getFilenameFromUri.js";
import getTimestamp from "../Core/getTimestamp.js";
import HeadingPitchRange from "../Core/HeadingPitchRange.js";
import HeadingPitchRoll from "../Core/HeadingPitchRoll.js";
import Iso8601 from "../Core/Iso8601.js";
import JulianDate from "../Core/JulianDate.js";
import CesiumMath from "../Core/Math.js";
import NearFarScalar from "../Core/NearFarScalar.js";
import objectToQuery from "../Core/objectToQuery.js";
import oneTimeWarning from "../Core/oneTimeWarning.js";
import PinBuilder from "../Core/PinBuilder.js";
import PolygonHierarchy from "../Core/PolygonHierarchy.js";
import queryToObject from "../Core/queryToObject.js";
import Rectangle from "../Core/Rectangle.js";
import Resource from "../Core/Resource.js";
import RuntimeError from "../Core/RuntimeError.js";
import TimeInterval from "../Core/TimeInterval.js";
import TimeIntervalCollection from "../Core/TimeIntervalCollection.js";
import HeightReference from "../Scene/HeightReference.js";
import HorizontalOrigin from "../Scene/HorizontalOrigin.js";
import LabelStyle from "../Scene/LabelStyle.js";
import SceneMode from "../Scene/SceneMode.js";
import Autolinker from "autolinker";
import Uri from "urijs";
import {
  configure,
  BlobReader,
  Data64URIWriter,
  TextWriter,
  ZipReader,
} from "@zip.js/zip.js/lib/zip-core.js";
import getElement from "./getElement.js";
import BillboardGraphics from "./BillboardGraphics.js";
import CompositePositionProperty from "./CompositePositionProperty.js";
import DataSource from "./DataSource.js";
import DataSourceClock from "./DataSourceClock.js";
import Entity from "./Entity.js";
import EntityCluster from "./EntityCluster.js";
import EntityCollection from "./EntityCollection.js";
import KmlCamera from "./KmlCamera.js";
import KmlLookAt from "./KmlLookAt.js";
import KmlTour from "./KmlTour.js";
import KmlTourFlyTo from "./KmlTourFlyTo.js";
import KmlTourWait from "./KmlTourWait.js";
import LabelGraphics from "./LabelGraphics.js";
import PathGraphics from "./PathGraphics.js";
import PolygonGraphics from "./PolygonGraphics.js";
import PolylineGraphics from "./PolylineGraphics.js";
import PositionPropertyArray from "./PositionPropertyArray.js";
import RectangleGraphics from "./RectangleGraphics.js";
import ReferenceProperty from "./ReferenceProperty.js";
import SampledPositionProperty from "./SampledPositionProperty.js";
import ScaledPositionProperty from "./ScaledPositionProperty.js";
import TimeIntervalCollectionProperty from "./TimeIntervalCollectionProperty.js";
import WallGraphics from "./WallGraphics.js";
 
//This is by no means an exhaustive list of MIME types.
//The purpose of this list is to be able to accurately identify content embedded
//in KMZ files. Eventually, we can make this configurable by the end user so they can add
//there own content types if they have KMZ files that require it.
const MimeTypes = {
  avi: "video/x-msvideo",
  bmp: "image/bmp",
  bz2: "application/x-bzip2",
  chm: "application/vnd.ms-htmlhelp",
  css: "text/css",
  csv: "text/csv",
  doc: "application/msword",
  dvi: "application/x-dvi",
  eps: "application/postscript",
  flv: "video/x-flv",
  gif: "image/gif",
  gz: "application/x-gzip",
  htm: "text/html",
  html: "text/html",
  ico: "image/vnd.microsoft.icon",
  jnlp: "application/x-java-jnlp-file",
  jpeg: "image/jpeg",
  jpg: "image/jpeg",
  m3u: "audio/x-mpegurl",
  m4v: "video/mp4",
  mathml: "application/mathml+xml",
  mid: "audio/midi",
  midi: "audio/midi",
  mov: "video/quicktime",
  mp3: "audio/mpeg",
  mp4: "video/mp4",
  mp4v: "video/mp4",
  mpeg: "video/mpeg",
  mpg: "video/mpeg",
  odp: "application/vnd.oasis.opendocument.presentation",
  ods: "application/vnd.oasis.opendocument.spreadsheet",
  odt: "application/vnd.oasis.opendocument.text",
  ogg: "application/ogg",
  pdf: "application/pdf",
  png: "image/png",
  pps: "application/vnd.ms-powerpoint",
  ppt: "application/vnd.ms-powerpoint",
  ps: "application/postscript",
  qt: "video/quicktime",
  rdf: "application/rdf+xml",
  rss: "application/rss+xml",
  rtf: "application/rtf",
  svg: "image/svg+xml",
  swf: "application/x-shockwave-flash",
  text: "text/plain",
  tif: "image/tiff",
  tiff: "image/tiff",
  txt: "text/plain",
  wav: "audio/x-wav",
  wma: "audio/x-ms-wma",
  wmv: "video/x-ms-wmv",
  xml: "application/xml",
  zip: "application/zip",
 
  detectFromFilename: function (filename) {
    let ext = filename.toLowerCase();
    ext = getExtensionFromUri(ext);
    return MimeTypes[ext];
  },
};
 
let parser;
Eif (typeof DOMParser !== "undefined") {
  parser = new DOMParser();
}
 
const autolinker = new Autolinker({
  stripPrefix: false,
  email: false,
  replaceFn: function (match) {
    //Prevent matching of non-explicit urls.
    //i.e. foo.id won't match but http://foo.id will
    return match.urlMatchType === "scheme" || match.urlMatchType === "www";
  },
});
 
const BILLBOARD_SIZE = 32;
 
const BILLBOARD_NEAR_DISTANCE = 2414016;
const BILLBOARD_NEAR_RATIO = 1.0;
const BILLBOARD_FAR_DISTANCE = 1.6093e7;
const BILLBOARD_FAR_RATIO = 0.1;
 
const kmlNamespaces = [
  null,
  undefined,
  "http://www.opengis.net/kml/2.2",
  "http://earth.google.com/kml/2.2",
  "http://earth.google.com/kml/2.1",
  "http://earth.google.com/kml/2.0",
];
const gxNamespaces = ["http://www.google.com/kml/ext/2.2"];
const atomNamespaces = ["http://www.w3.org/2005/Atom"];
const namespaces = {
  kml: kmlNamespaces,
  gx: gxNamespaces,
  atom: atomNamespaces,
  kmlgx: kmlNamespaces.concat(gxNamespaces),
};
 
// Ensure Specs/Data/KML/unsupported.kml is kept up to date with these supported types
const featureTypes = {
  Document: processDocument,
  Folder: processFolder,
  Placemark: processPlacemark,
  NetworkLink: processNetworkLink,
  GroundOverlay: processGroundOverlay,
  PhotoOverlay: processUnsupportedFeature,
  ScreenOverlay: processScreenOverlay,
  Tour: processTour,
};
 
function DeferredLoading(dataSource) {
  this._dataSource = dataSource;
  this._deferred = defer();
  this._stack = [];
  this._promises = [];
  this._timeoutSet = false;
  this._used = false;
 
  this._started = 0;
  this._timeThreshold = 1000; // Initial load is 1 second
}
 
Object.defineProperties(DeferredLoading.prototype, {
  dataSource: {
    get: function () {
      return this._dataSource;
    },
  },
});
 
DeferredLoading.prototype.addNodes = function (nodes, processingData) {
  this._stack.push({
    nodes: nodes,
    index: 0,
    processingData: processingData,
  });
  this._used = true;
};
 
DeferredLoading.prototype.addPromise = function (promise) {
  this._promises.push(promise);
};
 
DeferredLoading.prototype.wait = function () {
  // Case where we had a non-document/folder as the root
  const deferred = this._deferred;
  if (!this._used) {
    deferred.resolve();
  }
 
  return Promise.all([deferred.promise, Promise.all(this._promises)]);
};
 
DeferredLoading.prototype.process = function () {
  const isFirstCall = this._stack.length === 1;
  if (isFirstCall) {
    this._started = KmlDataSource._getTimestamp();
  }
 
  return this._process(isFirstCall);
};
 
DeferredLoading.prototype._giveUpTime = function () {
  Iif (this._timeoutSet) {
    // Timeout was already set so just return
    return;
  }
 
  this._timeoutSet = true;
  this._timeThreshold = 50; // After the first load lower threshold to 0.5 seconds
  const that = this;
  setTimeout(function () {
    that._timeoutSet = false;
    that._started = KmlDataSource._getTimestamp();
    that._process(true);
  }, 0);
};
 
DeferredLoading.prototype._nextNode = function () {
  const stack = this._stack;
  const top = stack[stack.length - 1];
  const index = top.index;
  const nodes = top.nodes;
  if (index === nodes.length) {
    return;
  }
  ++top.index;
 
  return nodes[index];
};
 
DeferredLoading.prototype._pop = function () {
  const stack = this._stack;
  stack.pop();
 
  // Return false if we are done
  if (stack.length === 0) {
    this._deferred.resolve();
    return false;
  }
 
  return true;
};
 
DeferredLoading.prototype._process = function (isFirstCall) {
  const dataSource = this.dataSource;
  const processingData = this._stack[this._stack.length - 1].processingData;
 
  let child = this._nextNode();
  while (defined(child)) {
    const featureProcessor = featureTypes[child.localName];
    if (
      defined(featureProcessor) &&
      (namespaces.kml.indexOf(child.namespaceURI) !== -1 ||
        namespaces.gx.indexOf(child.namespaceURI) !== -1)
    ) {
      featureProcessor(dataSource, child, processingData, this);
 
      // Give up time and continue loading later
      if (
        this._timeoutSet ||
        KmlDataSource._getTimestamp() > this._started + this._timeThreshold
      ) {
        this._giveUpTime();
        return;
      }
    }
 
    child = this._nextNode();
  }
 
  // If we are a recursive call from a subfolder, just return so the parent folder can continue processing
  // If we aren't then make another call to processNodes because there is stuff still left in the queue
  Iif (this._pop() && isFirstCall) {
    this._process(true);
  }
};
 
function isZipFile(blob) {
  const magicBlob = blob.slice(0, Math.min(4, blob.size));
  const deferred = defer();
  const reader = new FileReader();
  reader.addEventListener("load", function () {
    deferred.resolve(
      new DataView(reader.result).getUint32(0, false) === 0x504b0304,
    );
  });
  reader.addEventListener("error", function () {
    deferred.reject(reader.error);
  });
  reader.readAsArrayBuffer(magicBlob);
  return deferred.promise;
}
 
function readBlobAsText(blob) {
  const deferred = defer();
  const reader = new FileReader();
  reader.addEventListener("load", function () {
    deferred.resolve(reader.result);
  });
  reader.addEventListener("error", function () {
    deferred.reject(reader.error);
  });
  reader.readAsText(blob);
  return deferred.promise;
}
 
function insertNamespaces(text) {
  const namespaceMap = {
    xsi: "http://www.w3.org/2001/XMLSchema-instance",
  };
  let firstPart, lastPart, reg, declaration;
 
  for (const key in namespaceMap) {
    Eif (namespaceMap.hasOwnProperty(key)) {
      reg = RegExp(`[< ]${key}:`);
      declaration = `xmlns:${key}=`;
      if (reg.test(text) && text.indexOf(declaration) === -1) {
        Eif (!defined(firstPart)) {
          firstPart = text.substr(0, text.indexOf("<kml") + 4);
          lastPart = text.substr(firstPart.length);
        }
        firstPart += ` ${declaration}"${namespaceMap[key]}"`;
      }
    }
  }
 
  if (defined(firstPart)) {
    text = firstPart + lastPart;
  }
 
  return text;
}
 
function removeDuplicateNamespaces(text) {
  let index = text.indexOf("xmlns:");
  const endDeclaration = text.indexOf(">", index);
  let namespace, startIndex, endIndex;
 
  while (index !== -1 && index < endDeclaration) {
    namespace = text.slice(index, text.indexOf('"', index));
    startIndex = index;
    index = text.indexOf(namespace, index + 1);
    if (index !== -1) {
      endIndex = text.indexOf('"', text.indexOf('"', index) + 1);
      text = text.slice(0, index - 1) + text.slice(endIndex + 1, text.length);
      index = text.indexOf("xmlns:", startIndex - 1);
    } else {
      index = text.indexOf("xmlns:", startIndex + 1);
    }
  }
 
  return text;
}
 
async function loadXmlFromZip(entry, uriResolver) {
  let text = await entry.getData(new TextWriter());
  text = insertNamespaces(text);
  text = removeDuplicateNamespaces(text);
  uriResolver.kml = parser.parseFromString(text, "application/xml");
}
 
async function loadDataUriFromZip(entry, uriResolver) {
  const mimeType =
    MimeTypes.detectFromFilename(entry.filename) ?? "application/octet-stream";
  const dataUri = await entry.getData(new Data64URIWriter(mimeType));
  uriResolver[entry.filename] = dataUri;
}
 
function embedDataUris(div, elementType, attributeName, uriResolver) {
  const keys = uriResolver.keys;
  const baseUri = new Uri(".");
  const elements = div.querySelectorAll(elementType);
  for (let i = 0; i < elements.length; i++) {
    const element = elements[i];
    const value = element.getAttribute(attributeName);
    if (defined(value)) {
      const relativeUri = new Uri(value);
      const uri = relativeUri.absoluteTo(baseUri).toString();
      const index = keys.indexOf(uri);
      if (index !== -1) {
        const key = keys[index];
        element.setAttribute(attributeName, uriResolver[key]);
        if (elementType === "a" && element.getAttribute("download") === null) {
          element.setAttribute("download", key);
        }
      }
    }
  }
}
 
function applyBasePath(div, elementType, attributeName, sourceResource) {
  const elements = div.querySelectorAll(elementType);
  for (let i = 0; i < elements.length; i++) {
    const element = elements[i];
    const value = element.getAttribute(attributeName);
    const resource = resolveHref(value, sourceResource);
    if (defined(resource)) {
      element.setAttribute(attributeName, resource.url);
    }
  }
}
 
// an optional context is passed to allow for some malformed kmls (those with multiple geometries with same ids) to still parse
// correctly, as they do in Google Earth.
function createEntity(node, entityCollection, context) {
  let id = queryStringAttribute(node, "id");
  id = defined(id) && id.length !== 0 ? id : createGuid();
  if (defined(context)) {
    id = context + id;
  }
 
  // If we have a duplicate ID just generate one.
  // This isn't valid KML but Google Earth handles this case.
  let entity = entityCollection.getById(id);
  if (defined(entity)) {
    id = createGuid();
    Iif (defined(context)) {
      id = context + id;
    }
  }
 
  entity = entityCollection.add(new Entity({ id: id }));
  Eif (!defined(entity.kml)) {
    entity.addProperty("kml");
    entity.kml = new KmlFeatureData();
  }
  return entity;
}
 
function isExtrudable(altitudeMode, gxAltitudeMode) {
  return (
    altitudeMode === "absolute" ||
    altitudeMode === "relativeToGround" ||
    gxAltitudeMode === "relativeToSeaFloor"
  );
}
 
function readCoordinate(value, ellipsoid) {
  //Google Earth treats empty or missing coordinates as 0.
  if (!defined(value)) {
    return Cartesian3.fromDegrees(0, 0, 0, ellipsoid);
  }
 
  const digits = value.match(/[^\s,\n]+/g);
  if (!defined(digits)) {
    return Cartesian3.fromDegrees(0, 0, 0, ellipsoid);
  }
 
  let longitude = parseFloat(digits[0]);
  let latitude = parseFloat(digits[1]);
  let height = parseFloat(digits[2]);
 
  longitude = isNaN(longitude) ? 0.0 : longitude;
  latitude = isNaN(latitude) ? 0.0 : latitude;
  height = isNaN(height) ? 0.0 : height;
 
  return Cartesian3.fromDegrees(longitude, latitude, height, ellipsoid);
}
 
function readCoordinates(element, ellipsoid) {
  if (!defined(element)) {
    return undefined;
  }
 
  const tuples = element.textContent.match(/[^\s\n]+/g);
  if (!defined(tuples)) {
    return undefined;
  }
 
  const length = tuples.length;
  const result = new Array(length);
  let resultIndex = 0;
  for (let i = 0; i < length; i++) {
    result[resultIndex++] = readCoordinate(tuples[i], ellipsoid);
  }
  return result;
}
 
function queryNumericAttribute(node, attributeName) {
  if (!defined(node)) {
    return undefined;
  }
 
  const value = node.getAttribute(attributeName);
  Eif (value !== null) {
    const result = parseFloat(value);
    return !isNaN(result) ? result : undefined;
  }
  return undefined;
}
 
function queryStringAttribute(node, attributeName) {
  if (!defined(node)) {
    return undefined;
  }
  const value = node.getAttribute(attributeName);
  return value !== null ? value : undefined;
}
 
function queryFirstNode(node, tagName, namespace) {
  if (!defined(node)) {
    return undefined;
  }
  const childNodes = node.childNodes;
  const length = childNodes.length;
  for (let q = 0; q < length; q++) {
    const child = childNodes[q];
    if (
      child.localName === tagName &&
      namespace.indexOf(child.namespaceURI) !== -1
    ) {
      return child;
    }
  }
  return undefined;
}
 
function queryNodes(node, tagName, namespace) {
  Iif (!defined(node)) {
    return undefined;
  }
  const result = [];
  const childNodes = node.getElementsByTagNameNS("*", tagName);
  const length = childNodes.length;
  for (let q = 0; q < length; q++) {
    const child = childNodes[q];
    Eif (
      child.localName === tagName &&
      namespace.indexOf(child.namespaceURI) !== -1
    ) {
      result.push(child);
    }
  }
  return result;
}
 
function queryChildNodes(node, tagName, namespace) {
  Iif (!defined(node)) {
    return [];
  }
  const result = [];
  const childNodes = node.childNodes;
  const length = childNodes.length;
  for (let q = 0; q < length; q++) {
    const child = childNodes[q];
    if (
      child.localName === tagName &&
      namespace.indexOf(child.namespaceURI) !== -1
    ) {
      result.push(child);
    }
  }
  return result;
}
 
function queryNumericValue(node, tagName, namespace) {
  const resultNode = queryFirstNode(node, tagName, namespace);
  if (defined(resultNode)) {
    const result = parseFloat(resultNode.textContent);
    return !isNaN(result) ? result : undefined;
  }
  return undefined;
}
 
function queryStringValue(node, tagName, namespace) {
  const result = queryFirstNode(node, tagName, namespace);
  if (defined(result)) {
    return result.textContent.trim();
  }
  return undefined;
}
 
function queryBooleanValue(node, tagName, namespace) {
  const result = queryFirstNode(node, tagName, namespace);
  if (defined(result)) {
    const value = result.textContent.trim();
    return value === "1" || /^true$/i.test(value);
  }
  return undefined;
}
 
function resolveHref(href, sourceResource, uriResolver) {
  if (!defined(href)) {
    return undefined;
  }
 
  let resource;
  if (defined(uriResolver)) {
    // To resolve issues with KML sources defined in Windows style paths.
    href = href.replace(/\\/g, "/");
    let blob = uriResolver[href];
    if (defined(blob)) {
      resource = new Resource({
        url: blob,
      });
    } else {
      // Needed for multiple levels of KML files in a KMZ
      const baseUri = new Uri(sourceResource.getUrlComponent());
      const uri = new Uri(href);
      blob = uriResolver[uri.absoluteTo(baseUri)];
      if (defined(blob)) {
        resource = new Resource({
          url: blob,
        });
      }
    }
  }
 
  if (!defined(resource)) {
    resource = sourceResource.getDerivedResource({
      url: href,
    });
  }
 
  return resource;
}
 
const colorOptions = {
  maximumRed: undefined,
  red: undefined,
  maximumGreen: undefined,
  green: undefined,
  maximumBlue: undefined,
  blue: undefined,
};
 
function parseColorString(value, isRandom) {
  if (!defined(value) || /^\s*$/gm.test(value)) {
    return undefined;
  }
 
  Iif (value[0] === "#") {
    value = value.substring(1);
  }
 
  const alpha = parseInt(value.substring(0, 2), 16) / 255.0;
  const blue = parseInt(value.substring(2, 4), 16) / 255.0;
  const green = parseInt(value.substring(4, 6), 16) / 255.0;
  const red = parseInt(value.substring(6, 8), 16) / 255.0;
 
  if (!isRandom) {
    return new Color(red, green, blue, alpha);
  }
 
  if (red > 0) {
    colorOptions.maximumRed = red;
    colorOptions.red = undefined;
  } else {
    colorOptions.maximumRed = undefined;
    colorOptions.red = 0;
  }
  if (green > 0) {
    colorOptions.maximumGreen = green;
    colorOptions.green = undefined;
  } else {
    colorOptions.maximumGreen = undefined;
    colorOptions.green = 0;
  }
  if (blue > 0) {
    colorOptions.maximumBlue = blue;
    colorOptions.blue = undefined;
  } else {
    colorOptions.maximumBlue = undefined;
    colorOptions.blue = 0;
  }
  colorOptions.alpha = alpha;
  return Color.fromRandom(colorOptions);
}
 
function queryColorValue(node, tagName, namespace) {
  const value = queryStringValue(node, tagName, namespace);
  if (!defined(value)) {
    return undefined;
  }
  return parseColorString(
    value,
    queryStringValue(node, "colorMode", namespace) === "random",
  );
}
 
function processTimeStamp(featureNode) {
  const node = queryFirstNode(featureNode, "TimeStamp", namespaces.kmlgx);
  const whenString = queryStringValue(node, "when", namespaces.kmlgx);
 
  if (!defined(node) || !defined(whenString) || whenString.length === 0) {
    return undefined;
  }
 
  //According to the KML spec, a TimeStamp represents a "single moment in time"
  //However, since Cesium animates much differently than Google Earth, that doesn't
  //Make much sense here.  Instead, we use the TimeStamp as the moment the feature
  //comes into existence.  This works much better and gives a similar feel to
  //GE's experience.
  const when = JulianDate.fromIso8601(whenString);
  const result = new TimeIntervalCollection();
  result.addInterval(
    new TimeInterval({
      start: when,
      stop: Iso8601.MAXIMUM_VALUE,
    }),
  );
  return result;
}
 
function processTimeSpan(featureNode) {
  const node = queryFirstNode(featureNode, "TimeSpan", namespaces.kmlgx);
  if (!defined(node)) {
    return undefined;
  }
  let result;
 
  const beginNode = queryFirstNode(node, "begin", namespaces.kmlgx);
  let beginDate = defined(beginNode)
    ? JulianDate.fromIso8601(beginNode.textContent)
    : undefined;
 
  const endNode = queryFirstNode(node, "end", namespaces.kmlgx);
  let endDate = defined(endNode)
    ? JulianDate.fromIso8601(endNode.textContent)
    : undefined;
 
  if (defined(beginDate) && defined(endDate)) {
    if (JulianDate.lessThan(endDate, beginDate)) {
      const tmp = beginDate;
      beginDate = endDate;
      endDate = tmp;
    }
    result = new TimeIntervalCollection();
    result.addInterval(
      new TimeInterval({
        start: beginDate,
        stop: endDate,
      }),
    );
  } else if (defined(beginDate)) {
    result = new TimeIntervalCollection();
    result.addInterval(
      new TimeInterval({
        start: beginDate,
        stop: Iso8601.MAXIMUM_VALUE,
      }),
    );
  } else if (defined(endDate)) {
    result = new TimeIntervalCollection();
    result.addInterval(
      new TimeInterval({
        start: Iso8601.MINIMUM_VALUE,
        stop: endDate,
      }),
    );
  }
 
  return result;
}
 
function createDefaultBillboard() {
  const billboard = new BillboardGraphics();
  billboard.width = BILLBOARD_SIZE;
  billboard.height = BILLBOARD_SIZE;
  billboard.scaleByDistance = new NearFarScalar(
    BILLBOARD_NEAR_DISTANCE,
    BILLBOARD_NEAR_RATIO,
    BILLBOARD_FAR_DISTANCE,
    BILLBOARD_FAR_RATIO,
  );
  billboard.pixelOffsetScaleByDistance = new NearFarScalar(
    BILLBOARD_NEAR_DISTANCE,
    BILLBOARD_NEAR_RATIO,
    BILLBOARD_FAR_DISTANCE,
    BILLBOARD_FAR_RATIO,
  );
  return billboard;
}
 
function createDefaultPolygon() {
  const polygon = new PolygonGraphics();
  polygon.outline = true;
  polygon.outlineColor = Color.WHITE;
  return polygon;
}
 
function createDefaultLabel() {
  const label = new LabelGraphics();
  label.translucencyByDistance = new NearFarScalar(3000000, 1.0, 5000000, 0.0);
  label.pixelOffset = new Cartesian2(17, 0);
  label.horizontalOrigin = HorizontalOrigin.LEFT;
  label.font = "16px sans-serif";
  label.style = LabelStyle.FILL_AND_OUTLINE;
  return label;
}
 
function getIconHref(
  iconNode,
  dataSource,
  sourceResource,
  uriResolver,
  canRefresh,
) {
  let href = queryStringValue(iconNode, "href", namespaces.kml);
  if (!defined(href) || href.length === 0) {
    return undefined;
  }
 
  if (href.indexOf("root://icons/palette-") === 0) {
    const palette = href.charAt(21);
 
    // Get the icon number
    let x = queryNumericValue(iconNode, "x", namespaces.gx) ?? 0;
    let y = queryNumericValue(iconNode, "y", namespaces.gx) ?? 0;
    x = Math.min(x / 32, 7);
    y = 7 - Math.min(y / 32, 7);
    const iconNum = 8 * y + x;
 
    href = `https://maps.google.com/mapfiles/kml/pal${palette}/icon${iconNum}.png`;
  }
 
  const hrefResource = resolveHref(href, sourceResource, uriResolver);
 
  if (canRefresh) {
    const refreshMode = queryStringValue(
      iconNode,
      "refreshMode",
      namespaces.kml,
    );
    const viewRefreshMode = queryStringValue(
      iconNode,
      "viewRefreshMode",
      namespaces.kml,
    );
    if (refreshMode === "onInterval" || refreshMode === "onExpire") {
      oneTimeWarning(
        `kml-refreshMode-${refreshMode}`,
        `KML - Unsupported Icon refreshMode: ${refreshMode}`,
      );
    } else if (viewRefreshMode === "onStop" || viewRefreshMode === "onRegion") {
      oneTimeWarning(
        `kml-refreshMode-${viewRefreshMode}`,
        `KML - Unsupported Icon viewRefreshMode: ${viewRefreshMode}`,
      );
    }
 
    const viewBoundScale =
      queryStringValue(iconNode, "viewBoundScale", namespaces.kml) ?? 1.0;
    const defaultViewFormat =
      viewRefreshMode === "onStop"
        ? "BBOX=[bboxWest],[bboxSouth],[bboxEast],[bboxNorth]"
        : "";
    const viewFormat =
      queryStringValue(iconNode, "viewFormat", namespaces.kml) ??
      defaultViewFormat;
    const httpQuery = queryStringValue(iconNode, "httpQuery", namespaces.kml);
    Eif (defined(viewFormat)) {
      hrefResource.setQueryParameters(queryToObject(cleanupString(viewFormat)));
    }
    Iif (defined(httpQuery)) {
      hrefResource.setQueryParameters(queryToObject(cleanupString(httpQuery)));
    }
 
    const ellipsoid = dataSource._ellipsoid;
    processNetworkLinkQueryString(
      hrefResource,
      dataSource.camera,
      dataSource.canvas,
      viewBoundScale,
      dataSource._lastCameraView.bbox,
      ellipsoid,
    );
 
    return hrefResource;
  }
 
  return hrefResource;
}
 
function processBillboardIcon(
  dataSource,
  node,
  targetEntity,
  sourceResource,
  uriResolver,
) {
  let scale = queryNumericValue(node, "scale", namespaces.kml);
  const heading = queryNumericValue(node, "heading", namespaces.kml);
  const color = queryColorValue(node, "color", namespaces.kml);
 
  const iconNode = queryFirstNode(node, "Icon", namespaces.kml);
  let icon = getIconHref(
    iconNode,
    dataSource,
    sourceResource,
    uriResolver,
    false,
  );
 
  // If icon tags are present but blank, we do not want to show an icon
  if (defined(iconNode) && !defined(icon)) {
    icon = false;
  }
 
  const x = queryNumericValue(iconNode, "x", namespaces.gx);
  const y = queryNumericValue(iconNode, "y", namespaces.gx);
  const w = queryNumericValue(iconNode, "w", namespaces.gx);
  const h = queryNumericValue(iconNode, "h", namespaces.gx);
 
  const hotSpotNode = queryFirstNode(node, "hotSpot", namespaces.kml);
  const hotSpotX = queryNumericAttribute(hotSpotNode, "x");
  const hotSpotY = queryNumericAttribute(hotSpotNode, "y");
  const hotSpotXUnit = queryStringAttribute(hotSpotNode, "xunits");
  const hotSpotYUnit = queryStringAttribute(hotSpotNode, "yunits");
 
  let billboard = targetEntity.billboard;
  Eif (!defined(billboard)) {
    billboard = createDefaultBillboard();
    targetEntity.billboard = billboard;
  }
 
  billboard.image = icon;
  billboard.scale = scale;
  billboard.color = color;
 
  if (defined(x) || defined(y) || defined(w) || defined(h)) {
    billboard.imageSubRegion = new BoundingRectangle(x, y, w, h);
  }
 
  //GE treats a heading of zero as no heading
  //You can still point north using a 360 degree angle (or any multiple of 360)
  if (defined(heading) && heading !== 0) {
    billboard.rotation = CesiumMath.toRadians(-heading);
    billboard.alignedAxis = Cartesian3.UNIT_Z;
  }
 
  //Hotpot is the KML equivalent of pixel offset
  //The hotspot origin is the lower left, but we leave
  //our billboard origin at the center and simply
  //modify the pixel offset to take this into account
  scale = scale ?? 1.0;
 
  let xOffset;
  let yOffset;
  if (defined(hotSpotX)) {
    if (hotSpotXUnit === "pixels") {
      xOffset = -hotSpotX * scale;
    } else if (hotSpotXUnit === "insetPixels") {
      xOffset = (hotSpotX - BILLBOARD_SIZE) * scale;
    } else Eif (hotSpotXUnit === "fraction") {
      xOffset = -hotSpotX * BILLBOARD_SIZE * scale;
    }
    xOffset += BILLBOARD_SIZE * 0.5 * scale;
  }
 
  if (defined(hotSpotY)) {
    if (hotSpotYUnit === "pixels") {
      yOffset = hotSpotY * scale;
    } else if (hotSpotYUnit === "insetPixels") {
      yOffset = (-hotSpotY + BILLBOARD_SIZE) * scale;
    } else Eif (hotSpotYUnit === "fraction") {
      yOffset = hotSpotY * BILLBOARD_SIZE * scale;
    }
 
    yOffset -= BILLBOARD_SIZE * 0.5 * scale;
  }
 
  if (defined(xOffset) || defined(yOffset)) {
    billboard.pixelOffset = new Cartesian2(xOffset, yOffset);
  }
}
 
function applyStyle(
  dataSource,
  styleNode,
  targetEntity,
  sourceResource,
  uriResolver,
) {
  for (let i = 0, len = styleNode.childNodes.length; i < len; i++) {
    const node = styleNode.childNodes.item(i);
    if (node.localName === "IconStyle") {
      processBillboardIcon(
        dataSource,
        node,
        targetEntity,
        sourceResource,
        uriResolver,
      );
    } else if (node.localName === "LabelStyle") {
      let label = targetEntity.label;
      Eif (!defined(label)) {
        label = createDefaultLabel();
        targetEntity.label = label;
      }
      label.scale =
        queryNumericValue(node, "scale", namespaces.kml) ?? label.scale;
      label.fillColor =
        queryColorValue(node, "color", namespaces.kml) ?? label.fillColor;
      label.text = targetEntity.name;
    } else if (node.localName === "LineStyle") {
      let polyline = targetEntity.polyline;
      Eif (!defined(polyline)) {
        polyline = new PolylineGraphics();
        targetEntity.polyline = polyline;
      }
      polyline.width = queryNumericValue(node, "width", namespaces.kml);
      polyline.material = queryColorValue(node, "color", namespaces.kml);
      if (defined(queryColorValue(node, "outerColor", namespaces.gx))) {
        oneTimeWarning(
          "kml-gx:outerColor",
          "KML - gx:outerColor is not supported in a LineStyle",
        );
      }
      if (defined(queryNumericValue(node, "outerWidth", namespaces.gx))) {
        oneTimeWarning(
          "kml-gx:outerWidth",
          "KML - gx:outerWidth is not supported in a LineStyle",
        );
      }
      if (defined(queryNumericValue(node, "physicalWidth", namespaces.gx))) {
        oneTimeWarning(
          "kml-gx:physicalWidth",
          "KML - gx:physicalWidth is not supported in a LineStyle",
        );
      }
      if (defined(queryBooleanValue(node, "labelVisibility", namespaces.gx))) {
        oneTimeWarning(
          "kml-gx:labelVisibility",
          "KML - gx:labelVisibility is not supported in a LineStyle",
        );
      }
    } else if (node.localName === "PolyStyle") {
      let polygon = targetEntity.polygon;
      Eif (!defined(polygon)) {
        polygon = createDefaultPolygon();
        targetEntity.polygon = polygon;
      }
      polygon.material =
        queryColorValue(node, "color", namespaces.kml) ?? polygon.material;
      polygon.fill =
        queryBooleanValue(node, "fill", namespaces.kml) ?? polygon.fill;
      polygon.outline =
        queryBooleanValue(node, "outline", namespaces.kml) ?? polygon.outline;
    } else if (node.localName === "BalloonStyle") {
      const bgColor =
        parseColorString(queryStringValue(node, "bgColor", namespaces.kml)) ??
        Color.WHITE;
      const textColor =
        parseColorString(queryStringValue(node, "textColor", namespaces.kml)) ??
        Color.BLACK;
      const text = queryStringValue(node, "text", namespaces.kml);
 
      //This is purely an internal property used in style processing,
      //it never ends up on the final entity.
      targetEntity.addProperty("balloonStyle");
      targetEntity.balloonStyle = {
        bgColor: bgColor,
        textColor: textColor,
        text: text,
      };
    } else if (node.localName === "ListStyle") {
      const listItemType = queryStringValue(
        node,
        "listItemType",
        namespaces.kml,
      );
      Eif (listItemType === "radioFolder" || listItemType === "checkOffOnly") {
        oneTimeWarning(
          `kml-listStyle-${listItemType}`,
          `KML - Unsupported ListStyle with listItemType: ${listItemType}`,
        );
      }
    }
  }
}
 
//Processes and merges any inline styles for the provided node into the provided entity.
function computeFinalStyle(
  dataSource,
  placeMark,
  styleCollection,
  sourceResource,
  uriResolver,
) {
  const result = new Entity();
  let styleEntity;
 
  //Google earth seems to always use the last inline Style/StyleMap only
  let styleIndex = -1;
  const childNodes = placeMark.childNodes;
  const length = childNodes.length;
  for (let q = 0; q < length; q++) {
    const child = childNodes[q];
    if (child.localName === "Style" || child.localName === "StyleMap") {
      styleIndex = q;
    }
  }
 
  if (styleIndex !== -1) {
    const inlineStyleNode = childNodes[styleIndex];
    if (inlineStyleNode.localName === "Style") {
      applyStyle(
        dataSource,
        inlineStyleNode,
        result,
        sourceResource,
        uriResolver,
      );
    } else {
      // StyleMap
      const pairs = queryChildNodes(inlineStyleNode, "Pair", namespaces.kml);
      for (let p = 0; p < pairs.length; p++) {
        const pair = pairs[p];
        const key = queryStringValue(pair, "key", namespaces.kml);
        if (key === "normal") {
          const styleUrl = queryStringValue(pair, "styleUrl", namespaces.kml);
          Iif (defined(styleUrl)) {
            styleEntity = styleCollection.getById(styleUrl);
            if (!defined(styleEntity)) {
              styleEntity = styleCollection.getById(`#${styleUrl}`);
            }
            if (defined(styleEntity)) {
              result.merge(styleEntity);
            }
          } else {
            const node = queryFirstNode(pair, "Style", namespaces.kml);
            applyStyle(dataSource, node, result, sourceResource, uriResolver);
          }
        } else {
          oneTimeWarning(
            `kml-styleMap-${key}`,
            `KML - Unsupported StyleMap key: ${key}`,
          );
        }
      }
    }
  }
 
  //Google earth seems to always use the first external style only.
  const externalStyle = queryStringValue(placeMark, "styleUrl", namespaces.kml);
  if (defined(externalStyle)) {
    let id = externalStyle;
    if (externalStyle[0] !== "#" && externalStyle.indexOf("#") !== -1) {
      const tokens = externalStyle.split("#");
      const uri = tokens[0];
      const resource = sourceResource.getDerivedResource({
        url: uri,
      });
 
      id = `${resource.getUrlComponent()}#${tokens[1]}`;
    }
 
    styleEntity = styleCollection.getById(id);
    if (!defined(styleEntity)) {
      styleEntity = styleCollection.getById(`#${id}`);
    }
    Eif (defined(styleEntity)) {
      result.merge(styleEntity);
    }
  }
 
  return result;
}
 
//Asynchronously processes an external style file.
function processExternalStyles(dataSource, resource, styleCollection) {
  return resource.fetchXML().then(function (styleKml) {
    return processStyles(dataSource, styleKml, styleCollection, resource, true);
  });
}
 
//Processes all shared and external styles and stores
//their id into the provided styleCollection.
//Returns an array of promises that will resolve when
//each style is loaded.
function processStyles(
  dataSource,
  kml,
  styleCollection,
  sourceResource,
  isExternal,
  uriResolver,
) {
  let i;
  let id;
  let styleEntity;
 
  let node;
  const styleNodes = queryNodes(kml, "Style", namespaces.kml);
  Eif (defined(styleNodes)) {
    const styleNodesLength = styleNodes.length;
    for (i = 0; i < styleNodesLength; i++) {
      node = styleNodes[i];
      id = queryStringAttribute(node, "id");
      if (defined(id)) {
        id = `#${id}`;
        if (isExternal && defined(sourceResource)) {
          id = sourceResource.getUrlComponent() + id;
        }
        Eif (!defined(styleCollection.getById(id))) {
          styleEntity = new Entity({
            id: id,
          });
          styleCollection.add(styleEntity);
          applyStyle(
            dataSource,
            node,
            styleEntity,
            sourceResource,
            uriResolver,
          );
        }
      }
    }
  }
 
  const styleMaps = queryNodes(kml, "StyleMap", namespaces.kml);
  Eif (defined(styleMaps)) {
    const styleMapsLength = styleMaps.length;
    for (i = 0; i < styleMapsLength; i++) {
      const styleMap = styleMaps[i];
      id = queryStringAttribute(styleMap, "id");
      if (defined(id)) {
        const pairs = queryChildNodes(styleMap, "Pair", namespaces.kml);
        for (let p = 0; p < pairs.length; p++) {
          const pair = pairs[p];
          const key = queryStringValue(pair, "key", namespaces.kml);
          if (key === "normal") {
            id = `#${id}`;
            if (isExternal && defined(sourceResource)) {
              id = sourceResource.getUrlComponent() + id;
            }
            Eif (!defined(styleCollection.getById(id))) {
              styleEntity = styleCollection.getOrCreateEntity(id);
 
              let styleUrl = queryStringValue(pair, "styleUrl", namespaces.kml);
              if (defined(styleUrl)) {
                if (styleUrl[0] !== "#") {
                  styleUrl = `#${styleUrl}`;
                }
 
                if (isExternal && defined(sourceResource)) {
                  styleUrl = sourceResource.getUrlComponent() + styleUrl;
                }
                const base = styleCollection.getById(styleUrl);
 
                Eif (defined(base)) {
                  styleEntity.merge(base);
                }
              } else {
                node = queryFirstNode(pair, "Style", namespaces.kml);
                applyStyle(
                  dataSource,
                  node,
                  styleEntity,
                  sourceResource,
                  uriResolver,
                );
              }
            }
          } else E{
            oneTimeWarning(
              `kml-styleMap-${key}`,
              `KML - Unsupported StyleMap key: ${key}`,
            );
          }
        }
      }
    }
  }
 
  const promises = [];
  const styleUrlNodes = kml.getElementsByTagName("styleUrl");
  const styleUrlNodesLength = styleUrlNodes.length;
  for (i = 0; i < styleUrlNodesLength; i++) {
    const styleReference = styleUrlNodes[i].textContent;
    if (styleReference[0] !== "#") {
      //According to the spec, all local styles should start with a #
      //and everything else is an external style that has a # seperating
      //the URL of the document and the style.  However, Google Earth
      //also accepts styleUrls without a # as meaning a local style.
      const tokens = styleReference.split("#");
      if (tokens.length === 2) {
        const uri = tokens[0];
        const resource = sourceResource.getDerivedResource({
          url: uri,
        });
 
        promises.push(
          processExternalStyles(dataSource, resource, styleCollection),
        );
      }
    }
  }
 
  return promises;
}
 
function createDropLine(entityCollection, entity, styleEntity) {
  const entityPosition = new ReferenceProperty(entityCollection, entity.id, [
    "position",
  ]);
  const surfacePosition = new ScaledPositionProperty(entity.position);
  entity.polyline = defined(styleEntity.polyline)
    ? styleEntity.polyline.clone()
    : new PolylineGraphics();
  entity.polyline.positions = new PositionPropertyArray([
    entityPosition,
    surfacePosition,
  ]);
}
 
function heightReferenceFromAltitudeMode(altitudeMode, gxAltitudeMode) {
  if (
    (!defined(altitudeMode) && !defined(gxAltitudeMode)) ||
    altitudeMode === "clampToGround"
  ) {
    return HeightReference.CLAMP_TO_GROUND;
  }
 
  if (altitudeMode === "relativeToGround") {
    return HeightReference.RELATIVE_TO_GROUND;
  }
 
  if (altitudeMode === "absolute") {
    return HeightReference.NONE;
  }
 
  if (gxAltitudeMode === "clampToSeaFloor") {
    oneTimeWarning(
      "kml-gx:altitudeMode-clampToSeaFloor",
      "KML - <gx:altitudeMode>:clampToSeaFloor is currently not supported, using <kml:altitudeMode>:clampToGround.",
    );
    return HeightReference.CLAMP_TO_GROUND;
  }
 
  Eif (gxAltitudeMode === "relativeToSeaFloor") {
    oneTimeWarning(
      "kml-gx:altitudeMode-relativeToSeaFloor",
      "KML - <gx:altitudeMode>:relativeToSeaFloor is currently not supported, using <kml:altitudeMode>:relativeToGround.",
    );
    return HeightReference.RELATIVE_TO_GROUND;
  }
 
  if (defined(altitudeMode)) {
    oneTimeWarning(
      "kml-altitudeMode-unknown",
      `KML - Unknown <kml:altitudeMode>:${altitudeMode}, using <kml:altitudeMode>:CLAMP_TO_GROUND.`,
    );
  } else {
    oneTimeWarning(
      "kml-gx:altitudeMode-unknown",
      `KML - Unknown <gx:altitudeMode>:${gxAltitudeMode}, using <kml:altitudeMode>:CLAMP_TO_GROUND.`,
    );
  }
 
  // Clamp to ground is the default
  return HeightReference.CLAMP_TO_GROUND;
}
 
function createPositionPropertyFromAltitudeMode(
  property,
  altitudeMode,
  gxAltitudeMode,
) {
  if (
    gxAltitudeMode === "relativeToSeaFloor" ||
    altitudeMode === "absolute" ||
    altitudeMode === "relativeToGround"
  ) {
    //Just return the ellipsoid referenced property until we support MSL
    return property;
  }
 
  Iif (
    (defined(altitudeMode) && altitudeMode !== "clampToGround") || //
    (defined(gxAltitudeMode) && gxAltitudeMode !== "clampToSeaFloor")
  ) {
    oneTimeWarning(
      "kml-altitudeMode-unknown",
      `KML - Unknown altitudeMode: ${altitudeMode ?? gxAltitudeMode}`,
    );
  }
 
  // Clamp to ground is the default
  return new ScaledPositionProperty(property);
}
 
function createPositionPropertyArrayFromAltitudeMode(
  properties,
  altitudeMode,
  gxAltitudeMode,
  ellipsoid,
) {
  if (!defined(properties)) {
    return undefined;
  }
 
  Iif (
    gxAltitudeMode === "relativeToSeaFloor" ||
    altitudeMode === "absolute" ||
    altitudeMode === "relativeToGround"
  ) {
    //Just return the ellipsoid referenced property until we support MSL
    return properties;
  }
 
  Iif (
    (defined(altitudeMode) && altitudeMode !== "clampToGround") || //
    (defined(gxAltitudeMode) && gxAltitudeMode !== "clampToSeaFloor")
  ) {
    oneTimeWarning(
      "kml-altitudeMode-unknown",
      `KML - Unknown altitudeMode: ${altitudeMode ?? gxAltitudeMode}`,
    );
  }
 
  // Clamp to ground is the default
  const propertiesLength = properties.length;
  for (let i = 0; i < propertiesLength; i++) {
    const property = properties[i];
    ellipsoid.scaleToGeodeticSurface(property, property);
  }
  return properties;
}
 
function processPositionGraphics(
  dataSource,
  entity,
  styleEntity,
  heightReference,
) {
  let label = entity.label;
  if (!defined(label)) {
    label = defined(styleEntity.label)
      ? styleEntity.label.clone()
      : createDefaultLabel();
    entity.label = label;
  }
  label.text = entity.name;
 
  let billboard = entity.billboard;
  if (!defined(billboard)) {
    billboard = defined(styleEntity.billboard)
      ? styleEntity.billboard.clone()
      : createDefaultBillboard();
    entity.billboard = billboard;
  }
 
  if (!defined(billboard.image)) {
    billboard.image = dataSource._pinBuilder.fromColor(Color.YELLOW, 64);
 
    // If there were empty <Icon> tags in the KML, then billboard.image was set to false above
    // However, in this case, the false value would have been converted to a property afterwards
    // Thus, we check if billboard.image is defined with value of false
  } else if (!billboard.image.getValue()) {
    billboard.image = undefined;
  }
 
  let scale = 1.0;
  if (defined(billboard.scale)) {
    scale = billboard.scale.getValue();
    if (scale !== 0) {
      label.pixelOffset = new Cartesian2(scale * 16 + 1, 0);
    } else {
      //Minor tweaks to better match Google Earth.
      label.pixelOffset = undefined;
      label.horizontalOrigin = undefined;
    }
  }
 
  if (defined(heightReference) && dataSource._clampToGround) {
    billboard.heightReference = heightReference;
    label.heightReference = heightReference;
  }
}
 
function processPathGraphics(entity, styleEntity) {
  let path = entity.path;
  Eif (!defined(path)) {
    path = new PathGraphics();
    path.leadTime = 0;
    entity.path = path;
  }
 
  const polyline = styleEntity.polyline;
  if (defined(polyline)) {
    path.material = polyline.material;
    path.width = polyline.width;
  }
}
 
function processPoint(
  dataSource,
  entityCollection,
  geometryNode,
  entity,
  styleEntity,
) {
  const coordinatesString = queryStringValue(
    geometryNode,
    "coordinates",
    namespaces.kml,
  );
  const altitudeMode = queryStringValue(
    geometryNode,
    "altitudeMode",
    namespaces.kml,
  );
  const gxAltitudeMode = queryStringValue(
    geometryNode,
    "altitudeMode",
    namespaces.gx,
  );
  const extrude = queryBooleanValue(geometryNode, "extrude", namespaces.kml);
  const ellipsoid = dataSource._ellipsoid;
  const position = readCoordinate(coordinatesString, ellipsoid);
 
  entity.position = position;
  processPositionGraphics(
    dataSource,
    entity,
    styleEntity,
    heightReferenceFromAltitudeMode(altitudeMode, gxAltitudeMode),
  );
 
  if (extrude && isExtrudable(altitudeMode, gxAltitudeMode)) {
    createDropLine(entityCollection, entity, styleEntity);
  }
 
  return true;
}
 
function processLineStringOrLinearRing(
  dataSource,
  entityCollection,
  geometryNode,
  entity,
  styleEntity,
) {
  const coordinatesNode = queryFirstNode(
    geometryNode,
    "coordinates",
    namespaces.kml,
  );
  const altitudeMode = queryStringValue(
    geometryNode,
    "altitudeMode",
    namespaces.kml,
  );
  const gxAltitudeMode = queryStringValue(
    geometryNode,
    "altitudeMode",
    namespaces.gx,
  );
  const extrude = queryBooleanValue(geometryNode, "extrude", namespaces.kml);
  const tessellate = queryBooleanValue(
    geometryNode,
    "tessellate",
    namespaces.kml,
  );
  const canExtrude = isExtrudable(altitudeMode, gxAltitudeMode);
  const zIndex = queryNumericValue(geometryNode, "drawOrder", namespaces.gx);
 
  const ellipsoid = dataSource._ellipsoid;
  const coordinates = readCoordinates(coordinatesNode, ellipsoid);
  let polyline = styleEntity.polyline;
  if (canExtrude && extrude) {
    const wall = new WallGraphics();
    entity.wall = wall;
    wall.positions = coordinates;
    const polygon = styleEntity.polygon;
 
    if (defined(polygon)) {
      wall.fill = polygon.fill;
      wall.material = polygon.material;
    }
 
    //Always outline walls so they show up in 2D.
    wall.outline = true;
    if (defined(polyline)) {
      wall.outlineColor = defined(polyline.material)
        ? polyline.material.color
        : Color.WHITE;
      wall.outlineWidth = polyline.width;
    } else Iif (defined(polygon)) {
      wall.outlineColor = defined(polygon.material)
        ? polygon.material.color
        : Color.WHITE;
    }
  } else if (dataSource._clampToGround && !canExtrude && tessellate) {
    const polylineGraphics = new PolylineGraphics();
    polylineGraphics.clampToGround = true;
    entity.polyline = polylineGraphics;
    polylineGraphics.positions = coordinates;
    if (defined(polyline)) {
      polylineGraphics.material = defined(polyline.material)
        ? polyline.material.color.getValue(Iso8601.MINIMUM_VALUE)
        : Color.WHITE;
      polylineGraphics.width = polyline.width ?? 1.0;
    } else E{
      polylineGraphics.material = Color.WHITE;
      polylineGraphics.width = 1.0;
    }
    polylineGraphics.zIndex = zIndex;
  } else {
    if (defined(zIndex)) {
      oneTimeWarning(
        "kml-gx:drawOrder",
        "KML - gx:drawOrder is not supported in LineStrings when clampToGround is false",
      );
    }
    Iif (dataSource._clampToGround && !tessellate) {
      oneTimeWarning(
        "kml-line-tesselate",
        "Ignoring clampToGround for KML lines without the tessellate flag.",
      );
    }
 
    polyline = defined(polyline) ? polyline.clone() : new PolylineGraphics();
    entity.polyline = polyline;
    polyline.positions = createPositionPropertyArrayFromAltitudeMode(
      coordinates,
      altitudeMode,
      gxAltitudeMode,
      ellipsoid,
    );
    if (!tessellate || canExtrude) {
      polyline.arcType = ArcType.NONE;
    }
  }
 
  return true;
}
 
function processPolygon(
  dataSource,
  entityCollection,
  geometryNode,
  entity,
  styleEntity,
) {
  const outerBoundaryIsNode = queryFirstNode(
    geometryNode,
    "outerBoundaryIs",
    namespaces.kml,
  );
  let linearRingNode = queryFirstNode(
    outerBoundaryIsNode,
    "LinearRing",
    namespaces.kml,
  );
  let coordinatesNode = queryFirstNode(
    linearRingNode,
    "coordinates",
    namespaces.kml,
  );
  const ellipsoid = dataSource._ellipsoid;
  let coordinates = readCoordinates(coordinatesNode, ellipsoid);
  const extrude = queryBooleanValue(geometryNode, "extrude", namespaces.kml);
  const altitudeMode = queryStringValue(
    geometryNode,
    "altitudeMode",
    namespaces.kml,
  );
  const gxAltitudeMode = queryStringValue(
    geometryNode,
    "altitudeMode",
    namespaces.gx,
  );
  const canExtrude = isExtrudable(altitudeMode, gxAltitudeMode);
 
  const polygon = defined(styleEntity.polygon)
    ? styleEntity.polygon.clone()
    : createDefaultPolygon();
 
  const polyline = styleEntity.polyline;
  if (defined(polyline)) {
    polygon.outlineColor = defined(polyline.material)
      ? polyline.material.color
      : Color.WHITE;
    polygon.outlineWidth = polyline.width;
  }
  entity.polygon = polygon;
 
  if (canExtrude) {
    polygon.perPositionHeight = true;
    polygon.extrudedHeight = extrude ? 0 : undefined;
  } else Eif (!dataSource._clampToGround) {
    polygon.height = 0;
  }
 
  if (defined(coordinates)) {
    const hierarchy = new PolygonHierarchy(coordinates);
    const innerBoundaryIsNodes = queryChildNodes(
      geometryNode,
      "innerBoundaryIs",
      namespaces.kml,
    );
    for (let j = 0; j < innerBoundaryIsNodes.length; j++) {
      linearRingNode = queryChildNodes(
        innerBoundaryIsNodes[j],
        "LinearRing",
        namespaces.kml,
      );
      for (let k = 0; k < linearRingNode.length; k++) {
        coordinatesNode = queryFirstNode(
          linearRingNode[k],
          "coordinates",
          namespaces.kml,
        );
        coordinates = readCoordinates(coordinatesNode, ellipsoid);
        Eif (defined(coordinates)) {
          hierarchy.holes.push(new PolygonHierarchy(coordinates));
        }
      }
    }
    polygon.hierarchy = hierarchy;
  }
 
  return true;
}
 
function processTrack(
  dataSource,
  entityCollection,
  geometryNode,
  entity,
  styleEntity,
) {
  const altitudeMode = queryStringValue(
    geometryNode,
    "altitudeMode",
    namespaces.kml,
  );
  const gxAltitudeMode = queryStringValue(
    geometryNode,
    "altitudeMode",
    namespaces.gx,
  );
  const coordNodes = queryChildNodes(geometryNode, "coord", namespaces.gx);
  const angleNodes = queryChildNodes(geometryNode, "angles", namespaces.gx);
  const timeNodes = queryChildNodes(geometryNode, "when", namespaces.kml);
  const extrude = queryBooleanValue(geometryNode, "extrude", namespaces.kml);
  const canExtrude = isExtrudable(altitudeMode, gxAltitudeMode);
  const ellipsoid = dataSource._ellipsoid;
 
  if (angleNodes.length > 0) {
    oneTimeWarning(
      "kml-gx:angles",
      "KML - gx:angles are not supported in gx:Tracks",
    );
  }
 
  const length = Math.min(coordNodes.length, timeNodes.length);
  const coordinates = [];
  const times = [];
  for (let i = 0; i < length; i++) {
    const position = readCoordinate(coordNodes[i].textContent, ellipsoid);
    coordinates.push(position);
    times.push(JulianDate.fromIso8601(timeNodes[i].textContent));
  }
  const property = new SampledPositionProperty();
  property.addSamples(times, coordinates);
  entity.position = property;
  processPositionGraphics(
    dataSource,
    entity,
    styleEntity,
    heightReferenceFromAltitudeMode(altitudeMode, gxAltitudeMode),
  );
  processPathGraphics(entity, styleEntity);
 
  entity.availability = new TimeIntervalCollection();
 
  Eif (timeNodes.length > 0) {
    entity.availability.addInterval(
      new TimeInterval({
        start: times[0],
        stop: times[times.length - 1],
      }),
    );
  }
 
  if (canExtrude && extrude) {
    createDropLine(entityCollection, entity, styleEntity);
  }
 
  return true;
}
 
function addToMultiTrack(
  times,
  positions,
  composite,
  availability,
  dropShowProperty,
  extrude,
  altitudeMode,
  gxAltitudeMode,
  includeEndPoints,
) {
  const start = times[0];
  const stop = times[times.length - 1];
 
  const data = new SampledPositionProperty();
  data.addSamples(times, positions);
 
  composite.intervals.addInterval(
    new TimeInterval({
      start: start,
      stop: stop,
      isStartIncluded: includeEndPoints,
      isStopIncluded: includeEndPoints,
      data: createPositionPropertyFromAltitudeMode(
        data,
        altitudeMode,
        gxAltitudeMode,
      ),
    }),
  );
  availability.addInterval(
    new TimeInterval({
      start: start,
      stop: stop,
      isStartIncluded: includeEndPoints,
      isStopIncluded: includeEndPoints,
    }),
  );
  dropShowProperty.intervals.addInterval(
    new TimeInterval({
      start: start,
      stop: stop,
      isStartIncluded: includeEndPoints,
      isStopIncluded: includeEndPoints,
      data: extrude,
    }),
  );
}
 
function processMultiTrack(
  dataSource,
  entityCollection,
  geometryNode,
  entity,
  styleEntity,
) {
  // Multitrack options do not work in GE as detailed in the spec,
  // rather than altitudeMode being at the MultiTrack level,
  // GE just defers all settings to the underlying track.
 
  const interpolate = queryBooleanValue(
    geometryNode,
    "interpolate",
    namespaces.gx,
  );
  const trackNodes = queryChildNodes(geometryNode, "Track", namespaces.gx);
 
  let times;
  let lastStop;
  let lastStopPosition;
  let needDropLine = false;
  const dropShowProperty = new TimeIntervalCollectionProperty();
  const availability = new TimeIntervalCollection();
  const composite = new CompositePositionProperty();
  const ellipsoid = dataSource._ellipsoid;
  for (let i = 0, len = trackNodes.length; i < len; i++) {
    const trackNode = trackNodes[i];
    const timeNodes = queryChildNodes(trackNode, "when", namespaces.kml);
    const coordNodes = queryChildNodes(trackNode, "coord", namespaces.gx);
    const altitudeMode = queryStringValue(
      trackNode,
      "altitudeMode",
      namespaces.kml,
    );
    const gxAltitudeMode = queryStringValue(
      trackNode,
      "altitudeMode",
      namespaces.gx,
    );
    const canExtrude = isExtrudable(altitudeMode, gxAltitudeMode);
    const extrude = queryBooleanValue(trackNode, "extrude", namespaces.kml);
 
    const length = Math.min(coordNodes.length, timeNodes.length);
 
    const positions = [];
    times = [];
    for (let x = 0; x < length; x++) {
      const position = readCoordinate(coordNodes[x].textContent, ellipsoid);
      positions.push(position);
      times.push(JulianDate.fromIso8601(timeNodes[x].textContent));
    }
 
    if (interpolate) {
      //If we are interpolating, then we need to fill in the end of
      //the last track and the beginning of this one with a sampled
      //property.  From testing in Google Earth, this property
      //is never extruded and always absolute.
      if (defined(lastStop)) {
        addToMultiTrack(
          [lastStop, times[0]],
          [lastStopPosition, positions[0]],
          composite,
          availability,
          dropShowProperty,
          false,
          "absolute",
          undefined,
          false,
        );
      }
      lastStop = times[length - 1];
      lastStopPosition = positions[positions.length - 1];
    }
 
    addToMultiTrack(
      times,
      positions,
      composite,
      availability,
      dropShowProperty,
      canExtrude && extrude,
      altitudeMode,
      gxAltitudeMode,
      true,
    );
    needDropLine = needDropLine || (canExtrude && extrude);
  }
 
  entity.availability = availability;
  entity.position = composite;
  processPositionGraphics(dataSource, entity, styleEntity);
  processPathGraphics(entity, styleEntity);
  if (needDropLine) {
    createDropLine(entityCollection, entity, styleEntity);
    entity.polyline.show = dropShowProperty;
  }
 
  return true;
}
 
const geometryTypes = {
  Point: processPoint,
  LineString: processLineStringOrLinearRing,
  LinearRing: processLineStringOrLinearRing,
  Polygon: processPolygon,
  Track: processTrack,
  MultiTrack: processMultiTrack,
  MultiGeometry: processMultiGeometry,
  Model: processUnsupportedGeometry,
};
 
function processMultiGeometry(
  dataSource,
  entityCollection,
  geometryNode,
  entity,
  styleEntity,
  context,
) {
  const childNodes = geometryNode.childNodes;
  let hasGeometry = false;
  for (let i = 0, len = childNodes.length; i < len; i++) {
    const childNode = childNodes.item(i);
    const geometryProcessor = geometryTypes[childNode.localName];
    if (defined(geometryProcessor)) {
      const childEntity = createEntity(childNode, entityCollection, context);
      childEntity.parent = entity;
      childEntity.name = entity.name;
      childEntity.availability = entity.availability;
      childEntity.description = entity.description;
      childEntity.kml = entity.kml;
      Eif (
        geometryProcessor(
          dataSource,
          entityCollection,
          childNode,
          childEntity,
          styleEntity,
        )
      ) {
        hasGeometry = true;
      }
    }
  }
 
  return hasGeometry;
}
 
function processUnsupportedGeometry(
  dataSource,
  entityCollection,
  geometryNode,
  entity,
  styleEntity,
) {
  oneTimeWarning(
    "kml-unsupportedGeometry",
    `KML - Unsupported geometry: ${geometryNode.localName}`,
  );
  return false;
}
 
function processExtendedData(node, entity) {
  const extendedDataNode = queryFirstNode(node, "ExtendedData", namespaces.kml);
 
  if (!defined(extendedDataNode)) {
    return undefined;
  }
 
  if (defined(queryFirstNode(extendedDataNode, "SchemaData", namespaces.kml))) {
    oneTimeWarning("kml-schemaData", "KML - SchemaData is unsupported");
  }
  if (defined(queryStringAttribute(extendedDataNode, "xmlns:prefix"))) {
    oneTimeWarning(
      "kml-extendedData",
      "KML - ExtendedData with xmlns:prefix is unsupported",
    );
  }
 
  const result = {};
  const dataNodes = queryChildNodes(extendedDataNode, "Data", namespaces.kml);
  Eif (defined(dataNodes)) {
    const length = dataNodes.length;
    for (let i = 0; i < length; i++) {
      const dataNode = dataNodes[i];
      const name = queryStringAttribute(dataNode, "name");
      Eif (defined(name)) {
        result[name] = {
          displayName: queryStringValue(
            dataNode,
            "displayName",
            namespaces.kml,
          ),
          value: queryStringValue(dataNode, "value", namespaces.kml),
        };
      }
    }
  }
  entity.kml.extendedData = result;
}
 
let scratchDiv;
Eif (typeof document !== "undefined") {
  scratchDiv = document.createElement("div");
}
 
function processDescription(
  node,
  entity,
  styleEntity,
  uriResolver,
  sourceResource,
) {
  let i;
  let key;
  let keys;
 
  const kmlData = entity.kml;
  const extendedData = kmlData.extendedData;
  const description = queryStringValue(node, "description", namespaces.kml);
 
  const balloonStyle = entity.balloonStyle ?? styleEntity.balloonStyle;
 
  let background = Color.WHITE;
  let foreground = Color.BLACK;
  let text = description;
 
  if (defined(balloonStyle)) {
    background = balloonStyle.bgColor ?? Color.WHITE;
    foreground = balloonStyle.textColor ?? Color.BLACK;
    text = balloonStyle.text ?? description;
  }
 
  let value;
  if (defined(text)) {
    text = text.replace("$[name]", entity.name ?? "");
    text = text.replace("$[description]", description ?? "");
    text = text.replace("$[address]", kmlData.address ?? "");
    text = text.replace("$[Snippet]", kmlData.snippet ?? "");
    text = text.replace("$[id]", entity.id);
 
    //While not explicitly defined by the OGC spec, in Google Earth
    //The appearance of geDirections adds the directions to/from links
    //We simply replace this string with nothing.
    text = text.replace("$[geDirections]", "");
 
    if (defined(extendedData)) {
      const matches = text.match(/\$\[.+?\]/g);
      Eif (matches !== null) {
        for (i = 0; i < matches.length; i++) {
          const token = matches[i];
          let propertyName = token.substr(2, token.length - 3);
          const isDisplayName = /\/displayName$/.test(propertyName);
          propertyName = propertyName.replace(/\/displayName$/, "");
 
          value = extendedData[propertyName];
          if (defined(value)) {
            value = isDisplayName ? value.displayName : value.value;
          }
          if (defined(value)) {
            text = text.replace(token, value ?? "");
          }
        }
      }
    }
  } else if (defined(extendedData)) {
    //If no description exists, build a table out of the extended data
    keys = Object.keys(extendedData);
    if (keys.length > 0) {
      text =
        '<table class="cesium-infoBox-defaultTable cesium-infoBox-defaultTable-lighter"><tbody>';
      for (i = 0; i < keys.length; i++) {
        key = keys[i];
        value = extendedData[key];
        text += `<tr><th>${value.displayName ?? key}</th><td>${value.value ?? ""}</td></tr>`;
      }
      text += "</tbody></table>";
    }
  }
 
  if (!defined(text)) {
    //No description
    return;
  }
 
  //Turns non-explicit links into clickable links.
  text = autolinker.link(text);
 
  //Use a temporary div to manipulate the links
  //so that they open in a new window.
  scratchDiv.innerHTML = text;
  const links = scratchDiv.querySelectorAll("a");
  for (i = 0; i < links.length; i++) {
    links[i].setAttribute("target", "_blank");
  }
 
  //Rewrite any KMZ embedded urls
  if (defined(uriResolver) && uriResolver.keys.length > 1) {
    embedDataUris(scratchDiv, "a", "href", uriResolver);
    embedDataUris(scratchDiv, "link", "href", uriResolver);
    embedDataUris(scratchDiv, "area", "href", uriResolver);
    embedDataUris(scratchDiv, "img", "src", uriResolver);
    embedDataUris(scratchDiv, "iframe", "src", uriResolver);
    embedDataUris(scratchDiv, "video", "src", uriResolver);
    embedDataUris(scratchDiv, "audio", "src", uriResolver);
    embedDataUris(scratchDiv, "source", "src", uriResolver);
    embedDataUris(scratchDiv, "track", "src", uriResolver);
    embedDataUris(scratchDiv, "input", "src", uriResolver);
    embedDataUris(scratchDiv, "embed", "src", uriResolver);
    embedDataUris(scratchDiv, "script", "src", uriResolver);
    embedDataUris(scratchDiv, "video", "poster", uriResolver);
  }
 
  //Make relative urls absolute using the sourceResource
  applyBasePath(scratchDiv, "a", "href", sourceResource);
  applyBasePath(scratchDiv, "link", "href", sourceResource);
  applyBasePath(scratchDiv, "area", "href", sourceResource);
  applyBasePath(scratchDiv, "img", "src", sourceResource);
  applyBasePath(scratchDiv, "iframe", "src", sourceResource);
  applyBasePath(scratchDiv, "video", "src", sourceResource);
  applyBasePath(scratchDiv, "audio", "src", sourceResource);
  applyBasePath(scratchDiv, "source", "src", sourceResource);
  applyBasePath(scratchDiv, "track", "src", sourceResource);
  applyBasePath(scratchDiv, "input", "src", sourceResource);
  applyBasePath(scratchDiv, "embed", "src", sourceResource);
  applyBasePath(scratchDiv, "script", "src", sourceResource);
  applyBasePath(scratchDiv, "video", "poster", sourceResource);
 
  let tmp = '<div class="cesium-infoBox-description-lighter" style="';
  tmp += "overflow:auto;";
  tmp += "word-wrap:break-word;";
  tmp += `background-color:${background.toCssColorString()};`;
  tmp += `color:${foreground.toCssColorString()};`;
  tmp += '">';
  tmp += `${scratchDiv.innerHTML}</div>`;
  scratchDiv.innerHTML = "";
 
  //Set the final HTML as the description.
  entity.description = tmp;
}
 
function processFeature(dataSource, featureNode, processingData) {
  const entityCollection = processingData.entityCollection;
  const parent = processingData.parentEntity;
  const sourceResource = processingData.sourceResource;
  const uriResolver = processingData.uriResolver;
 
  const entity = createEntity(
    featureNode,
    entityCollection,
    processingData.context,
  );
  const kmlData = entity.kml;
  const styleEntity = computeFinalStyle(
    dataSource,
    featureNode,
    processingData.styleCollection,
    sourceResource,
    uriResolver,
  );
 
  const name = queryStringValue(featureNode, "name", namespaces.kml);
  entity.name = name;
  entity.parent = parent;
 
  let availability = processTimeSpan(featureNode);
  if (!defined(availability)) {
    availability = processTimeStamp(featureNode);
  }
  entity.availability = availability;
 
  mergeAvailabilityWithParent(entity);
 
  // Per KML spec "A Feature is visible only if it and all its ancestors are visible."
  function ancestryIsVisible(parentEntity) {
    if (!parentEntity) {
      return true;
    }
    return parentEntity.show && ancestryIsVisible(parentEntity.parent);
  }
 
  const visibility = queryBooleanValue(
    featureNode,
    "visibility",
    namespaces.kml,
  );
  entity.show = ancestryIsVisible(parent) && (visibility ?? true);
  //const open = queryBooleanValue(featureNode, 'open', namespaces.kml);
 
  const authorNode = queryFirstNode(featureNode, "author", namespaces.atom);
  const author = kmlData.author;
  author.name = queryStringValue(authorNode, "name", namespaces.atom);
  author.uri = queryStringValue(authorNode, "uri", namespaces.atom);
  author.email = queryStringValue(authorNode, "email", namespaces.atom);
 
  const linkNode = queryFirstNode(featureNode, "link", namespaces.atom);
  const link = kmlData.link;
  link.href = queryStringAttribute(linkNode, "href");
  link.hreflang = queryStringAttribute(linkNode, "hreflang");
  link.rel = queryStringAttribute(linkNode, "rel");
  link.type = queryStringAttribute(linkNode, "type");
  link.title = queryStringAttribute(linkNode, "title");
  link.length = queryStringAttribute(linkNode, "length");
 
  kmlData.address = queryStringValue(featureNode, "address", namespaces.kml);
  kmlData.phoneNumber = queryStringValue(
    featureNode,
    "phoneNumber",
    namespaces.kml,
  );
  kmlData.snippet = queryStringValue(featureNode, "Snippet", namespaces.kml);
 
  processExtendedData(featureNode, entity);
  processDescription(
    featureNode,
    entity,
    styleEntity,
    uriResolver,
    sourceResource,
  );
 
  const ellipsoid = dataSource._ellipsoid;
  processLookAt(featureNode, entity, ellipsoid);
  processCamera(featureNode, entity, ellipsoid);
 
  if (defined(queryFirstNode(featureNode, "Region", namespaces.kml))) {
    oneTimeWarning("kml-region", "KML - Placemark Regions are unsupported");
  }
 
  return {
    entity: entity,
    styleEntity: styleEntity,
  };
}
 
function processDocument(dataSource, node, processingData, deferredLoading) {
  deferredLoading.addNodes(node.childNodes, processingData);
  deferredLoading.process();
}
 
function processFolder(dataSource, node, processingData, deferredLoading) {
  const r = processFeature(dataSource, node, processingData);
  const newProcessingData = clone(processingData);
  newProcessingData.parentEntity = r.entity;
  processDocument(dataSource, node, newProcessingData, deferredLoading);
}
 
function processPlacemark(
  dataSource,
  placemark,
  processingData,
  deferredLoading,
) {
  const r = processFeature(dataSource, placemark, processingData);
  const entity = r.entity;
  const styleEntity = r.styleEntity;
 
  let hasGeometry = false;
  const childNodes = placemark.childNodes;
  for (let i = 0, len = childNodes.length; i < len && !hasGeometry; i++) {
    const childNode = childNodes.item(i);
    const geometryProcessor = geometryTypes[childNode.localName];
    if (defined(geometryProcessor)) {
      // pass the placemark entity id as a context for case of defining multiple child entities together to handle case
      // where some malformed kmls reuse the same id across placemarks, which works in GE, but is not technically to spec.
      geometryProcessor(
        dataSource,
        processingData.entityCollection,
        childNode,
        entity,
        styleEntity,
        entity.id,
      );
      hasGeometry = true;
    }
  }
 
  if (!hasGeometry) {
    entity.merge(styleEntity);
    processPositionGraphics(dataSource, entity, styleEntity);
  }
}
 
const playlistNodeProcessors = {
  FlyTo: processTourFlyTo,
  Wait: processTourWait,
  SoundCue: processTourUnsupportedNode,
  AnimatedUpdate: processTourUnsupportedNode,
  TourControl: processTourUnsupportedNode,
};
 
function processTour(dataSource, node, processingData, deferredLoading) {
  const name = queryStringValue(node, "name", namespaces.kml);
  const id = queryStringAttribute(node, "id");
  const tour = new KmlTour(name, id);
 
  const playlistNode = queryFirstNode(node, "Playlist", namespaces.gx);
  Eif (playlistNode) {
    const ellipsoid = dataSource._ellipsoid;
    const childNodes = playlistNode.childNodes;
    for (let i = 0; i < childNodes.length; i++) {
      const entryNode = childNodes[i];
      if (entryNode.localName) {
        const playlistNodeProcessor =
          playlistNodeProcessors[entryNode.localName];
        if (playlistNodeProcessor) {
          playlistNodeProcessor(tour, entryNode, ellipsoid);
        } else E{
          console.log(
            `Unknown KML Tour playlist entry type ${entryNode.localName}`,
          );
        }
      }
    }
  }
 
  dataSource._kmlTours.push(tour);
}
 
function processTourUnsupportedNode(tour, entryNode) {
  oneTimeWarning(`KML Tour unsupported node ${entryNode.localName}`);
}
 
function processTourWait(tour, entryNode) {
  const duration = queryNumericValue(entryNode, "duration", namespaces.gx);
  tour.addPlaylistEntry(new KmlTourWait(duration));
}
 
function processTourFlyTo(tour, entryNode, ellipsoid) {
  const duration = queryNumericValue(entryNode, "duration", namespaces.gx);
  const flyToMode = queryStringValue(entryNode, "flyToMode", namespaces.gx);
 
  const t = { kml: {} };
 
  processLookAt(entryNode, t, ellipsoid);
  processCamera(entryNode, t, ellipsoid);
 
  const view = t.kml.lookAt || t.kml.camera;
 
  const flyto = new KmlTourFlyTo(duration, flyToMode, view);
  tour.addPlaylistEntry(flyto);
}
 
function processCamera(featureNode, entity, ellipsoid) {
  const camera = queryFirstNode(featureNode, "Camera", namespaces.kml);
  if (defined(camera)) {
    const lon = queryNumericValue(camera, "longitude", namespaces.kml) ?? 0.0;
    const lat = queryNumericValue(camera, "latitude", namespaces.kml) ?? 0.0;
    const altitude =
      queryNumericValue(camera, "altitude", namespaces.kml) ?? 0.0;
 
    const heading = queryNumericValue(camera, "heading", namespaces.kml) ?? 0.0;
    const tilt = queryNumericValue(camera, "tilt", namespaces.kml) ?? 0.0;
    const roll = queryNumericValue(camera, "roll", namespaces.kml) ?? 0.0;
 
    const position = Cartesian3.fromDegrees(lon, lat, altitude, ellipsoid);
    const hpr = HeadingPitchRoll.fromDegrees(heading, tilt - 90.0, roll);
 
    entity.kml.camera = new KmlCamera(position, hpr);
  }
}
 
function processLookAt(featureNode, entity, ellipsoid) {
  const lookAt = queryFirstNode(featureNode, "LookAt", namespaces.kml);
  if (defined(lookAt)) {
    const lon = queryNumericValue(lookAt, "longitude", namespaces.kml) ?? 0.0;
    const lat = queryNumericValue(lookAt, "latitude", namespaces.kml) ?? 0.0;
    const altitude =
      queryNumericValue(lookAt, "altitude", namespaces.kml) ?? 0.0;
    let heading = queryNumericValue(lookAt, "heading", namespaces.kml);
    let tilt = queryNumericValue(lookAt, "tilt", namespaces.kml);
    const range = queryNumericValue(lookAt, "range", namespaces.kml) ?? 0.0;
 
    tilt = CesiumMath.toRadians(tilt ?? 0.0);
    heading = CesiumMath.toRadians(heading ?? 0.0);
 
    const hpr = new HeadingPitchRange(
      heading,
      tilt - CesiumMath.PI_OVER_TWO,
      range,
    );
    const viewPoint = Cartesian3.fromDegrees(lon, lat, altitude, ellipsoid);
 
    entity.kml.lookAt = new KmlLookAt(viewPoint, hpr);
  }
}
 
function processScreenOverlay(
  dataSource,
  screenOverlayNode,
  processingData,
  deferredLoading,
) {
  const screenOverlay = processingData.screenOverlayContainer;
  if (!defined(screenOverlay)) {
    return undefined;
  }
 
  const sourceResource = processingData.sourceResource;
  const uriResolver = processingData.uriResolver;
 
  const iconNode = queryFirstNode(screenOverlayNode, "Icon", namespaces.kml);
  const icon = getIconHref(
    iconNode,
    dataSource,
    sourceResource,
    uriResolver,
    false,
  );
 
  Iif (!defined(icon)) {
    return undefined;
  }
 
  const img = document.createElement("img");
  dataSource._screenOverlays.push(img);
 
  img.src = icon.url;
  img.onload = function () {
    const styles = ["position: absolute"];
 
    const screenXY = queryFirstNode(
      screenOverlayNode,
      "screenXY",
      namespaces.kml,
    );
    const overlayXY = queryFirstNode(
      screenOverlayNode,
      "overlayXY",
      namespaces.kml,
    );
    const size = queryFirstNode(screenOverlayNode, "size", namespaces.kml);
 
    let x, y;
    let xUnit, yUnit;
    let xStyle, yStyle;
 
    Eif (defined(size)) {
      x = queryNumericAttribute(size, "x");
      y = queryNumericAttribute(size, "y");
      xUnit = queryStringAttribute(size, "xunits");
      yUnit = queryStringAttribute(size, "yunits");
 
      Iif (defined(x) && x !== -1 && x !== 0) {
        if (xUnit === "fraction") {
          xStyle = `width: ${Math.floor(x * 100)}%`;
        } else if (xUnit === "pixels") {
          xStyle = `width: ${x}px`;
        }
 
        styles.push(xStyle);
      }
 
      Iif (defined(y) && y !== -1 && y !== 0) {
        if (yUnit === "fraction") {
          yStyle = `height: ${Math.floor(y * 100)}%`;
        } else if (yUnit === "pixels") {
          yStyle = `height: ${y}px`;
        }
 
        styles.push(yStyle);
      }
    }
 
    // set the interim style so the width/height properties get calculated
    img.style = styles.join(";");
 
    let xOrigin = 0;
    let yOrigin = img.height;
 
    Eif (defined(overlayXY)) {
      x = queryNumericAttribute(overlayXY, "x");
      y = queryNumericAttribute(overlayXY, "y");
      xUnit = queryStringAttribute(overlayXY, "xunits");
      yUnit = queryStringAttribute(overlayXY, "yunits");
 
      Eif (defined(x)) {
        if (xUnit === "fraction") {
          xOrigin = x * img.width;
        } else if (xUnit === "pixels") {
          xOrigin = x;
        } else Eif (xUnit === "insetPixels") {
          xOrigin = x;
        }
      }
 
      Eif (defined(y)) {
        if (yUnit === "fraction") {
          yOrigin = y * img.height;
        } else if (yUnit === "pixels") {
          yOrigin = y;
        } else Eif (yUnit === "insetPixels") {
          yOrigin = y;
        }
      }
    }
 
    Eif (defined(screenXY)) {
      x = queryNumericAttribute(screenXY, "x");
      y = queryNumericAttribute(screenXY, "y");
      xUnit = queryStringAttribute(screenXY, "xunits");
      yUnit = queryStringAttribute(screenXY, "yunits");
 
      Eif (defined(x)) {
        if (xUnit === "fraction") {
          xStyle = `${"left: " + "calc("}${Math.floor(
            x * 100,
          )}% - ${xOrigin}px)`;
        } else if (xUnit === "pixels") {
          xStyle = `left: ${x - xOrigin}px`;
        } else Eif (xUnit === "insetPixels") {
          xStyle = `right: ${x - xOrigin}px`;
        }
 
        styles.push(xStyle);
      }
 
      Eif (defined(y)) {
        if (yUnit === "fraction") {
          yStyle = `${"bottom: " + "calc("}${Math.floor(
            y * 100,
          )}% - ${yOrigin}px)`;
        } else if (yUnit === "pixels") {
          yStyle = `bottom: ${y - yOrigin}px`;
        } else Eif (yUnit === "insetPixels") {
          yStyle = `top: ${y - yOrigin}px`;
        }
 
        styles.push(yStyle);
      }
    }
 
    img.style = styles.join(";");
  };
 
  screenOverlay.appendChild(img);
}
 
function processGroundOverlay(
  dataSource,
  groundOverlay,
  processingData,
  deferredLoading,
) {
  const r = processFeature(dataSource, groundOverlay, processingData);
  const entity = r.entity;
 
  let geometry;
  let isLatLonQuad = false;
 
  const ellipsoid = dataSource._ellipsoid;
  const positions = readCoordinates(
    queryFirstNode(groundOverlay, "LatLonQuad", namespaces.gx),
    ellipsoid,
  );
  const zIndex = queryNumericValue(groundOverlay, "drawOrder", namespaces.kml);
  if (defined(positions)) {
    geometry = createDefaultPolygon();
    geometry.hierarchy = new PolygonHierarchy(positions);
    geometry.zIndex = zIndex;
    entity.polygon = geometry;
    isLatLonQuad = true;
  } else {
    geometry = new RectangleGraphics();
    geometry.zIndex = zIndex;
    entity.rectangle = geometry;
 
    const latLonBox = queryFirstNode(
      groundOverlay,
      "LatLonBox",
      namespaces.kml,
    );
    if (defined(latLonBox)) {
      let west = queryNumericValue(latLonBox, "west", namespaces.kml);
      let south = queryNumericValue(latLonBox, "south", namespaces.kml);
      let east = queryNumericValue(latLonBox, "east", namespaces.kml);
      let north = queryNumericValue(latLonBox, "north", namespaces.kml);
 
      Eif (defined(west)) {
        west = CesiumMath.negativePiToPi(CesiumMath.toRadians(west));
      }
      Eif (defined(south)) {
        south = CesiumMath.clampToLatitudeRange(CesiumMath.toRadians(south));
      }
      Eif (defined(east)) {
        east = CesiumMath.negativePiToPi(CesiumMath.toRadians(east));
      }
      Eif (defined(north)) {
        north = CesiumMath.clampToLatitudeRange(CesiumMath.toRadians(north));
      }
      geometry.coordinates = new Rectangle(west, south, east, north);
 
      const rotation = queryNumericValue(latLonBox, "rotation", namespaces.kml);
      if (defined(rotation)) {
        const rotationRadians = CesiumMath.toRadians(rotation);
        geometry.rotation = rotationRadians;
        geometry.stRotation = rotationRadians;
      }
    }
  }
 
  const iconNode = queryFirstNode(groundOverlay, "Icon", namespaces.kml);
  const href = getIconHref(
    iconNode,
    dataSource,
    processingData.sourceResource,
    processingData.uriResolver,
    true,
  );
  if (defined(href)) {
    if (isLatLonQuad) {
      oneTimeWarning(
        "kml-gx:LatLonQuad",
        "KML - gx:LatLonQuad Icon does not support texture projection.",
      );
    }
    const x = queryNumericValue(iconNode, "x", namespaces.gx);
    const y = queryNumericValue(iconNode, "y", namespaces.gx);
    const w = queryNumericValue(iconNode, "w", namespaces.gx);
    const h = queryNumericValue(iconNode, "h", namespaces.gx);
 
    if (defined(x) || defined(y) || defined(w) || defined(h)) {
      oneTimeWarning(
        "kml-groundOverlay-xywh",
        "KML - gx:x, gx:y, gx:w, gx:h aren't supported for GroundOverlays",
      );
    }
 
    geometry.material = href;
    geometry.material.color = queryColorValue(
      groundOverlay,
      "color",
      namespaces.kml,
    );
    geometry.material.transparent = true;
  } else {
    geometry.material = queryColorValue(groundOverlay, "color", namespaces.kml);
  }
 
  let altitudeMode = queryStringValue(
    groundOverlay,
    "altitudeMode",
    namespaces.kml,
  );
 
  if (defined(altitudeMode)) {
    if (altitudeMode === "absolute") {
      //Use height above ellipsoid until we support MSL.
      geometry.height = queryNumericValue(
        groundOverlay,
        "altitude",
        namespaces.kml,
      );
      geometry.zIndex = undefined;
    } else Eif (altitudeMode !== "clampToGround") {
      oneTimeWarning(
        "kml-altitudeMode-unknown",
        `KML - Unknown altitudeMode: ${altitudeMode}`,
      );
    }
    // else just use the default of 0 until we support 'clampToGround'
  } else {
    altitudeMode = queryStringValue(
      groundOverlay,
      "altitudeMode",
      namespaces.gx,
    );
    Iif (altitudeMode === "relativeToSeaFloor") {
      oneTimeWarning(
        "kml-altitudeMode-relativeToSeaFloor",
        "KML - altitudeMode relativeToSeaFloor is currently not supported, treating as absolute.",
      );
      geometry.height = queryNumericValue(
        groundOverlay,
        "altitude",
        namespaces.kml,
      );
      geometry.zIndex = undefined;
    } else Iif (altitudeMode === "clampToSeaFloor") {
      oneTimeWarning(
        "kml-altitudeMode-clampToSeaFloor",
        "KML - altitudeMode clampToSeaFloor is currently not supported, treating as clampToGround.",
      );
    } else Iif (defined(altitudeMode)) {
      oneTimeWarning(
        "kml-altitudeMode-unknown",
        `KML - Unknown altitudeMode: ${altitudeMode}`,
      );
    }
  }
}
 
function processUnsupportedFeature(
  dataSource,
  node,
  processingData,
  deferredLoading,
) {
  dataSource._unsupportedNode.raiseEvent(
    dataSource,
    processingData.parentEntity,
    node,
    processingData.entityCollection,
    processingData.styleCollection,
    processingData.sourceResource,
    processingData.uriResolver,
  );
  oneTimeWarning(
    `kml-unsupportedFeature-${node.nodeName}`,
    `KML - Unsupported feature: ${node.nodeName}`,
  );
}
 
const RefreshMode = {
  INTERVAL: 0,
  EXPIRE: 1,
  STOP: 2,
};
 
function cleanupString(s) {
  if (!defined(s) || s.length === 0) {
    return "";
  }
 
  const sFirst = s[0];
  if (sFirst === "&" || sFirst === "?") {
    s = s.substring(1);
  }
 
  return s;
}
 
const zeroRectangle = new Rectangle();
const scratchCartographic = new Cartographic();
const scratchCartesian2 = new Cartesian2();
const scratchCartesian3 = new Cartesian3();
 
function processNetworkLinkQueryString(
  resource,
  camera,
  canvas,
  viewBoundScale,
  bbox,
  ellipsoid,
) {
  function fixLatitude(value) {
    if (value < -CesiumMath.PI_OVER_TWO) {
      return -CesiumMath.PI_OVER_TWO;
    } else if (value > CesiumMath.PI_OVER_TWO) {
      return CesiumMath.PI_OVER_TWO;
    }
    return value;
  }
 
  function fixLongitude(value) {
    if (value > CesiumMath.PI) {
      return value - CesiumMath.TWO_PI;
    } else if (value < -CesiumMath.PI) {
      return value + CesiumMath.TWO_PI;
    }
 
    return value;
  }
 
  let queryString = objectToQuery(resource.queryParameters);
 
  // objectToQuery escapes [ and ], so fix that
  queryString = queryString.replace(/%5B/g, "[").replace(/%5D/g, "]");
 
  if (defined(camera) && camera._mode !== SceneMode.MORPHING) {
    let centerCartesian;
    let centerCartographic;
 
    bbox = bbox ?? zeroRectangle;
    Eif (defined(canvas)) {
      scratchCartesian2.x = canvas.clientWidth * 0.5;
      scratchCartesian2.y = canvas.clientHeight * 0.5;
      centerCartesian = camera.pickEllipsoid(
        scratchCartesian2,
        ellipsoid,
        scratchCartesian3,
      );
    }
 
    Iif (defined(centerCartesian)) {
      centerCartographic = ellipsoid.cartesianToCartographic(
        centerCartesian,
        scratchCartographic,
      );
    } else {
      centerCartographic = Rectangle.center(bbox, scratchCartographic);
      centerCartesian = ellipsoid.cartographicToCartesian(centerCartographic);
    }
 
    Iif (
      defined(viewBoundScale) &&
      !CesiumMath.equalsEpsilon(viewBoundScale, 1.0, CesiumMath.EPSILON9)
    ) {
      const newHalfWidth = bbox.width * viewBoundScale * 0.5;
      const newHalfHeight = bbox.height * viewBoundScale * 0.5;
      bbox = new Rectangle(
        fixLongitude(centerCartographic.longitude - newHalfWidth),
        fixLatitude(centerCartographic.latitude - newHalfHeight),
        fixLongitude(centerCartographic.longitude + newHalfWidth),
        fixLatitude(centerCartographic.latitude + newHalfHeight),
      );
    }
 
    queryString = queryString.replace(
      "[bboxWest]",
      CesiumMath.toDegrees(bbox.west).toString(),
    );
    queryString = queryString.replace(
      "[bboxSouth]",
      CesiumMath.toDegrees(bbox.south).toString(),
    );
    queryString = queryString.replace(
      "[bboxEast]",
      CesiumMath.toDegrees(bbox.east).toString(),
    );
    queryString = queryString.replace(
      "[bboxNorth]",
      CesiumMath.toDegrees(bbox.north).toString(),
    );
 
    const lon = CesiumMath.toDegrees(centerCartographic.longitude).toString();
    const lat = CesiumMath.toDegrees(centerCartographic.latitude).toString();
    queryString = queryString.replace("[lookatLon]", lon);
    queryString = queryString.replace("[lookatLat]", lat);
    queryString = queryString.replace(
      "[lookatTilt]",
      CesiumMath.toDegrees(camera.pitch).toString(),
    );
    queryString = queryString.replace(
      "[lookatHeading]",
      CesiumMath.toDegrees(camera.heading).toString(),
    );
    queryString = queryString.replace(
      "[lookatRange]",
      Cartesian3.distance(camera.positionWC, centerCartesian),
    );
    queryString = queryString.replace("[lookatTerrainLon]", lon);
    queryString = queryString.replace("[lookatTerrainLat]", lat);
    queryString = queryString.replace(
      "[lookatTerrainAlt]",
      centerCartographic.height.toString(),
    );
 
    ellipsoid.cartesianToCartographic(camera.positionWC, scratchCartographic);
    queryString = queryString.replace(
      "[cameraLon]",
      CesiumMath.toDegrees(scratchCartographic.longitude).toString(),
    );
    queryString = queryString.replace(
      "[cameraLat]",
      CesiumMath.toDegrees(scratchCartographic.latitude).toString(),
    );
    queryString = queryString.replace(
      "[cameraAlt]",
      CesiumMath.toDegrees(scratchCartographic.height).toString(),
    );
 
    const frustum = camera.frustum;
    const aspectRatio = frustum.aspectRatio;
    let horizFov = "";
    let vertFov = "";
    Eif (defined(aspectRatio)) {
      const fov = CesiumMath.toDegrees(frustum.fov);
      Iif (aspectRatio > 1.0) {
        horizFov = fov;
        vertFov = fov / aspectRatio;
      } else {
        vertFov = fov;
        horizFov = fov * aspectRatio;
      }
    }
    queryString = queryString.replace("[horizFov]", horizFov.toString());
    queryString = queryString.replace("[vertFov]", vertFov.toString());
  } else {
    queryString = queryString.replace("[bboxWest]", "-180");
    queryString = queryString.replace("[bboxSouth]", "-90");
    queryString = queryString.replace("[bboxEast]", "180");
    queryString = queryString.replace("[bboxNorth]", "90");
 
    queryString = queryString.replace("[lookatLon]", "");
    queryString = queryString.replace("[lookatLat]", "");
    queryString = queryString.replace("[lookatRange]", "");
    queryString = queryString.replace("[lookatTilt]", "");
    queryString = queryString.replace("[lookatHeading]", "");
    queryString = queryString.replace("[lookatTerrainLon]", "");
    queryString = queryString.replace("[lookatTerrainLat]", "");
    queryString = queryString.replace("[lookatTerrainAlt]", "");
 
    queryString = queryString.replace("[cameraLon]", "");
    queryString = queryString.replace("[cameraLat]", "");
    queryString = queryString.replace("[cameraAlt]", "");
    queryString = queryString.replace("[horizFov]", "");
    queryString = queryString.replace("[vertFov]", "");
  }
 
  if (defined(canvas)) {
    queryString = queryString.replace("[horizPixels]", canvas.clientWidth);
    queryString = queryString.replace("[vertPixels]", canvas.clientHeight);
  } else {
    queryString = queryString.replace("[horizPixels]", "");
    queryString = queryString.replace("[vertPixels]", "");
  }
 
  queryString = queryString.replace("[terrainEnabled]", "1");
  queryString = queryString.replace("[clientVersion]", "1");
  queryString = queryString.replace("[kmlVersion]", "2.2");
  queryString = queryString.replace("[clientName]", "Cesium");
  queryString = queryString.replace("[language]", "English");
 
  resource.setQueryParameters(queryToObject(queryString));
}
 
function processNetworkLink(dataSource, node, processingData, deferredLoading) {
  const r = processFeature(dataSource, node, processingData);
  const networkEntity = r.entity;
 
  const sourceResource = processingData.sourceResource;
  const uriResolver = processingData.uriResolver;
 
  let link = queryFirstNode(node, "Link", namespaces.kml);
 
  if (!defined(link)) {
    link = queryFirstNode(node, "Url", namespaces.kml);
  }
  Eif (defined(link)) {
    let href = queryStringValue(link, "href", namespaces.kml);
    let viewRefreshMode;
    let viewBoundScale;
    Eif (defined(href)) {
      let newSourceUri = href;
      href = resolveHref(href, sourceResource, processingData.uriResolver);
 
      // We need to pass in the original path if resolveHref returns a data uri because the network link
      //  references a document in a KMZ archive
      if (/^data:/.test(href.getUrlComponent())) {
        // So if sourceUri isn't the kmz file, then its another kml in the archive, so resolve it
        if (!/\.kmz/i.test(sourceResource.getUrlComponent())) {
          newSourceUri = sourceResource.getDerivedResource({
            url: newSourceUri,
          });
        }
      } else {
        newSourceUri = href.clone(); // Not a data uri so use the fully qualified uri
        viewRefreshMode = queryStringValue(
          link,
          "viewRefreshMode",
          namespaces.kml,
        );
        if (viewRefreshMode === "onRegion") {
          oneTimeWarning(
            "kml-refrehMode-onRegion",
            "KML - Unsupported viewRefreshMode: onRegion",
          );
          return;
        }
        viewBoundScale =
          queryStringValue(link, "viewBoundScale", namespaces.kml) ?? 1.0;
        const defaultViewFormat =
          viewRefreshMode === "onStop"
            ? "BBOX=[bboxWest],[bboxSouth],[bboxEast],[bboxNorth]"
            : "";
        const viewFormat =
          queryStringValue(link, "viewFormat", namespaces.kml) ??
          defaultViewFormat;
        const httpQuery = queryStringValue(link, "httpQuery", namespaces.kml);
        Eif (defined(viewFormat)) {
          href.setQueryParameters(queryToObject(cleanupString(viewFormat)));
        }
        if (defined(httpQuery)) {
          href.setQueryParameters(queryToObject(cleanupString(httpQuery)));
        }
 
        const ellipsoid = dataSource._ellipsoid;
        processNetworkLinkQueryString(
          href,
          dataSource.camera,
          dataSource.canvas,
          viewBoundScale,
          dataSource._lastCameraView.bbox,
          ellipsoid,
        );
      }
 
      const options = {
        sourceUri: newSourceUri,
        uriResolver: uriResolver,
        context: networkEntity.id,
        screenOverlayContainer: processingData.screenOverlayContainer,
      };
      const networkLinkCollection = new EntityCollection();
      const promise = load(dataSource, networkLinkCollection, href, options)
        .then(function (rootElement) {
          const entities = dataSource._entityCollection;
          const newEntities = networkLinkCollection.values;
          entities.suspendEvents();
          for (let i = 0; i < newEntities.length; i++) {
            const newEntity = newEntities[i];
            if (!defined(newEntity.parent)) {
              newEntity.parent = networkEntity;
              mergeAvailabilityWithParent(newEntity);
            }
 
            entities.add(newEntity);
          }
          entities.resumeEvents();
 
          // Add network links to a list if we need they will need to be updated
          const refreshMode = queryStringValue(
            link,
            "refreshMode",
            namespaces.kml,
          );
          let refreshInterval =
            queryNumericValue(link, "refreshInterval", namespaces.kml) ?? 0;
          if (
            (refreshMode === "onInterval" && refreshInterval > 0) ||
            refreshMode === "onExpire" ||
            viewRefreshMode === "onStop"
          ) {
            const networkLinkControl = queryFirstNode(
              rootElement,
              "NetworkLinkControl",
              namespaces.kml,
            );
            const hasNetworkLinkControl = defined(networkLinkControl);
 
            const now = JulianDate.now();
            const networkLinkInfo = {
              id: createGuid(),
              href: href,
              cookie: {},
              lastUpdated: now,
              updating: false,
              entity: networkEntity,
              viewBoundScale: viewBoundScale,
              needsUpdate: false,
              cameraUpdateTime: now,
            };
 
            let minRefreshPeriod = 0;
            if (hasNetworkLinkControl) {
              networkLinkInfo.cookie = queryToObject(
                queryStringValue(
                  networkLinkControl,
                  "cookie",
                  namespaces.kml,
                ) ?? "",
              );
              minRefreshPeriod =
                queryNumericValue(
                  networkLinkControl,
                  "minRefreshPeriod",
                  namespaces.kml,
                ) ?? 0;
            }
 
            if (refreshMode === "onInterval") {
              Eif (hasNetworkLinkControl) {
                refreshInterval = Math.max(minRefreshPeriod, refreshInterval);
              }
              networkLinkInfo.refreshMode = RefreshMode.INTERVAL;
              networkLinkInfo.time = refreshInterval;
            } else if (refreshMode === "onExpire") {
              let expires;
              if (hasNetworkLinkControl) {
                expires = queryStringValue(
                  networkLinkControl,
                  "expires",
                  namespaces.kml,
                );
              }
              if (defined(expires)) {
                try {
                  const date = JulianDate.fromIso8601(expires);
                  const diff = JulianDate.secondsDifference(date, now);
                  Iif (diff > 0 && diff < minRefreshPeriod) {
                    JulianDate.addSeconds(now, minRefreshPeriod, date);
                  }
                  networkLinkInfo.refreshMode = RefreshMode.EXPIRE;
                  networkLinkInfo.time = date;
                } catch (e) {
                  oneTimeWarning(
                    "kml-refreshMode-onInterval-onExpire",
                    "KML - NetworkLinkControl expires is not a valid date",
                  );
                }
              } else {
                oneTimeWarning(
                  "kml-refreshMode-onExpire",
                  "KML - refreshMode of onExpire requires the NetworkLinkControl to have an expires element",
                );
              }
            } else if (defined(dataSource.camera)) {
              // Only allow onStop refreshes if we have a camera
              networkLinkInfo.refreshMode = RefreshMode.STOP;
              networkLinkInfo.time =
                queryNumericValue(link, "viewRefreshTime", namespaces.kml) ?? 0;
            } else E{
              oneTimeWarning(
                "kml-refrehMode-onStop-noCamera",
                "A NetworkLink with viewRefreshMode=onStop requires the `camera` property to be defined.",
              );
            }
 
            if (defined(networkLinkInfo.refreshMode)) {
              dataSource._networkLinks.set(networkLinkInfo.id, networkLinkInfo);
            }
          }
        })
        .catch(function (error) {
          oneTimeWarning(`An error occured during loading ${href.url}`);
          dataSource._error.raiseEvent(dataSource, error);
        });
 
      deferredLoading.addPromise(promise);
    }
  }
}
 
function processFeatureNode(dataSource, node, processingData, deferredLoading) {
  const featureProcessor = featureTypes[node.localName];
  Eif (defined(featureProcessor)) {
    return featureProcessor(dataSource, node, processingData, deferredLoading);
  }
 
  return processUnsupportedFeature(
    dataSource,
    node,
    processingData,
    deferredLoading,
  );
}
 
function loadKml(
  dataSource,
  entityCollection,
  kml,
  sourceResource,
  uriResolver,
  screenOverlayContainer,
  context,
) {
  entityCollection.removeAll();
 
  const documentElement = kml.documentElement;
  const document =
    documentElement.localName === "Document"
      ? documentElement
      : queryFirstNode(documentElement, "Document", namespaces.kml);
  let name = queryStringValue(document, "name", namespaces.kml);
  if (!defined(name)) {
    name = getFilenameFromUri(sourceResource.getUrlComponent());
  }
 
  // Only set the name from the root document
  if (!defined(dataSource._name)) {
    dataSource._name = name;
  }
 
  const deferredLoading = new KmlDataSource._DeferredLoading(dataSource);
  const styleCollection = new EntityCollection(dataSource);
  return Promise.all(
    processStyles(
      dataSource,
      kml,
      styleCollection,
      sourceResource,
      false,
      uriResolver,
    ),
  ).then(function () {
    let element = kml.documentElement;
    if (element.localName === "kml") {
      const childNodes = element.childNodes;
      for (let i = 0; i < childNodes.length; i++) {
        const tmp = childNodes[i];
        if (defined(featureTypes[tmp.localName])) {
          element = tmp;
          break;
        }
      }
    }
 
    const processingData = {
      parentEntity: undefined,
      entityCollection: entityCollection,
      styleCollection: styleCollection,
      sourceResource: sourceResource,
      uriResolver: uriResolver,
      context: context,
      screenOverlayContainer: screenOverlayContainer,
    };
 
    entityCollection.suspendEvents();
    processFeatureNode(dataSource, element, processingData, deferredLoading);
    entityCollection.resumeEvents();
 
    return deferredLoading.wait().then(function () {
      return kml.documentElement;
    });
  });
}
 
async function loadKmz(
  dataSource,
  entityCollection,
  blob,
  sourceResource,
  screenOverlayContainer,
) {
  const zWorkerUri = buildModuleUrl("ThirdParty/Workers/zip-web-worker.js");
  const zWasmUri = buildModuleUrl("ThirdParty/zip-module.wasm");
  configure({
    workerURI: zWorkerUri,
    wasmURI: zWasmUri,
  });
 
  const reader = new ZipReader(new BlobReader(blob));
  const entries = await reader.getEntries();
 
  const promises = [];
  const uriResolver = {};
  let docEntry;
  for (let i = 0; i < entries.length; i++) {
    const entry = entries[i];
    if (!entry.directory) {
      if (/\.kml$/i.test(entry.filename)) {
        // We use the first KML document we come across
        //  https://developers.google.com/kml/documentation/kmzarchives
        // Unless we come across a .kml file at the root of the archive because GE does this
        if (!defined(docEntry) || !/\//i.test(entry.filename)) {
          Iif (defined(docEntry)) {
            // We found one at the root so load the initial kml as a data uri
            promises.push(loadDataUriFromZip(docEntry, uriResolver));
          }
          docEntry = entry;
        } else {
          // Wasn't the first kml and wasn't at the root
          promises.push(loadDataUriFromZip(entry, uriResolver));
        }
      } else {
        promises.push(loadDataUriFromZip(entry, uriResolver));
      }
    }
  }
 
  // Now load the root KML document
  if (defined(docEntry)) {
    promises.push(loadXmlFromZip(docEntry, uriResolver));
  }
  await Promise.all(promises);
  reader.close();
  if (!defined(uriResolver.kml)) {
    throw new RuntimeError("KMZ file does not contain a KML document.");
  }
  uriResolver.keys = Object.keys(uriResolver);
 
  return loadKml(
    dataSource,
    entityCollection,
    uriResolver.kml,
    sourceResource,
    uriResolver,
    screenOverlayContainer,
  );
}
 
function load(dataSource, entityCollection, data, options) {
  options = options ?? Frozen.EMPTY_OBJECT;
  let sourceUri = options.sourceUri;
  const uriResolver = options.uriResolver;
  const context = options.context;
  let screenOverlayContainer = options.screenOverlayContainer;
 
  let promise = data;
  if (typeof data === "string" || data instanceof Resource) {
    data = Resource.createIfNeeded(data);
    promise = data.fetchBlob();
    sourceUri = sourceUri ?? data.clone();
 
    // Add resource credits to our list of credits to display
    const resourceCredits = dataSource._resourceCredits;
    const credits = data.credits;
    Iif (defined(credits)) {
      const length = credits.length;
      for (let i = 0; i < length; i++) {
        resourceCredits.push(credits[i]);
      }
    }
  } else {
    sourceUri = sourceUri ?? Resource.DEFAULT.clone();
  }
 
  sourceUri = Resource.createIfNeeded(sourceUri);
 
  if (defined(screenOverlayContainer)) {
    screenOverlayContainer = getElement(screenOverlayContainer);
  }
 
  return Promise.resolve(promise)
    .then(function (dataToLoad) {
      if (dataToLoad instanceof Blob) {
        return isZipFile(dataToLoad).then(function (isZip) {
          if (isZip) {
            return loadKmz(
              dataSource,
              entityCollection,
              dataToLoad,
              sourceUri,
              screenOverlayContainer,
            );
          }
          return readBlobAsText(dataToLoad).then(function (text) {
            //There's no official way to validate if a parse was successful.
            //The following check detects the error on various browsers.
 
            //Insert missing namespaces
            text = insertNamespaces(text);
 
            //Remove Duplicate Namespaces
            text = removeDuplicateNamespaces(text);
 
            //IE raises an exception
            let kml;
            let error;
            try {
              kml = parser.parseFromString(text, "application/xml");
            } catch (e) {
              error = e.toString();
            }
 
            //The parse succeeds on Chrome and Firefox, but the error
            //handling is different in each.
            if (
              defined(error) ||
              kml.body ||
              kml.documentElement.tagName === "parsererror"
            ) {
              //Firefox has error information as the firstChild nodeValue.
              let msg = defined(error)
                ? error
                : kml.documentElement.firstChild.nodeValue;
 
              //Chrome has it in the body text.
              Iif (!msg) {
                msg = kml.body.innerText;
              }
 
              //Return the error
              throw new RuntimeError(msg);
            }
            return loadKml(
              dataSource,
              entityCollection,
              kml,
              sourceUri,
              uriResolver,
              screenOverlayContainer,
              context,
            );
          });
        });
      }
      return loadKml(
        dataSource,
        entityCollection,
        dataToLoad,
        sourceUri,
        uriResolver,
        screenOverlayContainer,
        context,
      );
    })
    .catch(function (error) {
      dataSource._error.raiseEvent(dataSource, error);
      console.log(error);
      return Promise.reject(error);
    });
}
 
// NOTE: LoadOptions properties are repeated in ConstructorOptions because some
// tooling does not support "base types" for @typedef.  Remove if/when
// https://github.com/microsoft/TypeScript/issues/20077 and/or
// https://github.com/jsdoc/jsdoc/issues/1199 actually get resolved
/**
 * @typedef {object} KmlDataSource.LoadOptions
 *
 * Initialization options for the `load` method.
 *
 * @property {string} [sourceUri] Overrides the url to use for resolving relative links and other KML network features.
 * @property {boolean} [clampToGround=false] true if we want the geometry features (Polygons, LineStrings and LinearRings) clamped to the ground.
 * @property {Ellipsoid} [ellipsoid=Ellipsoid.default] The global ellipsoid used for geographical calculations.
 * @property {Element|string} [screenOverlayContainer] A container for ScreenOverlay images.
 */
 
/**
 * @typedef {object} KmlDataSource.ConstructorOptions
 *
 * Options for constructing a new KmlDataSource, or calling the static `load` method.
 *
 * @property {Camera} [camera] The camera that is used for viewRefreshModes and sending camera properties to network links.
 * @property {HTMLCanvasElement} [canvas] The canvas that is used for sending viewer properties to network links.
 * @property {Credit|string} [credit] A credit for the data source, which is displayed on the canvas.
 *
 * @property {string} [sourceUri] Overrides the url to use for resolving relative links and other KML network features.
 * @property {boolean} [clampToGround=false] true if we want the geometry features (Polygons, LineStrings and LinearRings) clamped to the ground.
 * @property {Ellipsoid} [ellipsoid=Ellipsoid.default] The global ellipsoid used for geographical calculations.
 * @property {Element|string} [screenOverlayContainer] A container for ScreenOverlay images.
 
*/
 
/**
 * A {@link DataSource} which processes Keyhole Markup Language 2.2 (KML).
 * <p>
 * KML support in Cesium is incomplete, but a large amount of the standard,
 * as well as Google's <code>gx</code> extension namespace, is supported. See Github issue
 * {@link https://github.com/CesiumGS/cesium/issues/873|#873} for a
 * detailed list of what is and isn't supported. Cesium will also write information to the
 * console when it encounters most unsupported features.
 * </p>
 * <p>
 * Non visual feature data, such as <code>atom:author</code> and <code>ExtendedData</code>
 * is exposed via an instance of {@link KmlFeatureData}, which is added to each {@link Entity}
 * under the <code>kml</code> property.
 * </p>
 *
 * @alias KmlDataSource
 * @constructor
 *
 * @param {KmlDataSource.ConstructorOptions} [options] Object describing initialization options
 *
 * @see {@link http://www.opengeospatial.org/standards/kml/|Open Geospatial Consortium KML Standard}
 * @see {@link https://developers.google.com/kml/|Google KML Documentation}
 *
 * @demo {@link https://sandcastle.cesium.com/index.html?src=KML.html|Cesium Sandcastle KML Demo}
 *
 * @example
 * const viewer = new Cesium.Viewer('cesiumContainer');
 * viewer.dataSources.add(Cesium.KmlDataSource.load('../../SampleData/facilities.kmz',
 *      {
 *           camera: viewer.scene.camera,
 *           canvas: viewer.scene.canvas
 *      })
 * );
 */
function KmlDataSource(options) {
  options = options ?? Frozen.EMPTY_OBJECT;
  const camera = options.camera;
  const canvas = options.canvas;
 
  this._changed = new Event();
  this._error = new Event();
  this._loading = new Event();
  this._refresh = new Event();
  this._unsupportedNode = new Event();
 
  this._clock = undefined;
  this._entityCollection = new EntityCollection(this);
  this._name = undefined;
  this._isLoading = false;
  this._pinBuilder = new PinBuilder();
  this._networkLinks = new AssociativeArray();
  this._entityCluster = new EntityCluster();
 
  /**
   * The current size of this Canvas will be used to populate the Link parameters
   * for client height and width.
   *
   * @type {HTMLCanvasElement | undefined}
   */
  this.canvas = canvas;
 
  /**
   * The position and orientation of this {@link Camera} will be used to
   * populate various camera parameters when making network requests.
   * Camera movement will determine when to trigger NetworkLink refresh if
   * <code>viewRefreshMode</code> is <code>onStop</code>.
   *
   * @type {Camera | undefined}
   */
  this.camera = camera;
 
  this._lastCameraView = {
    position: defined(camera) ? Cartesian3.clone(camera.positionWC) : undefined,
    direction: defined(camera)
      ? Cartesian3.clone(camera.directionWC)
      : undefined,
    up: defined(camera) ? Cartesian3.clone(camera.upWC) : undefined,
    bbox: defined(camera)
      ? camera.computeViewRectangle()
      : Rectangle.clone(Rectangle.MAX_VALUE),
  };
 
  this._ellipsoid = options.ellipsoid ?? Ellipsoid.default;
 
  // User specified credit
  let credit = options.credit;
  if (typeof credit === "string") {
    credit = new Credit(credit);
  }
  this._credit = credit;
 
  // Create a list of Credit's from the resource that the user can't remove
  this._resourceCredits = [];
 
  this._kmlTours = [];
 
  this._screenOverlays = [];
}
 
/**
 * Creates a Promise to a new instance loaded with the provided KML data.
 *
 * @param {Resource|string|Document|Blob} data A url, parsed KML document, or Blob containing binary KMZ data or a parsed KML document.
 * @param {KmlDataSource.ConstructorOptions} [options] An object specifying configuration options
 *
 * @returns {Promise<KmlDataSource>} A promise that will resolve to a new KmlDataSource instance once the KML is loaded.
 */
KmlDataSource.load = function (data, options) {
  options = options ?? Frozen.EMPTY_OBJECT;
  const dataSource = new KmlDataSource(options);
  return dataSource.load(data, options);
};
 
Object.defineProperties(KmlDataSource.prototype, {
  /**
   * Gets or sets a human-readable name for this instance.
   * This will be automatically be set to the KML document name on load.
   * @memberof KmlDataSource.prototype
   * @type {string}
   */
  name: {
    get: function () {
      return this._name;
    },
    set: function (value) {
      Eif (this._name !== value) {
        this._name = value;
        this._changed.raiseEvent(this);
      }
    },
  },
  /**
   * Gets the clock settings defined by the loaded KML. This represents the total
   * availability interval for all time-dynamic data. If the KML does not contain
   * time-dynamic data, this value is undefined.
   * @memberof KmlDataSource.prototype
   * @type {DataSourceClock}
   */
  clock: {
    get: function () {
      return this._clock;
    },
  },
  /**
   * Gets the collection of {@link Entity} instances.
   * @memberof KmlDataSource.prototype
   * @type {EntityCollection}
   */
  entities: {
    get: function () {
      return this._entityCollection;
    },
  },
  /**
   * Gets a value indicating if the data source is currently loading data.
   * @memberof KmlDataSource.prototype
   * @type {boolean}
   */
  isLoading: {
    get: function () {
      return this._isLoading;
    },
  },
  /**
   * Gets an event that will be raised when the underlying data changes.
   * @memberof KmlDataSource.prototype
   * @type {Event}
   */
  changedEvent: {
    get: function () {
      return this._changed;
    },
  },
  /**
   * Gets an event that will be raised if an error is encountered during processing.
   * @memberof KmlDataSource.prototype
   * @type {Event}
   */
  errorEvent: {
    get: function () {
      return this._error;
    },
  },
  /**
   * Gets an event that will be raised when the data source either starts or stops loading.
   * @memberof KmlDataSource.prototype
   * @type {Event}
   */
  loadingEvent: {
    get: function () {
      return this._loading;
    },
  },
  /**
   * Gets an event that will be raised when the data source refreshes a network link.
   * @memberof KmlDataSource.prototype
   * @type {Event}
   */
  refreshEvent: {
    get: function () {
      return this._refresh;
    },
  },
  /**
   * Gets an event that will be raised when the data source finds an unsupported node type.
   * @memberof KmlDataSource.prototype
   * @type {Event}
   */
  unsupportedNodeEvent: {
    get: function () {
      return this._unsupportedNode;
    },
  },
  /**
   * Gets whether or not this data source should be displayed.
   * @memberof KmlDataSource.prototype
   * @type {boolean}
   */
  show: {
    get: function () {
      return this._entityCollection.show;
    },
    set: function (value) {
      this._entityCollection.show = value;
    },
  },
 
  /**
   * Gets or sets the clustering options for this data source. This object can be shared between multiple data sources.
   *
   * @memberof KmlDataSource.prototype
   * @type {EntityCluster}
   */
  clustering: {
    get: function () {
      return this._entityCluster;
    },
    set: function (value) {
      //>>includeStart('debug', pragmas.debug);
      if (!defined(value)) {
        throw new DeveloperError("value must be defined.");
      }
      //>>includeEnd('debug');
      this._entityCluster = value;
    },
  },
  /**
   * Gets the credit that will be displayed for the data source
   * @memberof KmlDataSource.prototype
   * @type {Credit}
   */
  credit: {
    get: function () {
      return this._credit;
    },
  },
  /**
   * Gets the KML Tours that are used to guide the camera to specified destinations on given time intervals.
   * @memberof KmlDataSource.prototype
   * @type {KmlTour[]}
   */
  kmlTours: {
    get: function () {
      return this._kmlTours;
    },
  },
});
 
/**
 * Asynchronously loads the provided KML data, replacing any existing data.
 *
 * @param {Resource|string|Document|Blob} data A url, parsed KML document, or Blob containing binary KMZ data or a parsed KML document.
 * @param {KmlDataSource.LoadOptions} [options] An object specifying configuration options
 *
 * @returns {Promise<KmlDataSource>} A promise that will resolve to this instances once the KML is loaded.
 */
KmlDataSource.prototype.load = function (data, options) {
  //>>includeStart('debug', pragmas.debug);
  if (!defined(data)) {
    throw new DeveloperError("data is required.");
  }
  //>>includeEnd('debug');
 
  options = options ?? Frozen.EMPTY_OBJECT;
  DataSource.setLoading(this, true);
 
  const oldName = this._name;
  this._name = undefined;
  this._clampToGround = options.clampToGround ?? false;
 
  const that = this;
  return load(this, this._entityCollection, data, options)
    .then(function () {
      let clock;
 
      const availability = that._entityCollection.computeAvailability();
 
      let start = availability.start;
      let stop = availability.stop;
      const isMinStart = JulianDate.equals(start, Iso8601.MINIMUM_VALUE);
      const isMaxStop = JulianDate.equals(stop, Iso8601.MAXIMUM_VALUE);
      if (!isMinStart || !isMaxStop) {
        let date;
 
        //If start is min time just start at midnight this morning, local time
        if (isMinStart) {
          date = new Date();
          date.setHours(0, 0, 0, 0);
          start = JulianDate.fromDate(date);
        }
 
        //If stop is max value just stop at midnight tonight, local time
        if (isMaxStop) {
          date = new Date();
          date.setHours(24, 0, 0, 0);
          stop = JulianDate.fromDate(date);
        }
 
        clock = new DataSourceClock();
        clock.startTime = start;
        clock.stopTime = stop;
        clock.currentTime = JulianDate.clone(start);
        clock.clockRange = ClockRange.LOOP_STOP;
        clock.clockStep = ClockStep.SYSTEM_CLOCK_MULTIPLIER;
        clock.multiplier = Math.round(
          Math.min(
            Math.max(JulianDate.secondsDifference(stop, start) / 60, 1),
            3.15569e7,
          ),
        );
      }
 
      let changed = false;
      if (clock !== that._clock) {
        that._clock = clock;
        changed = true;
      }
 
      if (oldName !== that._name) {
        changed = true;
      }
 
      if (changed) {
        that._changed.raiseEvent(that);
      }
 
      DataSource.setLoading(that, false);
 
      return that;
    })
    .catch(function (error) {
      DataSource.setLoading(that, false);
      that._error.raiseEvent(that, error);
      console.log(error);
      return Promise.reject(error);
    });
};
 
/**
 * Cleans up any non-entity elements created by the data source. Currently this only affects ScreenOverlay elements.
 */
KmlDataSource.prototype.destroy = function () {
  while (this._screenOverlays.length > 0) {
    const elem = this._screenOverlays.pop();
    elem.remove();
  }
};
 
function mergeAvailabilityWithParent(child) {
  const parent = child.parent;
  if (defined(parent)) {
    const parentAvailability = parent.availability;
    if (defined(parentAvailability)) {
      const childAvailability = child.availability;
      if (defined(childAvailability)) {
        childAvailability.intersect(parentAvailability);
      } else {
        child.availability = parentAvailability;
      }
    }
  }
}
 
function getNetworkLinkUpdateCallback(
  dataSource,
  networkLink,
  newEntityCollection,
  networkLinks,
  processedHref,
) {
  return function (rootElement) {
    Iif (!networkLinks.contains(networkLink.id)) {
      // Got into the odd case where a parent network link was updated while a child
      //  network link update was in flight, so just throw it away.
      return;
    }
    let remove = false;
    const networkLinkControl = queryFirstNode(
      rootElement,
      "NetworkLinkControl",
      namespaces.kml,
    );
    const hasNetworkLinkControl = defined(networkLinkControl);
 
    let minRefreshPeriod = 0;
    Eif (hasNetworkLinkControl) {
      Iif (
        defined(queryFirstNode(networkLinkControl, "Update", namespaces.kml))
      ) {
        oneTimeWarning(
          "kml-networkLinkControl-update",
          "KML - NetworkLinkControl updates aren't supported.",
        );
        networkLink.updating = false;
        networkLinks.remove(networkLink.id);
        return;
      }
      networkLink.cookie = queryToObject(
        queryStringValue(networkLinkControl, "cookie", namespaces.kml) ?? "",
      );
      minRefreshPeriod =
        queryNumericValue(
          networkLinkControl,
          "minRefreshPeriod",
          namespaces.kml,
        ) ?? 0;
    }
 
    const now = JulianDate.now();
    const refreshMode = networkLink.refreshMode;
    if (refreshMode === RefreshMode.INTERVAL) {
      Eif (defined(networkLinkControl)) {
        networkLink.time = Math.max(minRefreshPeriod, networkLink.time);
      }
    } else if (refreshMode === RefreshMode.EXPIRE) {
      let expires;
      Eif (defined(networkLinkControl)) {
        expires = queryStringValue(
          networkLinkControl,
          "expires",
          namespaces.kml,
        );
      }
      if (defined(expires)) {
        try {
          const date = JulianDate.fromIso8601(expires);
          const diff = JulianDate.secondsDifference(date, now);
          Iif (diff > 0 && diff < minRefreshPeriod) {
            JulianDate.addSeconds(now, minRefreshPeriod, date);
          }
          networkLink.time = date;
        } catch (e) {
          oneTimeWarning(
            "kml-networkLinkControl-expires",
            "KML - NetworkLinkControl expires is not a valid date",
          );
          remove = true;
        }
      } else E{
        oneTimeWarning(
          "kml-refreshMode-onExpire",
          "KML - refreshMode of onExpire requires the NetworkLinkControl to have an expires element",
        );
        remove = true;
      }
    }
 
    const networkLinkEntity = networkLink.entity;
    const entityCollection = dataSource._entityCollection;
    const newEntities = newEntityCollection.values;
 
    function removeChildren(entity) {
      entityCollection.remove(entity);
      const children = entity._children;
      const count = children.length;
      for (let i = 0; i < count; ++i) {
        removeChildren(children[i]);
      }
    }
 
    // Remove old entities
    entityCollection.suspendEvents();
    const entitiesCopy = entityCollection.values.slice();
    let i;
    for (i = 0; i < entitiesCopy.length; ++i) {
      const entityToRemove = entitiesCopy[i];
      if (entityToRemove.parent === networkLinkEntity) {
        entityToRemove.parent = undefined;
        removeChildren(entityToRemove);
      }
    }
    entityCollection.resumeEvents();
 
    // Add new entities
    entityCollection.suspendEvents();
    for (i = 0; i < newEntities.length; i++) {
      const newEntity = newEntities[i];
      if (!defined(newEntity.parent)) {
        newEntity.parent = networkLinkEntity;
        mergeAvailabilityWithParent(newEntity);
      }
      entityCollection.add(newEntity);
    }
    entityCollection.resumeEvents();
 
    // No refresh information remove it, otherwise update lastUpdate time
    Iif (remove) {
      networkLinks.remove(networkLink.id);
    } else {
      networkLink.lastUpdated = now;
    }
 
    const availability = entityCollection.computeAvailability();
 
    const start = availability.start;
    const stop = availability.stop;
    const isMinStart = JulianDate.equals(start, Iso8601.MINIMUM_VALUE);
    const isMaxStop = JulianDate.equals(stop, Iso8601.MAXIMUM_VALUE);
    Iif (!isMinStart || !isMaxStop) {
      const clock = dataSource._clock;
 
      if (clock.startTime !== start || clock.stopTime !== stop) {
        clock.startTime = start;
        clock.stopTime = stop;
        dataSource._changed.raiseEvent(dataSource);
      }
    }
 
    networkLink.updating = false;
    networkLink.needsUpdate = false;
    dataSource._refresh.raiseEvent(
      dataSource,
      processedHref.getUrlComponent(true),
    );
  };
}
 
const entitiesToIgnore = new AssociativeArray();
 
/**
 * Updates any NetworkLink that require updating.
 *
 * @param {JulianDate} time The simulation time.
 * @returns {boolean} True if this data source is ready to be displayed at the provided time, false otherwise.
 */
KmlDataSource.prototype.update = function (time) {
  const networkLinks = this._networkLinks;
  Iif (networkLinks.length === 0) {
    return true;
  }
 
  const now = JulianDate.now();
  const that = this;
 
  entitiesToIgnore.removeAll();
 
  function recurseIgnoreEntities(entity) {
    const children = entity._children;
    const count = children.length;
    for (let i = 0; i < count; ++i) {
      const child = children[i];
      entitiesToIgnore.set(child.id, child);
      recurseIgnoreEntities(child);
    }
  }
 
  let cameraViewUpdate = false;
  const lastCameraView = this._lastCameraView;
  const camera = this.camera;
  if (
    defined(camera) &&
    !(
      camera.positionWC.equalsEpsilon(
        lastCameraView.position,
        CesiumMath.EPSILON7,
      ) &&
      camera.directionWC.equalsEpsilon(
        lastCameraView.direction,
        CesiumMath.EPSILON7,
      ) &&
      camera.upWC.equalsEpsilon(lastCameraView.up, CesiumMath.EPSILON7)
    )
  ) {
    // Camera has changed so update the last view
    lastCameraView.position = Cartesian3.clone(camera.positionWC);
    lastCameraView.direction = Cartesian3.clone(camera.directionWC);
    lastCameraView.up = Cartesian3.clone(camera.upWC);
    lastCameraView.bbox = camera.computeViewRectangle();
    cameraViewUpdate = true;
  }
 
  const newNetworkLinks = new AssociativeArray();
  let changed = false;
  networkLinks.values.forEach(function (networkLink) {
    const entity = networkLink.entity;
    Iif (entitiesToIgnore.contains(entity.id)) {
      return;
    }
 
    Eif (!networkLink.updating) {
      let doUpdate = false;
      if (networkLink.refreshMode === RefreshMode.INTERVAL) {
        if (
          JulianDate.secondsDifference(now, networkLink.lastUpdated) >
          networkLink.time
        ) {
          doUpdate = true;
        }
      } else if (networkLink.refreshMode === RefreshMode.EXPIRE) {
        Eif (JulianDate.greaterThan(now, networkLink.time)) {
          doUpdate = true;
        }
      } else Eif (networkLink.refreshMode === RefreshMode.STOP) {
        Eif (cameraViewUpdate) {
          networkLink.needsUpdate = true;
          networkLink.cameraUpdateTime = now;
        }
 
        Eif (
          networkLink.needsUpdate &&
          JulianDate.secondsDifference(now, networkLink.cameraUpdateTime) >=
            networkLink.time
        ) {
          doUpdate = true;
        }
      }
 
      if (doUpdate) {
        recurseIgnoreEntities(entity);
        networkLink.updating = true;
        const newEntityCollection = new EntityCollection();
        const href = networkLink.href.clone();
 
        href.setQueryParameters(networkLink.cookie);
        const ellipsoid = that._ellipsoid ?? Ellipsoid.default;
        processNetworkLinkQueryString(
          href,
          that.camera,
          that.canvas,
          networkLink.viewBoundScale,
          lastCameraView.bbox,
          ellipsoid,
        );
 
        load(that, newEntityCollection, href, {
          context: entity.id,
        })
          .then(
            getNetworkLinkUpdateCallback(
              that,
              networkLink,
              newEntityCollection,
              newNetworkLinks,
              href,
            ),
          )
          .catch(function (error) {
            const msg = `NetworkLink ${networkLink.href} refresh failed: ${error}`;
            console.log(msg);
            that._error.raiseEvent(that, msg);
          });
        changed = true;
      }
    }
    newNetworkLinks.set(networkLink.id, networkLink);
  });
 
  if (changed) {
    this._networkLinks = newNetworkLinks;
    this._changed.raiseEvent(this);
  }
 
  return true;
};
 
/**
 * Contains KML Feature data loaded into the <code>Entity.kml</code> property by {@link KmlDataSource}.
 * @alias KmlFeatureData
 * @constructor
 */
function KmlFeatureData() {
  /**
   * @typedef KmlFeatureData.Author
   * @type {object}
   * @property {string} name Gets the name.
   * @property {string} uri Gets the URI.
   * @property {number} age Gets the email.
   */
 
  /**
   * Gets the atom syndication format author field.
   * @type {KmlFeatureData.Author}
   */
  this.author = {
    name: undefined,
    uri: undefined,
    email: undefined,
  };
 
  /**
   * @typedef KmlFeatureData.Link
   * @type {object}
   * @property {string} href Gets the href.
   * @property {string} hreflang Gets the language of the linked resource.
   * @property {string} rel Gets the link relation.
   * @property {string} type Gets the link type.
   * @property {string} title Gets the link title.
   * @property {string} length Gets the link length.
   */
 
  /**
   * Gets the link.
   * @type {KmlFeatureData.Link}
   */
  this.link = {
    href: undefined,
    hreflang: undefined,
    rel: undefined,
    type: undefined,
    title: undefined,
    length: undefined,
  };
 
  /**
   * Gets the unstructured address field.
   * @type {string}
   */
  this.address = undefined;
  /**
   * Gets the phone number.
   * @type {string}
   */
  this.phoneNumber = undefined;
  /**
   * Gets the snippet.
   * @type {string}
   */
  this.snippet = undefined;
  /**
   * Gets the extended data, parsed into a JSON object.
   * Currently only the <code>Data</code> property is supported.
   * <code>SchemaData</code> and custom data are ignored.
   * @type {string}
   */
  this.extendedData = undefined;
}
 
// For testing
KmlDataSource._DeferredLoading = DeferredLoading;
KmlDataSource._getTimestamp = getTimestamp;
 
export default KmlDataSource;