All files / engine/Source/Scene PointCloud.js

79.34% Statements 488/615
63.8% Branches 201/315
64.51% Functions 20/31
79.24% Lines 485/612

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413                                                                          1x                                         83x 83x       83x   83x 83x 83x 83x 83x 83x   83x 83x 83x     83x 83x 83x 83x 83x 83x 83x     83x 83x 83x 83x 83x 83x     83x 83x     83x 83x   83x 83x   83x   83x 83x 83x   83x 83x 83x 83x 83x 83x 83x   83x 83x 83x   83x 83x   83x 83x 83x   83x 83x 83x       83x   83x 83x     83x 83x 83x               83x 83x   83x 83x     1x     237x           132x           80x                             576x 496x   80x                 83x       83x 83x 83x 83x 83x 83x       83x 80x               83x 3x 3x 3x     83x 83x 80x 80x 80x 80x     83x 83x       83x 83x 80x                   80x           83x 83x           83x               83x     1x 1x 1x                 64x     1x 1x 1x 20x     64x       64x 64x 64x 64x 64x 64x 64x 64x 64x 1280x 1280x 1280x 1280x     64x 64x 64x         198x 198x                     198x       1x 1x 1x   1x 1x 1x 1x 1x   1x 1x     66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x         66x 66x 66x   66x 66x   66x 198x 198x 198x 198x 198x   198x           198x   198x                   198x 198x       198x         66x         66x     66x 66x         66x       66x                   66x                         66x   66x   66x 2x         64x     66x                   66x 66x 2x         64x         66x 66x                     66x 66x                       66x                                                 66x                       66x 66x     66x         66x           66x               66x             66x 66x       66x                                         75x 75x 75x 75x   75x                                                                                                                                                             75x   75x 2x                               75x 75x     75x         136x 136x 136x                     136x 136x 136x 136x                   300x 300x 1050x 1050x 300x         1x                       75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x         75x   75x 75x 75x 75x 225x 225x 225x   225x       75x 70x       70x           70x         70x         70x         70x         75x   75x 75x 75x 75x     75x 75x   75x 68x 68x   75x       75x 68x 68x     75x 75x   75x             75x 225x 225x 225x 225x       225x       75x 75x   75x 75x       75x 75x                 75x     75x 7x   75x     75x       75x   75x 75x                               75x     75x               75x   75x 1x     75x   75x 7x   7x                   7x     75x               75x       75x 2x     75x 68x     75x       75x 68x     75x           75x 1x         75x 7x   7x                     7x     68x     75x 2x     73x   75x     75x                       75x     75x 68x       75x         75x 68x   7x 1x           6x     75x   75x             75x       75x             75x           75x   75x   75x 7x       7x 7x 7x     75x         75x 7x             75x   75x       75x       75x 75x     75x 75x   9x   75x             75x   75x                   316x 303x   13x 3x 3x 3x 3x 3x 3x   2x 2x     2x 2x     2x     2x       2x     2x 2x     2x 2x 2x         2x     2x   2x   2x         2x 2x 2x 6x 6x 6x 2x   6x             2x 2x         2x 2x 2x         2x           2x           2x     1x 1x       13x     1x 1x   1x 317x   317x 1x 1x 1x     316x 316x 13x     303x 303x   303x 68x 68x     303x 66x 66x 66x 66x 66x     303x 69x 69x 69x   69x 59x   69x 2x             69x 2x 2x         2x 2x       69x 69x   69x 69x 69x 69x 69x       303x 4x 4x     303x 2x 2x     303x         303x         303x 65x 65x 65x     303x 303x         303x 75x     303x 303x       303x     303x     303x   303x   303x 303x 303x       1x       1x 67x 67x 66x 66x     67x      
import BoundingSphere from "../Core/BoundingSphere.js";
import Cartesian3 from "../Core/Cartesian3.js";
import Cartesian4 from "../Core/Cartesian4.js";
import Check from "../Core/Check.js";
import clone from "../Core/clone.js";
import Color from "../Core/Color.js";
import combine from "../Core/combine.js";
import ComponentDatatype from "../Core/ComponentDatatype.js";
import defined from "../Core/defined.js";
import destroyObject from "../Core/destroyObject.js";
import CesiumMath from "../Core/Math.js";
import Matrix4 from "../Core/Matrix4.js";
import oneTimeWarning from "../Core/oneTimeWarning.js";
import OrthographicFrustum from "../Core/OrthographicFrustum.js";
import PrimitiveType from "../Core/PrimitiveType.js";
import RuntimeError from "../Core/RuntimeError.js";
import Transforms from "../Core/Transforms.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 VertexArray from "../Renderer/VertexArray.js";
import MersenneTwister from "mersenne-twister";
import BlendingState from "./BlendingState.js";
import Cesium3DTileBatchTable from "./Cesium3DTileBatchTable.js";
import DracoLoader from "./DracoLoader.js";
import getClipAndStyleCode from "./getClipAndStyleCode.js";
import getClippingFunction from "./getClippingFunction.js";
import PntsParser from "./PntsParser.js";
import SceneMode from "./SceneMode.js";
import ShadowMode from "./ShadowMode.js";
import SplitDirection from "./SplitDirection.js";
import Splitter from "./Splitter.js";
import StencilConstants from "./StencilConstants.js";
 
const DecodingState = {
  NEEDS_DECODE: 0,
  DECODING: 1,
  READY: 2,
  FAILED: 3,
};
 
/**
 * Represents the contents of a
 * {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/TileFormats/PointCloud|Point Cloud}
 * tile. Used internally by {@link TimeDynamicPointCloud}.
 *
 * @alias PointCloud
 * @constructor
 *
 * @see TimeDynamicPointCloud
 *
 * @private
 */
