All files / engine/Source/Scene Globe.js

91.17% Statements 248/272
79.16% Branches 95/120
90% Functions 36/40
91.17% Lines 248/272

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                                                                                    383x 383x     383x   383x 383x   383x 383x   383x               383x 383x   383x 383x             383x   383x               383x   383x 383x                     383x                     383x                         383x                 383x                   383x                   383x               383x                   383x                 383x                   383x               383x               383x               383x               383x               383x               383x                   383x                 383x                   383x                   383x                   383x                     383x                         383x                   383x               383x               383x               383x                 383x               383x   383x 383x                 383x     1x               8x                   378x                       385x                       1188x     1188x                           80x     68x                     1x     12x                           3x                         2x     4x 1x   4x                                                         2048x     22x 22x 22x 22x                             510x                                               2x     7x 7x 7x                                     1x     2x                                             1x       2x 1x         1x                             7497x           390x     390x       390x 390x       5x 5x 5x   385x   390x   390x         390x       390x       19x 16x       16x         16x       1x 1x                               1x             19x     19x         19x   19x 19x   19x 19x   19x 19x         19x 32x 32x   32x       32x 32x 2x               2x           30x 30x                 32x         32x 23x       19x     19x 19x 7x             7x 6x       19x     1x                           1x 12x 12x           12x     1x 1x 1x 1x     537x                     1x   79x         79x 79x 24x           55x 55x 56x 56x 55x       55x       55x   55x 227x           227x         152x       55x             55x           35x     20x 20x     20x               20x 20x             20x             20x                                   20x                 20x       20x                 1x 1016x 10x     1006x 937x             1x 1014x 1014x 1014x   1014x       1014x   1x 1x 1x 1x 1x 1x 1x         1x   1x                     1014x 1014x   1014x 1014x 1003x   11x     1014x 1014x 1014x 1014x 1014x   1014x 1014x 1014x 1014x 1014x 1014x   1014x 1014x 1014x 1014x 1014x 1014x   1014x 1014x 1014x   1014x 1014x   1014x 1014x 1014x 1014x 1014x 1014x 1014x 1014x 1014x 1014x 1014x 1014x   1014x   1014x             1x 1007x 10x     997x 5x     997x           1x 1006x 10x     996x 996x                           1x 1x                                     1x 383x   383x 383x 383x      
import BoundingSphere from "../Core/BoundingSphere.js";
import buildModuleUrl from "../Core/buildModuleUrl.js";
import Cartesian3 from "../Core/Cartesian3.js";
import Cartographic from "../Core/Cartographic.js";
import Color from "../Core/Color.js";
import defined from "../Core/defined.js";
import destroyObject from "../Core/destroyObject.js";
import DeveloperError from "../Core/DeveloperError.js";
import Ellipsoid from "../Core/Ellipsoid.js";
import EllipsoidTerrainProvider from "../Core/EllipsoidTerrainProvider.js";
import Event from "../Core/Event.js";
import IntersectionTests from "../Core/IntersectionTests.js";
import NearFarScalar from "../Core/NearFarScalar.js";
import Ray from "../Core/Ray.js";
import Rectangle from "../Core/Rectangle.js";
import Resource from "../Core/Resource.js";
import ShaderSource from "../Renderer/ShaderSource.js";
import Texture from "../Renderer/Texture.js";
import GlobeFS from "../Shaders/GlobeFS.js";
import GlobeVS from "../Shaders/GlobeVS.js";
import AtmosphereCommon from "../Shaders/AtmosphereCommon.js";
import GroundAtmosphere from "../Shaders/GroundAtmosphere.js";
import GlobeSurfaceShaderSet from "./GlobeSurfaceShaderSet.js";
import GlobeSurfaceTileProvider from "./GlobeSurfaceTileProvider.js";
import GlobeTranslucency from "./GlobeTranslucency.js";
import ImageryLayerCollection from "./ImageryLayerCollection.js";
import QuadtreePrimitive from "./QuadtreePrimitive.js";
import SceneMode from "./SceneMode.js";
import ShadowMode from "./ShadowMode.js";
import CesiumMath from "../Core/Math.js";
 
/**
 * The globe rendered in the scene, including its terrain ({@link Globe#terrainProvider})
 * and imagery layers ({@link Globe#imageryLayers}).  Access the globe using {@link Scene#globe}.
 *
 * @alias Globe
 * @constructor
 *
 * @param {Ellipsoid} [ellipsoid=Ellipsoid.default] Determines the size and shape of the
 * globe.
 */
