All files / engine/Source/Scene Vector3DTilePrimitive.js

88.32% Statements 439/497
87.5% Branches 112/128
83.33% Functions 25/30
88.27% Lines 429/486

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277                                                                                                          228x   228x 228x     228x 228x       228x 228x 228x 228x   228x 228x   228x   228x 228x 228x 228x 228x     228x   228x 228x 228x 228x 228x   228x 228x 228x   228x 228x   228x 228x 228x   228x   228x 228x                   228x 228x 228x             228x             228x       228x 228x 228x 228x 228x 228x 228x   228x   228x 228x 316x 316x       1x                     1990x                           192x         1x           2555x 2327x     228x         228x         228x                   228x                                 228x           228x                         228x 228x 228x       2555x 2327x     228x   228x   228x 228x 228x 228x                                                       228x         228x           228x   228x     228x         228x             228x     228x         228x             228x 228x               228x     228x       228x                 456x     456x                                                                 1x                                                   1x                                                   2555x 2327x     228x     228x     228x 228x     1x 1x     2555x 2327x     228x                                                     228x                         26x   26x 26x 34x 34x 34x 34x   34x         34x   34x 34x     26x       9x 9x 9x 9x   9x   9x 9x   9x                   9x 9x   9x 17x 17x 13x                 13x 13x   4x 4x                   4x 4x 4x 4x       9x   9x 9x                                                                                                                                                                                                     17x           2235x 1569x     666x 666x   666x 666x   666x 1055x 1055x 1055x 368x 368x   687x       666x 298x 298x     368x         359x 359x     9x   9x     9x     9x 9x 9x 9x 9x       2235x   2235x 2235x 2235x 2235x   2235x         1995x     240x   240x 240x 240x 240x 240x   240x 316x 316x   316x 316x 300x         316x 316x 316x 316x 316x 316x 316x 316x 316x 316x   316x       316x   316x 316x   316x 316x 300x         316x 316x 316x 316x 316x 316x 316x 316x 316x 316x   316x       316x 316x     240x       2235x         2229x     6x 6x 6x   6x 6x   6x 6x 6x       6x 6x   6x     6x       317x 236x     81x 81x 81x   81x 81x 81x 81x 81x   81x 129x 129x 129x       129x 129x 129x           129x 129x 129x 129x 129x 129x 129x 129x 129x   129x       129x   129x 129x   129x 129x 129x           129x 129x 129x 129x 129x 129x 129x 129x 129x   129x       129x 129x     81x                 1x 138x 138x 138x 195x 195x                   1x 5x       12x   12x 12x     12x 12x 12x   12x 12x     12x 12x   12x 12x     12x 12x     1x   1x 1x   1x               1x 237x 12x 12x     225x   225x   225x   225x 225x     225x 360x 360x   360x     360x         225x 75x 75x   75x 120x     75x 75x                     1x 185x 128x     57x 57x 57x       57x 57x   57x 57x   57x 57x     57x 63x 63x   63x 57x       57x                 57x 57x   57x 57x   57x 72x 72x 57x     15x 15x 12x   3x       57x 3x                     57x 6x 6x   51x     57x       2542x   2542x   2542x   2542x 2542x     2542x 7862x 7568x 7568x 7568x   7862x 7566x 7566x 7566x       2542x 2538x     4x 4x 4x         10x 10x 10x 10x 10x 10x         2235x 2235x   2235x 2231x     4x 4x           4x 4x 4x           4x 4x 4x 4x 4x 4x     4x 4x               1x 2555x   2555x 2555x 2555x 2555x   2555x 2555x 2235x 2235x 2235x   2235x 10x   2225x       2555x 317x 317x                         1x                             1x 228x 228x 228x 228x 228x      
import Cartesian3 from "../Core/Cartesian3.js";
import Color from "../Core/Color.js";
import ComponentDatatype from "../Core/ComponentDatatype.js";
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import destroyObject from "../Core/destroyObject.js";
import IndexDatatype from "../Core/IndexDatatype.js";
import Matrix4 from "../Core/Matrix4.js";
import PrimitiveType from "../Core/PrimitiveType.js";
import Buffer from "../Renderer/Buffer.js";
import BufferUsage from "../Renderer/BufferUsage.js";
import DrawCommand from "../Renderer/DrawCommand.js";
import Pass from "../Renderer/Pass.js";
import RenderState from "../Renderer/RenderState.js";
import ShaderProgram from "../Renderer/ShaderProgram.js";
import ShaderSource from "../Renderer/ShaderSource.js";
import VertexArray from "../Renderer/VertexArray.js";
import ShadowVolumeFS from "../Shaders/ShadowVolumeFS.js";
import VectorTileVS from "../Shaders/VectorTileVS.js";
import BlendingState from "./BlendingState.js";
import Cesium3DTileFeature from "./Cesium3DTileFeature.js";
import ClassificationType from "./ClassificationType.js";
import DepthFunction from "./DepthFunction.js";
import Expression from "./Expression.js";
import StencilConstants from "./StencilConstants.js";
import StencilFunction from "./StencilFunction.js";
import StencilOperation from "./StencilOperation.js";
import Vector3DTileBatch from "./Vector3DTileBatch.js";
 
