All files / engine/Source/Scene GroundPrimitive.js

87.2% Statements 225/258
82.6% Branches 95/115
93.54% Functions 29/31
87.1% Lines 223/256

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                                      1x                                                                                                                                                                                             65x   65x 65x 65x 51x     51x 51x 50x 50x 50x     50x                           65x                             65x                 65x               65x                       65x                       65x   65x 65x   65x 65x   65x 65x   65x 65x   65x 65x   65x   65x   65x 65x                                 1x                         2x                               2x                               49x                               2x                               3x                               2x                               104x                       1x     57x 57x 57x 57x         57x 57x       1x 1x 1x 1x 1x     104x   104x       57x 57x           47x 47x 47x   47x 47x 47x 47x   47x 22448x         22448x           22448x         22448x         22448x 22448x   22448x 22448x 22448x 22448x     47x 47x 47x 47x 47x   47x       51x         51x 51x       47x 47x   47x           47x   47x 47x 47x           47x             47x         390x                         546x 546x               546x 546x 546x 546x 546x   546x                       18x 18x               18x 18x 18x 18x   18x                           184x 158x   26x     184x   184x   184x   184x 184x           184x 177x   177x 358x 358x 272x 272x                   358x 272x 272x                       177x 2x 2x 2x 2x 2x 2x                         184x 7x     7x   7x   7x 16x 16x 16x 16x   16x 16x 16x                 16x 2x 2x                                       1x 179x                             1x 250x 1x     249x   1x 1x                   248x 248x   248x 51x           51x     51x 51x       51x 57x 57x 57x 57x 51x 6x 6x     57x 57x 53x       53x 53x     57x 57x                   51x 51x   51x 51x         51x           51x     51x   51x                                                                                                                           51x 57x 57x 57x 57x                       51x 51x   51x       47x   51x                   184x                       51x     248x 248x 248x 248x 248x   246x 245x 47x   47x 45x                 1x                                           1x   28x 1x         27x                           1x 9x                                     1x 65x 65x                   1x 1077x                   1x   1028x     1028x      
import ApproximateTerrainHeights from "../Core/ApproximateTerrainHeights.js";
import BoundingSphere from "../Core/BoundingSphere.js";
import Cartesian3 from "../Core/Cartesian3.js";
import Cartographic from "../Core/Cartographic.js";
import Check from "../Core/Check.js";
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import destroyObject from "../Core/destroyObject.js";
import DeveloperError from "../Core/DeveloperError.js";
import GeometryInstance from "../Core/GeometryInstance.js";
import OrientedBoundingBox from "../Core/OrientedBoundingBox.js";
import Rectangle from "../Core/Rectangle.js";
import VerticalExaggeration from "../Core/VerticalExaggeration.js";
import ClassificationPrimitive from "./ClassificationPrimitive.js";
import ClassificationType from "./ClassificationType.js";
import PerInstanceColorAppearance from "./PerInstanceColorAppearance.js";
import SceneMode from "./SceneMode.js";
import ShadowVolumeAppearance from "./ShadowVolumeAppearance.js";
 
const GroundPrimitiveUniformMap = {
  u_globeMinimumAltitude: function () {
    return 55000.0;
  },
};
 
