All files / engine/Source/Core PolygonGeometry.js

92.52% Statements 545/589
86.99% Branches 281/323
95.83% Functions 23/24
92.64% Lines 542/585

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 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581                                                          1x 1x   11x 11x 11x 11x 11x   11x 11x 11x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x     111x 111x 111x 111x 111x       111x 111x 111x 111x 111x                 29x 29x 29x 29x 29x 29x   29x 29x 29x   29x       29x 22x 6x   16x     29x     29x     29x   29x 29x   29x 29x 29x 29x   29x 29x 29x                                   29x 29x           29x 29x   29x 19x 19x   19x     29x 80151x           80151x 82x 78x         78x 78x 78x   78x 78x 78x 25x 25x   78x 78x 78x     78x       80151x           80139x 80139x   80139x 1346x 1336x   1336x 39x         39x 11x   39x 39x 39x       39x     1336x   29x       1346x 12x 12x 12x             78793x 78793x 30x                                                             30x 30x       30x 30x               80139x 80115x 1330x 1330x 1330x 78785x 78737x 78737x 78737x     80115x 80090x 80090x 80090x       80139x 24x 16x   24x 24x 24x     80139x 42x 12x 12x 12x 30x 13x 13x 13x     42x 42x         42x 42x 42x         80139x 42x 25x 25x 25x   42x 42x         42x 42x 42x       80139x       29x 10x             29x 22x             29x 4x             29x 4x             29x 4x               111x 14x 14x   14x 7x 5x 2x 1x       7x 7x     14x             111x     1x                           38x         38x 33x                   33x 33x       33x 26x   26x   26x       26x 26x   26x   26x 156236x 156236x 156236x   156236x 156236x 156236x     26x 26x 2x 2x     2x     26x           26x 7x 3x 3x   3x 48x 48x 48x     3x     33x         38x 38x 38x         38x 38x       38x               38x           38x 38x 1x 1x         1x 1x 1x     1x               1x             38x                                                                                                                                                                                                 113x 112x 110x                 110x         1x           109x 109x 109x 109x 109x 109x 109x   109x 109x 109x   109x 106x 106x 106x     109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x 109x   109x 109x 109x           109x                                                                                                 1x 50x     50x     49x                                 49x                       1x   16x 14x     12x   12x             12x 12x   12x 12x   12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 3x             9x   12x 12x     1x 1x     1x                       1x   8x     6x   6x         6x 6x   6x 6x   6x         6x   6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x   6x             6x 3x 3x   3x   6x   6x 6x     6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x   6x 6x 6x   6x     1x 1x 1x                 338x   338x 338x 338x   338x 338x   338x 338x   338x 338x   338x   291x           291x   291x 126x         126x 126x 126x 126x 126x   126x         338x     338x 338x 248x     338x 244x     338x 97x       1x 1x 1x                                 1x             87x     87x 80x     87x 2x     85x 85x 85x 85x   85x 85x 85x 85x   85x 85x       85x 253x       253x                 253x     85x                 85x 10x 10x   10x 10x   10x 2x         85x             2x 2x 2x     85x             2x 2x 2x     85x     1x   66x                 66x     1x   70x   87x                                                   87x       87x           66x                                         66x 66x   78x         70x 66x         1x               65x         66x               66x 66x       66x                             1x 76x 76x 76x 76x 76x 76x 76x 76x 76x 76x   76x   76x 76x 6x     70x 70x                 70x 70x   70x 1x     70x                   70x 4x     66x 66x             66x   66x 66x   66x     66x                                     66x 34x 34x 34x 34x 34x 34x 38x                           38x 26x 26x             12x 4x 4x             4x 8x 3x 3x             3x   38x 33x 33x 33x     38x 38x 38x 39x 39x             39x 39x       32x 39x                     39x             39x   39x   39x   1x   1x     1x 1x               39x       66x 66x     66x         66x 66x       66x       66x                       1x         4x 4x   4x 4x   4x                             2x 2x 1x   1x 1x 1x 1x               1x           84x 64x 64x             84x                 2x 2x     2x          
import ArcType from "./ArcType.js";
import BoundingRectangle from "./BoundingRectangle.js";
import BoundingSphere from "./BoundingSphere.js";
import Cartesian2 from "./Cartesian2.js";
import Cartesian3 from "./Cartesian3.js";
import Cartographic from "./Cartographic.js";
import Check from "./Check.js";
import ComponentDatatype from "./ComponentDatatype.js";
import Frozen from "./Frozen.js";
import defined from "./defined.js";
import DeveloperError from "./DeveloperError.js";
import Ellipsoid from "./Ellipsoid.js";
import EllipsoidTangentPlane from "./EllipsoidTangentPlane.js";
import Geometry from "./Geometry.js";
import GeometryAttribute from "./GeometryAttribute.js";
import GeometryInstance from "./GeometryInstance.js";
import GeometryOffsetAttribute from "./GeometryOffsetAttribute.js";
import GeometryPipeline from "./GeometryPipeline.js";
import IndexDatatype from "./IndexDatatype.js";
import CesiumMath from "./Math.js";
import Matrix3 from "./Matrix3.js";
import PolygonGeometryLibrary from "./PolygonGeometryLibrary.js";
import PolygonPipeline from "./PolygonPipeline.js";
import Quaternion from "./Quaternion.js";
import Rectangle from "./Rectangle.js";
import Stereographic from "./Stereographic.js";
import VertexFormat from "./VertexFormat.js";
import WindingOrder from "./WindingOrder.js";
 
const scratchCarto1 = new Cartographic();
const scratchCarto2 = new Cartographic();
function adjustPosHeightsForNormal(position, p1, p2, ellipsoid) {
  const carto1 = ellipsoid.cartesianToCartographic(position, scratchCarto1);
  const height = carto1.height;
  const p1Carto = ellipsoid.cartesianToCartographic(p1, scratchCarto2);
  p1Carto.height = height;
  ellipsoid.cartographicToCartesian(p1Carto, p1);
 
  const p2Carto = ellipsoid.cartesianToCartographic(p2, scratchCarto2);
  p2Carto.height = height - 100;
  ellipsoid.cartographicToCartesian(p2Carto, p2);
}
 
const scratchBoundingRectangle = new BoundingRectangle();
const scratchPosition = new Cartesian3();
const scratchNormal = new Cartesian3();
const scratchTangent = new Cartesian3();
const scratchBitangent = new Cartesian3();
const p1Scratch = new Cartesian3();
const p2Scratch = new Cartesian3();
let scratchPerPosNormal = new Cartesian3();
let scratchPerPosTangent = new Cartesian3();
let scratchPerPosBitangent = new Cartesian3();
 
const appendTextureCoordinatesOrigin = new Cartesian2();
const appendTextureCoordinatesCartesian2 = new Cartesian2();
const appendTextureCoordinatesCartesian3 = new Cartesian3();
const appendTextureCoordinatesQuaternion = new Quaternion();
const appendTextureCoordinatesMatrix3 = new Matrix3();
const tangentMatrixScratch = new Matrix3();
 