function PointCloud(options) {
  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.object("options", options);
  Check.typeOf.object("options.arrayBuffer", options.arrayBuffer);
  //>>includeEnd('debug');
 
  // Hold onto the payload until the render resources are created
  this._parsedContent = undefined;
 
  this._drawCommand = undefined;
  this._isTranslucent = false;
  this._styleTranslucent = false;
  this._constantColor = Color.clone(Color.DARKGRAY);
  this._highlightColor = Color.clone(Color.WHITE);
  this._pointSize = 1.0;
 
  this._rtcCenter = undefined;
  this._quantizedVolumeScale = undefined;
  this._quantizedVolumeOffset = undefined;
 
  // These values are used to regenerate the shader when the style changes
  this._styleableShaderAttributes = undefined;
  this._isQuantized = false;
  this._isOctEncoded16P = false;
  this._isRGB565 = false;
  this._hasColors = false;
  this._hasNormals = false;
  this._hasBatchIds = false;
 
  // Draco
  this._decodingState = DecodingState.READY;
  this._dequantizeInShader = true;
  this._isQuantizedDraco = false;
  this._isOctEncodedDraco = false;
  this._quantizedRange = 0.0;
  this._octEncodedRange = 0.0;
 
  // Use per-point normals to hide back-facing points.
  this.backFaceCulling = false;
  this._backFaceCulling = false;
 
  // Whether to enable normal shading
  this.normalShading = true;
  this._normalShading = true;
 
  this._opaqueRenderState = undefined;
  this._translucentRenderState = undefined;
 
  this._mode = undefined;
 
  this._ready = false;
  this._pointsLength = 0;
  this._geometryByteLength = 0;
 
  this._vertexShaderLoaded = options.vertexShaderLoaded;
  this._fragmentShaderLoaded = options.fragmentShaderLoaded;
  this._uniformMapLoaded = options.uniformMapLoaded;
  this._batchTableLoaded = options.batchTableLoaded;
  this._pickIdLoaded = options.pickIdLoaded;
  this._opaquePass = options.opaquePass ?? Pass.OPAQUE;
  this._cull = options.cull ?? true;
 
  this.style = undefined;
  this._style = undefined;
  this.styleDirty = false;
 
  this.modelMatrix = Matrix4.clone(Matrix4.IDENTITY);
  this._modelMatrix = Matrix4.clone(Matrix4.IDENTITY);
 
  this.time = 0.0; // For styling
  this.shadows = ShadowMode.ENABLED;
  this._boundingSphere = undefined;
 
  this.clippingPlanes = undefined;
  this.isClipped = false;
  this.clippingPlanesDirty = false;
  // If defined, use this matrix to position the clipping planes instead of the modelMatrix.
  // This is so that when point clouds are part of a tileset they all get clipped relative
  // to the root tile.
  this.clippingPlanesOriginMatrix = undefined;
 
  this.attenuation = false;
  this._attenuation = false;
 
  // Options for geometric error based attenuation
  this.geometricError = 0.0;
  this.geometricErrorScale = 1.0;
  this.maximumAttenuation = this._pointSize;
 
  /**
   * The {@link SplitDirection} to apply to this point cloud.
   *
   * @type {SplitDirection}
   * @default {@link SplitDirection.NONE}
   */
  this.splitDirection = options.splitDirection ?? SplitDirection.NONE;
  this._splittingEnabled = false;
 
  this._error = undefined;
  initialize(this, options);
}
 
Object.defineProperties(PointCloud.prototype, {
  pointsLength: {
    get: function () {
      return this._pointsLength;
    },
  },
 
  geometryByteLength: {
    get: function () {
      return this._geometryByteLength;
    },
  },
 
  ready: {
    get: function () {
      return this._ready;
    },
  },
 
  color: {
    get: function () {
      return Color.clone(this._highlightColor);
    },
    set: function (value) {
      this._highlightColor = Color.clone(value, this._highlightColor);
    },
  },
 
  boundingSphere: {
    get: function () {
      if (defined(this._drawCommand)) {
        return this._drawCommand.boundingVolume;
      }
      return undefined;
    },
    set: function (value) {
      this._boundingSphere = BoundingSphere.clone(value, this._boundingSphere);
    },
  },
});
 
function initialize(pointCloud, options) {
  const parsedContent = PntsParser.parse(
    options.arrayBuffer,
    options.byteOffset,
  );
  pointCloud._parsedContent = parsedContent;
  pointCloud._rtcCenter = parsedContent.rtcCenter;
  pointCloud._hasNormals = parsedContent.hasNormals;
  pointCloud._hasColors = parsedContent.hasColors;
  pointCloud._hasBatchIds = parsedContent.hasBatchIds;
  pointCloud._isTranslucent = parsedContent.isTranslucent;
 
  // If points are not batched and there are per-point properties, use the
  // properties as metadata for styling purposes.
  if (!parsedContent.hasBatchIds && defined(parsedContent.batchTableBinary)) {
    parsedContent.styleableProperties =
      Cesium3DTileBatchTable.getBinaryProperties(
        parsedContent.pointsLength,
        parsedContent.batchTableJson,
        parsedContent.batchTableBinary,
      );
  }
 
  if (defined(parsedContent.draco)) {
    const draco = parsedContent.draco;
    pointCloud._decodingState = DecodingState.NEEDS_DECODE;
    draco.dequantizeInShader = pointCloud._dequantizeInShader;
  }
 
  const positions = parsedContent.positions;
  if (defined(positions)) {
    pointCloud._isQuantized = positions.isQuantized;
    pointCloud._quantizedVolumeScale = positions.quantizedVolumeScale;
    pointCloud._quantizedVolumeOffset = positions.quantizedVolumeOffset;
    pointCloud._quantizedRange = positions.quantizedRange;
  }
 
  const normals = parsedContent.normals;
  Iif (defined(normals)) {
    pointCloud._isOctEncoded16P = normals.octEncoded;
  }
 
  const colors = parsedContent.colors;
  if (defined(colors)) {
    Iif (defined(colors.constantColor)) {
      pointCloud._constantColor = Color.clone(
        colors.constantColor,
        pointCloud._constantColor,
      );
 
      // Constant colors are handled as a uniform rather than a vertex
      // attribute.
      pointCloud._hasColors = false;
    }
    pointCloud._isRGB565 = colors.isRGB565;
  }
 
  // PntsParser parses BATCH_ID as _FEATURE_ID_0 for EXT_mesh_features.
  // These properties aren't used but rename them to BATCH_ID to avoid
  // confusion when debugging.
  const batchIds = parsedContent.batchIds;
  Iif (defined(parsedContent.batchIds)) {
    batchIds.name = "BATCH_ID";
    batchIds.semantic = "BATCH_ID";
    batchIds.setIndex = undefined;
  }
 
  Iif (parsedContent.hasBatchIds) {
    pointCloud._batchTableLoaded(
      parsedContent.batchLength,
      parsedContent.batchTableJson,
      parsedContent.batchTableBinary,
    );
  }
 
  pointCloud._pointsLength = parsedContent.pointsLength;
}
 
const scratchMin = new Cartesian3();
const scratchMax = new Cartesian3();
const scratchPosition = new Cartesian3();
 
// Use MersenneTwister directly to avoid interfering with CesiumMath.nextRandomNumber()
// See https://github.com/CesiumGS/cesium/issues/9730
let randomNumberGenerator;
let randomValues;
 
function getRandomValues(samplesLength) {
  // Use same random values across all runs
  if (!defined(randomValues)) {
    // Use MersenneTwister directly to avoid interfering with CesiumMath.nextRandomNumber()
    // See https://github.com/CesiumGS/cesium/issues/9730
    randomNumberGenerator = new MersenneTwister(0);
    randomValues = new Array(samplesLength);
    for (let i = 0; i < samplesLength; ++i) {
      randomValues[i] = randomNumberGenerator.random();
    }
  }
  return randomValues;
}
 