/**
 * A ground primitive represents geometry draped over terrain or 3D Tiles in the {@link Scene}.
 * <p>
 * A primitive combines geometry instances with an {@link Appearance} that describes the full shading, including
 * {@link Material} and {@link RenderState}.  Roughly, the geometry instance defines the structure and placement,
 * and the appearance defines the visual characteristics.  Decoupling geometry and appearance allows us to mix
 * and match most of them and add a new geometry or appearance independently of each other.
 * </p>
 * <p>
 * Support for the WEBGL_depth_texture extension is required to use GeometryInstances with different PerInstanceColors
 * or materials besides PerInstanceColorAppearance.
 * </p>
 * <p>
 * Textured GroundPrimitives were designed for notional patterns and are not meant for precisely mapping
 * textures to terrain - for that use case, use {@link SingleTileImageryProvider}.
 * </p>
 * <p>
 * For correct rendering, this feature requires the EXT_frag_depth WebGL extension. For hardware that do not support this extension, there
 * will be rendering artifacts for some viewing angles.
 * </p>
 * <p>
 * Valid geometries are {@link CircleGeometry}, {@link CorridorGeometry}, {@link EllipseGeometry}, {@link PolygonGeometry}, and {@link RectangleGeometry}.
 * </p>
 *
 * @alias GroundPrimitive
 * @constructor
 *
 * @param {object} [options] Object with the following properties:
 * @param {Array|GeometryInstance} [options.geometryInstances] The geometry instances to render.
 * @param {Appearance} [options.appearance] The appearance used to render the primitive. Defaults to a flat PerInstanceColorAppearance when GeometryInstances have a color attribute.
 * @param {boolean} [options.show=true] Determines if this primitive will be shown.
 * @param {boolean} [options.vertexCacheOptimize=false] When <code>true</code>, geometry vertices are optimized for the pre and post-vertex-shader caches.
 * @param {boolean} [options.interleave=false] When <code>true</code>, geometry vertex attributes are interleaved, which can slightly improve rendering performance but increases load time.
 * @param {boolean} [options.compressVertices=true] When <code>true</code>, the geometry vertices are compressed, which will save memory.
 * @param {boolean} [options.releaseGeometryInstances=true] When <code>true</code>, the primitive does not keep a reference to the input <code>geometryInstances</code> to save memory.
 * @param {boolean} [options.allowPicking=true] When <code>true</code>, each geometry instance will only be pickable with {@link Scene#pick}.  When <code>false</code>, GPU memory is saved.
 * @param {boolean} [options.asynchronous=true] Determines if the primitive will be created asynchronously or block until ready. If false initializeTerrainHeights() must be called first.
 * @param {ClassificationType} [options.classificationType=ClassificationType.BOTH] Determines whether terrain, 3D Tiles or both will be classified.
 * @param {boolean} [options.debugShowBoundingVolume=false] For debugging only. Determines if this primitive's commands' bounding spheres are shown.
 * @param {boolean} [options.debugShowShadowVolume=false] For debugging only. Determines if the shadow volume for each geometry in the primitive is drawn. Must be <code>true</code> on
 *                  creation for the volumes to be created before the geometry is released or options.releaseGeometryInstance must be <code>false</code>.
 *
 * @example
 * // Example 1: Create primitive with a single instance
 * const rectangleInstance = new Cesium.GeometryInstance({
 *   geometry : new Cesium.RectangleGeometry({
 *     rectangle : Cesium.Rectangle.fromDegrees(-140.0, 30.0, -100.0, 40.0)
 *   }),
 *   id : 'rectangle',
 *   attributes : {
 *     color : new Cesium.ColorGeometryInstanceAttribute(0.0, 1.0, 1.0, 0.5)
 *   }
 * });
 * scene.primitives.add(new Cesium.GroundPrimitive({
 *   geometryInstances : rectangleInstance
 * }));
 *
 * // Example 2: Batch instances
 * const color = new Cesium.ColorGeometryInstanceAttribute(0.0, 1.0, 1.0, 0.5); // Both instances must have the same color.
 * const rectangleInstance = new Cesium.GeometryInstance({
 *   geometry : new Cesium.RectangleGeometry({
 *     rectangle : Cesium.Rectangle.fromDegrees(-140.0, 30.0, -100.0, 40.0)
 *   }),
 *   id : 'rectangle',
 *   attributes : {
 *     color : color
 *   }
 * });
 * const ellipseInstance = new Cesium.GeometryInstance({
 *     geometry : new Cesium.EllipseGeometry({
 *         center : Cesium.Cartesian3.fromDegrees(-105.0, 40.0),
 *         semiMinorAxis : 300000.0,
 *         semiMajorAxis : 400000.0
 *     }),
 *     id : 'ellipse',
 *     attributes : {
 *         color : color
 *     }
 * });
 * scene.primitives.add(new Cesium.GroundPrimitive({
 *   geometryInstances : [rectangleInstance, ellipseInstance]
 * }));
 *
 * @see Primitive
 * @see ClassificationPrimitive
 * @see GeometryInstance
 * @see Appearance
 */