function computeAttributes(options) {
  const vertexFormat = options.vertexFormat;
  const geometry = options.geometry;
  const shadowVolume = options.shadowVolume;
  const flatPositions = geometry.attributes.position.values;
  const flatTexcoords = defined(geometry.attributes.st)
    ? geometry.attributes.st.values
    : undefined;
 
  let length = flatPositions.length;
  const wall = options.wall;
  const top = options.top || wall;
  const bottom = options.bottom || wall;
  if (
    vertexFormat.st ||
    vertexFormat.normal ||
    vertexFormat.tangent ||
    vertexFormat.bitangent ||
    shadowVolume
  ) {
    // PERFORMANCE_IDEA: Compute before subdivision, then just interpolate during subdivision.
    // PERFORMANCE_IDEA: Compute with createGeometryFromPositions() for fast path when there's no holes.
    const boundingRectangle = options.boundingRectangle;
    const rotationAxis = options.rotationAxis;
    const projectTo2d = options.projectTo2d;
    const ellipsoid = options.ellipsoid;
    const stRotation = options.stRotation;
    const perPositionHeight = options.perPositionHeight;
 
    const origin = appendTextureCoordinatesOrigin;
    origin.x = boundingRectangle.x;
    origin.y = boundingRectangle.y;
 
    const textureCoordinates = vertexFormat.st
      ? new Float32Array(2 * (length / 3))
      : undefined;
    let normals;
    if (vertexFormat.normal) {
      if (perPositionHeight && top && !wall) {
        normals = geometry.attributes.normal.values;
      } else {
        normals = new Float32Array(length);
      }
    }
    const tangents = vertexFormat.tangent
      ? new Float32Array(length)
      : undefined;
    const bitangents = vertexFormat.bitangent
      ? new Float32Array(length)
      : undefined;
    const extrudeNormals = shadowVolume ? new Float32Array(length) : undefined;
 
    let textureCoordIndex = 0;
    let attrIndex = 0;
 
    let normal = scratchNormal;
    let tangent = scratchTangent;
    let bitangent = scratchBitangent;
    let recomputeNormal = true;
 
    let textureMatrix = appendTextureCoordinatesMatrix3;
    let tangentRotationMatrix = tangentMatrixScratch;
    Iif (stRotation !== 0.0) {
      let rotation = Quaternion.fromAxisAngle(
        rotationAxis,
        stRotation,
        appendTextureCoordinatesQuaternion,
      );
      textureMatrix = Matrix3.fromQuaternion(rotation, textureMatrix);
 
      rotation = Quaternion.fromAxisAngle(
        rotationAxis,
        -stRotation,
        appendTextureCoordinatesQuaternion,
      );
      tangentRotationMatrix = Matrix3.fromQuaternion(
        rotation,
        tangentRotationMatrix,
      );
    } else {
      textureMatrix = Matrix3.clone(Matrix3.IDENTITY, textureMatrix);
      tangentRotationMatrix = Matrix3.clone(
        Matrix3.IDENTITY,
        tangentRotationMatrix,
      );
    }
 
    let bottomOffset = 0;
    let bottomOffset2 = 0;
 
    if (top && bottom) {
      bottomOffset = length / 2;
      bottomOffset2 = length / 3;
 
      length /= 2;
    }
 
    for (let i = 0; i < length; i += 3) {
      const position = Cartesian3.fromArray(
        flatPositions,
        i,
        appendTextureCoordinatesCartesian3,
      );
 
      if (vertexFormat.st) {
        if (!defined(flatTexcoords)) {
          let p = Matrix3.multiplyByVector(
            textureMatrix,
            position,
            scratchPosition,
          );
          p = ellipsoid.scaleToGeodeticSurface(p, p);
          const st = projectTo2d([p], appendTextureCoordinatesCartesian2)[0];
          Cartesian2.subtract(st, origin, st);
 
          const stx = CesiumMath.clamp(st.x / boundingRectangle.width, 0, 1);
          const sty = CesiumMath.clamp(st.y / boundingRectangle.height, 0, 1);
          if (bottom) {
            textureCoordinates[textureCoordIndex + bottomOffset2] = stx;
            textureCoordinates[textureCoordIndex + 1 + bottomOffset2] = sty;
          }
          Eif (top) {
            textureCoordinates[textureCoordIndex] = stx;
            textureCoordinates[textureCoordIndex + 1] = sty;
          }
 
          textureCoordIndex += 2;
        }
      }
 
      if (
        vertexFormat.normal ||
        vertexFormat.tangent ||
        vertexFormat.bitangent ||
        shadowVolume
      ) {
        const attrIndex1 = attrIndex + 1;
        const attrIndex2 = attrIndex + 2;
 
        if (wall) {
          if (i + 3 < length) {
            const p1 = Cartesian3.fromArray(flatPositions, i + 3, p1Scratch);
 
            if (recomputeNormal) {
              const p2 = Cartesian3.fromArray(
                flatPositions,
                i + length,
                p2Scratch,
              );
              if (perPositionHeight) {
                adjustPosHeightsForNormal(position, p1, p2, ellipsoid);
              }
              Cartesian3.subtract(p1, position, p1);
              Cartesian3.subtract(p2, position, p2);
              normal = Cartesian3.normalize(
                Cartesian3.cross(p2, p1, normal),
                normal,
              );
              recomputeNormal = false;
            }
 
            if (Cartesian3.equalsEpsilon(p1, position, CesiumMath.EPSILON10)) {
              // if we've reached a corner
              recomputeNormal = true;
            }
          }
 
          if (vertexFormat.tangent || vertexFormat.bitangent) {
            bitangent = ellipsoid.geodeticSurfaceNormal(position, bitangent);
            Eif (vertexFormat.tangent) {
              tangent = Cartesian3.normalize(
                Cartesian3.cross(bitangent, normal, tangent),
                tangent,
              );
            }
          }
        } else {
          normal = ellipsoid.geodeticSurfaceNormal(position, normal);
          if (vertexFormat.tangent || vertexFormat.bitangent) {
            Iif (perPositionHeight) {
              scratchPerPosNormal = Cartesian3.fromArray(
                normals,
                attrIndex,
                scratchPerPosNormal,
              );
              scratchPerPosTangent = Cartesian3.cross(
                Cartesian3.UNIT_Z,
                scratchPerPosNormal,
                scratchPerPosTangent,
              );
              scratchPerPosTangent = Cartesian3.normalize(
                Matrix3.multiplyByVector(
                  tangentRotationMatrix,
                  scratchPerPosTangent,
                  scratchPerPosTangent,
                ),
                scratchPerPosTangent,
              );
              if (vertexFormat.bitangent) {
                scratchPerPosBitangent = Cartesian3.normalize(
                  Cartesian3.cross(
                    scratchPerPosNormal,
                    scratchPerPosTangent,
                    scratchPerPosBitangent,
                  ),
                  scratchPerPosBitangent,
                );
              }
            }
 
            tangent = Cartesian3.cross(Cartesian3.UNIT_Z, normal, tangent);
            tangent = Cartesian3.normalize(
              Matrix3.multiplyByVector(tangentRotationMatrix, tangent, tangent),
              tangent,
            );
            Eif (vertexFormat.bitangent) {
              bitangent = Cartesian3.normalize(
                Cartesian3.cross(normal, tangent, bitangent),
                bitangent,
              );
            }
          }
        }
 
        if (vertexFormat.normal) {
          if (options.wall) {
            normals[attrIndex + bottomOffset] = normal.x;
            normals[attrIndex1 + bottomOffset] = normal.y;
            normals[attrIndex2 + bottomOffset] = normal.z;
          } else if (bottom) {
            normals[attrIndex + bottomOffset] = -normal.x;
            normals[attrIndex1 + bottomOffset] = -normal.y;
            normals[attrIndex2 + bottomOffset] = -normal.z;
          }
 
          if ((top && !perPositionHeight) || wall) {
            normals[attrIndex] = normal.x;
            normals[attrIndex1] = normal.y;
            normals[attrIndex2] = normal.z;
          }
        }
 
        if (shadowVolume) {
          if (wall) {
            normal = ellipsoid.geodeticSurfaceNormal(position, normal);
          }
          extrudeNormals[attrIndex + bottomOffset] = -normal.x;
          extrudeNormals[attrIndex1 + bottomOffset] = -normal.y;
          extrudeNormals[attrIndex2 + bottomOffset] = -normal.z;
        }
 
        if (vertexFormat.tangent) {
          if (options.wall) {
            tangents[attrIndex + bottomOffset] = tangent.x;
            tangents[attrIndex1 + bottomOffset] = tangent.y;
            tangents[attrIndex2 + bottomOffset] = tangent.z;
          } else if (bottom) {
            tangents[attrIndex + bottomOffset] = -tangent.x;
            tangents[attrIndex1 + bottomOffset] = -tangent.y;
            tangents[attrIndex2 + bottomOffset] = -tangent.z;
          }
 
          Eif (top) {
            Iif (perPositionHeight) {
              tangents[attrIndex] = scratchPerPosTangent.x;
              tangents[attrIndex1] = scratchPerPosTangent.y;
              tangents[attrIndex2] = scratchPerPosTangent.z;
            } else {
              tangents[attrIndex] = tangent.x;
              tangents[attrIndex1] = tangent.y;
              tangents[attrIndex2] = tangent.z;
            }
          }
        }
 
        if (vertexFormat.bitangent) {
          if (bottom) {
            bitangents[attrIndex + bottomOffset] = bitangent.x;
            bitangents[attrIndex1 + bottomOffset] = bitangent.y;
            bitangents[attrIndex2 + bottomOffset] = bitangent.z;
          }
          Eif (top) {
            Iif (perPositionHeight) {
              bitangents[attrIndex] = scratchPerPosBitangent.x;
              bitangents[attrIndex1] = scratchPerPosBitangent.y;
              bitangents[attrIndex2] = scratchPerPosBitangent.z;
            } else {
              bitangents[attrIndex] = bitangent.x;
              bitangents[attrIndex1] = bitangent.y;
              bitangents[attrIndex2] = bitangent.z;
            }
          }
        }
        attrIndex += 3;
      }
    }
 
    if (vertexFormat.st && !defined(flatTexcoords)) {
      geometry.attributes.st = new GeometryAttribute({
        componentDatatype: ComponentDatatype.FLOAT,
        componentsPerAttribute: 2,
        values: textureCoordinates,
      });
    }
 
    if (vertexFormat.normal) {
      geometry.attributes.normal = new GeometryAttribute({
        componentDatatype: ComponentDatatype.FLOAT,
        componentsPerAttribute: 3,
        values: normals,
      });
    }
 
    if (vertexFormat.tangent) {
      geometry.attributes.tangent = new GeometryAttribute({
        componentDatatype: ComponentDatatype.FLOAT,
        componentsPerAttribute: 3,
        values: tangents,
      });
    }
 
    if (vertexFormat.bitangent) {
      geometry.attributes.bitangent = new GeometryAttribute({
        componentDatatype: ComponentDatatype.FLOAT,
        componentsPerAttribute: 3,
        values: bitangents,
      });
    }
 
    if (shadowVolume) {
      geometry.attributes.extrudeDirection = new GeometryAttribute({
        componentDatatype: ComponentDatatype.FLOAT,
        componentsPerAttribute: 3,
        values: extrudeNormals,
      });
    }
  }
 
  if (options.extrude && defined(options.offsetAttribute)) {
    const size = flatPositions.length / 3;
    let offsetAttribute = new Uint8Array(size);
 
    if (options.offsetAttribute === GeometryOffsetAttribute.TOP) {
      if ((top && bottom) || wall) {
        offsetAttribute = offsetAttribute.fill(1, 0, size / 2);
      } else if (top) {
        offsetAttribute = offsetAttribute.fill(1);
      }
    } else {
      const offsetValue =
        options.offsetAttribute === GeometryOffsetAttribute.NONE ? 0 : 1;
      offsetAttribute = offsetAttribute.fill(offsetValue);
    }
 
    geometry.attributes.applyOffset = new GeometryAttribute({
      componentDatatype: ComponentDatatype.UNSIGNED_BYTE,
      componentsPerAttribute: 1,
      values: offsetAttribute,
    });
  }
 
  return geometry;
}
 