function computeApproximateBoundingSphereFromPositions(positions) {
  const maximumSamplesLength = 20;
  const pointsLength = positions.length / 3;
  const samplesLength = Math.min(pointsLength, maximumSamplesLength);
  const randomValues = getRandomValues(maximumSamplesLength);
  const maxValue = Number.MAX_VALUE;
  const minValue = -Number.MAX_VALUE;
  const min = Cartesian3.fromElements(maxValue, maxValue, maxValue, scratchMin);
  const max = Cartesian3.fromElements(minValue, minValue, minValue, scratchMax);
  for (let i = 0; i < samplesLength; ++i) {
    const index = Math.floor(randomValues[i] * pointsLength);
    const position = Cartesian3.unpack(positions, index * 3, scratchPosition);
    Cartesian3.minimumByComponent(min, position, min);
    Cartesian3.maximumByComponent(max, position, max);
  }
 
  const boundingSphere = BoundingSphere.fromCornerPoints(min, max);
  boundingSphere.radius += CesiumMath.EPSILON2; // To avoid radius of zero
  return boundingSphere;
}
 
function prepareVertexAttribute(typedArray, name) {
  // WebGL does not support UNSIGNED_INT, INT, or DOUBLE vertex attributes. Convert these to FLOAT.
  const componentDatatype = ComponentDatatype.fromTypedArray(typedArray);
  Iif (
    componentDatatype === ComponentDatatype.INT ||
    componentDatatype === ComponentDatatype.UNSIGNED_INT ||
    componentDatatype === ComponentDatatype.DOUBLE
  ) {
    oneTimeWarning(
      "Cast pnts property to floats",
      `Point cloud property "${name}" will be cast to a float array because INT, UNSIGNED_INT, and DOUBLE are not valid WebGL vertex attribute types. Some precision may be lost.`,
    );
    return new Float32Array(typedArray);
  }
  return typedArray;
}
 
const scratchPointSizeAndTimeAndGeometricErrorAndDepthMultiplier =
  new Cartesian4();
const scratchQuantizedVolumeScaleAndOctEncodedRange = new Cartesian4();
const scratchColor = new Color();
 
const positionLocation = 0;
const colorLocation = 1;
const normalLocation = 2;
const batchIdLocation = 3;
const numberOfAttributes = 4;
 
const scratchClippingPlanesMatrix = new Matrix4();
const scratchInverseTransposeClippingPlanesMatrix = new Matrix4();
 