function GroundPrimitive(options) {
  options = options ?? Frozen.EMPTY_OBJECT;
 
  let appearance = options.appearance;
  const geometryInstances = options.geometryInstances;
  if (!defined(appearance) && defined(geometryInstances)) {
    const geometryInstancesArray = Array.isArray(geometryInstances)
      ? geometryInstances
      : [geometryInstances];
    const geometryInstanceCount = geometryInstancesArray.length;
    for (let i = 0; i < geometryInstanceCount; i++) {
      const attributes = geometryInstancesArray[i].attributes;
      Eif (defined(attributes) && defined(attributes.color)) {
        appearance = new PerInstanceColorAppearance({
          flat: true,
        });
        break;
      }
    }
  }
  /**
   * The {@link Appearance} used to shade this primitive. Each geometry
   * instance is shaded with the same appearance.  Some appearances, like
   * {@link PerInstanceColorAppearance} allow giving each instance unique
   * properties.
   *
   * @type Appearance
   *
   * @default undefined
   */
  this.appearance = appearance;
 
  /**
   * The geometry instances rendered with this primitive.  This may
   * be <code>undefined</code> if <code>options.releaseGeometryInstances</code>
   * is <code>true</code> when the primitive is constructed.
   * <p>
   * Changing this property after the primitive is rendered has no effect.
   * </p>
   *
   * @readonly
   * @type {Array|GeometryInstance}
   *
   * @default undefined
   */
  this.geometryInstances = options.geometryInstances;
  /**
   * Determines if the primitive will be shown.  This affects all geometry
   * instances in the primitive.
   *
   * @type {boolean}
   *
   * @default true
   */
  this.show = options.show ?? true;
  /**
   * Determines whether terrain, 3D Tiles or both will be classified.
   *
   * @type {ClassificationType}
   *
   * @default ClassificationType.BOTH
   */
  this.classificationType =
    options.classificationType ?? ClassificationType.BOTH;
  /**
   * This property is for debugging only; it is not for production use nor is it optimized.
   * <p>
   * Draws the bounding sphere for each draw command in the primitive.
   * </p>
   *
   * @type {boolean}
   *
   * @default false
   */
  this.debugShowBoundingVolume = options.debugShowBoundingVolume ?? false;
 
  /**
   * This property is for debugging only; it is not for production use nor is it optimized.
   * <p>
   * Draws the shadow volume for each geometry in the primitive.
   * </p>
   *
   * @type {boolean}
   *
   * @default false
   */
  this.debugShowShadowVolume = options.debugShowShadowVolume ?? false;
 
  this._boundingVolumes = [];
  this._boundingVolumes2D = [];
 
  this._ready = false;
  this._primitive = undefined;
 
  this._maxHeight = undefined;
  this._minHeight = undefined;
 
  this._maxTerrainHeight = ApproximateTerrainHeights._defaultMaxTerrainHeight;
  this._minTerrainHeight = ApproximateTerrainHeights._defaultMinTerrainHeight;
 
  this._boundingSpheresKeys = [];
  this._boundingSpheres = [];
 
  this._useFragmentCulling = false;
  // Used when inserting in an OrderedPrimitiveCollection
  this._zIndex = undefined;
 
  const that = this;
  this._classificationPrimitiveOptions = {
    geometryInstances: undefined,
    appearance: undefined,
    vertexCacheOptimize: options.vertexCacheOptimize ?? false,
    interleave: options.interleave ?? false,
    releaseGeometryInstances: options.releaseGeometryInstances ?? true,
    allowPicking: options.allowPicking ?? true,
    asynchronous: options.asynchronous ?? true,
    compressVertices: options.compressVertices ?? true,
    _createBoundingVolumeFunction: undefined,
    _updateAndQueueCommandsFunction: undefined,
    _pickPrimitive: that,
    _extruded: true,
    _uniformMap: GroundPrimitiveUniformMap,
  };
}
 
