All files / engine/Source/Scene GlobeSurfaceTile.js

94.85% Statements 332/350
89.94% Branches 152/169
94.44% Functions 34/36
94.76% Lines 326/344

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                                                                            1823x   1823x 1823x   1823x 1823x               1823x 1823x 1823x 1823x   1823x 1823x 1823x   1823x   1823x 1823x   1823x     1x                           44x   44x     44x   44x 44x 3x 3x         44x                               6569x 6407x 162x 114x   48x         1x             90x     90x 90x     1x 147x 6x 6x 1x   6x     147x   147x 147x 147x   147x 147x 25x   147x   147x     1x 147x 147x 147x 147x     1x         4631x 4631x 483x     4631x 988x 986x       1x                 4590x   4588x   4588x 4370x                             4588x 1993x     2595x     2595x     2595x       2595x       2595x           2595x 1179x 1179x 1179x 4x 4x         1179x   1179x             2595x 378x       1x           2636x 2636x 2636x 2636x     2636x   2636x 1673x 1673x 106x 106x     1567x 10x 10x     10x 10x 10x 10x 10x 10x           1557x         1557x     1557x         1557x             2636x     2636x   2636x                 93x 93x 93x 93x       93x 93x 93x 93x 93x   93x 91x           2x     93x 93x     93x 93x             93x 93x         93x 93x     1x       91x     1x     2x     1x         766x 766x 766x         766x   766x 766x   766x   766x   766x   766x   766x     93x 93x 91x 91x 2x 2x       93x 93x     93x 4x 4x 4x   2x       93x       1x 27x 27x 27x 12x     15x       988x           988x   485x 485x 485x 393x                 988x   37x       988x 451x 451x 451x                         4370x       4370x 4370x         147x     147x 50x                       4370x 150x                     4370x 1132x                 4370x 964x                   4370x 762x                     762x     4370x         733x 733x 8x   725x 725x 1x 1x 1x                     150x 150x   3x 3x     147x 147x 147x 147x   147x   35x     112x                 112x   78x     34x   34x   34x         34x 34x                 919x             919x 919x 919x       2x                   2x 2x   2x 2x                 2x             1132x         1132x   1132x                 1132x 921x 921x   919x     2x       211x 211x       1132x     1x                     964x   964x 964x 964x 964x 964x 964x 964x   964x   964x 964x   964x   137x     827x   827x   827x 827x             1x 582x 582x         582x   582x 582x 582x 76x 76x           76x 76x 76x 76x   506x     582x             1x 494x 141x   141x 141x     141x         37x 37x 6x                             762x       762x 762x         8x   8x 6x                   6x   6x             6x       1x       6x     8x       8x 8x     8x 8x               8x     5x 4x     1x     3x 3x                         3x     7x 7x   7x                 1x 755x   755x           1565x     755x     1x         1x 1x 1x 1x   1x 1x 1x   1x   1x 1x   1x      
import BoundingSphere from "../Core/BoundingSphere.js";
import Cartesian3 from "../Core/Cartesian3.js";
import Cartesian4 from "../Core/Cartesian4.js";
import defined from "../Core/defined.js";
import IndexDatatype from "../Core/IndexDatatype.js";
import PixelFormat from "../Core/PixelFormat.js";
import Request from "../Core/Request.js";
import RequestState from "../Core/RequestState.js";
import RequestType from "../Core/RequestType.js";
import TerrainEncoding from "../Core/TerrainEncoding.js";
import TileProviderError from "../Core/TileProviderError.js";
import Buffer from "../Renderer/Buffer.js";
import BufferUsage from "../Renderer/BufferUsage.js";
import PixelDatatype from "../Renderer/PixelDatatype.js";
import Sampler from "../Renderer/Sampler.js";
import Texture from "../Renderer/Texture.js";
import TextureMagnificationFilter from "../Renderer/TextureMagnificationFilter.js";
import TextureMinificationFilter from "../Renderer/TextureMinificationFilter.js";
import TextureWrap from "../Renderer/TextureWrap.js";
import VertexArray from "../Renderer/VertexArray.js";
import ImageryState from "./ImageryState.js";
import QuadtreeTileLoadState from "./QuadtreeTileLoadState.js";
import TerrainState from "./TerrainState.js";
 
