All files / engine/Source/Scene/Model PrimitiveOutlineGenerator.js

95.74% Statements 180/188
94.5% Branches 86/91
100% Functions 12/12
95.65% Lines 176/184

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                          1x 1x                                                                                                         18x 18x 18x 18x     18x 17x 16x                   15x                 15x                     15x                     15x                   15x   15x     1x                           11x                                 9x                                 15x   15x 15x 15x 15x       15x     15x 58562x 58562x 58562x       58562x 58562x 58562x 58562x             58562x                 58562x   21960x     21960x   21953x       21953x 21953x         21953x       21953x         21960x         1x 21959x       1x         21960x 14635x 14635x 7325x 7x 7x   7318x 7318x           21960x                         15x 15x                                                           80522x 80522x 80522x   80522x 80522x 14635x     65887x 65887x 65887x   65887x 65887x 4x     65883x 65883x 65883x   65883x 65883x 3x     65880x       65880x   36600x 36600x 36600x 29280x   21938x 21938x 21938x 7342x   22x 22x 22x 7320x   2x 2x 2x 7318x         7318x               7318x 7318x 7318x 7318x         7318x 3x   7315x         58562x 58562x 58562x 58562x   58562x 58562x 58562x 58562x   58562x 58562x 58562x 58562x     58562x                                                                                               212292x 212292x 212292x 212292x       212292x 87889x     124403x                                       21954x                                       1x     24x   24x       24x   24x     24x 24x         24x     24x 32x 32x 32x 113x       24x                       1x 4x 4x 3x     4x 1x     3x   3x 3x   3x   3x 36x 36x     3x                                 3x   3x                           39x     39x         39x 3x 36x 3x 33x 3x 30x 3x   39x                                               15x                     15x 15x 51316x 51316x 51316x 51316x 51316x 51316x                         1x 175686x 175686x 175686x 175686x        
import Check from "../../Core/Check.js";
import defined from "../../Core/defined.js";
import Frozen from "../../Core/Frozen.js";
import PixelFormat from "../../Core/PixelFormat.js";
import ContextLimits from "../../Renderer/ContextLimits.js";
import Sampler from "../../Renderer/Sampler.js";
import Texture from "../../Renderer/Texture.js";
import TextureMagnificationFilter from "../../Renderer/TextureMagnificationFilter.js";
import TextureMinificationFilter from "../../Renderer/TextureMinificationFilter.js";
import TextureWrap from "../../Renderer/TextureWrap.js";
 
// glTF does not allow an index value of 65535 because this is the primitive
// restart value in some APIs.
const MAX_GLTF_UINT16_INDEX = 65534;
const MAX_GLTF_UINT8_INDEX = 255;
 
/**
 * A class to handle the low-level details of processing indices and vertex
 * attributes for the CESIUM_primitive_outline extension.
 * <p>
 * To render outlines, a lookup texture is used 3 times, once per edge of a
 * triangle. In order to render correctly, all three vertices must agree on the
 * same ordering of the three edges when computing outline (texture)
 * coordinates. Sometimes this is not possible, as a vertex shared between
 * multiple triangles may become overly constrained. In such cases, vertices are
 * copied and indices are updated until valid outline coordinates can be
 * defined.
 * </p>
 *
 * @see {@link https://www.researchgate.net/publication/220067637_Fast_and_versatile_texture-based_wireframe_rendering|Fast and versatile texture-based wireframe rendering}
 *
 * @alias PrimitiveOutlineGenerator
 * @constructor
 *
 * @param {number} options Object with the following properties:
 * @param {Uint8Array|Uint16Array|Uint32Array} options.triangleIndices The original triangle indices of the primitive. The constructor takes ownership of this typed array as it will be modified internally. Use the updatedTriangleIndices getter to get the final result.
 * @param {number[]} options.outlineIndices The indices of edges in the triangle from the CESIUM_primitive_outline extension
 * @param {number} options.originalVertexCount The original number of vertices in the primitive
 * @example
 * // The constructor will compute the updated indices and generate outline
 * // coordinates.
 * const outlineGenerator = new PrimitiveOutlineGenerator({
 *   triangleIndices: primitive.indices.typedArray,
 *   outlineIndices: outlineIndices,
 *   originalVertexCount: primitive.attributes[0].count
 * });
 *
 * // Caller must update the indices (the data type may have been upgraded!)
 * primitive.indices.typedArray = outlineGenerator.updatedTriangleIndices;
 * primitive.indices.indexDatatype =
 *  IndexDatatype.fromTypedArray(primitive.indices.typedArray);
 *
 * // Create a new attribute for the generated outline coordinates
 * primitive.outlineCoordinates = new ModelComponents.Attribute();
 * // ... initialize as a vec3 attribute
 * primitive.outlineCoordinates.typedArray =
 *   outlineGenerator.outlineCoordinates;
 *
 * // Updating an attribute
 * const attribute = primitive.attributes[i];
 * attribute.typedArray = outlineGenerator.updateAttribute(
 *   attribute.typedArray
 * );
 *
 * @private
 */