Object.defineProperties(GroundPrimitive.prototype, {
  /**
   * When <code>true</code>, geometry vertices are optimized for the pre and post-vertex-shader caches.
   *
   * @memberof GroundPrimitive.prototype
   *
   * @type {boolean}
   * @readonly
   *
   * @default true
   */
  vertexCacheOptimize: {
    get: function () {
      return this._classificationPrimitiveOptions.vertexCacheOptimize;
    },
  },
 
  /**
   * Determines if geometry vertex attributes are interleaved, which can slightly improve rendering performance.
   *
   * @memberof GroundPrimitive.prototype
   *
   * @type {boolean}
   * @readonly
   *
   * @default false
   */
  interleave: {
    get: function () {
      return this._classificationPrimitiveOptions.interleave;
    },
  },
 
  /**
   * When <code>true</code>, the primitive does not keep a reference to the input <code>geometryInstances</code> to save memory.
   *
   * @memberof GroundPrimitive.prototype
   *
   * @type {boolean}
   * @readonly
   *
   * @default true
   */
  releaseGeometryInstances: {
    get: function () {
      return this._classificationPrimitiveOptions.releaseGeometryInstances;
    },
  },
 
  /**
   * When <code>true</code>, each geometry instance will only be pickable with {@link Scene#pick}.  When <code>false</code>, GPU memory is saved.
   *
   * @memberof GroundPrimitive.prototype
   *
   * @type {boolean}
   * @readonly
   *
   * @default true
   */
  allowPicking: {
    get: function () {
      return this._classificationPrimitiveOptions.allowPicking;
    },
  },
 
  /**
   * Determines if the geometry instances will be created and batched on a web worker.
   *
   * @memberof GroundPrimitive.prototype
   *
   * @type {boolean}
   * @readonly
   *
   * @default true
   */
  asynchronous: {
    get: function () {
      return this._classificationPrimitiveOptions.asynchronous;
    },
  },
 
  /**
   * When <code>true</code>, geometry vertices are compressed, which will save memory.
   *
   * @memberof GroundPrimitive.prototype
   *
   * @type {boolean}
   * @readonly
   *
   * @default true
   */
  compressVertices: {
    get: function () {
      return this._classificationPrimitiveOptions.compressVertices;
    },
  },
 
  /**
   * Determines if the primitive is complete and ready to render.  If this property is
   * true, the primitive will be rendered the next time that {@link GroundPrimitive#update}
   * is called.
   *
   * @memberof GroundPrimitive.prototype
   *
   * @type {boolean}
   * @readonly
   */
  ready: {
    get: function () {
      return this._ready;
    },
  },
});
 
/**
 * Determines if GroundPrimitive rendering is supported.
 *
 * @function
 * @param {Scene} scene The scene.
 * @returns {boolean} <code>true</code> if GroundPrimitives are supported; otherwise, returns <code>false</code>
 */
GroundPrimitive.isSupported = ClassificationPrimitive.isSupported;
 
function getComputeMaximumHeightFunction(primitive) {
  return function (granularity, ellipsoid) {
    const r = ellipsoid.maximumRadius;
    const delta = r / Math.cos(granularity * 0.5) - r;
    return primitive._maxHeight + delta;
  };
}
 
function getComputeMinimumHeightFunction(primitive) {
  return function (granularity, ellipsoid) {
    return primitive._minHeight;
  };
}
 
const scratchBVCartesianHigh = new Cartesian3();
const scratchBVCartesianLow = new Cartesian3();
const scratchBVCartesian = new Cartesian3();
const scratchBVCartographic = new Cartographic();
const scratchBVRectangle = new Rectangle();
 
function getRectangle(frameState, geometry) {
  const ellipsoid = frameState.mapProjection.ellipsoid;
 
  if (
    !defined(geometry.attributes) ||
    !defined(geometry.attributes.position3DHigh)
  ) {
    Eif (defined(geometry.rectangle)) {
      return geometry.rectangle;
    }
 
    return undefined;
  }
 
  const highPositions = geometry.attributes.position3DHigh.values;
  const lowPositions = geometry.attributes.position3DLow.values;
  const length = highPositions.length;
 
  let minLat = Number.POSITIVE_INFINITY;
  let minLon = Number.POSITIVE_INFINITY;
  let maxLat = Number.NEGATIVE_INFINITY;
  let maxLon = Number.NEGATIVE_INFINITY;
 
  for (let i = 0; i < length; i += 3) {
    const highPosition = Cartesian3.unpack(
      highPositions,
      i,
      scratchBVCartesianHigh,
    );
    const lowPosition = Cartesian3.unpack(
      lowPositions,
      i,
      scratchBVCartesianLow,
    );
 
    const position = Cartesian3.add(
      highPosition,
      lowPosition,
      scratchBVCartesian,
    );
    const cartographic = ellipsoid.cartesianToCartographic(
      position,
      scratchBVCartographic,
    );
 
    const latitude = cartographic.latitude;
    const longitude = cartographic.longitude;
 
    minLat = Math.min(minLat, latitude);
    minLon = Math.min(minLon, longitude);
    maxLat = Math.max(maxLat, latitude);
    maxLon = Math.max(maxLon, longitude);
  }
 
  const rectangle = scratchBVRectangle;
  rectangle.north = maxLat;
  rectangle.south = minLat;
  rectangle.east = maxLon;
  rectangle.west = minLon;
 
  return rectangle;
}
 