/**
 * Creates a batch of classification meshes.
 *
 * @alias Vector3DTilePrimitive
 * @constructor
 *
 * @param {object} options An object with following properties:
 * @param {Float32Array} options.positions The positions of the meshes.
 * @param {Uint16Array|Uint32Array} options.indices The indices of the triangulated meshes. The indices must be contiguous so that
 * the indices for mesh n are in [i, i + indexCounts[n]] where i = sum{indexCounts[0], indexCounts[n - 1]}.
 * @param {Uint32Array} options.indexCounts The number of indices for each mesh.
 * @param {Uint32Array} options.indexOffsets The offset into the index buffer for each mesh.
 * @param {Vector3DTileBatch[]} options.batchedIndices The index offset and count for each batch with the same color.
 * @param {Cartesian3} [options.center=Cartesian3.ZERO] The RTC center.
 * @param {Cesium3DTileBatchTable} options.batchTable The batch table for the tile containing the batched meshes.
 * @param {Uint16Array} options.batchIds The batch ids for each mesh.
 * @param {Uint16Array} options.vertexBatchIds The batch id for each vertex.
 * @param {BoundingSphere} options.boundingVolume The bounding volume for the entire batch of meshes.
 * @param {BoundingSphere[]} options.boundingVolumes The bounding volume for each mesh.
 * @param {ClassificationType} [options.classificationType] What this tile will classify.
 *
 * @private
 */
function Vector3DTilePrimitive(options) {
  options = options ?? Frozen.EMPTY_OBJECT;
 
  this._batchTable = options.batchTable;
  this._batchIds = options.batchIds;
 
  // These arrays are released after VAO creation.
  this._positions = options.positions;
  this._vertexBatchIds = options.vertexBatchIds;
 
  // These arrays are kept for re-batching indices based on colors.
  // If WebGL 2 is supported, indices will be released and re-batching uses buffer-to-buffer copies.
  this._indices = options.indices;
  this._indexCounts = options.indexCounts;
  this._indexOffsets = options.indexOffsets;
  this._batchedIndices = options.batchedIndices;
 
  this._boundingVolume = options.boundingVolume;
  this._boundingVolumes = options.boundingVolumes;
 
  this._center = options.center ?? Cartesian3.ZERO;
 
  this._va = undefined;
  this._sp = undefined;
  this._spStencil = undefined;
  this._spPick = undefined;
  this._uniformMap = undefined;
 
  // Only used with WebGL 2 to ping-pong ibos after copy.
  this._vaSwap = undefined;
 
  this._rsStencilDepthPass = undefined;
  this._rsStencilDepthPass3DTiles = undefined;
  this._rsColorPass = undefined;
  this._rsPickPass = undefined;
  this._rsWireframe = undefined;
 
  this._commands = [];
  this._commandsIgnoreShow = [];
  this._pickCommands = [];
 
  this._constantColor = Color.clone(Color.WHITE);
  this._highlightColor = this._constantColor;
 
  this._batchDirty = true;
  this._pickCommandsDirty = true;
  this._framesSinceLastRebatch = 0;
 
  this._updatingAllCommands = false;
 
  this._trianglesLength = this._indices.length / 3;
  this._geometryByteLength =
    this._indices.byteLength +
    this._positions.byteLength +
    this._vertexBatchIds.byteLength;
 
  /**
   * Draw the wireframe of the classification meshes.
   * @type {boolean}
   * @default false
   */
  this.debugWireframe = false;
  this._debugWireframe = this.debugWireframe;
  this._wireframeDirty = false;
 
  /**
   * Forces a re-batch instead of waiting after a number of frames have been rendered. For testing only.
   * @type {boolean}
   * @default false
   */
  this.forceRebatch = false;
 
  /**
   * What this tile will classify.
   * @type {ClassificationType}
   * @default ClassificationType.BOTH
   */
  this.classificationType =
    options.classificationType ?? ClassificationType.BOTH;
 
  // Hidden options
  this._vertexShaderSource = options._vertexShaderSource;
  this._fragmentShaderSource = options._fragmentShaderSource;
  this._attributeLocations = options._attributeLocations;
  this._uniformMap = options._uniformMap;
  this._pickId = options._pickId;
  this._modelMatrix = options._modelMatrix;
  this._boundingSphere = options._boundingSphere;
 
  this._batchIdLookUp = {};
 
  const length = this._batchIds.length;
  for (let i = 0; i < length; ++i) {
    const batchId = this._batchIds[i];
    this._batchIdLookUp[batchId] = i;
  }
}
 
Object.defineProperties(Vector3DTilePrimitive.prototype, {
  /**
   * Gets the number of triangles.
   *
   * @memberof Vector3DTilePrimitive.prototype
   *
   * @type {number}
   * @readonly
   */
  trianglesLength: {
    get: function () {
      return this._trianglesLength;
    },
  },
 
  /**
   * Gets the geometry memory in bytes.
   *
   * @memberof Vector3DTilePrimitive.prototype
   *
   * @type {number}
   * @readonly
   */
  geometryByteLength: {
    get: function () {
      return this._geometryByteLength;
    },
  },
});
 
const defaultAttributeLocations = {
  position: 0,
  a_batchId: 1,
};
 