/**
 * Contains additional information about a {@link QuadtreeTile} of the globe's surface, and
 * encapsulates state transition logic for loading tiles.
 *
 * @constructor
 * @alias GlobeSurfaceTile
 * @private
 */
function GlobeSurfaceTile() {
  /**
   * The {@link TileImagery} attached to this tile.
   * @type {TileImagery[]}
   * @default []
   */
  this.imagery = [];
 
  this.waterMaskTexture = undefined;
  this.waterMaskTranslationAndScale = new Cartesian4(0.0, 0.0, 1.0, 1.0);
 
  this.terrainData = undefined;
  this.vertexArray = undefined;
 
  /**
   * A bounding region used to estimate distance to the tile. The horizontal bounds are always tight-fitting,
   * but the `minimumHeight` and `maximumHeight` properties may be derived from the min/max of an ancestor tile
   * and be quite loose-fitting and thus very poor for estimating distance.
   * @type {TileBoundingRegion}
   */
  this.tileBoundingRegion = undefined;
  this.occludeePointInScaledSpace = new Cartesian3();
  this.boundingVolumeSourceTile = undefined;
  this.boundingVolumeIsFromMesh = false;
 
  this.terrainState = TerrainState.UNLOADED;
  this.mesh = undefined;
  this.fill = undefined;
 
  this.pickBoundingSphere = new BoundingSphere();
 
  this.surfaceShader = undefined;
  this.isClipped = true;
 
  this.clippedByBoundaries = false;
}
 
Object.defineProperties(GlobeSurfaceTile.prototype, {
  /**
   * Gets a value indicating whether or not this tile is eligible to be unloaded.
   * Typically, a tile is ineligible to be unloaded while an asynchronous operation,
   * such as a request for data, is in progress on it.  A tile will never be
   * unloaded while it is needed for rendering, regardless of the value of this
   * property.
   * @memberof GlobeSurfaceTile.prototype
   * @type {boolean}
   */
  eligibleForUnloading: {
    get: function () {
      // Do not remove tiles that are transitioning or that have
      // imagery that is transitioning.
      const terrainState = this.terrainState;
      const loadingIsTransitioning =
        terrainState === TerrainState.RECEIVING ||
        terrainState === TerrainState.TRANSFORMING;
 
      let shouldRemoveTile = !loadingIsTransitioning;
 
      const imagery = this.imagery;
      for (let i = 0, len = imagery.length; shouldRemoveTile && i < len; ++i) {
        const tileImagery = imagery[i];
        shouldRemoveTile =
          !defined(tileImagery.loadingImagery) ||
          tileImagery.loadingImagery.state !== ImageryState.TRANSITIONING;
      }
 
      return shouldRemoveTile;
    },
  },
 
  /**
   * Gets the {@link TerrainMesh} that is used for rendering this tile, if any.
   * Returns the value of the {@link GlobeSurfaceTile#mesh} property if
   * {@link GlobeSurfaceTile#vertexArray} is defined. Otherwise, It returns the
   * {@link TerrainFillMesh#mesh} property of the {@link GlobeSurfaceTile#fill}.
   * If there is no fill, it returns undefined.
   *
   * @memberof GlobeSurfaceTile.prototype
   * @type {TerrainMesh}
   */
  renderedMesh: {
    get: function () {
      if (defined(this.vertexArray)) {
        return this.mesh;
      } else if (defined(this.fill)) {
        return this.fill.mesh;
      }
      return undefined;
    },
  },
});
 
GlobeSurfaceTile.prototype.pick = function (
  ray,
  mode,
  projection,
  cullBackFaces,
  result,
) {
  Iif (!defined(this.renderedMesh)) {
    return undefined;
  }
  const value = this.renderedMesh.pick(ray, cullBackFaces, mode, projection);
  return Cartesian3.clone(value, result);
};
 
GlobeSurfaceTile.prototype.freeResources = function () {
  if (defined(this.waterMaskTexture)) {
    --this.waterMaskTexture.referenceCount;
    if (this.waterMaskTexture.referenceCount === 0) {
      this.waterMaskTexture.destroy();
    }
    this.waterMaskTexture = undefined;
  }
 
  this.terrainData = undefined;
 
  this.terrainState = TerrainState.UNLOADED;
  this.mesh = undefined;
  this.fill = this.fill && this.fill.destroy();
 
  const imageryList = this.imagery;
  for (let i = 0, len = imageryList.length; i < len; ++i) {
    imageryList[i].freeResources();
  }
  this.imagery.length = 0;
 
  this.freeVertexArray();
};
 