function createResources(pointCloud, frameState) {
  const context = frameState.context;
  const parsedContent = pointCloud._parsedContent;
  const pointsLength = pointCloud._pointsLength;
  const positions = parsedContent.positions;
  const colors = parsedContent.colors;
  const normals = parsedContent.normals;
  const batchIds = parsedContent.batchIds;
  const styleableProperties = parsedContent.styleableProperties;
  const hasStyleableProperties = defined(styleableProperties);
  const isQuantized = pointCloud._isQuantized;
  const isQuantizedDraco = pointCloud._isQuantizedDraco;
  const isOctEncoded16P = pointCloud._isOctEncoded16P;
  const isOctEncodedDraco = pointCloud._isOctEncodedDraco;
  const quantizedRange = pointCloud._quantizedRange;
  const octEncodedRange = pointCloud._octEncodedRange;
  const isRGB565 = pointCloud._isRGB565;
  const isTranslucent = pointCloud._isTranslucent;
  const hasColors = pointCloud._hasColors;
  const hasNormals = pointCloud._hasNormals;
  const hasBatchIds = pointCloud._hasBatchIds;
 
  let componentsPerAttribute;
  let componentDatatype;
 
  const styleableVertexAttributes = [];
  const styleableShaderAttributes = {};
  pointCloud._styleableShaderAttributes = styleableShaderAttributes;
 
  Eif (hasStyleableProperties) {
    let attributeLocation = numberOfAttributes;
 
    for (const name in styleableProperties) {
      Eif (styleableProperties.hasOwnProperty(name)) {
        const property = styleableProperties[name];
        const typedArray = prepareVertexAttribute(property.typedArray, name);
        componentsPerAttribute = property.componentCount;
        componentDatatype = ComponentDatatype.fromTypedArray(typedArray);
 
        const vertexBuffer = Buffer.createVertexBuffer({
          context: context,
          typedArray: typedArray,
          usage: BufferUsage.STATIC_DRAW,
        });
 
        pointCloud._geometryByteLength += vertexBuffer.sizeInBytes;
 
        const vertexAttribute = {
          index: attributeLocation,
          vertexBuffer: vertexBuffer,
          componentsPerAttribute: componentsPerAttribute,
          componentDatatype: componentDatatype,
          normalize: false,
          offsetInBytes: 0,
          strideInBytes: 0,
        };
 
        styleableVertexAttributes.push(vertexAttribute);
        styleableShaderAttributes[name] = {
          location: attributeLocation,
          componentCount: componentsPerAttribute,
        };
        ++attributeLocation;
      }
    }
  }
 
  const positionsVertexBuffer = Buffer.createVertexBuffer({
    context: context,
    typedArray: positions.typedArray,
    usage: BufferUsage.STATIC_DRAW,
  });
  pointCloud._geometryByteLength += positionsVertexBuffer.sizeInBytes;
 
  let colorsVertexBuffer;
  Eif (hasColors) {
    colorsVertexBuffer = Buffer.createVertexBuffer({
      context: context,
      typedArray: colors.typedArray,
      usage: BufferUsage.STATIC_DRAW,
    });
    pointCloud._geometryByteLength += colorsVertexBuffer.sizeInBytes;
  }
 
  let normalsVertexBuffer;
  Iif (hasNormals) {
    normalsVertexBuffer = Buffer.createVertexBuffer({
      context: context,
      typedArray: normals.typedArray,
      usage: BufferUsage.STATIC_DRAW,
    });
    pointCloud._geometryByteLength += normalsVertexBuffer.sizeInBytes;
  }
 
  let batchIdsVertexBuffer;
  Iif (hasBatchIds) {
    batchIds.typedArray = prepareVertexAttribute(
      batchIds.typedArray,
      "batchIds",
    );
    batchIdsVertexBuffer = Buffer.createVertexBuffer({
      context: context,
      typedArray: batchIds.typedArray,
      usage: BufferUsage.STATIC_DRAW,
    });
    pointCloud._geometryByteLength += batchIdsVertexBuffer.sizeInBytes;
  }
 
  let attributes = [];
 
  Iif (isQuantized) {
    componentDatatype = ComponentDatatype.UNSIGNED_SHORT;
  } else if (isQuantizedDraco) {
    componentDatatype =
      quantizedRange <= 255
        ? ComponentDatatype.UNSIGNED_BYTE
        : ComponentDatatype.UNSIGNED_SHORT;
  } else {
    componentDatatype = ComponentDatatype.FLOAT;
  }
 
  attributes.push({
    index: positionLocation,
    vertexBuffer: positionsVertexBuffer,
    componentsPerAttribute: 3,
    componentDatatype: componentDatatype,
    normalize: false,
    offsetInBytes: 0,
    strideInBytes: 0,
  });
 
  Eif (pointCloud._cull) {
    if (isQuantized || isQuantizedDraco) {
      pointCloud._boundingSphere = BoundingSphere.fromCornerPoints(
        Cartesian3.ZERO,
        pointCloud._quantizedVolumeScale,
      );
    } else {
      pointCloud._boundingSphere =
        computeApproximateBoundingSphereFromPositions(positions.typedArray);
    }
  }
 
  Eif (hasColors) {
    Iif (isRGB565) {
      attributes.push({
        index: colorLocation,
        vertexBuffer: colorsVertexBuffer,
        componentsPerAttribute: 1,
        componentDatatype: ComponentDatatype.UNSIGNED_SHORT,
        normalize: false,
        offsetInBytes: 0,
        strideInBytes: 0,
      });
    } else {
      const colorComponentsPerAttribute = isTranslucent ? 4 : 3;
      attributes.push({
        index: colorLocation,
        vertexBuffer: colorsVertexBuffer,
        componentsPerAttribute: colorComponentsPerAttribute,
        componentDatatype: ComponentDatatype.UNSIGNED_BYTE,
        normalize: true,
        offsetInBytes: 0,
        strideInBytes: 0,
      });
    }
  }
 
  Iif (hasNormals) {
    if (isOctEncoded16P) {
      componentsPerAttribute = 2;
      componentDatatype = ComponentDatatype.UNSIGNED_BYTE;
    } else if (isOctEncodedDraco) {
      componentsPerAttribute = 2;
      componentDatatype =
        octEncodedRange <= 255
          ? ComponentDatatype.UNSIGNED_BYTE
          : ComponentDatatype.UNSIGNED_SHORT;
    } else {
      componentsPerAttribute = 3;
      componentDatatype = ComponentDatatype.FLOAT;
    }
    attributes.push({
      index: normalLocation,
      vertexBuffer: normalsVertexBuffer,
      componentsPerAttribute: componentsPerAttribute,
      componentDatatype: componentDatatype,
      normalize: false,
      offsetInBytes: 0,
      strideInBytes: 0,
    });
  }
 
  Iif (hasBatchIds) {
    attributes.push({
      index: batchIdLocation,
      vertexBuffer: batchIdsVertexBuffer,
      componentsPerAttribute: 1,
      componentDatatype: ComponentDatatype.fromTypedArray(batchIds.typedArray),
      normalize: false,
      offsetInBytes: 0,
      strideInBytes: 0,
    });
  }
 
  Eif (hasStyleableProperties) {
    attributes = attributes.concat(styleableVertexAttributes);
  }
 
  const vertexArray = new VertexArray({
    context: context,
    attributes: attributes,
  });
 
  const opaqueRenderState = {
    depthTest: {
      enabled: true,
    },
  };
 
  const translucentRenderState = {
    depthTest: {
      enabled: true,
    },
    depthMask: false,
    blending: BlendingState.ALPHA_BLEND,
  };
 
  Iif (pointCloud._opaquePass === Pass.CESIUM_3D_TILE) {
    opaqueRenderState.stencilTest = StencilConstants.setCesium3DTileBit();
    opaqueRenderState.stencilMask = StencilConstants.CESIUM_3D_TILE_MASK;
    translucentRenderState.stencilTest = StencilConstants.setCesium3DTileBit();
    translucentRenderState.stencilMask = StencilConstants.CESIUM_3D_TILE_MASK;
  }
 
  pointCloud._opaqueRenderState = RenderState.fromCache(opaqueRenderState);
  pointCloud._translucentRenderState = RenderState.fromCache(
    translucentRenderState,
  );
 
  pointCloud._drawCommand = new DrawCommand({
    boundingVolume: new BoundingSphere(),
    cull: pointCloud._cull,
    modelMatrix: new Matrix4(),
    primitiveType: PrimitiveType.POINTS,
    vertexArray: vertexArray,
    count: pointsLength,
    shaderProgram: undefined, // Updated in createShaders
    uniformMap: undefined, // Updated in createShaders
    renderState: isTranslucent
      ? pointCloud._translucentRenderState
      : pointCloud._opaqueRenderState,
    pass: isTranslucent ? Pass.TRANSLUCENT : pointCloud._opaquePass,
    owner: pointCloud,
    castShadows: false,
    receiveShadows: false,
    pickId: pointCloud._pickIdLoaded(),
  });
}
 