function createVertexArray(primitive, context) {
  if (defined(primitive._va)) {
    return;
  }
 
  const positionBuffer = Buffer.createVertexBuffer({
    context: context,
    typedArray: primitive._positions,
    usage: BufferUsage.STATIC_DRAW,
  });
  const idBuffer = Buffer.createVertexBuffer({
    context: context,
    typedArray: primitive._vertexBatchIds,
    usage: BufferUsage.STATIC_DRAW,
  });
  const indexBuffer = Buffer.createIndexBuffer({
    context: context,
    typedArray: primitive._indices,
    usage: BufferUsage.DYNAMIC_DRAW,
    indexDatatype:
      primitive._indices.BYTES_PER_ELEMENT === 2
        ? IndexDatatype.UNSIGNED_SHORT
        : IndexDatatype.UNSIGNED_INT,
  });
 
  const vertexAttributes = [
    {
      index: 0,
      vertexBuffer: positionBuffer,
      componentDatatype: ComponentDatatype.fromTypedArray(primitive._positions),
      componentsPerAttribute: 3,
    },
    {
      index: 1,
      vertexBuffer: idBuffer,
      componentDatatype: ComponentDatatype.fromTypedArray(
        primitive._vertexBatchIds,
      ),
      componentsPerAttribute: 1,
    },
  ];
 
  primitive._va = new VertexArray({
    context: context,
    attributes: vertexAttributes,
    indexBuffer: indexBuffer,
  });
 
  Iif (context.webgl2) {
    primitive._vaSwap = new VertexArray({
      context: context,
      attributes: vertexAttributes,
      indexBuffer: Buffer.createIndexBuffer({
        context: context,
        sizeInBytes: indexBuffer.sizeInBytes,
        usage: BufferUsage.DYNAMIC_DRAW,
        indexDatatype: indexBuffer.indexDatatype,
      }),
    });
  }
 
  primitive._batchedPositions = undefined;
  primitive._transferrableBatchIds = undefined;
  primitive._vertexBatchIds = undefined;
}
 
function createShaders(primitive, context) {
  if (defined(primitive._sp)) {
    return;
  }
 
  const batchTable = primitive._batchTable;
  const attributeLocations =
    primitive._attributeLocations ?? defaultAttributeLocations;
 
  let pickId = primitive._pickId;
  const vertexShaderSource = primitive._vertexShaderSource;
  let fragmentShaderSource = primitive._fragmentShaderSource;
  Iif (defined(vertexShaderSource)) {
    primitive._sp = ShaderProgram.fromCache({
      context: context,
      vertexShaderSource: vertexShaderSource,
      fragmentShaderSource: fragmentShaderSource,
      attributeLocations: attributeLocations,
    });
    primitive._spStencil = primitive._sp;
 
    fragmentShaderSource = ShaderSource.replaceMain(
      fragmentShaderSource,
      "czm_non_pick_main",
    );
    fragmentShaderSource =
      `${fragmentShaderSource}void main() \n` +
      `{ \n` +
      `    czm_non_pick_main(); \n` +
      `    out_FragColor = ${pickId}; \n` +
      `} \n`;
    primitive._spPick = ShaderProgram.fromCache({
      context: context,
      vertexShaderSource: vertexShaderSource,
      fragmentShaderSource: fragmentShaderSource,
      attributeLocations: attributeLocations,
    });
    return;
  }
 
  const vsSource = batchTable.getVertexShaderCallback(
    false,
    "a_batchId",
    undefined,
  )(VectorTileVS);
  let fsSource = batchTable.getFragmentShaderCallback(
    false,
    undefined,
    true,
  )(ShadowVolumeFS);
 
  pickId = batchTable.getPickId();
 
  let vs = new ShaderSource({
    sources: [vsSource],
  });
  let fs = new ShaderSource({
    defines: ["VECTOR_TILE"],
    sources: [fsSource],
  });
 
  primitive._sp = ShaderProgram.fromCache({
    context: context,
    vertexShaderSource: vs,
    fragmentShaderSource: fs,
    attributeLocations: attributeLocations,
  });
 
  vs = new ShaderSource({
    sources: [VectorTileVS],
  });
  fs = new ShaderSource({
    defines: ["VECTOR_TILE"],
    sources: [ShadowVolumeFS],
  });
 
  primitive._spStencil = ShaderProgram.fromCache({
    context: context,
    vertexShaderSource: vs,
    fragmentShaderSource: fs,
    attributeLocations: attributeLocations,
  });
 
  fsSource = ShaderSource.replaceMain(fsSource, "czm_non_pick_main");
  fsSource =
    `${fsSource}\n` +
    `void main() \n` +
    `{ \n` +
    `    czm_non_pick_main(); \n` +
    `    out_FragColor = ${pickId}; \n` +
    `} \n`;
 
  const pickVS = new ShaderSource({
    sources: [vsSource],
  });
  const pickFS = new ShaderSource({
    defines: ["VECTOR_TILE"],
    sources: [fsSource],
  });
  primitive._spPick = ShaderProgram.fromCache({
    context: context,
    vertexShaderSource: pickVS,
    fragmentShaderSource: pickFS,
    attributeLocations: attributeLocations,
  });
}
 
function getStencilDepthRenderState(mask3DTiles) {
  const stencilFunction = mask3DTiles
    ? StencilFunction.EQUAL
    : StencilFunction.ALWAYS;
  return {
    colorMask: {
      red: false,
      green: false,
      blue: false,
      alpha: false,
    },
    stencilTest: {
      enabled: true,
      frontFunction: stencilFunction,
      frontOperation: {
        fail: StencilOperation.KEEP,
        zFail: StencilOperation.DECREMENT_WRAP,
        zPass: StencilOperation.KEEP,
      },
      backFunction: stencilFunction,
      backOperation: {
        fail: StencilOperation.KEEP,
        zFail: StencilOperation.INCREMENT_WRAP,
        zPass: StencilOperation.KEEP,
      },
      reference: StencilConstants.CESIUM_3D_TILE_MASK,
      mask: StencilConstants.CESIUM_3D_TILE_MASK,
    },
    stencilMask: StencilConstants.CLASSIFICATION_MASK,
    depthTest: {
      enabled: true,
      func: DepthFunction.LESS_OR_EQUAL,
    },
    depthMask: false,
  };
}
 