function Globe(ellipsoid) {
  ellipsoid = ellipsoid ?? Ellipsoid.default;
  const terrainProvider = new EllipsoidTerrainProvider({
    ellipsoid: ellipsoid,
  });
  const imageryLayerCollection = new ImageryLayerCollection();
 
  this._ellipsoid = ellipsoid;
  this._imageryLayerCollection = imageryLayerCollection;
 
  this._surfaceShaderSet = new GlobeSurfaceShaderSet();
  this._material = undefined;
 
  this._surface = new QuadtreePrimitive({
    tileProvider: new GlobeSurfaceTileProvider({
      terrainProvider: terrainProvider,
      imageryLayers: imageryLayerCollection,
      surfaceShaderSet: this._surfaceShaderSet,
    }),
  });
 
  this._terrainProvider = terrainProvider;
  this._terrainProviderChanged = new Event();
 
  this._undergroundColor = Color.clone(Color.BLACK);
  this._undergroundColorAlphaByDistance = new NearFarScalar(
    ellipsoid.maximumRadius / 1000.0,
    0.0,
    ellipsoid.maximumRadius / 5.0,
    1.0,
  );
 
  this._translucency = new GlobeTranslucency();
 
  makeShadersDirty(this);
 
  /**
   * Determines if the globe will be shown.
   *
   * @type {boolean}
   * @default true
   */
  this.show = true;
 
  this._oceanNormalMapResourceDirty = true;
  this._oceanNormalMapResource = new Resource({
    url: buildModuleUrl("Assets/Textures/waterNormalsSmall.jpg"),
  });
 
  /**
   * The maximum screen-space error used to drive level-of-detail refinement.  Higher
   * values will provide better performance but lower visual quality.
   *
   * @type {number}
   * @default 2
   */
  this.maximumScreenSpaceError = 2;
 
  /**
   * The size of the terrain tile cache, expressed as a number of tiles.  Any additional
   * tiles beyond this number will be freed, as long as they aren't needed for rendering
   * this frame.  A larger number will consume more memory but will show detail faster
   * when, for example, zooming out and then back in.
   *
   * @type {number}
   * @default 100
   */
  this.tileCacheSize = 100;
 
  /**
   * Gets or sets the number of loading descendant tiles that is considered "too many".
   * If a tile has too many loading descendants, that tile will be loaded and rendered before any of
   * its descendants are loaded and rendered. This means more feedback for the user that something
   * is happening at the cost of a longer overall load time. Setting this to 0 will cause each
   * tile level to be loaded successively, significantly increasing load time. Setting it to a large
   * number (e.g. 1000) will minimize the number of tiles that are loaded but tend to make
   * detail appear all at once after a long wait.
   * @type {number}
   * @default 20
   */
  this.loadingDescendantLimit = 20;
 
  /**
   * Gets or sets a value indicating whether the ancestors of rendered tiles should be preloaded.
   * Setting this to true optimizes the zoom-out experience and provides more detail in
   * newly-exposed areas when panning. The down side is that it requires loading more tiles.
   * @type {boolean}
   * @default true
   */
  this.preloadAncestors = true;
 
  /**
   * Gets or sets a value indicating whether the siblings of rendered tiles should be preloaded.
   * Setting this to true causes tiles with the same parent as a rendered tile to be loaded, even
   * if they are culled. Setting this to true may provide a better panning experience at the
   * cost of loading more tiles.
   * @type {boolean}
   * @default false
   */
  this.preloadSiblings = false;
 
  /**
   * The color to use to highlight terrain fill tiles. If undefined, fill tiles are not
   * highlighted at all. The alpha value is used to alpha blend with the tile's
   * actual color. Because terrain fill tiles do not represent the actual terrain surface,
   * it may be useful in some applications to indicate visually that they are not to be trusted.
   * @type {Color}
   * @default undefined
   */
  this.fillHighlightColor = undefined;
 
  /**
   * Enable lighting the globe with the scene's light source.
   *
   * @type {boolean}
   * @default false
   */
  this.enableLighting = false;
 
  /**
   * A multiplier to adjust terrain lambert lighting.
   * This number is multiplied by the result of <code>czm_getLambertDiffuse</code> in GlobeFS.glsl.
   * This only takes effect when <code>enableLighting</code> is <code>true</code>.
   *
   * @type {number}
   * @default 0.9
   */
  this.lambertDiffuseMultiplier = 0.9;
 
  /**
   * Enable dynamic lighting effects on atmosphere and fog. This only takes effect
   * when <code>enableLighting</code> is <code>true</code>.
   *
   * @type {boolean}
   * @default true
   */
  this.dynamicAtmosphereLighting = true;
 
  /**
   * Whether dynamic atmosphere lighting uses the sun direction instead of the scene's
   * light direction. This only takes effect when <code>enableLighting</code> and
   * <code>dynamicAtmosphereLighting</code> are <code>true</code>.
   *
   * @type {boolean}
   * @default false
   */
  this.dynamicAtmosphereLightingFromSun = false;
 
  /**
   * Enable the ground atmosphere, which is drawn over the globe when viewed from a distance between <code>lightingFadeInDistance</code> and <code>lightingFadeOutDistance</code>.
   *
   * @type {boolean}
   * @default true when using the WGS84 ellipsoid, false otherwise
   */
  this.showGroundAtmosphere = Ellipsoid.WGS84.equals(ellipsoid);
 
  /**
   * The intensity of the light that is used for computing the ground atmosphere color.
   *
   * @type {number}
   * @default 10.0
   */
  this.atmosphereLightIntensity = 10.0;
 
  /**
   * The Rayleigh scattering coefficient used in the atmospheric scattering equations for the ground atmosphere.
   *
   * @type {Cartesian3}
   * @default Cartesian3(5.5e-6, 13.0e-6, 28.4e-6)
   */
  this.atmosphereRayleighCoefficient = new Cartesian3(5.5e-6, 13.0e-6, 28.4e-6);
 
  /**
   * The Mie scattering coefficient used in the atmospheric scattering equations for the ground atmosphere.
   *
   * @type {Cartesian3}
   * @default Cartesian3(21e-6, 21e-6, 21e-6)
   */
  this.atmosphereMieCoefficient = new Cartesian3(21e-6, 21e-6, 21e-6);
 
  /**
   * The Rayleigh scale height used in the atmospheric scattering equations for the ground atmosphere, in meters.
   *
   * @type {number}
   * @default 10000.0
   */
  this.atmosphereRayleighScaleHeight = 10000.0;
 
  /**
   * The Mie scale height used in the atmospheric scattering equations for the ground atmosphere, in meters.
   *
   * @type {number}
   * @default 3200.0
   */
  this.atmosphereMieScaleHeight = 3200.0;
 
  /**
   * The anisotropy of the medium to consider for Mie scattering.
   * <p>
   * Valid values are between -1.0 and 1.0.
   * </p>
   * @type {number}
   * @default 0.9
   */
  this.atmosphereMieAnisotropy = 0.9;
 
  /**
   * The distance where everything becomes lit. This only takes effect
   * when <code>enableLighting</code> or <code>showGroundAtmosphere</code> is <code>true</code>.
   *
   * @type {number}
   * @default 1/2 * pi * ellipsoid.minimumRadius
   */
  this.lightingFadeOutDistance =
    CesiumMath.PI_OVER_TWO * ellipsoid.minimumRadius;
 
  /**
   * The distance where lighting resumes. This only takes effect
   * when <code>enableLighting</code> or <code>showGroundAtmosphere</code> is <code>true</code>.
   *
   * @type {number}
   * @default pi * ellipsoid.minimumRadius
   */
  this.lightingFadeInDistance = CesiumMath.PI * ellipsoid.minimumRadius;
 
  /**
   * The distance where the darkness of night from the ground atmosphere fades out to a lit ground atmosphere.
   * This only takes effect when <code>showGroundAtmosphere</code>, <code>enableLighting</code>, and
   * <code>dynamicAtmosphereLighting</code> are <code>true</code>.
   *
   * @type {number}
   * @default 1/2 * pi * ellipsoid.minimumRadius
   */
  this.nightFadeOutDistance = CesiumMath.PI_OVER_TWO * ellipsoid.minimumRadius;
 
  /**
   * The distance where the darkness of night from the ground atmosphere fades in to an unlit ground atmosphere.
   * This only takes effect when <code>showGroundAtmosphere</code>, <code>enableLighting</code>, and
   * <code>dynamicAtmosphereLighting</code> are <code>true</code>.
   *
   * @type {number}
   * @default 5/2 * pi * ellipsoid.minimumRadius
   */
  this.nightFadeInDistance =
    5.0 * CesiumMath.PI_OVER_TWO * ellipsoid.minimumRadius;
 
  /**
   * True if an animated wave effect should be shown in areas of the globe
   * covered by water; otherwise, false.  This property is ignored if the
   * <code>terrainProvider</code> does not provide a water mask.
   *
   * @type {boolean}
   * @default true
   */
  this.showWaterEffect = true;
 
  /**
   * True if primitives such as billboards, polylines, labels, etc. should be depth-tested
   * against the terrain surface, or false if such primitives should always be drawn on top
   * of terrain unless they're on the opposite side of the globe.  The disadvantage of depth
   * testing primitives against terrain is that slight numerical noise or terrain level-of-detail
   * switched can sometimes make a primitive that should be on the surface disappear underneath it.
   *
   * @type {boolean}
   * @default false
   *
   */
  this.depthTestAgainstTerrain = false;
 
  /**
   * Determines whether the globe casts or receives shadows from light sources. Setting the globe
   * to cast shadows may impact performance since the terrain is rendered again from the light's perspective.
   * Currently only terrain that is in view casts shadows. By default the globe does not cast shadows.
   *
   * @type {ShadowMode}
   * @default ShadowMode.RECEIVE_ONLY
   */
  this.shadows = ShadowMode.RECEIVE_ONLY;
 
  /**
   * The hue shift to apply to the atmosphere. Defaults to 0.0 (no shift).
   * A hue shift of 1.0 indicates a complete rotation of the hues available.
   * @type {number}
   * @default 0.0
   */
  this.atmosphereHueShift = 0.0;
 
  /**
   * The saturation shift to apply to the atmosphere. Defaults to 0.0 (no shift).
   * A saturation shift of -1.0 is monochrome.
   * @type {number}
   * @default 0.0
   */
  this.atmosphereSaturationShift = 0.0;
 
  /**
   * The brightness shift to apply to the atmosphere. Defaults to 0.0 (no shift).
   * A brightness shift of -1.0 is complete darkness, which will let space show through.
   * @type {number}
   * @default 0.0
   */
  this.atmosphereBrightnessShift = 0.0;
 
  /**
   * Whether to show terrain skirts. Terrain skirts are geometry extending downwards from a tile's edges used to hide seams between neighboring tiles.
   * Skirts are always hidden when the camera is underground or translucency is enabled.
   *
   * @type {boolean}
   * @default true
   */
  this.showSkirts = true;
 
  /**
   * Whether to cull back-facing terrain. Back faces are not culled when the camera is underground or translucency is enabled.
   *
   * @type {boolean}
   * @default true
   */
  this.backFaceCulling = true;
 
  this._oceanNormalMap = undefined;
  this._zoomedOutOceanSpecularIntensity = undefined;
 
  /**
   * Determines the darkness of the vertex shadow.
   * This only takes effect when <code>enableLighting</code> is <code>true</code>.
   *
   * @type {number}
   * @default 0.3
   */
  this.vertexShadowDarkness = 0.3;
}
 