const createGeometryFromPositionsExtrudedPositions = [];
 
function createGeometryFromPositionsExtruded(
  ellipsoid,
  polygon,
  textureCoordinates,
  granularity,
  hierarchy,
  perPositionHeight,
  closeTop,
  closeBottom,
  vertexFormat,
  arcType,
) {
  const geos = {
    walls: [],
  };
  let i;
 
  if (closeTop || closeBottom) {
    const topGeo = PolygonGeometryLibrary.createGeometryFromPositions(
      ellipsoid,
      polygon,
      textureCoordinates,
      granularity,
      perPositionHeight,
      vertexFormat,
      arcType,
    );
 
    const edgePoints = topGeo.attributes.position.values;
    const indices = topGeo.indices;
    let numPositions;
    let newIndices;
 
    if (closeTop && closeBottom) {
      const topBottomPositions = edgePoints.concat(edgePoints);
 
      numPositions = topBottomPositions.length / 3;
 
      newIndices = IndexDatatype.createTypedArray(
        numPositions,
        indices.length * 2,
      );
      newIndices.set(indices);
      const ilength = indices.length;
 
      const length = numPositions / 2;
 
      for (i = 0; i < ilength; i += 3) {
        const i0 = newIndices[i] + length;
        const i1 = newIndices[i + 1] + length;
        const i2 = newIndices[i + 2] + length;
 
        newIndices[i + ilength] = i2;
        newIndices[i + 1 + ilength] = i1;
        newIndices[i + 2 + ilength] = i0;
      }
 
      topGeo.attributes.position.values = topBottomPositions;
      if (perPositionHeight && vertexFormat.normal) {
        const normals = topGeo.attributes.normal.values;
        topGeo.attributes.normal.values = new Float32Array(
          topBottomPositions.length,
        );
        topGeo.attributes.normal.values.set(normals);
      }
 
      Iif (vertexFormat.st && defined(textureCoordinates)) {
        const texcoords = topGeo.attributes.st.values;
        topGeo.attributes.st.values = new Float32Array(numPositions * 2);
        topGeo.attributes.st.values = texcoords.concat(texcoords);
      }
 
      topGeo.indices = newIndices;
    } else if (closeBottom) {
      numPositions = edgePoints.length / 3;
      newIndices = IndexDatatype.createTypedArray(numPositions, indices.length);
 
      for (i = 0; i < indices.length; i += 3) {
        newIndices[i] = indices[i + 2];
        newIndices[i + 1] = indices[i + 1];
        newIndices[i + 2] = indices[i];
      }
 
      topGeo.indices = newIndices;
    }
 
    geos.topAndBottom = new GeometryInstance({
      geometry: topGeo,
    });
  }
 
  let outerRing = hierarchy.outerRing;
  const tangentPlane = EllipsoidTangentPlane.fromPoints(outerRing, ellipsoid);
  let positions2D = tangentPlane.projectPointsOntoPlane(
    outerRing,
    createGeometryFromPositionsExtrudedPositions,
  );
 
  let windingOrder = PolygonPipeline.computeWindingOrder2D(positions2D);
  Iif (windingOrder === WindingOrder.CLOCKWISE) {
    outerRing = outerRing.slice().reverse();
  }
 
  let wallGeo = PolygonGeometryLibrary.computeWallGeometry(
    outerRing,
    textureCoordinates,
    ellipsoid,
    granularity,
    perPositionHeight,
    arcType,
  );
  geos.walls.push(
    new GeometryInstance({
      geometry: wallGeo,
    }),
  );
 
  const holes = hierarchy.holes;
  for (i = 0; i < holes.length; i++) {
    let hole = holes[i];
    positions2D = tangentPlane.projectPointsOntoPlane(
      hole,
      createGeometryFromPositionsExtrudedPositions,
    );
 
    windingOrder = PolygonPipeline.computeWindingOrder2D(positions2D);
    Eif (windingOrder === WindingOrder.COUNTER_CLOCKWISE) {
      hole = hole.slice().reverse();
    }
 
    wallGeo = PolygonGeometryLibrary.computeWallGeometry(
      hole,
      textureCoordinates,
      ellipsoid,
      granularity,
      perPositionHeight,
      arcType,
    );
    geos.walls.push(
      new GeometryInstance({
        geometry: wallGeo,
      }),
    );
  }
 
  return geos;
}
 