GlobeSurfaceTile.prototype.freeVertexArray = function () {
  GlobeSurfaceTile._freeVertexArray(this.vertexArray);
  this.vertexArray = undefined;
  GlobeSurfaceTile._freeVertexArray(this.wireframeVertexArray);
  this.wireframeVertexArray = undefined;
};
 
GlobeSurfaceTile.initialize = function (
  tile,
  terrainProvider,
  imageryLayerCollection,
) {
  let surfaceTile = tile.data;
  if (!defined(surfaceTile)) {
    surfaceTile = tile.data = new GlobeSurfaceTile();
  }
 
  if (tile.state === QuadtreeTileLoadState.START) {
    prepareNewTile(tile, terrainProvider, imageryLayerCollection);
    tile.state = QuadtreeTileLoadState.LOADING;
  }
};
 
GlobeSurfaceTile.processStateMachine = function (
  tile,
  frameState,
  terrainProvider,
  imageryLayerCollection,
  quadtree,
  vertexArraysToDestroy,
  terrainOnly,
) {
  GlobeSurfaceTile.initialize(tile, terrainProvider, imageryLayerCollection);
 
  const surfaceTile = tile.data;
 
  if (tile.state === QuadtreeTileLoadState.LOADING) {
    processTerrainStateMachine(
      tile,
      frameState,
      terrainProvider,
      imageryLayerCollection,
      quadtree,
      vertexArraysToDestroy,
    );
  }
 
  // From here down we're loading imagery, not terrain. We don't want to load imagery until
  // we're certain that the terrain tiles are actually visible, though. We'll load terrainOnly
  // in these scenarios:
  //   * our bounding volume isn't accurate so we're not certain this tile is really visible (see GlobeSurfaceTileProvider#loadTile).
  //   * we want to upsample from this tile but don't plan to render it (see processTerrainStateMachine).
  if (terrainOnly) {
    return;
  }
 
  const wasAlreadyRenderable = tile.renderable;
 
  // The terrain is renderable as soon as we have a valid vertex array.
  tile.renderable = defined(surfaceTile.vertexArray);
 
  // But it's not done loading until it's in the READY state.
  const isTerrainDoneLoading = surfaceTile.terrainState === TerrainState.READY;
 
  // If this tile's terrain and imagery are just upsampled from its parent, mark the tile as
  // upsampled only.  We won't refine a tile if its four children are upsampled only.
  tile.upsampledFromParent =
    defined(surfaceTile.terrainData) &&
    surfaceTile.terrainData.wasCreatedByUpsampling();
 
  const isImageryDoneLoading = surfaceTile.processImagery(
    tile,
    terrainProvider,
    frameState,
  );
 
  if (isTerrainDoneLoading && isImageryDoneLoading) {
    const callbacks = tile._loadedCallbacks;
    const newCallbacks = {};
    for (const layerId in callbacks) {
      Eif (callbacks.hasOwnProperty(layerId)) {
        Iif (!callbacks[layerId](tile)) {
          newCallbacks[layerId] = callbacks[layerId];
        }
      }
    }
    tile._loadedCallbacks = newCallbacks;
 
    tile.state = QuadtreeTileLoadState.DONE;
  }
 
  // Once a tile is renderable, it stays renderable, because doing otherwise would
  // cause detail (or maybe even the entire globe) to vanish when adding a new
  // imagery layer. `GlobeSurfaceTileProvider._onLayerAdded` sets renderable to
  // false for all affected tiles that are not currently being rendered.
  if (wasAlreadyRenderable) {
    tile.renderable = true;
  }
};
 