function createUniformMap(pointCloud, frameState) {
  const context = frameState.context;
  const isQuantized = pointCloud._isQuantized;
  const isQuantizedDraco = pointCloud._isQuantizedDraco;
  const isOctEncodedDraco = pointCloud._isOctEncodedDraco;
 
  let uniformMap = {
    u_pointSizeAndTimeAndGeometricErrorAndDepthMultiplier: function () {
      const scratch =
        scratchPointSizeAndTimeAndGeometricErrorAndDepthMultiplier;
      scratch.x = pointCloud._attenuation
        ? pointCloud.maximumAttenuation
        : pointCloud._pointSize;
      scratch.x *= frameState.pixelRatio;
 
      scratch.y = pointCloud.time;
 
      if (pointCloud._attenuation) {
        const frustum = frameState.camera.frustum;
        let depthMultiplier;
        // Attenuation is maximumAttenuation in 2D/ortho
        if (
          frameState.mode === SceneMode.SCENE2D ||
          frustum instanceof OrthographicFrustum
        ) {
          depthMultiplier = Number.POSITIVE_INFINITY;
        } else {
          depthMultiplier =
            context.drawingBufferHeight /
            frameState.camera.frustum.sseDenominator;
        }
 
        scratch.z = pointCloud.geometricError * pointCloud.geometricErrorScale;
        scratch.w = depthMultiplier;
      }
 
      return scratch;
    },
    u_highlightColor: function () {
      return pointCloud._highlightColor;
    },
    u_constantColor: function () {
      return pointCloud._constantColor;
    },
    u_clippingPlanes: function () {
      const clippingPlanes = pointCloud.clippingPlanes;
      const isClipped = pointCloud.isClipped;
      return isClipped ? clippingPlanes.texture : context.defaultTexture;
    },
    u_clippingPlanesEdgeStyle: function () {
      const clippingPlanes = pointCloud.clippingPlanes;
      if (!defined(clippingPlanes)) {
        return Color.TRANSPARENT;
      }
 
      const style = Color.clone(clippingPlanes.edgeColor, scratchColor);
      style.alpha = clippingPlanes.edgeWidth;
      return style;
    },
    u_clippingPlanesMatrix: function () {
      const clippingPlanes = pointCloud.clippingPlanes;
      if (!defined(clippingPlanes)) {
        return Matrix4.IDENTITY;
      }
 
      const clippingPlanesOriginMatrix =
        pointCloud.clippingPlanesOriginMatrix ?? pointCloud._modelMatrix;
      Matrix4.multiply(
        context.uniformState.view3D,
        clippingPlanesOriginMatrix,
        scratchClippingPlanesMatrix,
      );
      const transform = Matrix4.multiply(
        scratchClippingPlanesMatrix,
        clippingPlanes.modelMatrix,
        scratchClippingPlanesMatrix,
      );
 
      return Matrix4.inverseTranspose(
        transform,
        scratchInverseTransposeClippingPlanesMatrix,
      );
    },
  };
 
  Splitter.addUniforms(pointCloud, uniformMap);
 
  if (isQuantized || isQuantizedDraco || isOctEncodedDraco) {
    uniformMap = combine(uniformMap, {
      u_quantizedVolumeScaleAndOctEncodedRange: function () {
        const scratch = scratchQuantizedVolumeScaleAndOctEncodedRange;
        if (defined(pointCloud._quantizedVolumeScale)) {
          const scale = Cartesian3.clone(
            pointCloud._quantizedVolumeScale,
            scratch,
          );
          Cartesian3.divideByScalar(scale, pointCloud._quantizedRange, scratch);
        }
        scratch.w = pointCloud._octEncodedRange;
        return scratch;
      },
    });
  }
 
  Eif (defined(pointCloud._uniformMapLoaded)) {
    uniformMap = pointCloud._uniformMapLoaded(uniformMap);
  }
 
  pointCloud._drawCommand.uniformMap = uniformMap;
}
 
function getStyleablePropertyIds(source, propertyIds) {
  // Get all the property IDs used by this style
  const regex = /czm_3dtiles_property_(\d+)/g;
  let matches = regex.exec(source);
  while (matches !== null) {
    const id = parseInt(matches[1]);
    if (propertyIds.indexOf(id) === -1) {
      propertyIds.push(id);
    }
    matches = regex.exec(source);
  }
}
 
function getBuiltinPropertyNames(source, propertyNames) {
  // Get all the builtin property names used by this style, ignoring the function signature
  source = source.slice(source.indexOf("\n"));
  const regex = /czm_3dtiles_builtin_property_(\w+)/g;
  let matches = regex.exec(source);
  while (matches !== null) {
    const name = matches[1];
    if (propertyNames.indexOf(name) === -1) {
      propertyNames.push(name);
    }
    matches = regex.exec(source);
  }
}
 
function getVertexAttribute(vertexArray, index) {
  const numberOfAttributes = vertexArray.numberOfAttributes;
  for (let i = 0; i < numberOfAttributes; ++i) {
    const attribute = vertexArray.getAttribute(i);
    if (attribute.index === index) {
      return attribute;
    }
  }
}
 
const builtinVariableSubstitutionMap = {
  POSITION: "czm_3dtiles_builtin_property_POSITION",
  POSITION_ABSOLUTE: "czm_3dtiles_builtin_property_POSITION_ABSOLUTE",
  COLOR: "czm_3dtiles_builtin_property_COLOR",
  NORMAL: "czm_3dtiles_builtin_property_NORMAL",
};
 