const colorRenderState = {
  stencilTest: {
    enabled: true,
    frontFunction: StencilFunction.NOT_EQUAL,
    frontOperation: {
      fail: StencilOperation.ZERO,
      zFail: StencilOperation.ZERO,
      zPass: StencilOperation.ZERO,
    },
    backFunction: StencilFunction.NOT_EQUAL,
    backOperation: {
      fail: StencilOperation.ZERO,
      zFail: StencilOperation.ZERO,
      zPass: StencilOperation.ZERO,
    },
    reference: 0,
    mask: StencilConstants.CLASSIFICATION_MASK,
  },
  stencilMask: StencilConstants.CLASSIFICATION_MASK,
  depthTest: {
    enabled: false,
  },
  depthMask: false,
  blending: BlendingState.PRE_MULTIPLIED_ALPHA_BLEND,
};
 
const pickRenderState = {
  stencilTest: {
    enabled: true,
    frontFunction: StencilFunction.NOT_EQUAL,
    frontOperation: {
      fail: StencilOperation.ZERO,
      zFail: StencilOperation.ZERO,
      zPass: StencilOperation.ZERO,
    },
    backFunction: StencilFunction.NOT_EQUAL,
    backOperation: {
      fail: StencilOperation.ZERO,
      zFail: StencilOperation.ZERO,
      zPass: StencilOperation.ZERO,
    },
    reference: 0,
    mask: StencilConstants.CLASSIFICATION_MASK,
  },
  stencilMask: StencilConstants.CLASSIFICATION_MASK,
  depthTest: {
    enabled: false,
  },
  depthMask: false,
};
 
function createRenderStates(primitive) {
  if (defined(primitive._rsStencilDepthPass)) {
    return;
  }
 
  primitive._rsStencilDepthPass = RenderState.fromCache(
    getStencilDepthRenderState(false),
  );
  primitive._rsStencilDepthPass3DTiles = RenderState.fromCache(
    getStencilDepthRenderState(true),
  );
  primitive._rsColorPass = RenderState.fromCache(colorRenderState);
  primitive._rsPickPass = RenderState.fromCache(pickRenderState);
}
 
const modifiedModelViewScratch = new Matrix4();
const rtcScratch = new Cartesian3();
 
function createUniformMap(primitive, context) {
  if (defined(primitive._uniformMap)) {
    return;
  }
 
  const uniformMap = {
    u_modifiedModelViewProjection: function () {
      const viewMatrix = context.uniformState.view;
      const projectionMatrix = context.uniformState.projection;
      Matrix4.clone(viewMatrix, modifiedModelViewScratch);
      Matrix4.multiplyByPoint(
        modifiedModelViewScratch,
        primitive._center,
        rtcScratch,
      );
      Matrix4.setTranslation(
        modifiedModelViewScratch,
        rtcScratch,
        modifiedModelViewScratch,
      );
      Matrix4.multiply(
        projectionMatrix,
        modifiedModelViewScratch,
        modifiedModelViewScratch,
      );
      return modifiedModelViewScratch;
    },
    u_highlightColor: function () {
      return primitive._highlightColor;
    },
  };
 
  primitive._uniformMap =
    primitive._batchTable.getUniformMapCallback()(uniformMap);
}
 
function copyIndicesCPU(
  indices,
  newIndices,
  currentOffset,
  offsets,
  counts,
  batchIds,
  batchIdLookUp,
) {
  const sizeInBytes = indices.constructor.BYTES_PER_ELEMENT;
 
  const batchedIdsLength = batchIds.length;
  for (let j = 0; j < batchedIdsLength; ++j) {
    const batchedId = batchIds[j];
    const index = batchIdLookUp[batchedId];
    const offset = offsets[index];
    const count = counts[index];
 
    const subarray = new indices.constructor(
      indices.buffer,
      sizeInBytes * offset,
      count,
    );
    newIndices.set(subarray, currentOffset);
 
    offsets[index] = currentOffset;
    currentOffset += count;
  }
 
  return currentOffset;
}
 
function rebatchCPU(primitive, batchedIndices) {
  const indices = primitive._indices;
  const indexOffsets = primitive._indexOffsets;
  const indexCounts = primitive._indexCounts;
  const batchIdLookUp = primitive._batchIdLookUp;
 
  const newIndices = new indices.constructor(indices.length);
 
  let current = batchedIndices.pop();
  const newBatchedIndices = [current];
 
  let currentOffset = copyIndicesCPU(
    indices,
    newIndices,
    0,
    indexOffsets,
    indexCounts,
    current.batchIds,
    batchIdLookUp,
  );
 
  current.offset = 0;
  current.count = currentOffset;
 
  while (batchedIndices.length > 0) {
    const next = batchedIndices.pop();
    if (Color.equals(next.color, current.color)) {
      currentOffset = copyIndicesCPU(
        indices,
        newIndices,
        currentOffset,
        indexOffsets,
        indexCounts,
        next.batchIds,
        batchIdLookUp,
      );
      current.batchIds = current.batchIds.concat(next.batchIds);
      current.count = currentOffset - current.offset;
    } else {
      const offset = currentOffset;
      currentOffset = copyIndicesCPU(
        indices,
        newIndices,
        currentOffset,
        indexOffsets,
        indexCounts,
        next.batchIds,
        batchIdLookUp,
      );
 
      next.offset = offset;
      next.count = currentOffset - offset;
      newBatchedIndices.push(next);
      current = next;
    }
  }
 
  primitive._va.indexBuffer.copyFromArrayView(newIndices);
 
  primitive._indices = newIndices;
  primitive._batchedIndices = newBatchedIndices;
}
 