GlobeSurfaceTile.prototype.processImagery = function (
  tile,
  terrainProvider,
  frameState,
  skipLoading,
) {
  const surfaceTile = tile.data;
  let isUpsampledOnly = tile.upsampledFromParent;
  let isAnyTileLoaded = false;
  let isDoneLoading = true;
 
  // Transition imagery states
  const tileImageryCollection = surfaceTile.imagery;
  let i, len;
  for (i = 0, len = tileImageryCollection.length; i < len; ++i) {
    const tileImagery = tileImageryCollection[i];
    if (!defined(tileImagery.loadingImagery)) {
      isUpsampledOnly = false;
      continue;
    }
 
    if (tileImagery.loadingImagery.state === ImageryState.PLACEHOLDER) {
      const imageryLayer = tileImagery.loadingImagery.imageryLayer;
      if (imageryLayer.ready) {
        // Remove the placeholder and add the actual skeletons (if any)
        // at the same position.  Then continue the loop at the same index.
        tileImagery.freeResources();
        tileImageryCollection.splice(i, 1);
        imageryLayer._createTileImagerySkeletons(tile, terrainProvider, i);
        --i;
        len = tileImageryCollection.length;
        continue;
      } else E{
        isUpsampledOnly = false;
      }
    }
 
    const thisTileDoneLoading = tileImagery.processStateMachine(
      tile,
      frameState,
      skipLoading,
    );
    isDoneLoading = isDoneLoading && thisTileDoneLoading;
 
    // The imagery is renderable as soon as we have any renderable imagery for this region.
    isAnyTileLoaded =
      isAnyTileLoaded ||
      thisTileDoneLoading ||
      defined(tileImagery.readyImagery);
 
    isUpsampledOnly =
      isUpsampledOnly &&
      defined(tileImagery.loadingImagery) &&
      (tileImagery.loadingImagery.state === ImageryState.FAILED ||
        tileImagery.loadingImagery.state === ImageryState.INVALID);
  }
 
  tile.upsampledFromParent = isUpsampledOnly;
 
  // Allow rendering if any available layers are loaded
  tile.renderable = tile.renderable && (isAnyTileLoaded || isDoneLoading);
 
  return isDoneLoading;
};
 
function toggleGeodeticSurfaceNormals(
  surfaceTile,
  enabled,
  ellipsoid,
  frameState,
) {
  const renderedMesh = surfaceTile.renderedMesh;
  const vertexBuffer = renderedMesh.vertices;
  const encoding = renderedMesh.encoding;
  const vertexCount = vertexBuffer.length / encoding.stride;
 
  // Calculate the new stride and generate a new buffer
  // Clone the other encoding, toggle geodetic surface normals, then clone again to get updated stride
  let newEncoding = TerrainEncoding.clone(encoding);
  newEncoding.hasGeodeticSurfaceNormals = enabled;
  newEncoding = TerrainEncoding.clone(newEncoding);
  const newStride = newEncoding.stride;
  const newVertexBuffer = new Float32Array(vertexCount * newStride);
 
  if (enabled) {
    encoding.addGeodeticSurfaceNormals(
      vertexBuffer,
      newVertexBuffer,
      ellipsoid,
    );
  } else {
    encoding.removeGeodeticSurfaceNormals(vertexBuffer, newVertexBuffer);
  }
 
  renderedMesh.vertices = newVertexBuffer;
  renderedMesh.stride = newStride;
 
  // delete the old vertex array (which deletes the vertex buffer attached to it), and create a new vertex array with the new vertex buffer
  const isFill = renderedMesh !== surfaceTile.mesh;
  Iif (isFill) {
    GlobeSurfaceTile._freeVertexArray(surfaceTile.fill.vertexArray);
    surfaceTile.fill.vertexArray = GlobeSurfaceTile._createVertexArrayForMesh(
      frameState.context,
      renderedMesh,
    );
  } else {
    GlobeSurfaceTile._freeVertexArray(surfaceTile.vertexArray);
    surfaceTile.vertexArray = GlobeSurfaceTile._createVertexArrayForMesh(
      frameState.context,
      renderedMesh,
    );
  }
  GlobeSurfaceTile._freeVertexArray(surfaceTile.wireframeVertexArray);
  surfaceTile.wireframeVertexArray = undefined;
}
 
GlobeSurfaceTile.prototype.addGeodeticSurfaceNormals = function (
  ellipsoid,
  frameState,
) {
  toggleGeodeticSurfaceNormals(this, true, ellipsoid, frameState);
};
 
GlobeSurfaceTile.prototype.removeGeodeticSurfaceNormals = function (
  frameState,
) {
  toggleGeodeticSurfaceNormals(this, false, undefined, frameState);
};
 