Object.defineProperties(Globe.prototype, {
  /**
   * Gets an ellipsoid describing the shape of this globe.
   * @memberof Globe.prototype
   * @type {Ellipsoid}
   */
  ellipsoid: {
    get: function () {
      return this._ellipsoid;
    },
  },
  /**
   * Gets the collection of image layers that will be rendered on this globe.
   * @memberof Globe.prototype
   * @type {ImageryLayerCollection}
   */
  imageryLayers: {
    get: function () {
      return this._imageryLayerCollection;
    },
  },
  /**
   * Gets an event that's raised when an imagery layer is added, shown, hidden, moved, or removed.
   *
   * @memberof Globe.prototype
   * @type {Event}
   * @readonly
   */
  imageryLayersUpdatedEvent: {
    get: function () {
      return this._surface.tileProvider.imageryLayersUpdatedEvent;
    },
  },
  /**
   * Returns <code>true</code> when the tile load queue is empty, <code>false</code> otherwise.  When the load queue is empty,
   * all terrain and imagery for the current view have been loaded.
   * @memberof Globe.prototype
   * @type {boolean}
   * @readonly
   */
  tilesLoaded: {
    get: function () {
      Iif (!defined(this._surface)) {
        return true;
      }
      return (
        this._surface._tileLoadQueueHigh.length === 0 &&
        this._surface._tileLoadQueueMedium.length === 0 &&
        this._surface._tileLoadQueueLow.length === 0
      );
    },
  },
  /**
   * Gets or sets the color of the globe when no imagery is available.
   * @memberof Globe.prototype
   * @type {Color}
   */
  baseColor: {
    get: function () {
      return this._surface.tileProvider.baseColor;
    },
    set: function (value) {
      this._surface.tileProvider.baseColor = value;
    },
  },
  /**
   * A property specifying a {@link ClippingPlaneCollection} used to selectively disable rendering on the outside of each plane.
   *
   * @memberof Globe.prototype
   * @type {ClippingPlaneCollection}
   */
  clippingPlanes: {
    get: function () {
      return this._surface.tileProvider.clippingPlanes;
    },
    set: function (value) {
      this._surface.tileProvider.clippingPlanes = value;
    },
  },
  /**
   * A property specifying a {@link ClippingPolygonCollection} used to selectively disable rendering inside or outside a list of polygons.
   *
   * @memberof Globe.prototype
   * @type {ClippingPolygonCollection}
   */
  clippingPolygons: {
    get: function () {
      return this._surface.tileProvider.clippingPolygons;
    },
    set: function (value) {
      this._surface.tileProvider.clippingPolygons = value;
    },
  },
  /**
   * A property specifying a {@link Rectangle} used to limit globe rendering to a cartographic area.
   * Defaults to the maximum extent of cartographic coordinates.
   *
   * @memberof Globe.prototype
   * @type {Rectangle}
   * @default {@link Rectangle.MAX_VALUE}
   */
  cartographicLimitRectangle: {
    get: function () {
      return this._surface.tileProvider.cartographicLimitRectangle;
    },
    set: function (value) {
      if (!defined(value)) {
        value = Rectangle.clone(Rectangle.MAX_VALUE);
      }
      this._surface.tileProvider.cartographicLimitRectangle = value;
    },
  },
  /**
   * The normal map to use for rendering waves in the ocean.  Setting this property will
   * only have an effect if the configured terrain provider includes a water mask.
   * @memberof Globe.prototype
   * @type {string}
   * @default buildModuleUrl('Assets/Textures/waterNormalsSmall.jpg')
   */
  oceanNormalMapUrl: {
    get: function () {
      return this._oceanNormalMapResource.url;
    },
    set: function (value) {
      this._oceanNormalMapResource.url = value;
      this._oceanNormalMapResourceDirty = true;
    },
  },
  /**
   * The terrain provider providing surface geometry for this globe.
   * @type {TerrainProvider}
   *
   * @memberof Globe.prototype
   * @type {TerrainProvider}
   *
   */
  terrainProvider: {
    get: function () {
      return this._terrainProvider;
    },
    set: function (value) {
      Eif (value !== this._terrainProvider) {
        this._terrainProvider = value;
        this._terrainProviderChanged.raiseEvent(value);
        Iif (defined(this._material)) {
          makeShadersDirty(this);
        }
      }
    },
  },
  /**
   * Gets an event that's raised when the terrain provider is changed
   *
   * @memberof Globe.prototype
   * @type {Event}
   * @readonly
   */
  terrainProviderChanged: {
    get: function () {
      return this._terrainProviderChanged;
    },
  },
  /**
   * Gets an event that's raised when the length of the tile load queue has changed since the last render frame.  When the load queue is empty,
   * all terrain and imagery for the current view have been loaded.  The event passes the new length of the tile load queue.
   *
   * @memberof Globe.prototype
   * @type {Event}
   */
  tileLoadProgressEvent: {
    get: function () {
      return this._surface.tileLoadProgressEvent;
    },
  },
 
  /**
   * Gets or sets the material appearance of the Globe.  This can be one of several built-in {@link Material} objects or a custom material, scripted with
   * {@link https://github.com/CesiumGS/cesium/wiki/Fabric|Fabric}.
   * @memberof Globe.prototype
   * @type {Material | undefined}
   */
  material: {
    get: function () {
      return this._material;
    },
    set: function (material) {
      Eif (this._material !== material) {
        this._material = material;
        makeShadersDirty(this);
      }
    },
  },
 
  /**
   * The color to render the back side of the globe when the camera is underground or the globe is translucent,
   * blended with the globe color based on the camera's distance.
   * <br /><br />
   * To disable underground coloring, set <code>undergroundColor</code> to <code>undefined</code>.
   *
   * @memberof Globe.prototype
   * @type {Color}
   * @default {@link Color.BLACK}
   *
   * @see Globe#undergroundColorAlphaByDistance
   */
  undergroundColor: {
    get: function () {
      return this._undergroundColor;
    },
    set: function (value) {
      this._undergroundColor = Color.clone(value, this._undergroundColor);
    },
  },
 
  /**
   * Gets or sets the near and far distance for blending {@link Globe#undergroundColor} with the globe color.
   * The alpha will interpolate between the {@link NearFarScalar#nearValue} and
   * {@link NearFarScalar#farValue} while the camera distance falls within the lower and upper bounds
   * of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}.
   * Outside of these ranges the alpha remains clamped to the nearest bound. If undefined,
   * the underground color will not be blended with the globe color.
   * <br /> <br />
   * When the camera is above the ellipsoid the distance is computed from the nearest
   * point on the ellipsoid instead of the camera's position.
   *
   * @memberof Globe.prototype
   * @type {NearFarScalar}
   *
   * @see Globe#undergroundColor
   *
   */
  undergroundColorAlphaByDistance: {
    get: function () {
      return this._undergroundColorAlphaByDistance;
    },
    set: function (value) {
      //>>includeStart('debug', pragmas.debug);
      if (defined(value) && value.far < value.near) {
        throw new DeveloperError(
          "far distance must be greater than near distance.",
        );
      }
      //>>includeEnd('debug');
      this._undergroundColorAlphaByDistance = NearFarScalar.clone(
        value,
        this._undergroundColorAlphaByDistance,
      );
    },
  },
 
  /**
   * Properties for controlling globe translucency.
   *
   * @memberof Globe.prototype
   * @type {GlobeTranslucency}
   */
  translucency: {
    get: function () {
      return this._translucency;
    },
  },
});
 