function copyIndicesGPU(
  readBuffer,
  writeBuffer,
  currentOffset,
  offsets,
  counts,
  batchIds,
  batchIdLookUp,
) {
  const sizeInBytes = readBuffer.bytesPerIndex;
 
  const batchedIdsLength = batchIds.length;
  for (let j = 0; j < batchedIdsLength; ++j) {
    const batchedId = batchIds[j];
    const index = batchIdLookUp[batchedId];
    const offset = offsets[index];
    const count = counts[index];
 
    writeBuffer.copyFromBuffer(
      readBuffer,
      offset * sizeInBytes,
      currentOffset * sizeInBytes,
      count * sizeInBytes,
    );
 
    offsets[index] = currentOffset;
    currentOffset += count;
  }
 
  return currentOffset;
}
 
function rebatchGPU(primitive, batchedIndices) {
  const indexOffsets = primitive._indexOffsets;
  const indexCounts = primitive._indexCounts;
  const batchIdLookUp = primitive._batchIdLookUp;
 
  let current = batchedIndices.pop();
  const newBatchedIndices = [current];
 
  const readBuffer = primitive._va.indexBuffer;
  const writeBuffer = primitive._vaSwap.indexBuffer;
 
  let currentOffset = copyIndicesGPU(
    readBuffer,
    writeBuffer,
    0,
    indexOffsets,
    indexCounts,
    current.batchIds,
    batchIdLookUp,
  );
 
  current.offset = 0;
  current.count = currentOffset;
 
  while (batchedIndices.length > 0) {
    const next = batchedIndices.pop();
    if (Color.equals(next.color, current.color)) {
      currentOffset = copyIndicesGPU(
        readBuffer,
        writeBuffer,
        currentOffset,
        indexOffsets,
        indexCounts,
        next.batchIds,
        batchIdLookUp,
      );
      current.batchIds = current.batchIds.concat(next.batchIds);
      current.count = currentOffset - current.offset;
    } else {
      const offset = currentOffset;
      currentOffset = copyIndicesGPU(
        readBuffer,
        writeBuffer,
        currentOffset,
        indexOffsets,
        indexCounts,
        next.batchIds,
        batchIdLookUp,
      );
      next.offset = offset;
      next.count = currentOffset - offset;
      newBatchedIndices.push(next);
      current = next;
    }
  }
 
  const temp = primitive._va;
  primitive._va = primitive._vaSwap;
  primitive._vaSwap = temp;
 
  primitive._batchedIndices = newBatchedIndices;
}
 
function compareColors(a, b) {
  return b.color.toRgba() - a.color.toRgba();
}
 
// PERFORMANCE_IDEA: For WebGL 2, we can use copyBufferSubData for buffer-to-buffer copies.
// PERFORMANCE_IDEA: Not supported, but we could use glMultiDrawElements here.
function rebatchCommands(primitive, context) {
  if (!primitive._batchDirty) {
    return false;
  }
 
  const batchedIndices = primitive._batchedIndices;
  const length = batchedIndices.length;
 
  let needToRebatch = false;
  const colorCounts = {};
 
  for (let i = 0; i < length; ++i) {
    const color = batchedIndices[i].color;
    const rgba = color.toRgba();
    if (defined(colorCounts[rgba])) {
      needToRebatch = true;
      break;
    } else {
      colorCounts[rgba] = true;
    }
  }
 
  if (!needToRebatch) {
    primitive._batchDirty = false;
    return false;
  }
 
  if (
    needToRebatch &&
    !primitive.forceRebatch &&
    primitive._framesSinceLastRebatch < 120
  ) {
    ++primitive._framesSinceLastRebatch;
    return;
  }
 
  batchedIndices.sort(compareColors);
 
  Iif (context.webgl2) {
    rebatchGPU(primitive, batchedIndices);
  } else {
    rebatchCPU(primitive, batchedIndices);
  }
 
  primitive._framesSinceLastRebatch = 0;
  primitive._batchDirty = false;
  primitive._pickCommandsDirty = true;
  primitive._wireframeDirty = true;
  return true;
}
 