GlobeSurfaceTile.prototype.updateExaggeration = function (
  tile,
  frameState,
  quadtree,
) {
  const surfaceTile = this;
  const mesh = surfaceTile.renderedMesh;
  Iif (mesh === undefined) {
    return;
  }
 
  // Check the tile's terrain encoding to see if it has been exaggerated yet
  const exaggeration = frameState.verticalExaggeration;
  const exaggerationRelativeHeight =
    frameState.verticalExaggerationRelativeHeight;
  const hasExaggerationScale = exaggeration !== 1.0;
 
  const encoding = mesh.encoding;
  const encodingExaggerationScaleChanged =
    encoding.exaggeration !== exaggeration;
  const encodingRelativeHeightChanged =
    encoding.exaggerationRelativeHeight !== exaggerationRelativeHeight;
  const exaggerationChanged =
    encodingExaggerationScaleChanged || encodingRelativeHeightChanged;
 
  if (exaggerationChanged) {
    // Turning exaggeration scale on/off requires adding or removing geodetic surface normals
    // Relative height only translates, so it has no effect on normals
    Eif (encodingExaggerationScaleChanged) {
      if (hasExaggerationScale && !encoding.hasGeodeticSurfaceNormals) {
        const ellipsoid = tile.tilingScheme.ellipsoid;
        surfaceTile.addGeodeticSurfaceNormals(ellipsoid, frameState);
      } else Eif (!hasExaggerationScale && encoding.hasGeodeticSurfaceNormals) {
        surfaceTile.removeGeodeticSurfaceNormals(frameState);
      }
    }
 
    encoding.exaggeration = exaggeration;
    encoding.exaggerationRelativeHeight = exaggerationRelativeHeight;
 
    // Notify the quadtree that this tile's height has changed
    if (quadtree !== undefined) {
      quadtree._tileToUpdateHeights.push(tile);
      const customData = tile.customData;
      for (const data of customData) {
        // Restart the level so that a height update is triggered
        data.level = -1;
      }
    }
 
    mesh.updateExaggeration(exaggeration, exaggerationRelativeHeight);
  }
};
 
GlobeSurfaceTile.prototype.updateSceneMode = function (mode) {
  const surfaceTile = this;
  const mesh = surfaceTile.renderedMesh;
  if (mesh === undefined) {
    return;
  }
 
  mesh.updateSceneMode(mode);
};
 
function prepareNewTile(tile, terrainProvider, imageryLayerCollection) {
  let available = terrainProvider.getTileDataAvailable(
    tile.x,
    tile.y,
    tile.level,
  );
 
  if (!defined(available) && defined(tile.parent)) {
    // Provider doesn't know if this tile is available. Does the parent tile know?
    const parent = tile.parent;
    const parentSurfaceTile = parent.data;
    if (defined(parentSurfaceTile) && defined(parentSurfaceTile.terrainData)) {
      available = parentSurfaceTile.terrainData.isChildAvailable(
        parent.x,
        parent.y,
        tile.x,
        tile.y,
      );
    }
  }
 
  if (available === false) {
    // This tile is not available, so mark it failed so we start upsampling right away.
    tile.data.terrainState = TerrainState.FAILED;
  }
 
  // Map imagery tiles to this terrain tile
  for (let i = 0, len = imageryLayerCollection.length; i < len; ++i) {
    const layer = imageryLayerCollection.get(i);
    Eif (layer.show) {
      layer._createTileImagerySkeletons(tile, terrainProvider);
    }
  }
}
 