function createShaders(pointCloud, frameState, style) {
  let i;
  let name;
  let attribute;
 
  const context = frameState.context;
  const hasStyle = defined(style);
  const isQuantized = pointCloud._isQuantized;
  const isQuantizedDraco = pointCloud._isQuantizedDraco;
  const isOctEncoded16P = pointCloud._isOctEncoded16P;
  const isOctEncodedDraco = pointCloud._isOctEncodedDraco;
  const isRGB565 = pointCloud._isRGB565;
  const isTranslucent = pointCloud._isTranslucent;
  const hasColors = pointCloud._hasColors;
  const hasNormals = pointCloud._hasNormals;
  const hasBatchIds = pointCloud._hasBatchIds;
  const backFaceCulling = pointCloud._backFaceCulling;
  const normalShading = pointCloud._normalShading;
  const vertexArray = pointCloud._drawCommand.vertexArray;
  const clippingPlanes = pointCloud.clippingPlanes;
  const attenuation = pointCloud._attenuation;
 
  let colorStyleFunction;
  let showStyleFunction;
  let pointSizeStyleFunction;
  let styleTranslucent = isTranslucent;
 
  const variableSubstitutionMap = clone(builtinVariableSubstitutionMap);
  const propertyIdToAttributeMap = {};
  const styleableShaderAttributes = pointCloud._styleableShaderAttributes;
  for (name in styleableShaderAttributes) {
    Eif (styleableShaderAttributes.hasOwnProperty(name)) {
      attribute = styleableShaderAttributes[name];
      variableSubstitutionMap[name] =
        `czm_3dtiles_property_${attribute.location}`;
      propertyIdToAttributeMap[attribute.location] = attribute;
    }
  }
 
  if (hasStyle) {
    const shaderState = {
      translucent: false,
    };
    const parameterList =
      "(" +
      "vec3 czm_3dtiles_builtin_property_POSITION, " +
      "vec3 czm_3dtiles_builtin_property_POSITION_ABSOLUTE, " +
      "vec4 czm_3dtiles_builtin_property_COLOR, " +
      "vec3 czm_3dtiles_builtin_property_NORMAL" +
      ")";
    colorStyleFunction = style.getColorShaderFunction(
      `getColorFromStyle${parameterList}`,
      variableSubstitutionMap,
      shaderState,
    );
    showStyleFunction = style.getShowShaderFunction(
      `getShowFromStyle${parameterList}`,
      variableSubstitutionMap,
      shaderState,
    );
    pointSizeStyleFunction = style.getPointSizeShaderFunction(
      `getPointSizeFromStyle${parameterList}`,
      variableSubstitutionMap,
      shaderState,
    );
    Iif (defined(colorStyleFunction) && shaderState.translucent) {
      styleTranslucent = true;
    }
  }
 
  pointCloud._styleTranslucent = styleTranslucent;
 
  const hasColorStyle = defined(colorStyleFunction);
  const hasShowStyle = defined(showStyleFunction);
  const hasPointSizeStyle = defined(pointSizeStyleFunction);
  const hasClippedContent = pointCloud.isClipped;
 
  // Get the properties in use by the style
  const styleablePropertyIds = [];
  const builtinPropertyNames = [];
 
  if (hasColorStyle) {
    getStyleablePropertyIds(colorStyleFunction, styleablePropertyIds);
    getBuiltinPropertyNames(colorStyleFunction, builtinPropertyNames);
  }
  Iif (hasShowStyle) {
    getStyleablePropertyIds(showStyleFunction, styleablePropertyIds);
    getBuiltinPropertyNames(showStyleFunction, builtinPropertyNames);
  }
  if (hasPointSizeStyle) {
    getStyleablePropertyIds(pointSizeStyleFunction, styleablePropertyIds);
    getBuiltinPropertyNames(pointSizeStyleFunction, builtinPropertyNames);
  }
 
  const usesColorSemantic = builtinPropertyNames.indexOf("COLOR") >= 0;
  const usesNormalSemantic = builtinPropertyNames.indexOf("NORMAL") >= 0;
 
  Iif (usesNormalSemantic && !hasNormals) {
    throw new RuntimeError(
      "Style references the NORMAL semantic but the point cloud does not have normals",
    );
  }
 
  // Disable vertex attributes that aren't used in the style, enable attributes that are
  for (name in styleableShaderAttributes) {
    Eif (styleableShaderAttributes.hasOwnProperty(name)) {
      attribute = styleableShaderAttributes[name];
      const enabled = styleablePropertyIds.indexOf(attribute.location) >= 0;
      const vertexAttribute = getVertexAttribute(
        vertexArray,
        attribute.location,
      );
      vertexAttribute.enabled = enabled;
    }
  }
 
  const usesColors = hasColors && (!hasColorStyle || usesColorSemantic);
  Eif (hasColors) {
    // Disable the color vertex attribute if the color style does not reference the color semantic
    const colorVertexAttribute = getVertexAttribute(vertexArray, colorLocation);
    colorVertexAttribute.enabled = usesColors;
  }
 
  const usesNormals =
    hasNormals && (normalShading || backFaceCulling || usesNormalSemantic);
  Iif (hasNormals) {
    // Disable the normal vertex attribute if normals are not used
    const normalVertexAttribute = getVertexAttribute(
      vertexArray,
      normalLocation,
    );
    normalVertexAttribute.enabled = usesNormals;
  }
 
  const attributeLocations = {
    a_position: positionLocation,
  };
  if (usesColors) {
    attributeLocations.a_color = colorLocation;
  }
  Iif (usesNormals) {
    attributeLocations.a_normal = normalLocation;
  }
  Iif (hasBatchIds) {
    attributeLocations.a_batchId = batchIdLocation;
  }
 
  let attributeDeclarations = "";
 
  const length = styleablePropertyIds.length;
  for (i = 0; i < length; ++i) {
    const propertyId = styleablePropertyIds[i];
    attribute = propertyIdToAttributeMap[propertyId];
    const componentCount = attribute.componentCount;
    const attributeName = `czm_3dtiles_property_${propertyId}`;
    let attributeType;
    if (componentCount === 1) {
      attributeType = "float";
    } else {
      attributeType = `vec${componentCount}`;
    }
 
    attributeDeclarations += `in ${attributeType} ${attributeName}; \n`;
    attributeLocations[attributeName] = attribute.location;
  }
 
  createUniformMap(pointCloud, frameState);
 
  let vs =
    "in vec3 a_position; \n" +
    "out vec4 v_color; \n" +
    "uniform vec4 u_pointSizeAndTimeAndGeometricErrorAndDepthMultiplier; \n" +
    "uniform vec4 u_constantColor; \n" +
    "uniform vec4 u_highlightColor; \n";
 
  // The time variable is named differently for compatibility with custom
  // shaders in Model.
  vs += "float u_pointSize; \n" + "float tiles3d_tileset_time; \n";
 
  if (attenuation) {
    vs += "float u_geometricError; \n" + "float u_depthMultiplier; \n";
  }
 
  vs += attributeDeclarations;
 
  if (usesColors) {
    Iif (isTranslucent) {
      vs += "in vec4 a_color; \n";
    } else Iif (isRGB565) {
      vs +=
        "in float a_color; \n" +
        "const float SHIFT_RIGHT_11 = 1.0 / 2048.0; \n" +
        "const float SHIFT_RIGHT_5 = 1.0 / 32.0; \n" +
        "const float SHIFT_LEFT_11 = 2048.0; \n" +
        "const float SHIFT_LEFT_5 = 32.0; \n" +
        "const float NORMALIZE_6 = 1.0 / 64.0; \n" +
        "const float NORMALIZE_5 = 1.0 / 32.0; \n";
    } else {
      vs += "in vec3 a_color; \n";
    }
  }
  Iif (usesNormals) {
    if (isOctEncoded16P || isOctEncodedDraco) {
      vs += "in vec2 a_normal; \n";
    } else {
      vs += "in vec3 a_normal; \n";
    }
  }
 
  Iif (hasBatchIds) {
    vs += "in float a_batchId; \n";
  }
 
  if (isQuantized || isQuantizedDraco || isOctEncodedDraco) {
    vs += "uniform vec4 u_quantizedVolumeScaleAndOctEncodedRange; \n";
  }
 
  if (hasColorStyle) {
    vs += colorStyleFunction;
  }
 
  Iif (hasShowStyle) {
    vs += showStyleFunction;
  }
 
  if (hasPointSizeStyle) {
    vs += pointSizeStyleFunction;
  }
 
  vs +=
    "void main() \n" +
    "{ \n" +
    "    u_pointSize = u_pointSizeAndTimeAndGeometricErrorAndDepthMultiplier.x; \n" +
    "    tiles3d_tileset_time = u_pointSizeAndTimeAndGeometricErrorAndDepthMultiplier.y; \n";
 
  if (attenuation) {
    vs +=
      "    u_geometricError = u_pointSizeAndTimeAndGeometricErrorAndDepthMultiplier.z; \n" +
      "    u_depthMultiplier = u_pointSizeAndTimeAndGeometricErrorAndDepthMultiplier.w; \n";
  }
 
  if (usesColors) {
    Iif (isTranslucent) {
      vs += "    vec4 color = a_color; \n";
    } else Iif (isRGB565) {
      vs +=
        "    float compressed = a_color; \n" +
        "    float r = floor(compressed * SHIFT_RIGHT_11); \n" +
        "    compressed -= r * SHIFT_LEFT_11; \n" +
        "    float g = floor(compressed * SHIFT_RIGHT_5); \n" +
        "    compressed -= g * SHIFT_LEFT_5; \n" +
        "    float b = compressed; \n" +
        "    vec3 rgb = vec3(r * NORMALIZE_5, g * NORMALIZE_6, b * NORMALIZE_5); \n" +
        "    vec4 color = vec4(rgb, 1.0); \n";
    } else {
      vs += "    vec4 color = vec4(a_color, 1.0); \n";
    }
  } else {
    vs += "    vec4 color = u_constantColor; \n";
  }
 
  if (isQuantized || isQuantizedDraco) {
    vs +=
      "    vec3 position = a_position * u_quantizedVolumeScaleAndOctEncodedRange.xyz; \n";
  } else {
    vs += "    vec3 position = a_position; \n";
  }
  vs +=
    "    vec3 position_absolute = vec3(czm_model * vec4(position, 1.0)); \n";
 
  Iif (usesNormals) {
    if (isOctEncoded16P) {
      vs += "    vec3 normal = czm_octDecode(a_normal); \n";
    } else if (isOctEncodedDraco) {
      // Draco oct-encoding decodes to zxy order
      vs +=
        "    vec3 normal = czm_octDecode(a_normal, u_quantizedVolumeScaleAndOctEncodedRange.w).zxy; \n";
    } else {
      vs += "    vec3 normal = a_normal; \n";
    }
    vs += "    vec3 normalEC = czm_normal * normal; \n";
  } else {
    vs += "    vec3 normal = vec3(1.0); \n";
  }
 
  if (hasColorStyle) {
    vs +=
      "    color = getColorFromStyle(position, position_absolute, color, normal); \n";
  }
 
  Iif (hasShowStyle) {
    vs +=
      "    float show = float(getShowFromStyle(position, position_absolute, color, normal)); \n";
  }
 
  if (hasPointSizeStyle) {
    vs +=
      "    gl_PointSize = getPointSizeFromStyle(position, position_absolute, color, normal) * czm_pixelRatio; \n";
  } else if (attenuation) {
    vs +=
      "    vec4 positionEC = czm_modelView * vec4(position, 1.0); \n" +
      "    float depth = -positionEC.z; \n" +
      // compute SSE for this point
      "    gl_PointSize = min((u_geometricError / depth) * u_depthMultiplier, u_pointSize); \n";
  } else {
    vs += "    gl_PointSize = u_pointSize; \n";
  }
 
  vs += "    color = color * u_highlightColor; \n";
 
  Iif (usesNormals && normalShading) {
    vs +=
      "    float diffuseStrength = czm_getLambertDiffuse(czm_lightDirectionEC, normalEC); \n" +
      "    diffuseStrength = max(diffuseStrength, 0.4); \n" + // Apply some ambient lighting
      "    color.xyz *= diffuseStrength * czm_lightColor; \n";
  }
 
  vs +=
    "    v_color = color; \n" +
    "    gl_Position = czm_modelViewProjection * vec4(position, 1.0); \n";
 
  Iif (usesNormals && backFaceCulling) {
    vs +=
      "    float visible = step(-normalEC.z, 0.0); \n" +
      "    gl_Position *= visible; \n" +
      "    gl_PointSize *= visible; \n";
  }
 
  Iif (hasShowStyle) {
    vs +=
      "    gl_Position.w *= float(show); \n" +
      "    gl_PointSize *= float(show); \n";
  }
 
  vs += "} \n";
 
  let fs = "in vec4 v_color; \n";
 
  if (hasClippedContent) {
    fs +=
      "uniform highp sampler2D u_clippingPlanes; \n" +
      "uniform mat4 u_clippingPlanesMatrix; \n" +
      "uniform vec4 u_clippingPlanesEdgeStyle; \n";
    fs += "\n";
    fs += getClippingFunction(clippingPlanes, context);
    fs += "\n";
  }
 
  fs +=
    "void main() \n" +
    "{ \n" +
    "    out_FragColor = czm_gammaCorrect(v_color); \n";
 
  if (hasClippedContent) {
    fs += getClipAndStyleCode(
      "u_clippingPlanes",
      "u_clippingPlanesMatrix",
      "u_clippingPlanesEdgeStyle",
    );
  }
 
  fs += "} \n";
 
  Iif (pointCloud.splitDirection !== SplitDirection.NONE) {
    fs = Splitter.modifyFragmentShader(fs);
  }
 
  Iif (defined(pointCloud._vertexShaderLoaded)) {
    vs = pointCloud._vertexShaderLoaded(vs);
  }
 
  Eif (defined(pointCloud._fragmentShaderLoaded)) {
    fs = pointCloud._fragmentShaderLoaded(fs);
  }
 
  const drawCommand = pointCloud._drawCommand;
  if (defined(drawCommand.shaderProgram)) {
    // Destroy the old shader
    drawCommand.shaderProgram.destroy();
  }
  drawCommand.shaderProgram = ShaderProgram.fromCache({
    context: context,
    vertexShaderSource: vs,
    fragmentShaderSource: fs,
    attributeLocations: attributeLocations,
  });
 
  try {
    // Check if the shader compiles correctly. If not there is likely a syntax error with the style.
    drawCommand.shaderProgram._bind();
  } catch (error) {
    // Rephrase the error.
    throw new RuntimeError(
      "Error generating style shader: this may be caused by a type mismatch, index out-of-bounds, or other syntax error.",
    );
  }
}
 