function makeShadersDirty(globe) {
  const defines = [];
 
  const requireNormals =
    defined(globe._material) &&
    (defined(globe._material.shaderSource.match(/slope/)) ||
      defined(globe._material.shaderSource.match("normalEC")));
 
  const fragmentSources = [AtmosphereCommon, GroundAtmosphere];
  if (
    defined(globe._material) &&
    (!requireNormals || globe._terrainProvider.hasVertexNormals)
  ) {
    fragmentSources.push(globe._material.shaderSource);
    defines.push("APPLY_MATERIAL");
    globe._surface._tileProvider.materialUniformMap = globe._material._uniforms;
  } else {
    globe._surface._tileProvider.materialUniformMap = undefined;
  }
  fragmentSources.push(GlobeFS);
 
  globe._surfaceShaderSet.baseVertexShaderSource = new ShaderSource({
    sources: [AtmosphereCommon, GroundAtmosphere, GlobeVS],
    defines: defines,
  });
 
  globe._surfaceShaderSet.baseFragmentShaderSource = new ShaderSource({
    sources: fragmentSources,
    defines: defines,
  });
  globe._surfaceShaderSet.material = globe._material;
}
 
function createComparePickTileFunction(rayOrigin) {
  return function (a, b) {
    const aDist = BoundingSphere.distanceSquaredTo(
      a.pickBoundingSphere,
      rayOrigin,
    );
    const bDist = BoundingSphere.distanceSquaredTo(
      b.pickBoundingSphere,
      rayOrigin,
    );
 
    return aDist - bDist;
  };
}
 