function setMinMaxTerrainHeights(primitive, rectangle, ellipsoid) {
  const result = ApproximateTerrainHeights.getMinimumMaximumHeights(
    rectangle,
    ellipsoid,
  );
 
  primitive._minTerrainHeight = result.minimumTerrainHeight;
  primitive._maxTerrainHeight = result.maximumTerrainHeight;
}
 
function createBoundingVolume(groundPrimitive, frameState, geometry) {
  const ellipsoid = frameState.mapProjection.ellipsoid;
  const rectangle = getRectangle(frameState, geometry);
 
  const obb = OrientedBoundingBox.fromRectangle(
    rectangle,
    groundPrimitive._minHeight,
    groundPrimitive._maxHeight,
    ellipsoid,
  );
  groundPrimitive._boundingVolumes.push(obb);
 
  Eif (!frameState.scene3DOnly) {
    const projection = frameState.mapProjection;
    const boundingVolume = BoundingSphere.fromRectangleWithHeights2D(
      rectangle,
      projection,
      groundPrimitive._maxHeight,
      groundPrimitive._minHeight,
    );
    Cartesian3.fromElements(
      boundingVolume.center.z,
      boundingVolume.center.x,
      boundingVolume.center.y,
      boundingVolume.center,
    );
 
    groundPrimitive._boundingVolumes2D.push(boundingVolume);
  }
}
 
function boundingVolumeIndex(commandIndex, length) {
  return Math.floor((commandIndex % length) / 2);
}
 
function updateAndQueueRenderCommand(
  groundPrimitive,
  command,
  frameState,
  modelMatrix,
  cull,
  boundingVolume,
  debugShowBoundingVolume,
) {
  // Use derived appearance command for 2D if needed
  const classificationPrimitive = groundPrimitive._primitive;
  Iif (
    frameState.mode !== SceneMode.SCENE3D &&
    command.shaderProgram === classificationPrimitive._spColor &&
    classificationPrimitive._needs2DShader
  ) {
    command = command.derivedCommands.appearance2D;
  }
 
  command.owner = groundPrimitive;
  command.modelMatrix = modelMatrix;
  command.boundingVolume = boundingVolume;
  command.cull = cull;
  command.debugShowBoundingVolume = debugShowBoundingVolume;
 
  frameState.commandList.push(command);
}
 
function updateAndQueuePickCommand(
  groundPrimitive,
  command,
  frameState,
  modelMatrix,
  cull,
  boundingVolume,
) {
  // Use derived pick command for 2D if needed
  const classificationPrimitive = groundPrimitive._primitive;
  Iif (
    frameState.mode !== SceneMode.SCENE3D &&
    command.shaderProgram === classificationPrimitive._spPick &&
    classificationPrimitive._needs2DShader
  ) {
    command = command.derivedCommands.pick2D;
  }
 
  command.owner = groundPrimitive;
  command.modelMatrix = modelMatrix;
  command.boundingVolume = boundingVolume;
  command.cull = cull;
 
  frameState.commandList.push(command);
}
 