function createColorCommands(primitive, context) {
  const needsRebatch = rebatchCommands(primitive, context);
 
  const commands = primitive._commands;
  const batchedIndices = primitive._batchedIndices;
  const length = batchedIndices.length;
  const commandsLength = length * 2;
 
  if (
    defined(commands) &&
    !needsRebatch &&
    commands.length === commandsLength
  ) {
    return;
  }
 
  commands.length = commandsLength;
 
  const vertexArray = primitive._va;
  const sp = primitive._sp;
  const modelMatrix = primitive._modelMatrix ?? Matrix4.IDENTITY;
  const uniformMap = primitive._uniformMap;
  const bv = primitive._boundingVolume;
 
  for (let j = 0; j < length; ++j) {
    const offset = batchedIndices[j].offset;
    const count = batchedIndices[j].count;
 
    let stencilDepthCommand = commands[j * 2];
    if (!defined(stencilDepthCommand)) {
      stencilDepthCommand = commands[j * 2] = new DrawCommand({
        owner: primitive,
      });
    }
 
    stencilDepthCommand.vertexArray = vertexArray;
    stencilDepthCommand.modelMatrix = modelMatrix;
    stencilDepthCommand.offset = offset;
    stencilDepthCommand.count = count;
    stencilDepthCommand.renderState = primitive._rsStencilDepthPass;
    stencilDepthCommand.shaderProgram = sp;
    stencilDepthCommand.uniformMap = uniformMap;
    stencilDepthCommand.boundingVolume = bv;
    stencilDepthCommand.cull = false;
    stencilDepthCommand.pass = Pass.TERRAIN_CLASSIFICATION;
 
    const stencilDepthDerivedCommand = DrawCommand.shallowClone(
      stencilDepthCommand,
      stencilDepthCommand.derivedCommands.tileset,
    );
    stencilDepthDerivedCommand.renderState =
      primitive._rsStencilDepthPass3DTiles;
    stencilDepthDerivedCommand.pass = Pass.CESIUM_3D_TILE_CLASSIFICATION;
    stencilDepthCommand.derivedCommands.tileset = stencilDepthDerivedCommand;
 
    let colorCommand = commands[j * 2 + 1];
    if (!defined(colorCommand)) {
      colorCommand = commands[j * 2 + 1] = new DrawCommand({
        owner: primitive,
      });
    }
 
    colorCommand.vertexArray = vertexArray;
    colorCommand.modelMatrix = modelMatrix;
    colorCommand.offset = offset;
    colorCommand.count = count;
    colorCommand.renderState = primitive._rsColorPass;
    colorCommand.shaderProgram = sp;
    colorCommand.uniformMap = uniformMap;
    colorCommand.boundingVolume = bv;
    colorCommand.cull = false;
    colorCommand.pass = Pass.TERRAIN_CLASSIFICATION;
 
    const colorDerivedCommand = DrawCommand.shallowClone(
      colorCommand,
      colorCommand.derivedCommands.tileset,
    );
    colorDerivedCommand.pass = Pass.CESIUM_3D_TILE_CLASSIFICATION;
    colorCommand.derivedCommands.tileset = colorDerivedCommand;
  }
 
  primitive._commandsDirty = true;
}
 
function createColorCommandsIgnoreShow(primitive, frameState) {
  if (
    primitive.classificationType === ClassificationType.TERRAIN ||
    !frameState.invertClassification ||
    (defined(primitive._commandsIgnoreShow) && !primitive._commandsDirty)
  ) {
    return;
  }
 
  const commands = primitive._commands;
  const commandsIgnoreShow = primitive._commandsIgnoreShow;
  const spStencil = primitive._spStencil;
 
  const commandsLength = commands.length;
  const length = (commandsIgnoreShow.length = commandsLength / 2);
 
  let commandIndex = 0;
  for (let j = 0; j < length; ++j) {
    const commandIgnoreShow = (commandsIgnoreShow[j] = DrawCommand.shallowClone(
      commands[commandIndex],
      commandsIgnoreShow[j],
    ));
    commandIgnoreShow.shaderProgram = spStencil;
    commandIgnoreShow.pass = Pass.CESIUM_3D_TILE_CLASSIFICATION_IGNORE_SHOW;
 
    commandIndex += 2;
  }
 
  primitive._commandsDirty = false;
}
 
function createPickCommands(primitive) {
  if (!primitive._pickCommandsDirty) {
    return;
  }
 
  const length = primitive._indexOffsets.length;
  const pickCommands = primitive._pickCommands;
  pickCommands.length = length * 2;
 
  const vertexArray = primitive._va;
  const spStencil = primitive._spStencil;
  const spPick = primitive._spPick;
  const modelMatrix = primitive._modelMatrix ?? Matrix4.IDENTITY;
  const uniformMap = primitive._uniformMap;
 
  for (let j = 0; j < length; ++j) {
    const offset = primitive._indexOffsets[j];
    const count = primitive._indexCounts[j];
    const bv = defined(primitive._boundingVolumes)
      ? primitive._boundingVolumes[j]
      : primitive.boundingVolume;
 
    let stencilDepthCommand = pickCommands[j * 2];
    Eif (!defined(stencilDepthCommand)) {
      stencilDepthCommand = pickCommands[j * 2] = new DrawCommand({
        owner: primitive,
        pickOnly: true,
      });
    }
 
    stencilDepthCommand.vertexArray = vertexArray;
    stencilDepthCommand.modelMatrix = modelMatrix;
    stencilDepthCommand.offset = offset;
    stencilDepthCommand.count = count;
    stencilDepthCommand.renderState = primitive._rsStencilDepthPass;
    stencilDepthCommand.shaderProgram = spStencil;
    stencilDepthCommand.uniformMap = uniformMap;
    stencilDepthCommand.boundingVolume = bv;
    stencilDepthCommand.pass = Pass.TERRAIN_CLASSIFICATION;
 
    const stencilDepthDerivedCommand = DrawCommand.shallowClone(
      stencilDepthCommand,
      stencilDepthCommand.derivedCommands.tileset,
    );
    stencilDepthDerivedCommand.renderState =
      primitive._rsStencilDepthPass3DTiles;
    stencilDepthDerivedCommand.pass = Pass.CESIUM_3D_TILE_CLASSIFICATION;
    stencilDepthCommand.derivedCommands.tileset = stencilDepthDerivedCommand;
 
    let colorCommand = pickCommands[j * 2 + 1];
    Eif (!defined(colorCommand)) {
      colorCommand = pickCommands[j * 2 + 1] = new DrawCommand({
        owner: primitive,
        pickOnly: true,
      });
    }
 
    colorCommand.vertexArray = vertexArray;
    colorCommand.modelMatrix = modelMatrix;
    colorCommand.offset = offset;
    colorCommand.count = count;
    colorCommand.renderState = primitive._rsPickPass;
    colorCommand.shaderProgram = spPick;
    colorCommand.uniformMap = uniformMap;
    colorCommand.boundingVolume = bv;
    colorCommand.pass = Pass.TERRAIN_CLASSIFICATION;
 
    const colorDerivedCommand = DrawCommand.shallowClone(
      colorCommand,
      colorCommand.derivedCommands.tileset,
    );
    colorDerivedCommand.pass = Pass.CESIUM_3D_TILE_CLASSIFICATION;
    colorCommand.derivedCommands.tileset = colorDerivedCommand;
  }
 
  primitive._pickCommandsDirty = false;
}
 