function decodeDraco(pointCloud, context) {
  if (pointCloud._decodingState === DecodingState.READY) {
    return false;
  }
  if (pointCloud._decodingState === DecodingState.NEEDS_DECODE) {
    const parsedContent = pointCloud._parsedContent;
    const draco = parsedContent.draco;
    const decodePromise = DracoLoader.decodePointCloud(draco, context);
    Eif (defined(decodePromise)) {
      pointCloud._decodingState = DecodingState.DECODING;
      decodePromise
        .then(function (result) {
          pointCloud._decodingState = DecodingState.READY;
          const decodedPositions = defined(result.POSITION)
            ? result.POSITION.array
            : undefined;
          const decodedRgb = defined(result.RGB) ? result.RGB.array : undefined;
          const decodedRgba = defined(result.RGBA)
            ? result.RGBA.array
            : undefined;
          const decodedNormals = defined(result.NORMAL)
            ? result.NORMAL.array
            : undefined;
          const decodedBatchIds = defined(result.BATCH_ID)
            ? result.BATCH_ID.array
            : undefined;
          const isQuantizedDraco =
            defined(decodedPositions) &&
            defined(result.POSITION.data.quantization);
          const isOctEncodedDraco =
            defined(decodedNormals) && defined(result.NORMAL.data.quantization);
          Eif (isQuantizedDraco) {
            // Draco quantization range == quantized volume scale - size in meters of the quantized volume
            // Internal quantized range is the range of values of the quantized data, e.g. 255 for 8-bit, 1023 for 10-bit, etc
            const quantization = result.POSITION.data.quantization;
            const range = quantization.range;
            pointCloud._quantizedVolumeScale = Cartesian3.fromElements(
              range,
              range,
              range,
            );
            pointCloud._quantizedVolumeOffset = Cartesian3.unpack(
              quantization.minValues,
            );
            pointCloud._quantizedRange =
              (1 << quantization.quantizationBits) - 1.0;
            pointCloud._isQuantizedDraco = true;
          }
          Iif (isOctEncodedDraco) {
            pointCloud._octEncodedRange =
              (1 << result.NORMAL.data.quantization.quantizationBits) - 1.0;
            pointCloud._isOctEncodedDraco = true;
          }
          let styleableProperties = parsedContent.styleableProperties;
          const batchTableProperties = draco.batchTableProperties;
          for (const name in batchTableProperties) {
            Eif (batchTableProperties.hasOwnProperty(name)) {
              const property = result[name];
              if (!defined(styleableProperties)) {
                styleableProperties = {};
              }
              styleableProperties[name] = {
                typedArray: property.array,
                componentCount: property.data.componentsPerAttribute,
              };
            }
          }
 
          Eif (defined(decodedPositions)) {
            parsedContent.positions = {
              typedArray: decodedPositions,
            };
          }
 
          const decodedColors = decodedRgba ?? decodedRgb;
          Eif (defined(decodedColors)) {
            parsedContent.colors = {
              typedArray: decodedColors,
            };
          }
 
          Iif (defined(decodedNormals)) {
            parsedContent.normals = {
              typedArray: decodedNormals,
            };
          }
 
          Iif (defined(decodedBatchIds)) {
            parsedContent.batchIds = {
              typedArray: decodedBatchIds,
            };
          }
 
          parsedContent.styleableProperties = styleableProperties;
        })
        .catch(function (error) {
          pointCloud._decodingState = DecodingState.FAILED;
          pointCloud._error = error;
        });
    }
  }
  return true;
}
 