function updateAndQueueCommands(
  groundPrimitive,
  frameState,
  colorCommands,
  pickCommands,
  modelMatrix,
  cull,
  debugShowBoundingVolume,
  twoPasses,
) {
  let boundingVolumes;
  if (frameState.mode === SceneMode.SCENE3D) {
    boundingVolumes = groundPrimitive._boundingVolumes;
  } else {
    boundingVolumes = groundPrimitive._boundingVolumes2D;
  }
 
  const classificationType = groundPrimitive.classificationType;
  const queueTerrainCommands =
    classificationType !== ClassificationType.CESIUM_3D_TILE;
  const queue3DTilesCommands =
    classificationType !== ClassificationType.TERRAIN;
 
  const passes = frameState.passes;
  const classificationPrimitive = groundPrimitive._primitive;
 
  let i;
  let boundingVolume;
  let command;
 
  if (passes.render) {
    const colorLength = colorCommands.length;
 
    for (i = 0; i < colorLength; ++i) {
      boundingVolume = boundingVolumes[boundingVolumeIndex(i, colorLength)];
      if (queueTerrainCommands) {
        command = colorCommands[i];
        updateAndQueueRenderCommand(
          groundPrimitive,
          command,
          frameState,
          modelMatrix,
          cull,
          boundingVolume,
          debugShowBoundingVolume,
        );
      }
      if (queue3DTilesCommands) {
        command = colorCommands[i].derivedCommands.tileset;
        updateAndQueueRenderCommand(
          groundPrimitive,
          command,
          frameState,
          modelMatrix,
          cull,
          boundingVolume,
          debugShowBoundingVolume,
        );
      }
    }
 
    if (frameState.invertClassification) {
      const ignoreShowCommands = classificationPrimitive._commandsIgnoreShow;
      const ignoreShowCommandsLength = ignoreShowCommands.length;
      for (i = 0; i < ignoreShowCommandsLength; ++i) {
        boundingVolume = boundingVolumes[i];
        command = ignoreShowCommands[i];
        updateAndQueueRenderCommand(
          groundPrimitive,
          command,
          frameState,
          modelMatrix,
          cull,
          boundingVolume,
          debugShowBoundingVolume,
        );
      }
    }
  }
 
  if (passes.pick) {
    const pickLength = pickCommands.length;
 
    let pickOffsets;
    Eif (!groundPrimitive._useFragmentCulling) {
      // Must be using pick offsets
      pickOffsets = classificationPrimitive._primitive._pickOffsets;
    }
    for (i = 0; i < pickLength; ++i) {
      boundingVolume = boundingVolumes[boundingVolumeIndex(i, pickLength)];
      Eif (!groundPrimitive._useFragmentCulling) {
        const pickOffset = pickOffsets[boundingVolumeIndex(i, pickLength)];
        boundingVolume = boundingVolumes[pickOffset.index];
      }
      Eif (queueTerrainCommands) {
        command = pickCommands[i];
        updateAndQueuePickCommand(
          groundPrimitive,
          command,
          frameState,
          modelMatrix,
          cull,
          boundingVolume,
        );
      }
      if (queue3DTilesCommands) {
        command = pickCommands[i].derivedCommands.tileset;
        updateAndQueuePickCommand(
          groundPrimitive,
          command,
          frameState,
          modelMatrix,
          cull,
          boundingVolume,
        );
      }
    }
  }
}
 
/**
 * Initializes the minimum and maximum terrain heights. This only needs to be called if you are creating the
 * GroundPrimitive synchronously.
 *
 * @returns {Promise<void>} A promise that will resolve once the terrain heights have been loaded.
 *
 */
GroundPrimitive.initializeTerrainHeights = function () {
  return ApproximateTerrainHeights.initialize();
};
 
/**
 * Called when {@link Viewer} or {@link CesiumWidget} render the scene to
 * get the draw commands needed to render this primitive.
 * <p>
 * Do not call this function directly.  This is documented just to
 * list the exceptions that may be propagated when the scene is rendered:
 * </p>
 *
 * @exception {DeveloperError} For synchronous GroundPrimitive, you must call GroundPrimitive.initializeTerrainHeights() and wait for the returned promise to resolve.
 * @exception {DeveloperError} All instance geometries must have the same primitiveType.
 * @exception {DeveloperError} Appearance and material have a uniform with the same name.
 */