/**
 * A description of a polygon on the ellipsoid. The polygon is defined by a polygon hierarchy. Polygon geometry can be rendered with both {@link Primitive} and {@link GroundPrimitive}.
 *
 * @alias PolygonGeometry
 * @constructor
 *
 * @param {object} options Object with the following properties:
 * @param {PolygonHierarchy} options.polygonHierarchy A polygon hierarchy that can include holes.
 * @param {number} [options.height=0.0] The distance in meters between the polygon and the ellipsoid surface.
 * @param {number} [options.extrudedHeight] The distance in meters between the polygon's extruded face and the ellipsoid surface.
 * @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
 * @param {number} [options.stRotation=0.0] The rotation of the texture coordinates, in radians. A positive rotation is counter-clockwise.
 * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.default] The ellipsoid to be used as a reference.
 * @param {number} [options.granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
 * @param {boolean} [options.perPositionHeight=false] Use the height of options.positions for each position instead of using options.height to determine the height.
 * @param {boolean} [options.closeTop=true] When false, leaves off the top of an extruded polygon open.
 * @param {boolean} [options.closeBottom=true] When false, leaves off the bottom of an extruded polygon open.
 * @param {ArcType} [options.arcType=ArcType.GEODESIC] The type of line the polygon edges must follow. Valid options are {@link ArcType.GEODESIC} and {@link ArcType.RHUMB}.
 * @param {PolygonHierarchy} [options.textureCoordinates] Texture coordinates as a {@link PolygonHierarchy} of {@link Cartesian2} points. Has no effect for ground primitives.
 *
 * @see PolygonGeometry#createGeometry
 * @see PolygonGeometry#fromPositions
 *
 * @demo {@link https://sandcastle.cesium.com/index.html?src=Polygon.html|Cesium Sandcastle Polygon Demo}
 *
 * @example
 * // 1. create a polygon from points
 * const polygon = new Cesium.PolygonGeometry({
 *   polygonHierarchy : new Cesium.PolygonHierarchy(
 *     Cesium.Cartesian3.fromDegreesArray([
 *       -72.0, 40.0,
 *       -70.0, 35.0,
 *       -75.0, 30.0,
 *       -70.0, 30.0,
 *       -68.0, 40.0
 *     ])
 *   )
 * });
 * const geometry = Cesium.PolygonGeometry.createGeometry(polygon);
 *
 * // 2. create a nested polygon with holes
 * const polygonWithHole = new Cesium.PolygonGeometry({
 *   polygonHierarchy : new Cesium.PolygonHierarchy(
 *     Cesium.Cartesian3.fromDegreesArray([
 *       -109.0, 30.0,
 *       -95.0, 30.0,
 *       -95.0, 40.0,
 *       -109.0, 40.0
 *     ]),
 *     [new Cesium.PolygonHierarchy(
 *       Cesium.Cartesian3.fromDegreesArray([
 *         -107.0, 31.0,
 *         -107.0, 39.0,
 *         -97.0, 39.0,
 *         -97.0, 31.0
 *       ]),
 *       [new Cesium.PolygonHierarchy(
 *         Cesium.Cartesian3.fromDegreesArray([
 *           -105.0, 33.0,
 *           -99.0, 33.0,
 *           -99.0, 37.0,
 *           -105.0, 37.0
 *         ]),
 *         [new Cesium.PolygonHierarchy(
 *           Cesium.Cartesian3.fromDegreesArray([
 *             -103.0, 34.0,
 *             -101.0, 34.0,
 *             -101.0, 36.0,
 *             -103.0, 36.0
 *           ])
 *         )]
 *       )]
 *     )]
 *   )
 * });
 * const geometry = Cesium.PolygonGeometry.createGeometry(polygonWithHole);
 *
 * // 3. create extruded polygon
 * const extrudedPolygon = new Cesium.PolygonGeometry({
 *   polygonHierarchy : new Cesium.PolygonHierarchy(
 *     Cesium.Cartesian3.fromDegreesArray([
 *       -72.0, 40.0,
 *       -70.0, 35.0,
 *       -75.0, 30.0,
 *       -70.0, 30.0,
 *       -68.0, 40.0
 *     ])
 *   ),
 *   extrudedHeight: 300000
 * });
 * const geometry = Cesium.PolygonGeometry.createGeometry(extrudedPolygon);
 */
function PolygonGeometry(options) {
  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.object("options", options);
  Check.typeOf.object("options.polygonHierarchy", options.polygonHierarchy);
  Iif (
    defined(options.perPositionHeight) &&
    options.perPositionHeight &&
    defined(options.height)
  ) {
    throw new DeveloperError(
      "Cannot use both options.perPositionHeight and options.height",
    );
  }
  if (
    defined(options.arcType) &&
    options.arcType !== ArcType.GEODESIC &&
    options.arcType !== ArcType.RHUMB
  ) {
    throw new DeveloperError(
      "Invalid arcType. Valid options are ArcType.GEODESIC and ArcType.RHUMB.",
    );
  }
  //>>includeEnd('debug');
 
  const polygonHierarchy = options.polygonHierarchy;
  const vertexFormat = options.vertexFormat ?? VertexFormat.DEFAULT;
  const ellipsoid = options.ellipsoid ?? Ellipsoid.default;
  const granularity = options.granularity ?? CesiumMath.RADIANS_PER_DEGREE;
  const stRotation = options.stRotation ?? 0.0;
  const textureCoordinates = options.textureCoordinates;
  const perPositionHeight = options.perPositionHeight ?? false;
  const perPositionHeightExtrude =
    perPositionHeight && defined(options.extrudedHeight);
  let height = options.height ?? 0.0;
  let extrudedHeight = options.extrudedHeight ?? height;
 
  if (!perPositionHeightExtrude) {
    const h = Math.max(height, extrudedHeight);
    extrudedHeight = Math.min(height, extrudedHeight);
    height = h;
  }
 
  this._vertexFormat = VertexFormat.clone(vertexFormat);
  this._ellipsoid = Ellipsoid.clone(ellipsoid);
  this._granularity = granularity;
  this._stRotation = stRotation;
  this._height = height;
  this._extrudedHeight = extrudedHeight;
  this._closeTop = options.closeTop ?? true;
  this._closeBottom = options.closeBottom ?? true;
  this._polygonHierarchy = polygonHierarchy;
  this._perPositionHeight = perPositionHeight;
  this._perPositionHeightExtrude = perPositionHeightExtrude;
  this._shadowVolume = options.shadowVolume ?? false;
  this._workerName = "createPolygonGeometry";
  this._offsetAttribute = options.offsetAttribute;
  this._arcType = options.arcType ?? ArcType.GEODESIC;
 
  this._rectangle = undefined;
  this._textureCoordinateRotationPoints = undefined;
  this._textureCoordinates = textureCoordinates;
 
  /**
   * The number of elements used to pack the object into an array.
   * @type {number}
   */
  this.packedLength =
    PolygonGeometryLibrary.computeHierarchyPackedLength(
      polygonHierarchy,
      Cartesian3,
    ) +
    Ellipsoid.packedLength +
    VertexFormat.packedLength +
    (textureCoordinates
      ? PolygonGeometryLibrary.computeHierarchyPackedLength(
          textureCoordinates,
          Cartesian2,
        )
      : 1) +
    12;
}
 