function PrimitiveOutlineGenerator(options) {
  options = options ?? Frozen.EMPTY_OBJECT;
  const triangleIndices = options.triangleIndices;
  const outlineIndices = options.outlineIndices;
  const originalVertexCount = options.originalVertexCount;
 
  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.object("options.triangleIndices", triangleIndices);
  Check.typeOf.object("options.outlineIndices", outlineIndices);
  Check.typeOf.number("options.originalVertexCount", originalVertexCount);
  //>>includeEnd('debug');
 
  /**
   * The triangle indices. It will be modified in place.
   *
   * @type {Uint8Array|Uint16Array|Uint32Array}
   *
   * @private
   */
  this._triangleIndices = triangleIndices;
 
  /**
   * How many vertices were originally in the primitive
   *
   * @type {number}
   *
   * @private
   */
  this._originalVertexCount = originalVertexCount;
 
  /**
   * The outline indices represent edges of the primitive's triangle mesh where
   * outlines must be drawn. This is stored as a hash set for efficient
   * checks of whether an edge is present.
   *
   * @type {EdgeSet}
   *
   * @private
   */
  this._edges = new EdgeSet(outlineIndices, originalVertexCount);
 
  /**
   * The typed array that will store the outline texture coordinates
   * once computed. This typed array should be turned into a vertex attribute
   * when rendering outlines.
   *
   * @type {Float32Array}
   *
   * @private
   */
  this._outlineCoordinatesTypedArray = undefined;
 
  /**
   * Array containing the indices of any vertices that must be copied and
   * appended to the list.
   *
   * @type {number[]}
   *
   * @private
   */
  this._extraVertices = [];
 
  initialize(this);
}
 
Object.defineProperties(PrimitiveOutlineGenerator.prototype, {
  /**
   * The updated triangle indices after generating outlines. The caller is for
   * responsible for updating the primitive's indices to use this array.
   *
   * @memberof PrimitiveOutlineGenerator.prototype
   *
   * @type {Uint8Array|Uint16Array|Uint32Array}
   * @readonly
   *
   * @private
   */
  updatedTriangleIndices: {
    get: function () {
      return this._triangleIndices;
    },
  },
 
  /**
   * The computed outline coordinates. The caller is responsible for
   * turning this into a vec3 attribute for rendering.
   *
   * @memberof PrimitiveOutlineGenerator.prototype
   *
   * @type {Float32Array}
   * @readonly
   *
   * @private
   */
  outlineCoordinates: {
    get: function () {
      return this._outlineCoordinatesTypedArray;
    },
  },
});
 
/**
 * Initialize the outline generator from the CESIUM_primitive_outline
 * extension data. This updates the triangle indices and generates outline
 * coordinates, but does not update other attributes (see
 * {@link PrimitiveOutlineGenerator#updateAttribute})
 *
 * @param {PrimitiveOutlineGenerator} outlineGenerator The outline generator
 *
 * @private
 */