GroundPrimitive.prototype.update = function (frameState) {
  if (!defined(this._primitive) && !defined(this.geometryInstances)) {
    return;
  }
 
  if (!ApproximateTerrainHeights.initialized) {
    //>>includeStart('debug', pragmas.debug);
    Eif (!this.asynchronous) {
      throw new DeveloperError(
        "For synchronous GroundPrimitives, you must call GroundPrimitive.initializeTerrainHeights() and wait for the returned promise to resolve.",
      );
    }
    //>>includeEnd('debug');
 
    GroundPrimitive.initializeTerrainHeights();
    return;
  }
 
  const that = this;
  const primitiveOptions = this._classificationPrimitiveOptions;
 
  if (!defined(this._primitive)) {
    const ellipsoid = frameState.mapProjection.ellipsoid;
 
    let instance;
    let geometry;
    let instanceType;
 
    const instances = Array.isArray(this.geometryInstances)
      ? this.geometryInstances
      : [this.geometryInstances];
    const length = instances.length;
    const groundInstances = new Array(length);
 
    let i;
    let rectangle;
    for (i = 0; i < length; ++i) {
      instance = instances[i];
      geometry = instance.geometry;
      const instanceRectangle = getRectangle(frameState, geometry);
      if (!defined(rectangle)) {
        rectangle = Rectangle.clone(instanceRectangle);
      } else Eif (defined(instanceRectangle)) {
        Rectangle.union(rectangle, instanceRectangle, rectangle);
      }
 
      const id = instance.id;
      if (defined(id) && defined(instanceRectangle)) {
        const boundingSphere = ApproximateTerrainHeights.getBoundingSphere(
          instanceRectangle,
          ellipsoid,
        );
        this._boundingSpheresKeys.push(id);
        this._boundingSpheres.push(boundingSphere);
      }
 
      instanceType = geometry.constructor;
      Iif (!defined(instanceType) || !defined(instanceType.createShadowVolume)) {
        //>>includeStart('debug', pragmas.debug);
        throw new DeveloperError(
          "Not all of the geometry instances have GroundPrimitive support.",
        );
        //>>includeEnd('debug');
      }
    }
 
    // Now compute the min/max heights for the primitive
    setMinMaxTerrainHeights(this, rectangle, ellipsoid);
    const exaggeration = frameState.verticalExaggeration;
    const exaggerationRelativeHeight =
      frameState.verticalExaggerationRelativeHeight;
    this._minHeight = VerticalExaggeration.getHeight(
      this._minTerrainHeight,
      exaggeration,
      exaggerationRelativeHeight,
    );
    this._maxHeight = VerticalExaggeration.getHeight(
      this._maxTerrainHeight,
      exaggeration,
      exaggerationRelativeHeight,
    );
 
    const useFragmentCulling = GroundPrimitive._supportsMaterials(
      frameState.context,
    );
    this._useFragmentCulling = useFragmentCulling;
 
    Iif (useFragmentCulling) {
      // Determine whether to add spherical or planar extent attributes for computing texture coordinates.
      // This depends on the size of the GeometryInstances.
      let attributes;
      let usePlanarExtents = true;
      for (i = 0; i < length; ++i) {
        instance = instances[i];
        geometry = instance.geometry;
        rectangle = getRectangle(frameState, geometry);
        if (ShadowVolumeAppearance.shouldUseSphericalCoordinates(rectangle)) {
          usePlanarExtents = false;
          break;
        }
      }
 
      for (i = 0; i < length; ++i) {
        instance = instances[i];
        geometry = instance.geometry;
        instanceType = geometry.constructor;
 
        const boundingRectangle = getRectangle(frameState, geometry);
        const textureCoordinateRotationPoints =
          geometry.textureCoordinateRotationPoints;
 
        if (usePlanarExtents) {
          attributes =
            ShadowVolumeAppearance.getPlanarTextureCoordinateAttributes(
              boundingRectangle,
              textureCoordinateRotationPoints,
              ellipsoid,
              frameState.mapProjection,
              this._maxHeight,
            );
        } else {
          attributes =
            ShadowVolumeAppearance.getSphericalExtentGeometryInstanceAttributes(
              boundingRectangle,
              textureCoordinateRotationPoints,
              ellipsoid,
              frameState.mapProjection,
            );
        }
 
        const instanceAttributes = instance.attributes;
        for (const attributeKey in instanceAttributes) {
          if (instanceAttributes.hasOwnProperty(attributeKey)) {
            attributes[attributeKey] = instanceAttributes[attributeKey];
          }
        }
 
        groundInstances[i] = new GeometryInstance({
          geometry: instanceType.createShadowVolume(
            geometry,
            getComputeMinimumHeightFunction(this),
            getComputeMaximumHeightFunction(this),
          ),
          attributes: attributes,
          id: instance.id,
        });
      }
    } else {
      // ClassificationPrimitive will check if the colors are all the same if it detects lack of fragment culling attributes
      for (i = 0; i < length; ++i) {
        instance = instances[i];
        geometry = instance.geometry;
        instanceType = geometry.constructor;
        groundInstances[i] = new GeometryInstance({
          geometry: instanceType.createShadowVolume(
            geometry,
            getComputeMinimumHeightFunction(this),
            getComputeMaximumHeightFunction(this),
          ),
          attributes: instance.attributes,
          id: instance.id,
        });
      }
    }
 
    primitiveOptions.geometryInstances = groundInstances;
    primitiveOptions.appearance = this.appearance;
 
    primitiveOptions._createBoundingVolumeFunction = function (
      frameState,
      geometry,
    ) {
      createBoundingVolume(that, frameState, geometry);
    };
    primitiveOptions._updateAndQueueCommandsFunction = function (
      primitive,
      frameState,
      colorCommands,
      pickCommands,
      modelMatrix,
      cull,
      debugShowBoundingVolume,
      twoPasses,
    ) {
      updateAndQueueCommands(
        that,
        frameState,
        colorCommands,
        pickCommands,
        modelMatrix,
        cull,
        debugShowBoundingVolume,
        twoPasses,
      );
    };
 
    this._primitive = new ClassificationPrimitive(primitiveOptions);
  }
 
  this._primitive.appearance = this.appearance;
  this._primitive.show = this.show;
  this._primitive.debugShowShadowVolume = this.debugShowShadowVolume;
  this._primitive.debugShowBoundingVolume = this.debugShowBoundingVolume;
  this._primitive.update(frameState);
 
  frameState.afterRender.push(() => {
    if (!this._ready && defined(this._primitive) && this._primitive.ready) {
      this._ready = true;
 
      if (this.releaseGeometryInstances) {
        this.geometryInstances = undefined;
      }
    }
  });
};
 