/**
 * A description of a polygon from an array of positions. Polygon geometry can be rendered with both {@link Primitive} and {@link GroundPrimitive}.
 *
 * @param {object} options Object with the following properties:
 * @param {Cartesian3[]} options.positions An array of positions that defined the corner points of the polygon.
 * @param {number} [options.height=0.0] The height of the polygon.
 * @param {number} [options.extrudedHeight] The height of the polygon extrusion.
 * @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
 * @param {number} [options.stRotation=0.0] The rotation of the texture coordinates, in radians. A positive rotation is counter-clockwise.
 * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.default] The ellipsoid to be used as a reference.
 * @param {number} [options.granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
 * @param {boolean} [options.perPositionHeight=false] Use the height of options.positions for each position instead of using options.height to determine the height.
 * @param {boolean} [options.closeTop=true] When false, leaves off the top of an extruded polygon open.
 * @param {boolean} [options.closeBottom=true] When false, leaves off the bottom of an extruded polygon open.
 * @param {ArcType} [options.arcType=ArcType.GEODESIC] The type of line the polygon edges must follow. Valid options are {@link ArcType.GEODESIC} and {@link ArcType.RHUMB}.
 * @param {PolygonHierarchy} [options.textureCoordinates] Texture coordinates as a {@link PolygonHierarchy} of {@link Cartesian2} points. Has no effect for ground primitives.
 * @returns {PolygonGeometry}
 *
 * @example
 * // create a polygon from points
 * const polygon = Cesium.PolygonGeometry.fromPositions({
 *   positions : Cesium.Cartesian3.fromDegreesArray([
 *     -72.0, 40.0,
 *     -70.0, 35.0,
 *     -75.0, 30.0,
 *     -70.0, 30.0,
 *     -68.0, 40.0
 *   ])
 * });
 * const geometry = Cesium.PolygonGeometry.createGeometry(polygon);
 *
 * @see PolygonGeometry#createGeometry
 */
PolygonGeometry.fromPositions = function (options) {
  options = options ?? Frozen.EMPTY_OBJECT;
 
  //>>includeStart('debug', pragmas.debug);
  Check.defined("options.positions", options.positions);
  //>>includeEnd('debug');
 
  const newOptions = {
    polygonHierarchy: {
      positions: options.positions,
    },
    height: options.height,
    extrudedHeight: options.extrudedHeight,
    vertexFormat: options.vertexFormat,
    stRotation: options.stRotation,
    ellipsoid: options.ellipsoid,
    granularity: options.granularity,
    perPositionHeight: options.perPositionHeight,
    closeTop: options.closeTop,
    closeBottom: options.closeBottom,
    offsetAttribute: options.offsetAttribute,
    arcType: options.arcType,
    textureCoordinates: options.textureCoordinates,
  };
  return new PolygonGeometry(newOptions);
};
 
/**
 * Stores the provided instance into the provided array.
 *
 * @param {PolygonGeometry} value The value to pack.
 * @param {number[]} array The array to pack into.
 * @param {number} [startingIndex=0] The index into the array at which to start packing the elements.
 *
 * @returns {number[]} The array that was packed into
 */
PolygonGeometry.pack = function (value, array, startingIndex) {
  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.object("value", value);
  Check.defined("array", array);
  //>>includeEnd('debug');
 
  startingIndex = startingIndex ?? 0;
 
  startingIndex = PolygonGeometryLibrary.packPolygonHierarchy(
    value._polygonHierarchy,
    array,
    startingIndex,
    Cartesian3,
  );
 
  Ellipsoid.pack(value._ellipsoid, array, startingIndex);
  startingIndex += Ellipsoid.packedLength;
 
  VertexFormat.pack(value._vertexFormat, array, startingIndex);
  startingIndex += VertexFormat.packedLength;
 
  array[startingIndex++] = value._height;
  array[startingIndex++] = value._extrudedHeight;
  array[startingIndex++] = value._granularity;
  array[startingIndex++] = value._stRotation;
  array[startingIndex++] = value._perPositionHeightExtrude ? 1.0 : 0.0;
  array[startingIndex++] = value._perPositionHeight ? 1.0 : 0.0;
  array[startingIndex++] = value._closeTop ? 1.0 : 0.0;
  array[startingIndex++] = value._closeBottom ? 1.0 : 0.0;
  array[startingIndex++] = value._shadowVolume ? 1.0 : 0.0;
  array[startingIndex++] = value._offsetAttribute ?? -1;
  array[startingIndex++] = value._arcType;
  if (defined(value._textureCoordinates)) {
    startingIndex = PolygonGeometryLibrary.packPolygonHierarchy(
      value._textureCoordinates,
      array,
      startingIndex,
      Cartesian2,
    );
  } else {
    array[startingIndex++] = -1.0;
  }
  array[startingIndex++] = value.packedLength;
  return array;
};
 
const scratchEllipsoid = Ellipsoid.clone(Ellipsoid.UNIT_SPHERE);
const scratchVertexFormat = new VertexFormat();
 
//Only used to avoid inability to default construct.
const dummyOptions = {
  polygonHierarchy: {},
};
 
/**
 * Retrieves an instance from a packed array.
 *
 * @param {number[]} array The packed array.
 * @param {number} [startingIndex=0] The starting index of the element to be unpacked.
 * @param {PolygonGeometry} [result] The object into which to store the result.
 * @returns {PolygonGeometry} The modified result parameter or a new PolygonGeometry instance if one was not provided.
 */