/**
 * Creates features for each mesh and places it at the batch id index of features.
 *
 * @param {Vector3DTileContent} content The vector tile content.
 * @param {Cesium3DTileFeature[]} features An array of features where the polygon features will be placed.
 */
Vector3DTilePrimitive.prototype.createFeatures = function (content, features) {
  const batchIds = this._batchIds;
  const length = batchIds.length;
  for (let i = 0; i < length; ++i) {
    const batchId = batchIds[i];
    features[batchId] = new Cesium3DTileFeature(content, batchId);
  }
};
 
/**
 * Colors the entire tile when enabled is true. The resulting color will be (mesh batch table color * color).
 *
 * @param {boolean} enabled Whether to enable debug coloring.
 * @param {Color} color The debug color.
 */
Vector3DTilePrimitive.prototype.applyDebugSettings = function (enabled, color) {
  this._highlightColor = enabled ? color : this._constantColor;
};
 
function clearStyle(polygons, features) {
  polygons._updatingAllCommands = true;
 
  const batchIds = polygons._batchIds;
  let length = batchIds.length;
  let i;
 
  for (i = 0; i < length; ++i) {
    const batchId = batchIds[i];
    const feature = features[batchId];
 
    feature.show = true;
    feature.color = Color.WHITE;
  }
 
  const batchedIndices = polygons._batchedIndices;
  length = batchedIndices.length;
 
  for (i = 0; i < length; ++i) {
    batchedIndices[i].color = Color.clone(Color.WHITE);
  }
 
  polygons._updatingAllCommands = false;
  polygons._batchDirty = true;
}
 
const scratchColor = new Color();
 
const DEFAULT_COLOR_VALUE = Color.WHITE;
const DEFAULT_SHOW_VALUE = true;
 
const complexExpressionReg = /\$/;
 
/**
 * Apply a style to the content.
 *
 * @param {Cesium3DTileStyle} style The style.
 * @param {Cesium3DTileFeature[]} features The array of features.
 */
Vector3DTilePrimitive.prototype.applyStyle = function (style, features) {
  if (!defined(style)) {
    clearStyle(this, features);
    return;
  }
 
  const colorExpression = style.color;
  const isSimpleStyle =
    colorExpression instanceof Expression &&
    !complexExpressionReg.test(colorExpression.expression);
  this._updatingAllCommands = isSimpleStyle;
 
  const batchIds = this._batchIds;
  let length = batchIds.length;
  let i;
 
  for (i = 0; i < length; ++i) {
    const batchId = batchIds[i];
    const feature = features[batchId];
 
    feature.color = defined(style.color)
      ? style.color.evaluateColor(feature, scratchColor)
      : DEFAULT_COLOR_VALUE;
    feature.show = defined(style.show)
      ? style.show.evaluate(feature)
      : DEFAULT_SHOW_VALUE;
  }
 
  if (isSimpleStyle) {
    const batchedIndices = this._batchedIndices;
    length = batchedIndices.length;
 
    for (i = 0; i < length; ++i) {
      batchedIndices[i].color = Color.clone(Color.WHITE);
    }
 
    this._updatingAllCommands = false;
    this._batchDirty = true;
  }
};
 
/**
 * Call when updating the color of a mesh with batchId changes color. The meshes will need to be re-batched
 * on the next update.
 *
 * @param {number} batchId The batch id of the meshes whose color has changed.
 * @param {Color} color The new polygon color.
 */