const scratchComputedTranslation = new Cartesian4();
const scratchScale = new Cartesian3();
 
PointCloud.prototype.update = function (frameState) {
  const context = frameState.context;
 
  if (defined(this._error)) {
    const error = this._error;
    this._error = undefined;
    throw error;
  }
 
  const decoding = decodeDraco(this, context);
  if (decoding) {
    return;
  }
 
  let shadersDirty = false;
  let modelMatrixDirty = !Matrix4.equals(this._modelMatrix, this.modelMatrix);
 
  if (this._mode !== frameState.mode) {
    this._mode = frameState.mode;
    modelMatrixDirty = true;
  }
 
  if (!defined(this._drawCommand)) {
    createResources(this, frameState);
    modelMatrixDirty = true;
    shadersDirty = true;
    this._ready = true;
    this._parsedContent = undefined; // Unload
  }
 
  if (modelMatrixDirty) {
    Matrix4.clone(this.modelMatrix, this._modelMatrix);
    const modelMatrix = this._drawCommand.modelMatrix;
    Matrix4.clone(this._modelMatrix, modelMatrix);
 
    if (defined(this._rtcCenter)) {
      Matrix4.multiplyByTranslation(modelMatrix, this._rtcCenter, modelMatrix);
    }
    if (defined(this._quantizedVolumeOffset)) {
      Matrix4.multiplyByTranslation(
        modelMatrix,
        this._quantizedVolumeOffset,
        modelMatrix,
      );
    }
 
    if (frameState.mode !== SceneMode.SCENE3D) {
      const projection = frameState.mapProjection;
      const translation = Matrix4.getColumn(
        modelMatrix,
        3,
        scratchComputedTranslation,
      );
      Eif (!Cartesian4.equals(translation, Cartesian4.UNIT_W)) {
        Transforms.basisTo2D(projection, modelMatrix, modelMatrix);
      }
    }
 
    const boundingSphere = this._drawCommand.boundingVolume;
    BoundingSphere.clone(this._boundingSphere, boundingSphere);
 
    Eif (this._cull) {
      const center = boundingSphere.center;
      Matrix4.multiplyByPoint(modelMatrix, center, center);
      const scale = Matrix4.getScale(modelMatrix, scratchScale);
      boundingSphere.radius *= Cartesian3.maximumComponent(scale);
    }
  }
 
  if (this.clippingPlanesDirty) {
    this.clippingPlanesDirty = false;
    shadersDirty = true;
  }
 
  if (this._attenuation !== this.attenuation) {
    this._attenuation = this.attenuation;
    shadersDirty = true;
  }
 
  Iif (this.backFaceCulling !== this._backFaceCulling) {
    this._backFaceCulling = this.backFaceCulling;
    shadersDirty = true;
  }
 
  Iif (this.normalShading !== this._normalShading) {
    this._normalShading = this.normalShading;
    shadersDirty = true;
  }
 
  if (this._style !== this.style || this.styleDirty) {
    this._style = this.style;
    this.styleDirty = false;
    shadersDirty = true;
  }
 
  const splittingEnabled = this.splitDirection !== SplitDirection.NONE;
  Iif (this._splittingEnabled !== splittingEnabled) {
    this._splittingEnabled = splittingEnabled;
    shadersDirty = true;
  }
 
  if (shadersDirty) {
    createShaders(this, frameState, this._style);
  }
 
  this._drawCommand.castShadows = ShadowMode.castShadows(this.shadows);
  this._drawCommand.receiveShadows = ShadowMode.receiveShadows(this.shadows);
 
  // Update the render state
  const isTranslucent =
    this._highlightColor.alpha < 1.0 ||
    this._constantColor.alpha < 1.0 ||
    this._styleTranslucent;
  this._drawCommand.renderState = isTranslucent
    ? this._translucentRenderState
    : this._opaqueRenderState;
  this._drawCommand.pass = isTranslucent ? Pass.TRANSLUCENT : this._opaquePass;
 
  const commandList = frameState.commandList;
 
  const passes = frameState.passes;
  Eif (passes.render || passes.pick) {
    commandList.push(this._drawCommand);
  }
};
 
PointCloud.prototype.isDestroyed = function () {
  return false;
};
 
PointCloud.prototype.destroy = function () {
  const command = this._drawCommand;
  if (defined(command)) {
    command.vertexArray = command.vertexArray && command.vertexArray.destroy();
    command.shaderProgram =
      command.shaderProgram && command.shaderProgram.destroy();
  }
  return destroyObject(this);
};
export default PointCloud;