function processTerrainStateMachine(
  tile,
  frameState,
  terrainProvider,
  imageryLayerCollection,
  quadtree,
  vertexArraysToDestroy,
) {
  const surfaceTile = tile.data;
 
  // If this tile is FAILED, we'll need to upsample from the parent. If the parent isn't
  // ready for that, let's push it along.
  const parent = tile.parent;
  if (
    surfaceTile.terrainState === TerrainState.FAILED &&
    parent !== undefined
  ) {
    const parentReady =
      parent.data !== undefined &&
      parent.data.terrainData !== undefined &&
      parent.data.terrainData.canUpsample !== false;
    if (!parentReady) {
      GlobeSurfaceTile.processStateMachine(
        parent,
        frameState,
        terrainProvider,
        imageryLayerCollection,
        quadtree,
        vertexArraysToDestroy,
        true,
      );
    }
  }
 
  if (surfaceTile.terrainState === TerrainState.FAILED) {
    upsample(
      surfaceTile,
      tile,
      frameState,
      terrainProvider,
      tile.x,
      tile.y,
      tile.level,
    );
  }
 
  if (surfaceTile.terrainState === TerrainState.UNLOADED) {
    requestTileGeometry(
      surfaceTile,
      terrainProvider,
      tile.x,
      tile.y,
      tile.level,
    );
  }
 
  if (surfaceTile.terrainState === TerrainState.RECEIVED) {
    transform(
      surfaceTile,
      frameState,
      terrainProvider,
      tile.x,
      tile.y,
      tile.level,
    );
  }
 
  if (surfaceTile.terrainState === TerrainState.TRANSFORMED) {
    createResources(
      surfaceTile,
      frameState.context,
      terrainProvider,
      tile.x,
      tile.y,
      tile.level,
      vertexArraysToDestroy,
    );
 
    // Update the tile's exaggeration in case the globe's exaggeration changed while the tile was being processed
    surfaceTile.updateExaggeration(tile, frameState, quadtree);
  }
 
  if (
    surfaceTile.terrainState >= TerrainState.RECEIVED &&
    surfaceTile.waterMaskTexture === undefined &&
    terrainProvider.hasWaterMask
  ) {
    const terrainData = surfaceTile.terrainData;
    if (terrainData.waterMask !== undefined) {
      createWaterMaskTextureIfNeeded(frameState.context, surfaceTile);
    } else {
      const sourceTile = surfaceTile._findAncestorTileWithTerrainData(tile);
      if (defined(sourceTile) && defined(sourceTile.data.waterMaskTexture)) {
        surfaceTile.waterMaskTexture = sourceTile.data.waterMaskTexture;
        ++surfaceTile.waterMaskTexture.referenceCount;
        surfaceTile._computeWaterMaskTranslationAndScale(
          tile,
          sourceTile,
          surfaceTile.waterMaskTranslationAndScale,
        );
      }
    }
  }
}
 
function upsample(surfaceTile, tile, frameState, terrainProvider, x, y, level) {
  const parent = tile.parent;
  if (!parent) {
    // Trying to upsample from a root tile. No can do. This tile is a failure.
    tile.state = QuadtreeTileLoadState.FAILED;
    return;
  }
 
  const sourceData = parent.data.terrainData;
  const sourceX = parent.x;
  const sourceY = parent.y;
  const sourceLevel = parent.level;
 
  if (!defined(sourceData)) {
    // Parent is not available, so we can't upsample this tile yet.
    return;
  }
 
  const terrainDataPromise = sourceData.upsample(
    terrainProvider.tilingScheme,
    sourceX,
    sourceY,
    sourceLevel,
    x,
    y,
    level,
  );
  if (!defined(terrainDataPromise)) {
    // The upsample request has been deferred - try again later.
    return;
  }
 
  surfaceTile.terrainState = TerrainState.RECEIVING;
 
  Promise.resolve(terrainDataPromise)
    .then(function (terrainData) {
      Iif (!defined(terrainData)) {
        // The upsample request has been deferred - try again later.
        return;
      }
 
      surfaceTile.terrainData = terrainData;
      surfaceTile.terrainState = TerrainState.RECEIVED;
    })
    .catch(function () {
      surfaceTile.terrainState = TerrainState.FAILED;
    });
}
 
function requestTileGeometry(surfaceTile, terrainProvider, x, y, level) {
  function success(terrainData) {
    Iif (!defined(terrainData)) {
      // Throttled due to low priority - try again later.
      surfaceTile.terrainState = TerrainState.UNLOADED;
      surfaceTile.request = undefined;
      return;
    }
 
    surfaceTile.terrainData = terrainData;
    surfaceTile.terrainState = TerrainState.RECEIVED;
    surfaceTile.request = undefined;
  }
 
  function failure(error) {
    Iif (surfaceTile.request.state === RequestState.CANCELLED) {
      // Cancelled due to low priority - try again later.
      surfaceTile.terrainData = undefined;
      surfaceTile.terrainState = TerrainState.UNLOADED;
      surfaceTile.request = undefined;
      return;
    }
 
    // Initially assume failure.  reportError may retry, in which case the state will
    // change to RECEIVING or UNLOADED.
    surfaceTile.terrainState = TerrainState.FAILED;
    surfaceTile.request = undefined;
 
    const message = `Failed to obtain terrain tile X: ${x} Y: ${y} Level: ${level}. Error message: "${error}"`;
    terrainProvider._requestError = TileProviderError.reportError(
      terrainProvider._requestError,
      terrainProvider,
      terrainProvider.errorEvent,
      message,
      x,
      y,
      level,
    );
    Iif (terrainProvider._requestError.retry) {
      doRequest();
    }
  }
 
  function doRequest() {
    // Request the terrain from the terrain provider.
    const request = new Request({
      throttle: false,
      throttleByServer: true,
      type: RequestType.TERRAIN,
    });
    surfaceTile.request = request;
 
    const requestPromise = terrainProvider.requestTileGeometry(
      x,
      y,
      level,
      request,
    );
 
    // If the request method returns undefined (instead of a promise), the request
    // has been deferred.
    if (defined(requestPromise)) {
      surfaceTile.terrainState = TerrainState.RECEIVING;
      Promise.resolve(requestPromise)
        .then(function (terrainData) {
          success(terrainData);
        })
        .catch(function (e) {
          failure(e);
        });
    } else {
      // Deferred - try again later.
      surfaceTile.terrainState = TerrainState.UNLOADED;
      surfaceTile.request = undefined;
    }
  }
 
  doRequest();
}
 