function initialize(outlineGenerator) {
  // triangle indices may be extended from 16-bits to 32 bits if needed.
  let triangleIndices = outlineGenerator._triangleIndices;
 
  const edges = outlineGenerator._edges;
  const outlineCoordinates = [];
  const extraVertices = outlineGenerator._extraVertices;
  const vertexCount = outlineGenerator._originalVertexCount;
 
  // Dictionary of unmatchable vertex index -> copied vertex index. This is
  // used so we don't copy the same vertex more than necessary.
  const vertexCopies = {};
 
  // For each triangle, adjust vertex data so that the correct edges are outlined.
  for (let i = 0; i < triangleIndices.length; i += 3) {
    let i0 = triangleIndices[i];
    let i1 = triangleIndices[i + 1];
    let i2 = triangleIndices[i + 2];
 
    // Check which edges need to be outlined based on the contents of the
    // outline indices from the extension.
    const all = false; // set this to true to draw a full wireframe.
    const hasEdge01 = all || edges.hasEdge(i0, i1);
    const hasEdge12 = all || edges.hasEdge(i1, i2);
    const hasEdge20 = all || edges.hasEdge(i2, i0);
 
    // Attempt to compute outline coordinates. If no consistent ordering of
    // edges can be computed (due to constraints from adjacent faces), the
    // first attempt may fail. In such cases, make a copy of a vertex and
    // try again. This relaxes the constraints, so the while loop will
    // eventually finish.
    let unmatchableVertexIndex = matchAndStoreCoordinates(
      outlineCoordinates,
      i0,
      i1,
      i2,
      hasEdge01,
      hasEdge12,
      hasEdge20,
    );
    while (defined(unmatchableVertexIndex)) {
      // Copy the unmatchable index and try again.
      let copy = vertexCopies[unmatchableVertexIndex];
 
      // Only copy if we haven't already
      if (!defined(copy)) {
        // The new vertex will appear at the end of the vertex list
        copy = vertexCount + extraVertices.length;
 
        // Sometimes the copied vertex will in turn be a copy, so search
        // for the original one
        let original = unmatchableVertexIndex;
        while (original >= vertexCount) {
          original = extraVertices[original - vertexCount];
        }
 
        // Store the original vertex that needs to be copied
        extraVertices.push(original);
 
        // mark that we've seen this unmatchable vertex before so we don't
        // copy it multiple times.
        vertexCopies[unmatchableVertexIndex] = copy;
      }
 
      // Corner case: copying a vertex may overflow the range of an
      // 8- or 16- bit index buffer, so upgrade to a larger data type.
      if (
        copy > MAX_GLTF_UINT16_INDEX &&
        (triangleIndices instanceof Uint16Array ||
          triangleIndices instanceof Uint8Array)
      ) {
        triangleIndices = new Uint32Array(triangleIndices);
      } else if (
        copy > MAX_GLTF_UINT8_INDEX &&
        triangleIndices instanceof Uint8Array
      ) {
        triangleIndices = new Uint16Array(triangleIndices);
      }
 
      // Update the triangle indices buffer to use the copied vertex instead
      // of the original one.
      if (unmatchableVertexIndex === i0) {
        i0 = copy;
        triangleIndices[i] = copy;
      } else if (unmatchableVertexIndex === i1) {
        i1 = copy;
        triangleIndices[i + 1] = copy;
      } else {
        i2 = copy;
        triangleIndices[i + 2] = copy;
      }
 
      // Attempt to generate outline coordinates again. This is more likely
      // to succeed since the copied vertex has no constraints on which order
      // of the 3 edges to use.
      unmatchableVertexIndex = matchAndStoreCoordinates(
        outlineCoordinates,
        i0,
        i1,
        i2,
        hasEdge01,
        hasEdge12,
        hasEdge20,
      );
    }
  }
 
  // Store the triangle indices in case we had to expand to 32-bit indices
  outlineGenerator._triangleIndices = triangleIndices;
  outlineGenerator._outlineCoordinatesTypedArray = new Float32Array(
    outlineCoordinates,
  );
}
 
/**
 * This function attempts to compute a valid ordering of edges for this triangle
 * and if found, computes outline coordinates for the three vertices. If not
 * possible, one of the vertices is returned so it can be copied.
 *
 * @param {number[]} outlineCoordinates An array to store the computed outline coordinates. There are 3 components per vertex. This will be modified in place.
 * @param {number} i0 The index of the first vertex of the triangle.
 * @param {number} i1 The index of the second vertex of the triangle.
 * @param {number} i2 The index of the third vertex of the triangle.
 * @param {boolean} hasEdge01 Whether there is an outline edge between vertices 0 and 1 of the triangle
 * @param {boolean} hasEdge12 Whether there is an outline edge between vertices 1 and 2 of the triangle
 * @param {boolean} hasEdge20 Whether there is an outline edge between vertices 2 and 0 of the triangle
 * @returns {number} If it's not possible to compute consistent outline coordinates for this triangle, the index of the most constrained vertex of i0, i1 and i2 is returned. Otherwise, this function returns undefined to indicate a successful match.
 *
 * @private
 */