PolygonGeometry.unpack = function (array, startingIndex, result) {
  //>>includeStart('debug', pragmas.debug);
  Check.defined("array", array);
  //>>includeEnd('debug');
 
  startingIndex = startingIndex ?? 0;
 
  const polygonHierarchy = PolygonGeometryLibrary.unpackPolygonHierarchy(
    array,
    startingIndex,
    Cartesian3,
  );
  startingIndex = polygonHierarchy.startingIndex;
  delete polygonHierarchy.startingIndex;
 
  const ellipsoid = Ellipsoid.unpack(array, startingIndex, scratchEllipsoid);
  startingIndex += Ellipsoid.packedLength;
 
  const vertexFormat = VertexFormat.unpack(
    array,
    startingIndex,
    scratchVertexFormat,
  );
  startingIndex += VertexFormat.packedLength;
 
  const height = array[startingIndex++];
  const extrudedHeight = array[startingIndex++];
  const granularity = array[startingIndex++];
  const stRotation = array[startingIndex++];
  const perPositionHeightExtrude = array[startingIndex++] === 1.0;
  const perPositionHeight = array[startingIndex++] === 1.0;
  const closeTop = array[startingIndex++] === 1.0;
  const closeBottom = array[startingIndex++] === 1.0;
  const shadowVolume = array[startingIndex++] === 1.0;
  const offsetAttribute = array[startingIndex++];
  const arcType = array[startingIndex++];
  const textureCoordinates =
    array[startingIndex] === -1.0
      ? undefined
      : PolygonGeometryLibrary.unpackPolygonHierarchy(
          array,
          startingIndex,
          Cartesian2,
        );
  if (defined(textureCoordinates)) {
    startingIndex = textureCoordinates.startingIndex;
    delete textureCoordinates.startingIndex;
  } else {
    startingIndex++;
  }
  const packedLength = array[startingIndex++];
 
  Eif (!defined(result)) {
    result = new PolygonGeometry(dummyOptions);
  }
 
  result._polygonHierarchy = polygonHierarchy;
  result._ellipsoid = Ellipsoid.clone(ellipsoid, result._ellipsoid);
  result._vertexFormat = VertexFormat.clone(vertexFormat, result._vertexFormat);
  result._height = height;
  result._extrudedHeight = extrudedHeight;
  result._granularity = granularity;
  result._stRotation = stRotation;
  result._perPositionHeightExtrude = perPositionHeightExtrude;
  result._perPositionHeight = perPositionHeight;
  result._closeTop = closeTop;
  result._closeBottom = closeBottom;
  result._shadowVolume = shadowVolume;
  result._offsetAttribute =
    offsetAttribute === -1 ? undefined : offsetAttribute;
  result._arcType = arcType;
  result._textureCoordinates = textureCoordinates;
  result.packedLength = packedLength;
 
  return result;
};
 
const scratchCartesian0 = new Cartesian2();
const scratchCartesian1 = new Cartesian2();
const scratchPolarClosest = new Stereographic();
function expandRectangle(
  polar,
  lastPolar,
  ellipsoid,
  arcType,
  polygon,
  result,
) {
  const longitude = polar.longitude;
  const lonAdjusted =
    longitude >= 0.0 ? longitude : longitude + CesiumMath.TWO_PI;
  polygon.westOverIdl = Math.min(polygon.westOverIdl, lonAdjusted);
  polygon.eastOverIdl = Math.max(polygon.eastOverIdl, lonAdjusted);
 
  result.west = Math.min(result.west, longitude);
  result.east = Math.max(result.east, longitude);
 
  const latitude = polar.getLatitude(ellipsoid);
  let segmentLatitude = latitude;
 
  result.south = Math.min(result.south, latitude);
  result.north = Math.max(result.north, latitude);
 
  if (arcType !== ArcType.RHUMB) {
    // Geodesics will need to find the closest point on line. Rhumb lines will not have a latitude greater in magnitude than either of their endpoints.
    const segment = Cartesian2.subtract(
      lastPolar.position,
      polar.position,
      scratchCartesian0,
    );
    const t =
      Cartesian2.dot(lastPolar.position, segment) /
      Cartesian2.dot(segment, segment);
    if (t > 0.0 && t < 1.0) {
      const projected = Cartesian2.add(
        lastPolar.position,
        Cartesian2.multiplyByScalar(segment, -t, segment),
        scratchCartesian1,
      );
      const closestPolar = Stereographic.clone(lastPolar, scratchPolarClosest);
      closestPolar.position = projected;
      const adjustedLatitude = closestPolar.getLatitude(ellipsoid);
      result.south = Math.min(result.south, adjustedLatitude);
      result.north = Math.max(result.north, adjustedLatitude);
 
      Iif (Math.abs(latitude) > Math.abs(adjustedLatitude)) {
        segmentLatitude = adjustedLatitude;
      }
    }
  }
  const direction = lastPolar.x * polar.y - polar.x * lastPolar.y;
 
  // The total internal angle in either hemisphere determines if the pole is inside or outside the polygon
  let angle = Math.sign(direction);
  if (angle !== 0.0) {
    angle *= Cartesian2.angleBetween(lastPolar.position, polar.position);
  }
 
  if (segmentLatitude >= 0.0) {
    polygon.northAngle += angle;
  }
 
  if (segmentLatitude <= 0.0) {
    polygon.southAngle += angle;
  }
}
 
const scratchPolar = new Stereographic();
const scratchPolarPrevious = new Stereographic();
const polygon = {
  northAngle: 0.0,
  southAngle: 0.0,
  westOverIdl: 0.0,
  eastOverIdl: 0.0,
};
 
/**
 * Computes a rectangle which encloses the polygon defined by the list of positions, including cases over the international date line and the poles.
 *
 * @param {Cartesian3[]} positions A linear ring defining the outer boundary of the polygon.
 * @param {Ellipsoid} [ellipsoid=Ellipsoid.default] The ellipsoid to be used as a reference.
 * @param {ArcType} [arcType=ArcType.GEODESIC] The type of line the polygon edges must follow. Valid options are {@link ArcType.GEODESIC} and {@link ArcType.RHUMB}.
 * @param {Rectangle} [result] An object in which to store the result.
 *
 * @returns {Rectangle} The result rectangle
 */
PolygonGeometry.computeRectangleFromPositions = function (
  positions,
  ellipsoid,
  arcType,
  result,
) {
  //>>includeStart('debug', pragmas.debug);
  Check.defined("positions", positions);
  //>>includeEnd('debug');
 
  if (!defined(result)) {
    result = new Rectangle();
  }
 
  if (positions.length < 3) {
    return result;
  }
 
  result.west = Number.POSITIVE_INFINITY;
  result.east = Number.NEGATIVE_INFINITY;
  result.south = Number.POSITIVE_INFINITY;
  result.north = Number.NEGATIVE_INFINITY;
 
  polygon.northAngle = 0.0;
  polygon.southAngle = 0.0;
  polygon.westOverIdl = Number.POSITIVE_INFINITY;
  polygon.eastOverIdl = Number.NEGATIVE_INFINITY;
 
  const positionsLength = positions.length;
  let lastPolarPosition = Stereographic.fromCartesian(
    positions[0],
    scratchPolarPrevious,
  );
  for (let i = 1; i < positionsLength; i++) {
    const polarPosition = Stereographic.fromCartesian(
      positions[i],
      scratchPolar,
    );
    expandRectangle(
      polarPosition,
      lastPolarPosition,
      ellipsoid,
      arcType,
      polygon,
      result,
    );
 
    lastPolarPosition = Stereographic.clone(polarPosition, lastPolarPosition);
  }
 
  expandRectangle(
    Stereographic.fromCartesian(positions[0], scratchPolar),
    lastPolarPosition,
    ellipsoid,
    arcType,
    polygon,
    result,
  );
 
  if (result.east - result.west > polygon.eastOverIdl - polygon.westOverIdl) {
    result.west = polygon.westOverIdl;
    result.east = polygon.eastOverIdl;
 
    Eif (result.east > CesiumMath.PI) {
      result.east = result.east - CesiumMath.TWO_PI;
    }
    if (result.west > CesiumMath.PI) {
      result.west = result.west - CesiumMath.TWO_PI;
    }
  }
 
  // If either pole is inside the polygon, adjust the rectangle so the pole is included
  if (
    CesiumMath.equalsEpsilon(
      Math.abs(polygon.northAngle),
      CesiumMath.TWO_PI,
      CesiumMath.EPSILON10,
    )
  ) {
    result.north = CesiumMath.PI_OVER_TWO;
    result.east = CesiumMath.PI;
    result.west = -CesiumMath.PI;
  }
 
  if (
    CesiumMath.equalsEpsilon(
      Math.abs(polygon.southAngle),
      CesiumMath.TWO_PI,
      CesiumMath.EPSILON10,
    )
  ) {
    result.south = -CesiumMath.PI_OVER_TWO;
    result.east = CesiumMath.PI;
    result.west = -CesiumMath.PI;
  }
 
  return result;
};
 