const scratchCreateMeshOptions = {
  tilingScheme: undefined,
  x: 0,
  y: 0,
  level: 0,
  exaggeration: 1.0,
  exaggerationRelativeHeight: 0.0,
  throttle: true,
};
 
function transform(surfaceTile, frameState, terrainProvider, x, y, level) {
  const tilingScheme = terrainProvider.tilingScheme;
 
  const createMeshOptions = scratchCreateMeshOptions;
  createMeshOptions.tilingScheme = tilingScheme;
  createMeshOptions.x = x;
  createMeshOptions.y = y;
  createMeshOptions.level = level;
  createMeshOptions.exaggeration = frameState.verticalExaggeration;
  createMeshOptions.exaggerationRelativeHeight =
    frameState.verticalExaggerationRelativeHeight;
  createMeshOptions.throttle = true;
 
  const terrainData = surfaceTile.terrainData;
  const meshPromise = terrainData.createMesh(createMeshOptions);
 
  if (!defined(meshPromise)) {
    // Postponed.
    return;
  }
 
  surfaceTile.terrainState = TerrainState.TRANSFORMING;
 
  Promise.resolve(meshPromise)
    .then(function (mesh) {
      surfaceTile.mesh = mesh;
      surfaceTile.terrainState = TerrainState.TRANSFORMED;
    })
    .catch(function () {
      surfaceTile.terrainState = TerrainState.FAILED;
    });
}
 
GlobeSurfaceTile._createVertexArrayForMesh = function (context, mesh) {
  const typedArray = mesh.vertices;
  const buffer = Buffer.createVertexBuffer({
    context: context,
    typedArray: typedArray,
    usage: BufferUsage.STATIC_DRAW,
  });
  const attributes = mesh.encoding.getAttributes(buffer);
 
  const indexBuffers = mesh.indices.indexBuffers || {};
  let indexBuffer = indexBuffers[context.id];
  if (!defined(indexBuffer) || indexBuffer.isDestroyed()) {
    const indices = mesh.indices;
    indexBuffer = Buffer.createIndexBuffer({
      context: context,
      typedArray: indices,
      usage: BufferUsage.STATIC_DRAW,
      indexDatatype: IndexDatatype.fromSizeInBytes(indices.BYTES_PER_ELEMENT),
    });
    indexBuffer.vertexArrayDestroyable = false;
    indexBuffer.referenceCount = 1;
    indexBuffers[context.id] = indexBuffer;
    mesh.indices.indexBuffers = indexBuffers;
  } else {
    ++indexBuffer.referenceCount;
  }
 
  return new VertexArray({
    context: context,
    attributes: attributes,
    indexBuffer: indexBuffer,
  });
};
 
GlobeSurfaceTile._freeVertexArray = function (vertexArray) {
  if (defined(vertexArray)) {
    const indexBuffer = vertexArray.indexBuffer;
 
    Eif (!vertexArray.isDestroyed()) {
      vertexArray.destroy();
    }
 
    if (
      defined(indexBuffer) &&
      !indexBuffer.isDestroyed() &&
      defined(indexBuffer.referenceCount)
    ) {
      --indexBuffer.referenceCount;
      if (indexBuffer.referenceCount === 0) {
        indexBuffer.destroy();
      }
    }
  }
};
 