function matchAndStoreCoordinates(
  outlineCoordinates,
  i0,
  i1,
  i2,
  hasEdge01,
  hasEdge12,
  hasEdge20,
) {
  const a0 = hasEdge20 ? 1.0 : 0.0;
  const b0 = hasEdge01 ? 1.0 : 0.0;
  const c0 = 0.0;
 
  const i0Mask = computeOrderMask(outlineCoordinates, i0, a0, b0, c0);
  if (i0Mask === 0) {
    return i0;
  }
 
  const a1 = 0.0;
  const b1 = hasEdge01 ? 1.0 : 0.0;
  const c1 = hasEdge12 ? 1.0 : 0.0;
 
  const i1Mask = computeOrderMask(outlineCoordinates, i1, a1, b1, c1);
  if (i1Mask === 0) {
    return i1;
  }
 
  const a2 = hasEdge20 ? 1.0 : 0.0;
  const b2 = 0.0;
  const c2 = hasEdge12 ? 1.0 : 0.0;
 
  const i2Mask = computeOrderMask(outlineCoordinates, i2, a2, b2, c2);
  if (i2Mask === 0) {
    return i2;
  }
 
  const workingOrders = i0Mask & i1Mask & i2Mask;
 
  let a, b, c;
 
  if (workingOrders & (1 << 0)) {
    // 0 - abc
    a = 0;
    b = 1;
    c = 2;
  } else if (workingOrders & (1 << 1)) {
    // 1 - acb
    a = 0;
    c = 1;
    b = 2;
  } else if (workingOrders & (1 << 2)) {
    // 2 - bac
    b = 0;
    a = 1;
    c = 2;
  } else if (workingOrders & (1 << 3)) {
    // 3 - bca
    b = 0;
    c = 1;
    a = 2;
  } else Iif (workingOrders & (1 << 4)) {
    // 4 - cab
    c = 0;
    a = 1;
    b = 2;
  } else Iif (workingOrders & (1 << 5)) {
    // 5 - cba
    c = 0;
    b = 1;
    a = 2;
  } else {
    // No ordering works. Report the most constrained vertex (i.e. the one with
    // fewest valid orderings) as unmatched so we copy that one.
    const i0ValidOrderCount = popcount6Bit(i0Mask);
    const i1ValidOrderCount = popcount6Bit(i1Mask);
    const i2ValidOrderCount = popcount6Bit(i2Mask);
    Iif (
      i0ValidOrderCount < i1ValidOrderCount &&
      i0ValidOrderCount < i2ValidOrderCount
    ) {
      return i0;
    } else if (i1ValidOrderCount < i2ValidOrderCount) {
      return i1;
    }
    return i2;
  }
 
  // We found a valid ordering of the edges, so store the outline coordinates
  // for this triangle.
  const i0Start = i0 * 3;
  outlineCoordinates[i0Start + a] = a0;
  outlineCoordinates[i0Start + b] = b0;
  outlineCoordinates[i0Start + c] = c0;
 
  const i1Start = i1 * 3;
  outlineCoordinates[i1Start + a] = a1;
  outlineCoordinates[i1Start + b] = b1;
  outlineCoordinates[i1Start + c] = c1;
 
  const i2Start = i2 * 3;
  outlineCoordinates[i2Start + a] = a2;
  outlineCoordinates[i2Start + b] = b2;
  outlineCoordinates[i2Start + c] = c2;
 
  // successful match
  return undefined;
}
 