const scratchArray = [];
const scratchSphereIntersectionResult = {
  start: 0.0,
  stop: 0.0,
};
 
/**
 * Find an intersection between a ray and the globe surface that was rendered. The ray must be given in world coordinates.
 *
 * @param {Ray} ray The ray to test for intersection.
 * @param {Scene} scene The scene.
 * @param {boolean} [cullBackFaces=true] Set to true to not pick back faces.
 * @param {Cartesian3} [result] The object onto which to store the result.
 * @returns {Cartesian3|undefined} The intersection or <code>undefined</code> if none was found.  The returned position is in projected coordinates for 2D and Columbus View.
 *
 * @private
 */
Globe.prototype.pickWorldCoordinates = function (
  ray,
  scene,
  cullBackFaces,
  result,
) {
  //>>includeStart('debug', pragmas.debug);
  Iif (!defined(ray)) {
    throw new DeveloperError("ray is required");
  }
  Iif (!defined(scene)) {
    throw new DeveloperError("scene is required");
  }
  //>>includeEnd('debug');
 
  cullBackFaces = cullBackFaces ?? true;
 
  const mode = scene.mode;
  const projection = scene.mapProjection;
 
  const sphereIntersections = scratchArray;
  sphereIntersections.length = 0;
 
  const tilesToRender = this._surface._tilesToRender;
  let length = tilesToRender.length;
 
  let tile;
  let i;
 
  for (i = 0; i < length; ++i) {
    tile = tilesToRender[i];
    const surfaceTile = tile.data;
 
    Iif (!defined(surfaceTile)) {
      continue;
    }
 
    let boundingVolume = surfaceTile.pickBoundingSphere;
    if (mode !== SceneMode.SCENE3D) {
      surfaceTile.pickBoundingSphere = boundingVolume =
        BoundingSphere.fromRectangleWithHeights2D(
          tile.rectangle,
          projection,
          surfaceTile.tileBoundingRegion.minimumHeight,
          surfaceTile.tileBoundingRegion.maximumHeight,
          boundingVolume,
        );
      Cartesian3.fromElements(
        boundingVolume.center.z,
        boundingVolume.center.x,
        boundingVolume.center.y,
        boundingVolume.center,
      );
    } else if (defined(surfaceTile.renderedMesh)) {
      BoundingSphere.clone(
        surfaceTile.tileBoundingRegion.boundingSphere,
        boundingVolume,
      );
    } else E{
      // So wait how did we render this thing then? It shouldn't be possible to get here.
      continue;
    }
 
    const boundingSphereIntersection = IntersectionTests.raySphere(
      ray,
      boundingVolume,
      scratchSphereIntersectionResult,
    );
    if (defined(boundingSphereIntersection)) {
      sphereIntersections.push(surfaceTile);
    }
  }
 
  sphereIntersections.sort(createComparePickTileFunction(ray.origin));
 
  let intersection;
  length = sphereIntersections.length;
  for (i = 0; i < length; ++i) {
    intersection = sphereIntersections[i].pick(
      ray,
      scene.mode,
      scene.mapProjection,
      cullBackFaces,
      result,
    );
    if (defined(intersection)) {
      break;
    }
  }
 
  return intersection;
};
 