function createResources(
  surfaceTile,
  context,
  terrainProvider,
  x,
  y,
  level,
  vertexArraysToDestroy,
) {
  surfaceTile.vertexArray = GlobeSurfaceTile._createVertexArrayForMesh(
    context,
    surfaceTile.mesh,
  );
  surfaceTile.terrainState = TerrainState.READY;
  surfaceTile.fill =
    surfaceTile.fill && surfaceTile.fill.destroy(vertexArraysToDestroy);
}
 
function getContextWaterMaskData(context) {
  let data = context.cache.tile_waterMaskData;
 
  if (!defined(data)) {
    const allWaterTexture = Texture.create({
      context: context,
      pixelFormat: PixelFormat.LUMINANCE,
      pixelDatatype: PixelDatatype.UNSIGNED_BYTE,
      source: {
        arrayBufferView: new Uint8Array([255]),
        width: 1,
        height: 1,
      },
    });
    allWaterTexture.referenceCount = 1;
 
    const sampler = new Sampler({
      wrapS: TextureWrap.CLAMP_TO_EDGE,
      wrapT: TextureWrap.CLAMP_TO_EDGE,
      minificationFilter: TextureMinificationFilter.LINEAR,
      magnificationFilter: TextureMagnificationFilter.LINEAR,
    });
 
    data = {
      allWaterTexture: allWaterTexture,
      sampler: sampler,
      destroy: function () {
        this.allWaterTexture.destroy();
      },
    };
 
    context.cache.tile_waterMaskData = data;
  }
 
  return data;
}
 
function createWaterMaskTextureIfNeeded(context, surfaceTile) {
  const waterMask = surfaceTile.terrainData.waterMask;
  const waterMaskData = getContextWaterMaskData(context);
  let texture;
 
  const waterMaskLength = waterMask.length;
  Iif (waterMask instanceof ImageBitmap) {
    texture = Texture.create({
      context: context,
      source: waterMask,
      sampler: waterMaskData.sampler,
      flipY: false,
      skipColorSpaceConversion: true,
    });
  } else if (waterMaskLength === 1) {
    // Length 1 means the tile is entirely land or entirely water.
    // A value of 0 indicates entirely land, a value of 1 indicates entirely water.
    if (waterMask[0] !== 0) {
      texture = waterMaskData.allWaterTexture;
    } else {
      // Leave the texture undefined if the tile is entirely land.
      return;
    }
  } else {
    const textureSize = Math.sqrt(waterMaskLength);
    texture = Texture.create({
      context: context,
      pixelFormat: PixelFormat.LUMINANCE,
      pixelDatatype: PixelDatatype.UNSIGNED_BYTE,
      source: {
        width: textureSize,
        height: textureSize,
        arrayBufferView: waterMask,
      },
      sampler: waterMaskData.sampler,
      flipY: false,
    });
 
    texture.referenceCount = 0;
  }
 
  ++texture.referenceCount;
  surfaceTile.waterMaskTexture = texture;
 
  Cartesian4.fromElements(
    0.0,
    0.0,
    1.0,
    1.0,
    surfaceTile.waterMaskTranslationAndScale,
  );
}
 
GlobeSurfaceTile.prototype._findAncestorTileWithTerrainData = function (tile) {
  let sourceTile = tile.parent;
 
  while (
    defined(sourceTile) &&
    (!defined(sourceTile.data) ||
      !defined(sourceTile.data.terrainData) ||
      sourceTile.data.terrainData.wasCreatedByUpsampling())
  ) {
    sourceTile = sourceTile.parent;
  }
 
  return sourceTile;
};
 
GlobeSurfaceTile.prototype._computeWaterMaskTranslationAndScale = function (
  tile,
  sourceTile,
  result,
) {
  const sourceTileRectangle = sourceTile.rectangle;
  const tileRectangle = tile.rectangle;
  const tileWidth = tileRectangle.width;
  const tileHeight = tileRectangle.height;
 
  const scaleX = tileWidth / sourceTileRectangle.width;
  const scaleY = tileHeight / sourceTileRectangle.height;
  result.x =
    (scaleX * (tileRectangle.west - sourceTileRectangle.west)) / tileWidth;
  result.y =
    (scaleY * (tileRectangle.south - sourceTileRectangle.south)) / tileHeight;
  result.z = scaleX;
  result.w = scaleY;
 
  return result;
};
export default GlobeSurfaceTile;