/**
 * Each vertex has three coordinates, a, b, and c.
 * a is the coordinate that applies to edge 2-0 for the vertex.
 * b is the coordinate that applies to edge 0-1 for the vertex.
 * c is the coordinate that applies to edge 1-2 for the vertex.
 *
 * A single triangle with all edges highlighted:
 *
 *                 | a | b | c |
 *                 | 1 | 1 | 0 |
 *                       0
 *                      / \
 *                     /   \
 *           edge 0-1 /     \ edge 2-0
 *                   /       \
 *                  /         \
 * | a | b | c |   1-----------2   | a | b | c |
 * | 0 | 1 | 1 |     edge 1-2      | 1 | 0 | 1 |
 *
 * There are 6 possible orderings of coordinates a, b, and c:
 * 0 - abc
 * 1 - acb
 * 2 - bac
 * 3 - bca
 * 4 - cab
 * 5 - cba
 *
 * All vertices must use the _same ordering_ for the edges to be rendered
 * correctly. So we compute a bitmask for each vertex, where the bit at
 * each position indicates whether that ordering works (i.e. doesn't
 * conflict with already-assigned coordinates) for that vertex.
 *
 * Then we can find an ordering that works for all three vertices with a
 * bitwise AND.
 *
 * @param {number[]} outlineCoordinates The array of outline coordinates
 * @param {number} vertexIndex The index of the vertex to compute the mask for
 * @param {number} a The outline coordinate for edge 2-0
 * @param {number} b The outline coordinate for edge 0-1
 * @param {number} c The outline coordinate for edge 1-2
 * @returns {number} A bitmask with 6 bits where a 1 indicates the corresponding ordering is valid.
 *
 * @private
 */
function computeOrderMask(outlineCoordinates, vertexIndex, a, b, c) {
  const startIndex = vertexIndex * 3;
  const first = outlineCoordinates[startIndex];
  const second = outlineCoordinates[startIndex + 1];
  const third = outlineCoordinates[startIndex + 2];
 
  // If one coordinate is undefined, they all are since matchAndStoreCoordinates sets
  // all 3 components at once. In this case, all orderings are fine.
  if (!defined(first)) {
    return 0b111111;
  }
 
  return (
    ((first === a && second === b && third === c) << 0) |
    ((first === a && second === c && third === b) << 1) |
    ((first === b && second === a && third === c) << 2) |
    ((first === b && second === c && third === a) << 3) |
    ((first === c && second === a && third === b) << 4) |
    ((first === c && second === b && third === a) << 5)
  );
}
 
/**
 * Compute the popcount for 6-bit integers (values 0-63). This is the
 * number of 1s in the binary representation of the value.
 *
 * @param {number} value The value to compute the popcount for
 * @returns {number} The number of 1s in the binary representation of value
 *
 * @private
 */
function popcount6Bit(value) {
  return (
    (value & 1) +
    ((value >> 1) & 1) +
    ((value >> 2) & 1) +
    ((value >> 3) & 1) +
    ((value >> 4) & 1) +
    ((value >> 5) & 1)
  );
}
 
/**
 * After computing the outline coordinates, some vertices may need to be
 * copied and appended to the end of the list of vertices. This function updates
 * a typed array for a single attribute (e.g. POSITION or NORMAL).
 *
 * @param {Uint8Array|Int8Array|Uint16Array|Int16Array|Uint32Array|Int32Array|Float32Array} attributeTypedArray The attribute values to update. This function takes ownership of this typed array
 * @returns {Uint8Array|Int8Array|Uint16Array|Int16Array|Uint32Array|Int32Array|Float32Array} A new typed array that contains the existing attribute values, plus any copied values at the end.
 *
 * @private
 */
PrimitiveOutlineGenerator.prototype.updateAttribute = function (
  attributeTypedArray,
) {
  const extraVertices = this._extraVertices;
 
  const originalLength = attributeTypedArray.length;
 
  // This is a stride in number of typed elements. For example, a VEC3 would
  // have a stride of 3 (floats)
  const stride = originalLength / this._originalVertexCount;
 
  const extraVerticesLength = extraVertices.length;
 
  // Make a larger typed array of the same type as the input
  const ArrayType = attributeTypedArray.constructor;
  const result = new ArrayType(
    attributeTypedArray.length + extraVerticesLength * stride,
  );
 
  // Copy original vertices
  result.set(attributeTypedArray);
 
  // Copy the vertices added for outlining
  for (let i = 0; i < extraVerticesLength; i++) {
    const sourceIndex = extraVertices[i] * stride;
    const resultIndex = originalLength + i * stride;
    for (let j = 0; j < stride; j++) {
      result[resultIndex + j] = result[sourceIndex + j];
    }
  }
 
  return result;
};
 