const cartoScratch = new Cartographic();
/**
 * Find an intersection between a ray and the globe surface that was rendered. The ray must be given in world coordinates.
 *
 * @param {Ray} ray The ray to test for intersection.
 * @param {Scene} scene The scene.
 * @param {Cartesian3} [result] The object onto which to store the result.
 * @returns {Cartesian3|undefined} The intersection or <code>undefined</code> if none was found.
 *
 * @example
 * // find intersection of ray through a pixel and the globe
 * const ray = viewer.camera.getPickRay(windowCoordinates);
 * const intersection = globe.pick(ray, scene);
 */
Globe.prototype.pick = function (ray, scene, result) {
  result = this.pickWorldCoordinates(ray, scene, true, result);
  Iif (defined(result) && scene.mode !== SceneMode.SCENE3D) {
    result = Cartesian3.fromElements(result.y, result.z, result.x, result);
    const carto = scene.mapProjection.unproject(result, cartoScratch);
    result = this._ellipsoid.cartographicToCartesian(carto, result);
  }
 
  return result;
};
 
const scratchGetHeightCartesian = new Cartesian3();
const scratchGetHeightIntersection = new Cartesian3();
const scratchGetHeightCartographic = new Cartographic();
const scratchGetHeightRay = new Ray();
 
function tileIfContainsCartographic(tile, cartographic) {
  return defined(tile) && Rectangle.contains(tile.rectangle, cartographic)
    ? tile
    : undefined;
}
 
/**
 * Get the height of the surface at a given cartographic.
 *
 * @param {Cartographic} cartographic The cartographic for which to find the height.
 * @returns {number|undefined} The height of the cartographic or undefined if it could not be found.
 */