const scratchPolarForPlane = new Stereographic();
function getTangentPlane(rectangle, positions, ellipsoid) {
  Iif (rectangle.height >= CesiumMath.PI || rectangle.width >= CesiumMath.PI) {
    const polar = Stereographic.fromCartesian(
      positions[0],
      scratchPolarForPlane,
    );
    return polar.tangentPlane;
  }
 
  // Use a local tangent plane for smaller extents
  return EllipsoidTangentPlane.fromPoints(positions, ellipsoid);
}
 
const scratchCartographicCyllindrical = new Cartographic();
function createProjectTo2d(rectangle, outerPositions, ellipsoid) {
  return (positions, results) => {
    // If the polygon positions span a large enough extent, use a specialized projection
    Iif (rectangle.height >= CesiumMath.PI || rectangle.width >= CesiumMath.PI) {
      // polygons that cross the equator must use cyllindrical coordinates to correctly compute winding order.
      if (rectangle.south < 0 && rectangle.north > 0) {
        if (!defined(results)) {
          results = [];
        }
 
        for (let i = 0; i < positions.length; ++i) {
          const cartographic = ellipsoid.cartesianToCartographic(
            positions[i],
            scratchCartographicCyllindrical,
          );
          results[i] = new Cartesian2(
            cartographic.longitude / CesiumMath.PI,
            cartographic.latitude / CesiumMath.PI_OVER_TWO,
          );
        }
 
        results.length = positions.length;
        return results;
      }
 
      return Stereographic.fromCartesianArray(positions, results);
    }
 
    // Use a local tangent plane for smaller extents
    const tangentPlane = EllipsoidTangentPlane.fromPoints(
      outerPositions,
      ellipsoid,
    );
    return tangentPlane.projectPointsOntoPlane(positions, results);
  };
}
 
function createProjectPositionTo2d(rectangle, outerRing, ellipsoid) {
  // If the polygon positions span a large enough extent, use a specialized projection
  Iif (rectangle.height >= CesiumMath.PI || rectangle.width >= CesiumMath.PI) {
    return (position, result) => {
      // polygons that cross the equator must use cyllindrical coordinates to correctly compute winding order.
      if (rectangle.south < 0 && rectangle.north > 0) {
        const cartographic = ellipsoid.cartesianToCartographic(
          position,
          scratchCartographicCyllindrical,
        );
        if (!defined(result)) {
          result = new Cartesian2();
        }
        result.x = cartographic.longitude / CesiumMath.PI;
        result.y = cartographic.latitude / CesiumMath.PI_OVER_TWO;
 
        return result;
      }
 
      return Stereographic.fromCartesian(position, result);
    };
  }
 
  const tangentPlane = EllipsoidTangentPlane.fromPoints(outerRing, ellipsoid);
  return (position, result) => {
    // Use a local tangent plane for smaller extents
    return tangentPlane.projectPointsOntoPlane(position, result);
  };
}
 
function createSplitPolygons(rectangle, ellipsoid, arcType, perPositionHeight) {
  return (polygons, results) => {
    if (
      !perPositionHeight &&
      (rectangle.height >= CesiumMath.PI_OVER_TWO ||
        rectangle.width >= 2 * CesiumMath.PI_OVER_THREE)
    ) {
      return PolygonGeometryLibrary.splitPolygonsOnEquator(
        polygons,
        ellipsoid,
        arcType,
        results,
      );
    }
 
    return polygons;
  };
}
 
function computeBoundingRectangle(outerRing, rectangle, ellipsoid, stRotation) {
  Iif (rectangle.height >= CesiumMath.PI || rectangle.width >= CesiumMath.PI) {
    return BoundingRectangle.fromRectangle(
      rectangle,
      undefined,
      scratchBoundingRectangle,
    );
  }
 
  const outerPositions = outerRing;
  const tangentPlane = EllipsoidTangentPlane.fromPoints(
    outerPositions,
    ellipsoid,
  );
  return PolygonGeometryLibrary.computeBoundingRectangle(
    tangentPlane.plane.normal,
    tangentPlane.projectPointOntoPlane.bind(tangentPlane),
    outerPositions,
    stRotation,
    scratchBoundingRectangle,
  );
}
 
/**
 * Computes the geometric representation of a polygon, including its vertices, indices, and a bounding sphere.
 *
 * @param {PolygonGeometry} polygonGeometry A description of the polygon.
 * @returns {Geometry|undefined} The computed vertices and indices.
 */