/**
 * Create a mip-mapped lookup texture for rendering outlines. The texture is
 * constant, so it is cached on the context.
 *
 * @param {Context} context The context to use for creating the texture
 * @returns {Texture} The outline lookup texture.
 *
 * @private
 */
PrimitiveOutlineGenerator.createTexture = function (context) {
  let cache = context.cache.modelOutliningCache;
  if (!defined(cache)) {
    cache = context.cache.modelOutliningCache = {};
  }
 
  if (defined(cache.outlineTexture)) {
    return cache.outlineTexture;
  }
 
  const maxSize = Math.min(4096, ContextLimits.maximumTextureSize);
 
  let size = maxSize;
  const levelZero = createMipLevel(size);
 
  const mipLevels = [];
 
  while (size > 1) {
    size >>= 1;
    mipLevels.push(createMipLevel(size));
  }
 
  const texture = new Texture({
    context: context,
    source: {
      arrayBufferView: levelZero,
      mipLevels: mipLevels,
    },
    width: maxSize,
    height: 1,
    pixelFormat: PixelFormat.LUMINANCE,
    sampler: new Sampler({
      wrapS: TextureWrap.CLAMP_TO_EDGE,
      wrapT: TextureWrap.CLAMP_TO_EDGE,
      minificationFilter: TextureMinificationFilter.LINEAR_MIPMAP_LINEAR,
      magnificationFilter: TextureMagnificationFilter.LINEAR,
    }),
  });
 
  cache.outlineTexture = texture;
 
  return texture;
};
 
/**
 * Create an outline lookup texture for a single mip level. This is a texture of
 * mostly 0 values, except for the last value which is brighter to indicate
 * the outline.
 *
 * @param {number} size The width of the texture for this mip level
 * @returns {Uint8Array} A typed array containing the texels of the mip level
 *
 * @private
 */
function createMipLevel(size) {
  const texture = new Uint8Array(size);
 
  // This lookup texture creates an outline with width 0.75 px in screen space.
  texture[size - 1] = 192;
 
  // As we reach the top of the mip pyramid, a single set pixel becomes a
  // significant portion of the texture. This doesn't look great when zoomed
  // out, so attenuate the value by 50% at each level.
  if (size === 8) {
    texture[size - 1] = 96;
  } else if (size === 4) {
    texture[size - 1] = 48;
  } else if (size === 2) {
    texture[size - 1] = 24;
  } else if (size === 1) {
    texture[size - 1] = 12;
  }
  return texture;
}
 
/**
 * A hash set that provides quick lookups of whether an edge exists between
 * two vertices.
 *
 * @alias EdgeSet
 * @constructor
 *
 * @param {number[]} edgeIndices An array of vertex indices with an even number of elements where each pair of indices defines an edge.
 * @param {number} originalVertexCount The original number of vertices. This is used for computing a hash function.
 *
 * @private
 */
function EdgeSet(edgeIndices, originalVertexCount) {
  /**
   * Original number of vertices in the primitive. This is used for computing
   * the hash key
   *
   * @type {number}
   *
   * @private
   */
  this._originalVertexCount = originalVertexCount;
 
  /**
   * The internal hash set used to store the edges. Edges are hashed as follows:
   * <p>
   * smallerVertexIndex * originalVertexCount + biggerVertexIndex
   * <p>
   * @type {Set}
   *
   * @private
   */
  this._edges = new Set();
  for (let i = 0; i < edgeIndices.length; i += 2) {
    const a = edgeIndices[i];
    const b = edgeIndices[i + 1];
    const small = Math.min(a, b);
    const big = Math.max(a, b);
    const hash = small * this._originalVertexCount + big;
    this._edges.add(hash);
  }
}
 
/**
 * Check if an edge exists in the set. The order of the input vertices does
 * not matter.
 * @param {number} a The first index
 * @param {number} b The second index
 * @returns {boolean} true if there is an edge between a and b
 *
 * @private
 */
EdgeSet.prototype.hasEdge = function (a, b) {
  const small = Math.min(a, b);
  const big = Math.max(a, b);
  const hash = small * this._originalVertexCount + big;
  return this._edges.has(hash);
};
 
export default PrimitiveOutlineGenerator;