Vector3DTilePrimitive.prototype.updateCommands = function (batchId, color) {
  if (this._updatingAllCommands) {
    return;
  }
 
  const batchIdLookUp = this._batchIdLookUp;
  const index = batchIdLookUp[batchId];
  Iif (!defined(index)) {
    return;
  }
 
  const indexOffsets = this._indexOffsets;
  const indexCounts = this._indexCounts;
 
  const offset = indexOffsets[index];
  const count = indexCounts[index];
 
  const batchedIndices = this._batchedIndices;
  const length = batchedIndices.length;
 
  let i;
  for (i = 0; i < length; ++i) {
    const batchedOffset = batchedIndices[i].offset;
    const batchedCount = batchedIndices[i].count;
 
    if (offset >= batchedOffset && offset < batchedOffset + batchedCount) {
      break;
    }
  }
 
  batchedIndices.push(
    new Vector3DTileBatch({
      color: Color.clone(color),
      offset: offset,
      count: count,
      batchIds: [batchId],
    }),
  );
 
  const startIds = [];
  const endIds = [];
 
  const batchIds = batchedIndices[i].batchIds;
  const batchIdsLength = batchIds.length;
 
  for (let j = 0; j < batchIdsLength; ++j) {
    const id = batchIds[j];
    if (id === batchId) {
      continue;
    }
 
    const offsetIndex = batchIdLookUp[id];
    if (indexOffsets[offsetIndex] < offset) {
      startIds.push(id);
    } else {
      endIds.push(id);
    }
  }
 
  if (endIds.length !== 0) {
    batchedIndices.push(
      new Vector3DTileBatch({
        color: Color.clone(batchedIndices[i].color),
        offset: offset + count,
        count:
          batchedIndices[i].offset + batchedIndices[i].count - (offset + count),
        batchIds: endIds,
      }),
    );
  }
 
  if (startIds.length !== 0) {
    batchedIndices[i].count = offset - batchedIndices[i].offset;
    batchedIndices[i].batchIds = startIds;
  } else {
    batchedIndices.splice(i, 1);
  }
 
  this._batchDirty = true;
};
 
function queueCommands(primitive, frameState, commands, commandsIgnoreShow) {
  const classificationType = primitive.classificationType;
  const queueTerrainCommands =
    classificationType !== ClassificationType.CESIUM_3D_TILE;
  const queue3DTilesCommands =
    classificationType !== ClassificationType.TERRAIN;
 
  const commandList = frameState.commandList;
  let commandLength = commands.length;
  let command;
  let i;
  for (i = 0; i < commandLength; ++i) {
    if (queueTerrainCommands) {
      command = commands[i];
      command.pass = Pass.TERRAIN_CLASSIFICATION;
      commandList.push(command);
    }
    if (queue3DTilesCommands) {
      command = commands[i].derivedCommands.tileset;
      command.pass = Pass.CESIUM_3D_TILE_CLASSIFICATION;
      commandList.push(command);
    }
  }
 
  if (!frameState.invertClassification || !defined(commandsIgnoreShow)) {
    return;
  }
 
  commandLength = commandsIgnoreShow.length;
  for (i = 0; i < commandLength; ++i) {
    commandList.push(commandsIgnoreShow[i]);
  }
}
 
function queueWireframeCommands(frameState, commands) {
  const commandList = frameState.commandList;
  const commandLength = commands.length;
  for (let i = 0; i < commandLength; i += 2) {
    const command = commands[i + 1];
    command.pass = Pass.OPAQUE;
    commandList.push(command);
  }
}
 
function updateWireframe(primitive) {
  let earlyExit = primitive.debugWireframe === primitive._debugWireframe;
  earlyExit =
    earlyExit && !(primitive.debugWireframe && primitive._wireframeDirty);
  if (earlyExit) {
    return;
  }
 
  Eif (!defined(primitive._rsWireframe)) {
    primitive._rsWireframe = RenderState.fromCache({});
  }
 
  let rs;
  let type;
 
  if (primitive.debugWireframe) {
    rs = primitive._rsWireframe;
    type = PrimitiveType.LINES;
  } else E{
    rs = primitive._rsColorPass;
    type = PrimitiveType.TRIANGLES;
  }
 
  const commands = primitive._commands;
  const commandLength = commands.length;
  for (let i = 0; i < commandLength; i += 2) {
    const command = commands[i + 1];
    command.renderState = rs;
    command.primitiveType = type;
  }
 
  primitive._debugWireframe = primitive.debugWireframe;
  primitive._wireframeDirty = false;
}
 
/**
 * Updates the batches and queues the commands for rendering.
 *
 * @param {FrameState} frameState The current frame state.
 */
Vector3DTilePrimitive.prototype.update = function (frameState) {
  const context = frameState.context;
 
  createVertexArray(this, context);
  createShaders(this, context);
  createRenderStates(this);
  createUniformMap(this, context);
 
  const passes = frameState.passes;
  if (passes.render) {
    createColorCommands(this, context);
    createColorCommandsIgnoreShow(this, frameState);
    updateWireframe(this);
 
    if (this._debugWireframe) {
      queueWireframeCommands(frameState, this._commands);
    } else {
      queueCommands(this, frameState, this._commands, this._commandsIgnoreShow);
    }
  }
 
  if (passes.pick) {
    createPickCommands(this);
    queueCommands(this, frameState, this._pickCommands);
  }
};
 
/**
 * 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>.
 */
Vector3DTilePrimitive.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.
 */
Vector3DTilePrimitive.prototype.destroy = function () {
  this._va = this._va && this._va.destroy();
  this._sp = this._sp && this._sp.destroy();
  this._spPick = this._spPick && this._spPick.destroy();
  this._vaSwap = this._vaSwap && this._vaSwap.destroy();
  return destroyObject(this);
};
export default Vector3DTilePrimitive;