PolygonGeometry.createGeometry = function (polygonGeometry) {
  const vertexFormat = polygonGeometry._vertexFormat;
  const ellipsoid = polygonGeometry._ellipsoid;
  const granularity = polygonGeometry._granularity;
  const stRotation = polygonGeometry._stRotation;
  const polygonHierarchy = polygonGeometry._polygonHierarchy;
  const perPositionHeight = polygonGeometry._perPositionHeight;
  const closeTop = polygonGeometry._closeTop;
  const closeBottom = polygonGeometry._closeBottom;
  const arcType = polygonGeometry._arcType;
  const textureCoordinates = polygonGeometry._textureCoordinates;
 
  const hasTextureCoordinates = defined(textureCoordinates);
 
  const outerPositions = polygonHierarchy.positions;
  if (outerPositions.length < 3) {
    return;
  }
 
  const rectangle = polygonGeometry.rectangle;
  const results = PolygonGeometryLibrary.polygonsFromHierarchy(
    polygonHierarchy,
    hasTextureCoordinates,
    createProjectTo2d(rectangle, outerPositions, ellipsoid),
    !perPositionHeight,
    ellipsoid,
    createSplitPolygons(rectangle, ellipsoid, arcType, perPositionHeight),
  );
 
  const hierarchy = results.hierarchy;
  const polygons = results.polygons;
 
  const dummyFunction = function (identity) {
    return identity;
  };
 
  const textureCoordinatePolygons = hasTextureCoordinates
    ? PolygonGeometryLibrary.polygonsFromHierarchy(
        textureCoordinates,
        true,
        dummyFunction,
        false,
        ellipsoid,
      ).polygons
    : undefined;
 
  if (hierarchy.length === 0) {
    return;
  }
 
  const outerRing = hierarchy[0].outerRing;
  const boundingRectangle = computeBoundingRectangle(
    outerRing,
    rectangle,
    ellipsoid,
    stRotation,
  );
 
  const geometries = [];
 
  const height = polygonGeometry._height;
  const extrudedHeight = polygonGeometry._extrudedHeight;
  const extrude =
    polygonGeometry._perPositionHeightExtrude ||
    !CesiumMath.equalsEpsilon(height, extrudedHeight, 0, CesiumMath.EPSILON2);
 
  const options = {
    perPositionHeight: perPositionHeight,
    vertexFormat: vertexFormat,
    geometry: undefined,
    rotationAxis: getTangentPlane(rectangle, outerRing, ellipsoid).plane.normal,
    projectTo2d: createProjectPositionTo2d(rectangle, outerRing, ellipsoid),
    boundingRectangle: boundingRectangle,
    ellipsoid: ellipsoid,
    stRotation: stRotation,
    textureCoordinates: undefined,
    bottom: false,
    top: true,
    wall: false,
    extrude: false,
    arcType: arcType,
  };
 
  let i;
 
  if (extrude) {
    options.extrude = true;
    options.top = closeTop;
    options.bottom = closeBottom;
    options.shadowVolume = polygonGeometry._shadowVolume;
    options.offsetAttribute = polygonGeometry._offsetAttribute;
    for (i = 0; i < polygons.length; i++) {
      const splitGeometry = createGeometryFromPositionsExtruded(
        ellipsoid,
        polygons[i],
        hasTextureCoordinates ? textureCoordinatePolygons[i] : undefined,
        granularity,
        hierarchy[i],
        perPositionHeight,
        closeTop,
        closeBottom,
        vertexFormat,
        arcType,
      );
 
      let topAndBottom;
      if (closeTop && closeBottom) {
        topAndBottom = splitGeometry.topAndBottom;
        options.geometry = PolygonGeometryLibrary.scaleToGeodeticHeightExtruded(
          topAndBottom.geometry,
          height,
          extrudedHeight,
          ellipsoid,
          perPositionHeight,
        );
      } else if (closeTop) {
        topAndBottom = splitGeometry.topAndBottom;
        topAndBottom.geometry.attributes.position.values =
          PolygonPipeline.scaleToGeodeticHeight(
            topAndBottom.geometry.attributes.position.values,
            height,
            ellipsoid,
            !perPositionHeight,
          );
        options.geometry = topAndBottom.geometry;
      } else if (closeBottom) {
        topAndBottom = splitGeometry.topAndBottom;
        topAndBottom.geometry.attributes.position.values =
          PolygonPipeline.scaleToGeodeticHeight(
            topAndBottom.geometry.attributes.position.values,
            extrudedHeight,
            ellipsoid,
            true,
          );
        options.geometry = topAndBottom.geometry;
      }
      if (closeTop || closeBottom) {
        options.wall = false;
        topAndBottom.geometry = computeAttributes(options);
        geometries.push(topAndBottom);
      }
 
      const walls = splitGeometry.walls;
      options.wall = true;
      for (let k = 0; k < walls.length; k++) {
        const wall = walls[k];
        options.geometry = PolygonGeometryLibrary.scaleToGeodeticHeightExtruded(
          wall.geometry,
          height,
          extrudedHeight,
          ellipsoid,
          perPositionHeight,
        );
        wall.geometry = computeAttributes(options);
        geometries.push(wall);
      }
    }
  } else {
    for (i = 0; i < polygons.length; i++) {
      const geometryInstance = new GeometryInstance({
        geometry: PolygonGeometryLibrary.createGeometryFromPositions(
          ellipsoid,
          polygons[i],
          hasTextureCoordinates ? textureCoordinatePolygons[i] : undefined,
          granularity,
          perPositionHeight,
          vertexFormat,
          arcType,
        ),
      });
      geometryInstance.geometry.attributes.position.values =
        PolygonPipeline.scaleToGeodeticHeight(
          geometryInstance.geometry.attributes.position.values,
          height,
          ellipsoid,
          !perPositionHeight,
        );
      options.geometry = geometryInstance.geometry;
 
      geometryInstance.geometry = computeAttributes(options);
 
      if (defined(polygonGeometry._offsetAttribute)) {
        const length =
          geometryInstance.geometry.attributes.position.values.length;
        const offsetValue =
          polygonGeometry._offsetAttribute === GeometryOffsetAttribute.NONE
            ? 0
            : 1;
        const applyOffset = new Uint8Array(length / 3).fill(offsetValue);
        geometryInstance.geometry.attributes.applyOffset =
          new GeometryAttribute({
            componentDatatype: ComponentDatatype.UNSIGNED_BYTE,
            componentsPerAttribute: 1,
            values: applyOffset,
          });
      }
 
      geometries.push(geometryInstance);
    }
  }
 
  const geometry = GeometryPipeline.combineInstances(geometries)[0];
  geometry.attributes.position.values = new Float64Array(
    geometry.attributes.position.values,
  );
  geometry.indices = IndexDatatype.createTypedArray(
    geometry.attributes.position.values.length / 3,
    geometry.indices,
  );
 
  const attributes = geometry.attributes;
  const boundingSphere = BoundingSphere.fromVertices(
    attributes.position.values,
  );
 
  Iif (!vertexFormat.position) {
    delete attributes.position;
  }
 
  return new Geometry({
    attributes: attributes,
    indices: geometry.indices,
    primitiveType: geometry.primitiveType,
    boundingSphere: boundingSphere,
    offsetAttribute: polygonGeometry._offsetAttribute,
  });
};
 
/**
 * @private
 */
PolygonGeometry.createShadowVolume = function (
  polygonGeometry,
  minHeightFunc,
  maxHeightFunc,
) {
  const granularity = polygonGeometry._granularity;
  const ellipsoid = polygonGeometry._ellipsoid;
 
  const minHeight = minHeightFunc(granularity, ellipsoid);
  const maxHeight = maxHeightFunc(granularity, ellipsoid);
 
  return new PolygonGeometry({
    polygonHierarchy: polygonGeometry._polygonHierarchy,
    ellipsoid: ellipsoid,
    stRotation: polygonGeometry._stRotation,
    granularity: granularity,
    perPositionHeight: false,
    extrudedHeight: minHeight,
    height: maxHeight,
    vertexFormat: VertexFormat.POSITION_ONLY,
    shadowVolume: true,
    arcType: polygonGeometry._arcType,
  });
};
 
function textureCoordinateRotationPoints(polygonGeometry) {
  const stRotation = -polygonGeometry._stRotation;
  if (stRotation === 0.0) {
    return [0, 0, 0, 1, 1, 0];
  }
  const ellipsoid = polygonGeometry._ellipsoid;
  const positions = polygonGeometry._polygonHierarchy.positions;
  const boundingRectangle = polygonGeometry.rectangle;
  return Geometry._textureCoordinateRotationPoints(
    positions,
    stRotation,
    ellipsoid,
    boundingRectangle,
  );
}
 
Object.defineProperties(PolygonGeometry.prototype, {
  /**
   * @private
   */
  rectangle: {
    get: function () {
      if (!defined(this._rectangle)) {
        const positions = this._polygonHierarchy.positions;
        this._rectangle = PolygonGeometry.computeRectangleFromPositions(
          positions,
          this._ellipsoid,
          this._arcType,
        );
      }
 
      return this._rectangle;
    },
  },
  /**
   * For remapping texture coordinates when rendering PolygonGeometries as GroundPrimitives.
   * @private
   */
  textureCoordinateRotationPoints: {
    get: function () {
      Eif (!defined(this._textureCoordinateRotationPoints)) {
        this._textureCoordinateRotationPoints =
          textureCoordinateRotationPoints(this);
      }
      return this._textureCoordinateRotationPoints;
    },
  },
});
export default PolygonGeometry;