/**
 * @private
 */
GroundPrimitive.prototype.getBoundingSphere = function (id) {
  const index = this._boundingSpheresKeys.indexOf(id);
  if (index !== -1) {
    return this._boundingSpheres[index];
  }
 
  return undefined;
};
 
/**
 * Returns the modifiable per-instance attributes for a {@link GeometryInstance}.
 *
 * @param {*} id The id of the {@link GeometryInstance}.
 * @returns {object} The typed array in the attribute's format or undefined if the is no instance with id.
 *
 * @exception {DeveloperError} must call update before calling getGeometryInstanceAttributes.
 *
 * @example
 * const attributes = primitive.getGeometryInstanceAttributes('an id');
 * attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.AQUA);
 * attributes.show = Cesium.ShowGeometryInstanceAttribute.toValue(true);
 */
GroundPrimitive.prototype.getGeometryInstanceAttributes = function (id) {
  //>>includeStart('debug', pragmas.debug);
  if (!defined(this._primitive)) {
    throw new DeveloperError(
      "must call update before calling getGeometryInstanceAttributes",
    );
  }
  //>>includeEnd('debug');
  return this._primitive.getGeometryInstanceAttributes(id);
};
 
/**
 * Returns true if this object was destroyed; otherwise, false.
 * <p>
 * If this object was destroyed, it should not be used; calling any function other than
 * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
 * </p>
 *
 * @returns {boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
 *
 * @see GroundPrimitive#destroy
 */
GroundPrimitive.prototype.isDestroyed = function () {
  return false;
};
 
/**
 * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
 * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
 * <p>
 * Once an object is destroyed, it should not be used; calling any function other than
 * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
 * assign the return value (<code>undefined</code>) to the object as done in the example.
 * </p>
 *
 * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
 *
 * @example
 * e = e && e.destroy();
 *
 * @see GroundPrimitive#isDestroyed
 */
GroundPrimitive.prototype.destroy = function () {
  this._primitive = this._primitive && this._primitive.destroy();
  return destroyObject(this);
};
 
/**
 * Exposed for testing.
 *
 * @param {Context} context Rendering context
 * @returns {boolean} Whether or not the current context supports materials on GroundPrimitives.
 * @private
 */
GroundPrimitive._supportsMaterials = function (context) {
  return context.depthTexture;
};
 
/**
 * Checks if the given Scene supports materials on GroundPrimitives.
 * Materials on GroundPrimitives require support for the WEBGL_depth_texture extension.
 *
 * @param {Scene} scene The current scene.
 * @returns {boolean} Whether or not the current scene supports materials on GroundPrimitives.
 */
GroundPrimitive.supportsMaterials = function (scene) {
  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.object("scene", scene);
  //>>includeEnd('debug');
 
  return GroundPrimitive._supportsMaterials(scene.frameState.context);
};
export default GroundPrimitive;