Globe.prototype.getHeight = function (cartographic) {
  //>>includeStart('debug', pragmas.debug);
  Iif (!defined(cartographic)) {
    throw new DeveloperError("cartographic is required");
  }
  //>>includeEnd('debug');
 
  const levelZeroTiles = this._surface._levelZeroTiles;
  if (!defined(levelZeroTiles)) {
    return;
  }
 
  let tile;
  let i;
 
  const length = levelZeroTiles.length;
  for (i = 0; i < length; ++i) {
    tile = levelZeroTiles[i];
    if (Rectangle.contains(tile.rectangle, cartographic)) {
      break;
    }
  }
 
  Iif (i >= length) {
    return undefined;
  }
 
  let tileWithMesh = tile;
 
  while (defined(tile)) {
    tile =
      tileIfContainsCartographic(tile._southwestChild, cartographic) ||
      tileIfContainsCartographic(tile._southeastChild, cartographic) ||
      tileIfContainsCartographic(tile._northwestChild, cartographic) ||
      tile._northeastChild;
 
    if (
      defined(tile) &&
      defined(tile.data) &&
      defined(tile.data.renderedMesh)
    ) {
      tileWithMesh = tile;
    }
  }
 
  tile = tileWithMesh;
 
  // This tile was either rendered or culled.
  // It is sometimes useful to get a height from a culled tile,
  // e.g. when we're getting a height in order to place a billboard
  // on terrain, and the camera is looking at that same billboard.
  // The culled tile must have a valid mesh, though.
  if (
    !defined(tile) ||
    !defined(tile.data) ||
    !defined(tile.data.renderedMesh)
  ) {
    // Tile was not rendered (culled).
    return undefined;
  }
 
  const projection = this._surface._tileProvider.tilingScheme.projection;
  const ellipsoid = this._surface._tileProvider.tilingScheme.ellipsoid;
 
  //cartesian has to be on the ellipsoid surface for `ellipsoid.geodeticSurfaceNormal`
  const cartesian = Cartesian3.fromRadians(
    cartographic.longitude,
    cartographic.latitude,
    0.0,
    ellipsoid,
    scratchGetHeightCartesian,
  );
 
  const ray = scratchGetHeightRay;
  const surfaceNormal = ellipsoid.geodeticSurfaceNormal(
    cartesian,
    ray.direction,
  );
 
  // Try to find the intersection point between the surface normal and z-axis.
  // minimum height (-11500.0) for the terrain set, need to get this information from the terrain provider
  const rayOrigin = ellipsoid.getSurfaceNormalIntersectionWithZAxis(
    cartesian,
    11500.0,
    ray.origin,
  );
 
  // Theoretically, not with Earth datums, the intersection point can be outside the ellipsoid
  Iif (!defined(rayOrigin)) {
    // intersection point is outside the ellipsoid, try other value
    // minimum height (-11500.0) for the terrain set, need to get this information from the terrain provider
    let minimumHeight;
    if (defined(tile.data.tileBoundingRegion)) {
      minimumHeight = tile.data.tileBoundingRegion.minimumHeight;
    }
    const magnitude = Math.min(minimumHeight ?? 0.0, -11500.0);
 
    // multiply by the *positive* value of the magnitude
    const vectorToMinimumPoint = Cartesian3.multiplyByScalar(
      surfaceNormal,
      Math.abs(magnitude) + 1,
      scratchGetHeightIntersection,
    );
    Cartesian3.subtract(cartesian, vectorToMinimumPoint, ray.origin);
  }
 
  const intersection = tile.data.pick(
    ray,
    // Globe height is the same at a given cartographic regardless of the scene mode,
    // but the ray is constructed via a surface normal (which assumes 3D), so pick in 3D mode.
    SceneMode.SCENE3D,
    projection,
    false,
    scratchGetHeightIntersection,
  );
  Iif (!defined(intersection)) {
    return undefined;
  }
 
  return ellipsoid.cartesianToCartographic(
    intersection,
    scratchGetHeightCartographic,
  ).height;
};
 
/**
 * @private
 */
Globe.prototype.update = function (frameState) {
  if (!this.show) {
    return;
  }
 
  if (frameState.passes.render) {
    this._surface.update(frameState);
  }
};
 
/**
 * @private
 */
Globe.prototype.beginFrame = function (frameState) {
  const surface = this._surface;
  const tileProvider = surface.tileProvider;
  const terrainProvider = this.terrainProvider;
  const hasWaterMask =
    defined(terrainProvider) &&
    terrainProvider.hasWaterMask &&
    terrainProvider.hasWaterMask;
 
  if (hasWaterMask && this._oceanNormalMapResourceDirty) {
    // url changed, load new normal map asynchronously
    this._oceanNormalMapResourceDirty = false;
    const oceanNormalMapResource = this._oceanNormalMapResource;
    const oceanNormalMapUrl = oceanNormalMapResource.url;
    if (defined(oceanNormalMapUrl)) {
      const that = this;
      oceanNormalMapResource.fetchImage().then(function (image) {
        Iif (oceanNormalMapUrl !== that._oceanNormalMapResource.url) {
          // url changed while we were loading
          return;
        }
 
        that._oceanNormalMap =
          that._oceanNormalMap && that._oceanNormalMap.destroy();
        that._oceanNormalMap = new Texture({
          context: frameState.context,
          source: image,
        });
      });
    } else E{
      this._oceanNormalMap =
        this._oceanNormalMap && this._oceanNormalMap.destroy();
    }
  }
 
  const pass = frameState.passes;
  const mode = frameState.mode;
 
  Eif (pass.render) {
    if (this.showGroundAtmosphere) {
      this._zoomedOutOceanSpecularIntensity = 0.4;
    } else {
      this._zoomedOutOceanSpecularIntensity = 0.5;
    }
 
    surface.maximumScreenSpaceError = this.maximumScreenSpaceError;
    surface.tileCacheSize = this.tileCacheSize;
    surface.loadingDescendantLimit = this.loadingDescendantLimit;
    surface.preloadAncestors = this.preloadAncestors;
    surface.preloadSiblings = this.preloadSiblings;
 
    tileProvider.terrainProvider = this.terrainProvider;
    tileProvider.lightingFadeOutDistance = this.lightingFadeOutDistance;
    tileProvider.lightingFadeInDistance = this.lightingFadeInDistance;
    tileProvider.nightFadeOutDistance = this.nightFadeOutDistance;
    tileProvider.nightFadeInDistance = this.nightFadeInDistance;
    tileProvider.zoomedOutOceanSpecularIntensity =
      mode === SceneMode.SCENE3D ? this._zoomedOutOceanSpecularIntensity : 0.0;
    tileProvider.hasWaterMask = hasWaterMask;
    tileProvider.showWaterEffect = this.showWaterEffect;
    tileProvider.oceanNormalMap = this._oceanNormalMap;
    tileProvider.enableLighting = this.enableLighting;
    tileProvider.dynamicAtmosphereLighting = this.dynamicAtmosphereLighting;
    tileProvider.dynamicAtmosphereLightingFromSun =
      this.dynamicAtmosphereLightingFromSun;
    tileProvider.showGroundAtmosphere = this.showGroundAtmosphere;
    tileProvider.atmosphereLightIntensity = this.atmosphereLightIntensity;
    tileProvider.atmosphereRayleighCoefficient =
      this.atmosphereRayleighCoefficient;
    tileProvider.atmosphereMieCoefficient = this.atmosphereMieCoefficient;
    tileProvider.atmosphereRayleighScaleHeight =
      this.atmosphereRayleighScaleHeight;
    tileProvider.atmosphereMieScaleHeight = this.atmosphereMieScaleHeight;
    tileProvider.atmosphereMieAnisotropy = this.atmosphereMieAnisotropy;
    tileProvider.shadows = this.shadows;
    tileProvider.hueShift = this.atmosphereHueShift;
    tileProvider.saturationShift = this.atmosphereSaturationShift;
    tileProvider.brightnessShift = this.atmosphereBrightnessShift;
    tileProvider.fillHighlightColor = this.fillHighlightColor;
    tileProvider.showSkirts = this.showSkirts;
    tileProvider.backFaceCulling = this.backFaceCulling;
    tileProvider.vertexShadowDarkness = this.vertexShadowDarkness;
    tileProvider.undergroundColor = this._undergroundColor;
    tileProvider.undergroundColorAlphaByDistance =
      this._undergroundColorAlphaByDistance;
    tileProvider.lambertDiffuseMultiplier = this.lambertDiffuseMultiplier;
 
    surface.beginFrame(frameState);
  }
};
 
/**
 * @private
 */
Globe.prototype.render = function (frameState) {
  if (!this.show) {
    return;
  }
 
  if (defined(this._material)) {
    this._material.update(frameState.context);
  }
 
  this._surface.render(frameState);
};
 
/**
 * @private
 */
Globe.prototype.endFrame = function (frameState) {
  if (!this.show) {
    return;
  }
 
  Eif (frameState.passes.render) {
    this._surface.endFrame(frameState);
  }
};
 
/**
 * Returns true if this object was destroyed; otherwise, false.
 * <br /><br />
 * If this object was destroyed, it should not be used; calling any function other than
 * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
 *
 * @returns {boolean} True if this object was destroyed; otherwise, false.
 *
 * @see Globe#destroy
 */
Globe.prototype.isDestroyed = function () {
  return false;
};
 
/**
 * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
 * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
 * <br /><br />
 * Once an object is destroyed, it should not be used; calling any function other than
 * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
 * assign the return value (<code>undefined</code>) to the object as done in the example.
 *
 * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
 *
 *
 * @example
 * globe = globe && globe.destroy();
 *
 * @see Globe#isDestroyed
 */
Globe.prototype.destroy = function () {
  this._surfaceShaderSet =
    this._surfaceShaderSet && this._surfaceShaderSet.destroy();
  this._surface = this._surface && this._surface.destroy();
  this._oceanNormalMap = this._oceanNormalMap && this._oceanNormalMap.destroy();
  return destroyObject(this);
};
export default Globe;