All files / Sources/Rendering/OpenGL/HardwareSelector index.js

69.87% Statements 283/405
49.26% Branches 100/203
86.48% Functions 32/37
70.22% Lines 276/393

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              1x 1x 1x 1x   1x     21213x       21214x     21214x 21214x       99372x 13379x   85993x 85993x 85993x 85993x 85993x         13380x 13380x 13380x 13380x                     25698x 25698x 25698x 25698x 25698x                   25698x         25698x           25698x   4485x     21213x 21213x   21213x 21213x   21213x           21213x     21213x 21213x   9764x     9764x     9764x     21213x 21213x               7834x       13379x           13379x           13379x   13379x                                                                                                                                                                                         13x   13x 13x 127x 127x 127x   7x 7x   120x 120x       127x 127x 127x 127x 127x 127x 12x         12x               127x 127x 127x     13x         13x 13x 13x 13x   13x   13x   13x 328x 25698x 25698x           25698x 21213x 21213x 127x           21086x 21086x 21086x 9752x 226x     21086x 1209x           13x                             216x     216x 14x 14x 14x       216x 14x     14x   14x 14x 6x 6x 6x 6x   6x   8x 8x 8x 8x         8x       14x 14x 14x 14x 14x 14x   14x 6x 6x 6x 6x 6x 6x           216x 14x 14x 14x     216x 43x   43x 43x     216x 43x   43x 43x         216x                           216x   13x     13x       13x     13x     13x                   13x 13x 13x       216x 14x         14x           14x                 14x       14x 14x 14x   14x 14x 14x         56x 43x 43x           10x 10x   33x   43x   43x 43x         14x 43x 43x   14x   14x     14x 14x       14x     216x 43x 1759x 367x           216x 56x 14x     6x   8x     8x     42x       216x 43x             43x   43x       43x 43x     43x 14x 10x 10x       10x 10x 10x 10x           10x     14x         216x 14x 14x 329x 25699x 25699x 21214x 21214x 122x 122x   21214x   25699x           216x 2196x 586x 586x         216x               216x                               216x     1759x   216x 586x 586x 586x                     216x           1x 1x 1x 1x 1x                   1x         1x           1x         1x 1x   1x 1x 1x           1x     1x 1x                     1x 1x                       1x           1x           1x   1x                                                                                                                                 216x                                                                                           734x 21215x       216x 1x 1x       216x 216x 14x 14x 14x 14x 14x 14x                   1x                               216x     216x   216x 216x   216x 216x     216x 216x               216x 216x 216x     216x         1x                
import macro from 'vtk.js/Sources/macros';
import Constants from 'vtk.js/Sources/Rendering/OpenGL/HardwareSelector/Constants';
import vtkHardwareSelector from 'vtk.js/Sources/Rendering/Core/HardwareSelector';
import vtkOpenGLFramebuffer from 'vtk.js/Sources/Rendering/OpenGL/Framebuffer';
import vtkSelectionNode from 'vtk.js/Sources/Common/DataModel/SelectionNode';
import vtkDataSet from 'vtk.js/Sources/Common/DataModel/DataSet';
 
const { PassTypes } = Constants;
const { SelectionContent, SelectionField } = vtkSelectionNode;
const { FieldAssociations } = vtkDataSet;
const { vtkErrorMacro } = macro;
 
const idOffset = 1;
 
function getInfoHash(info) {
  return `${info.propID} ${info.compositeID}`;
}
 
function getAlpha(xx, yy, pb, area) {
  Iif (!pb) {
    return 0;
  }
  const offset = (yy * (area[2] - area[0] + 1) + xx) * 4;
  return pb[offset + 3];
}
 
function convert(xx, yy, pb, area) {
  if (!pb) {
    return 0;
  }
  const offset = (yy * (area[2] - area[0] + 1) + xx) * 4;
  const r = pb[offset];
  const g = pb[offset + 1];
  const b = pb[offset + 2];
  return (b * 256 + g) * 256 + r;
}
 
function getID(low24, high8) {
  /* eslint-disable no-bitwise */
  let val = high8;
  val <<= 24;
  val |= low24;
  return val;
  /* eslint-enable no-bitwise */
}
 
function getPixelInformationWithData(
  buffdata,
  inDisplayPosition,
  maxDistance,
  outSelectedPosition
) {
  // Base case
  const maxDist = maxDistance < 0 ? 0 : maxDistance;
  if (maxDist === 0) {
    outSelectedPosition[0] = inDisplayPosition[0];
    outSelectedPosition[1] = inDisplayPosition[1];
    Iif (
      inDisplayPosition[0] < buffdata.area[0] ||
      inDisplayPosition[0] > buffdata.area[2] ||
      inDisplayPosition[1] < buffdata.area[1] ||
      inDisplayPosition[1] > buffdata.area[3]
    ) {
      return null;
    }
 
    // offset inDisplayPosition based on the lower-left-corner of the Area.
    const displayPosition = [
      inDisplayPosition[0] - buffdata.area[0],
      inDisplayPosition[1] - buffdata.area[1],
    ];
 
    const actorid = convert(
      displayPosition[0],
      displayPosition[1],
      buffdata.pixBuffer[PassTypes.ACTOR_PASS],
      buffdata.area
    );
    if (actorid <= 0 || actorid - idOffset >= buffdata.props.length) {
      // the pixel did not hit any actor.
      return null;
    }
 
    const info = {};
    info.valid = true;
 
    info.propID = actorid - idOffset;
    info.prop = buffdata.props[info.propID];
 
    let compositeID = convert(
      displayPosition[0],
      displayPosition[1],
      buffdata.pixBuffer[PassTypes.COMPOSITE_INDEX_PASS],
      buffdata.area
    );
    Iif (compositeID < 0 || compositeID > 0xffffff) {
      compositeID = 0;
    }
    info.compositeID = compositeID - idOffset;
    if (buffdata.captureZValues) {
      const offset =
        (displayPosition[1] * (buffdata.area[2] - buffdata.area[0] + 1) +
          displayPosition[0]) *
        4;
      info.zValue =
        (256 * buffdata.zBuffer[offset] + buffdata.zBuffer[offset + 1]) /
        65535.0;
      info.displayPosition = inDisplayPosition;
    }
 
    if (buffdata.pixBuffer[PassTypes.ID_LOW24]) {
      if (
        getAlpha(
          displayPosition[0],
          displayPosition[1],
          buffdata.pixBuffer[PassTypes.ID_LOW24],
          buffdata.area
        ) === 0.0
      ) {
        return info;
      }
    }
 
    const low24 = convert(
      displayPosition[0],
      displayPosition[1],
      buffdata.pixBuffer[PassTypes.ID_LOW24],
      buffdata.area
    );
    const high24 = convert(
      displayPosition[0],
      displayPosition[1],
      buffdata.pixBuffer[PassTypes.ID_HIGH24],
      buffdata.area
    );
    info.attributeID = getID(low24, high24, 0);
 
    return info;
  }
 
  // Iterate over successively growing boxes.
  // They recursively call the base case to handle single pixels.
  const dispPos = [inDisplayPosition[0], inDisplayPosition[1]];
  const curPos = [0, 0];
  let info = getPixelInformationWithData(
    buffdata,
    inDisplayPosition,
    0,
    outSelectedPosition
  );
  if (info && info.valid) {
    return info;
  }
  for (let dist = 1; dist < maxDist; ++dist) {
    // Vertical sides of box.
    for (
      let y = dispPos[1] > dist ? dispPos[1] - dist : 0;
      y <= dispPos[1] + dist;
      ++y
    ) {
      curPos[1] = y;
      if (dispPos[0] >= dist) {
        curPos[0] = dispPos[0] - dist;
        info = getPixelInformationWithData(
          buffdata,
          curPos,
          0,
          outSelectedPosition
        );
        if (info && info.valid) {
          return info;
        }
      }
      curPos[0] = dispPos[0] + dist;
      info = getPixelInformationWithData(
        buffdata,
        curPos,
        0,
        outSelectedPosition
      );
      if (info && info.valid) {
        return info;
      }
    }
    // Horizontal sides of box.
    for (
      let x = dispPos[0] >= dist ? dispPos[0] - (dist - 1) : 0;
      x <= dispPos[0] + (dist - 1);
      ++x
    ) {
      curPos[0] = x;
      if (dispPos[1] >= dist) {
        curPos[1] = dispPos[1] - dist;
        info = getPixelInformationWithData(
          buffdata,
          curPos,
          0,
          outSelectedPosition
        );
        if (info && info.valid) {
          return info;
        }
      }
      curPos[1] = dispPos[1] + dist;
      info = getPixelInformationWithData(
        buffdata,
        curPos,
        0,
        outSelectedPosition
      );
      if (info && info.valid) {
        return info;
      }
    }
  }
 
  // nothing hit.
  outSelectedPosition[0] = inDisplayPosition[0];
  outSelectedPosition[1] = inDisplayPosition[1];
  return null;
}
 
//-----------------------------------------------------------------------------
function convertSelection(
  fieldassociation,
  dataMap,
  captureZValues,
  renderer,
  openGLRenderWindow
) {
  const sel = [];
 
  let count = 0;
  dataMap.forEach((value, key) => {
    const child = vtkSelectionNode.newInstance();
    child.setContentType(SelectionContent.INDICES);
    switch (fieldassociation) {
      case FieldAssociations.FIELD_ASSOCIATION_CELLS:
        child.setFieldType(SelectionField.CELL);
        break;
      case FieldAssociations.FIELD_ASSOCIATION_POINTS:
        child.setFieldType(SelectionField.POINT);
        break;
      default:
        vtkErrorMacro('Unknown field association');
    }
    child.getProperties().propID = value.info.propID;
    child.getProperties().prop = value.info.prop;
    child.getProperties().compositeID = value.info.compositeID;
    child.getProperties().attributeID = value.info.attributeID;
    child.getProperties().pixelCount = value.pixelCount;
    if (captureZValues) {
      child.getProperties().displayPosition = [
        value.info.displayPosition[0],
        value.info.displayPosition[1],
        value.info.zValue,
      ];
      child.getProperties().worldPosition = openGLRenderWindow.displayToWorld(
        value.info.displayPosition[0],
        value.info.displayPosition[1],
        value.info.zValue,
        renderer
      );
    }
 
    child.setSelectionList(value.attributeIDs);
    sel[count] = child;
    count++;
  });
 
  return sel;
}
 
//----------------------------------------------------------------------------
function generateSelectionWithData(buffdata, fx1, fy1, fx2, fy2) {
  const x1 = Math.floor(fx1);
  const y1 = Math.floor(fy1);
  const x2 = Math.floor(fx2);
  const y2 = Math.floor(fy2);
 
  const dataMap = new Map();
 
  const outSelectedPosition = [0, 0];
 
  for (let yy = y1; yy <= y2; yy++) {
    for (let xx = x1; xx <= x2; xx++) {
      const pos = [xx, yy];
      const info = getPixelInformationWithData(
        buffdata,
        pos,
        0,
        outSelectedPosition
      );
      if (info && info.valid) {
        const hash = getInfoHash(info);
        if (!dataMap.has(hash)) {
          dataMap.set(hash, {
            info,
            pixelCount: 1,
            attributeIDs: [info.attributeID],
          });
        } else {
          const dmv = dataMap.get(hash);
          dmv.pixelCount++;
          if (buffdata.captureZValues) {
            if (info.zValue < dmv.info.zValue) {
              dmv.info = info;
            }
          }
          if (dmv.attributeIDs.indexOf(info.attributeID) === -1) {
            dmv.attributeIDs.push(info.attributeID);
          }
        }
      }
    }
  }
  return convertSelection(
    buffdata.fieldAssociation,
    dataMap,
    buffdata.captureZValues,
    buffdata.renderer,
    buffdata.openGLRenderWindow
  );
}
 
// ----------------------------------------------------------------------------
// vtkOpenGLHardwareSelector methods
// ----------------------------------------------------------------------------
 
function vtkOpenGLHardwareSelector(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkOpenGLHardwareSelector');
 
  //----------------------------------------------------------------------------
  publicAPI.releasePixBuffers = () => {
    model.rawPixBuffer = [];
    model.pixBuffer = [];
    model.zBuffer = null;
  };
 
  //----------------------------------------------------------------------------
  publicAPI.beginSelection = () => {
    model._openGLRenderer = model._openGLRenderWindow.getViewNodeFor(
      model._renderer
    );
    model.maxAttributeId = 0;
 
    const size = model._openGLRenderWindow.getSize();
    if (!model.framebuffer) {
      model.framebuffer = vtkOpenGLFramebuffer.newInstance();
      model.framebuffer.setOpenGLRenderWindow(model._openGLRenderWindow);
      model.framebuffer.saveCurrentBindingsAndBuffers();
      model.framebuffer.create(size[0], size[1]);
      // this calls model.framebuffer.bind()
      model.framebuffer.populateFramebuffer();
    } else {
      model.framebuffer.setOpenGLRenderWindow(model._openGLRenderWindow);
      model.framebuffer.saveCurrentBindingsAndBuffers();
      const fbSize = model.framebuffer.getSize();
      Iif (!fbSize || fbSize[0] !== size[0] || fbSize[1] !== size[1]) {
        model.framebuffer.create(size[0], size[1]);
        // this calls model.framebuffer.bind()
        model.framebuffer.populateFramebuffer();
      } else {
        model.framebuffer.bind();
      }
    }
 
    model._openGLRenderer.clear();
    model._openGLRenderer.setSelector(publicAPI);
    model.hitProps = {};
    model.propPixels = {};
    model.props = [];
    publicAPI.releasePixBuffers();
 
    if (model.fieldAssociation === FieldAssociations.FIELD_ASSOCIATION_POINTS) {
      const gl = model._openGLRenderWindow.getContext();
      const originalBlending = gl.isEnabled(gl.BLEND);
      gl.disable(gl.BLEND);
      model._openGLRenderWindow.traverseAllPasses();
      if (originalBlending) {
        gl.enable(gl.BLEND);
      }
    }
  };
 
  //----------------------------------------------------------------------------
  publicAPI.endSelection = () => {
    model.hitProps = {};
    model._openGLRenderer.setSelector(null);
    model.framebuffer.restorePreviousBindingsAndBuffers();
  };
 
  publicAPI.preCapturePass = () => {
    const gl = model._openGLRenderWindow.getContext();
    // Disable blending
    model.originalBlending = gl.isEnabled(gl.BLEND);
    gl.disable(gl.BLEND);
  };
 
  publicAPI.postCapturePass = () => {
    const gl = model._openGLRenderWindow.getContext();
    // Restore blending if it was enabled prior to the capture
    if (model.originalBlending) {
      gl.enable(gl.BLEND);
    }
  };
 
  //----------------------------------------------------------------------------
  publicAPI.select = () => {
    let sel = null;
    if (publicAPI.captureBuffers()) {
      sel = publicAPI.generateSelection(
        model.area[0],
        model.area[1],
        model.area[2],
        model.area[3]
      );
      publicAPI.releasePixBuffers();
    }
    return sel;
  };
 
  publicAPI.getSourceDataAsync = async (renderer, fx1, fy1, fx2, fy2) => {
    // assign the renderer
    model._renderer = renderer;
 
    // set area to all if no arguments provided
    Iif (fx1 === undefined) {
      const size = model._openGLRenderWindow.getSize();
      publicAPI.setArea(0, 0, size[0] - 1, size[1] - 1);
    } else {
      publicAPI.setArea(fx1, fy1, fx2, fy2);
    }
    // just do capture buffers and package up the result
    Iif (!publicAPI.captureBuffers()) {
      return false;
    }
    const result = {
      area: [...model.area],
      pixBuffer: [...model.pixBuffer],
      captureZValues: model.captureZValues,
      zBuffer: model.zBuffer,
      props: [...model.props],
      fieldAssociation: model.fieldAssociation,
      renderer,
      openGLRenderWindow: model._openGLRenderWindow,
    };
    result.generateSelection = (...args) =>
      generateSelectionWithData(result, ...args);
    return result;
  };
 
  //----------------------------------------------------------------------------
  publicAPI.captureBuffers = () => {
    Iif (!model._renderer || !model._openGLRenderWindow) {
      vtkErrorMacro('Renderer and view must be set before calling Select.');
      return false;
    }
 
    model._openGLRenderer = model._openGLRenderWindow.getViewNodeFor(
      model._renderer
    );
 
    // todo revisit making selection part of core
    // then we can do this in core
    model._openGLRenderWindow.getRenderable().preRender();
 
    // int rgba[4];
    // rwin.getColorBufferSizes(rgba);
    // if (rgba[0] < 8 || rgba[1] < 8 || rgba[2] < 8) {
    //   vtkErrorMacro("Color buffer depth must be at least 8 bit. "
    //     "Currently: " << rgba[0] << ", " << rgba[1] << ", " <<rgba[2]);
    //   return false;
    // }
    publicAPI.invokeEvent({ type: 'StartEvent' });
 
    // Initialize renderer for selection.
    // change the renderer's background to black, which will indicate a miss
    model.originalBackground = model._renderer.getBackgroundByReference();
    model._renderer.setBackground(0.0, 0.0, 0.0, 0.0);
    const rpasses = model._openGLRenderWindow.getRenderPasses();
 
    publicAPI.beginSelection();
    const pixelBufferSavedPasses = [];
    for (
      model.currentPass = PassTypes.MIN_KNOWN_PASS;
      model.currentPass <= PassTypes.MAX_KNOWN_PASS;
      model.currentPass++
    ) {
      if (publicAPI.passRequired(model.currentPass)) {
        publicAPI.preCapturePass(model.currentPass);
        if (
          model.captureZValues &&
          model.currentPass === PassTypes.ACTOR_PASS &&
          typeof rpasses[0].requestDepth === 'function' &&
          typeof rpasses[0].getFramebuffer === 'function'
        ) {
          rpasses[0].requestDepth();
          model._openGLRenderWindow.traverseAllPasses();
        } else {
          model._openGLRenderWindow.traverseAllPasses();
        }
        publicAPI.postCapturePass(model.currentPass);
 
        publicAPI.savePixelBuffer(model.currentPass);
        pixelBufferSavedPasses.push(model.currentPass);
      }
    }
 
    // Process pixel buffers
    pixelBufferSavedPasses.forEach((pass) => {
      model.currentPass = pass;
      publicAPI.processPixelBuffers();
    });
    model.currentPass = PassTypes.MAX_KNOWN_PASS;
 
    publicAPI.endSelection();
 
    // restore original background
    model._renderer.setBackground(model.originalBackground);
    publicAPI.invokeEvent({ type: 'EndEvent' });
 
    // restore image, not needed?
    // model._openGLRenderWindow.traverseAllPasses();
    return true;
  };
 
  publicAPI.processPixelBuffers = () => {
    model.props.forEach((prop, index) => {
      if (publicAPI.isPropHit(index)) {
        prop.processSelectorPixelBuffers(publicAPI, model.propPixels[index]);
      }
    });
  };
 
  //----------------------------------------------------------------------------
  publicAPI.passRequired = (pass) => {
    if (pass === PassTypes.ID_HIGH24) {
      if (
        model.fieldAssociation === FieldAssociations.FIELD_ASSOCIATION_POINTS
      ) {
        return model.maximumPointId > 0x00ffffff;
      }
      if (
        model.fieldAssociation === FieldAssociations.FIELD_ASSOCIATION_CELLS
      ) {
        return model.maximumCellId > 0x00ffffff;
      }
    }
    return true;
  };
 
  //----------------------------------------------------------------------------
  publicAPI.savePixelBuffer = (passNo) => {
    model.pixBuffer[passNo] = model._openGLRenderWindow.getPixelData(
      model.area[0],
      model.area[1],
      model.area[2],
      model.area[3]
    );
 
    if (!model.rawPixBuffer[passNo]) {
      const size =
        (model.area[2] - model.area[0] + 1) *
        (model.area[3] - model.area[1] + 1) *
        4;
 
      model.rawPixBuffer[passNo] = new Uint8Array(size);
      model.rawPixBuffer[passNo].set(model.pixBuffer[passNo]);
    }
 
    if (passNo === PassTypes.ACTOR_PASS) {
      if (model.captureZValues) {
        const rpasses = model._openGLRenderWindow.getRenderPasses();
        if (
          typeof rpasses[0].requestDepth === 'function' &&
          typeof rpasses[0].getFramebuffer === 'function'
        ) {
          const fb = rpasses[0].getFramebuffer();
          fb.saveCurrentBindingsAndBuffers();
          fb.bind();
          model.zBuffer = model._openGLRenderWindow.getPixelData(
            model.area[0],
            model.area[1],
            model.area[2],
            model.area[3]
          );
          fb.restorePreviousBindingsAndBuffers();
        }
      }
      publicAPI.buildPropHitList(model.rawPixBuffer[passNo]);
    }
  };
 
  //----------------------------------------------------------------------------
  publicAPI.buildPropHitList = (pixelbuffer) => {
    let offset = 0;
    for (let yy = 0; yy <= model.area[3] - model.area[1]; yy++) {
      for (let xx = 0; xx <= model.area[2] - model.area[0]; xx++) {
        let val = convert(xx, yy, pixelbuffer, model.area);
        if (val > 0) {
          val--;
          if (!(val in model.hitProps)) {
            model.hitProps[val] = true;
            model.propPixels[val] = [];
          }
          model.propPixels[val].push(offset * 4);
        }
        ++offset;
      }
    }
  };
 
  //----------------------------------------------------------------------------
  publicAPI.renderProp = (prop) => {
    if (model.currentPass === PassTypes.ACTOR_PASS) {
      publicAPI.setPropColorValueFromInt(model.props.length + idOffset);
      model.props.push(prop);
    }
  };
 
  //----------------------------------------------------------------------------
  publicAPI.renderCompositeIndex = (index) => {
    if (model.currentPass === PassTypes.COMPOSITE_INDEX_PASS) {
      publicAPI.setPropColorValueFromInt(index + idOffset);
    }
  };
 
  //----------------------------------------------------------------------------
  // TODO: make inline
  publicAPI.renderAttributeId = (attribid) => {
    if (attribid < 0) {
      // negative attribid is valid. It happens when rendering higher order
      // elements where new points are added for rendering smooth surfaces.
      return;
    }
 
    model.maxAttributeId =
      attribid > model.maxAttributeId ? attribid : model.maxAttributeId;
 
    // if (model.currentPass < PassTypes.ID_LOW24) {
    //   return; // useless...
    // }
  };
 
  //----------------------------------------------------------------------------
  publicAPI.passTypeToString = (type) => macro.enumToString(PassTypes, type);
 
  //----------------------------------------------------------------------------
  publicAPI.isPropHit = (id) => Boolean(model.hitProps[id]);
 
  publicAPI.setPropColorValueFromInt = (val) => {
    model.propColorValue[0] = (val % 256) / 255.0;
    model.propColorValue[1] = (Math.floor(val / 256) % 256) / 255.0;
    model.propColorValue[2] = (Math.floor(val / 65536) % 256) / 255.0;
  };
 
  // info has
  //   valid
  //   propId
  //   prop
  //   compositeID
  //   attributeID
 
  //----------------------------------------------------------------------------
  publicAPI.getPixelInformation = (
    inDisplayPosition,
    maxDistance,
    outSelectedPosition
  ) => {
    // Base case
    const maxDist = maxDistance < 0 ? 0 : maxDistance;
    if (maxDist === 0) {
      outSelectedPosition[0] = inDisplayPosition[0];
      outSelectedPosition[1] = inDisplayPosition[1];
      Iif (
        inDisplayPosition[0] < model.area[0] ||
        inDisplayPosition[0] > model.area[2] ||
        inDisplayPosition[1] < model.area[1] ||
        inDisplayPosition[1] > model.area[3]
      ) {
        return null;
      }
 
      // offset inDisplayPosition based on the lower-left-corner of the Area.
      const displayPosition = [
        inDisplayPosition[0] - model.area[0],
        inDisplayPosition[1] - model.area[1],
      ];
 
      const actorid = convert(
        displayPosition[0],
        displayPosition[1],
        model.pixBuffer[PassTypes.ACTOR_PASS],
        model.area
      );
      Iif (actorid <= 0 || actorid - idOffset >= model.props.length) {
        // the pixel did not hit any actor.
        return null;
      }
 
      const info = {};
      info.valid = true;
 
      info.propID = actorid - idOffset;
      info.prop = model.props[info.propID];
      let compositeID = convert(
        displayPosition[0],
        displayPosition[1],
        model.pixBuffer[PassTypes.COMPOSITE_INDEX_PASS],
        model.area
      );
      Iif (compositeID < 0 || compositeID > 0xffffff) {
        compositeID = 0;
      }
      info.compositeID = compositeID - idOffset;
      Iif (model.captureZValues) {
        const offset =
          (displayPosition[1] * (model.area[2] - model.area[0] + 1) +
            displayPosition[0]) *
          4;
        info.zValue =
          (256 * model.zBuffer[offset] + model.zBuffer[offset + 1]) / 65535.0;
        info.displayPosition = inDisplayPosition;
      }
 
      // Skip attribute ids if alpha is zero (missed)
      if (model.pixBuffer[PassTypes.ID_LOW24]) {
        Iif (
          getAlpha(
            displayPosition[0],
            displayPosition[1],
            model.pixBuffer[PassTypes.ID_LOW24],
            model.area
          ) === 0.0
        ) {
          return info;
        }
      }
 
      const low24 = convert(
        displayPosition[0],
        displayPosition[1],
        model.pixBuffer[PassTypes.ID_LOW24],
        model.area
      );
      const high24 = convert(
        displayPosition[0],
        displayPosition[1],
        model.pixBuffer[PassTypes.ID_HIGH24],
        model.area
      );
      info.attributeID = getID(low24, high24);
 
      return info;
    }
 
    // Iterate over successively growing boxes.
    // They recursively call the base case to handle single pixels.
    const dispPos = [inDisplayPosition[0], inDisplayPosition[1]];
    const curPos = [0, 0];
    let info = publicAPI.getPixelInformation(
      inDisplayPosition,
      0,
      outSelectedPosition
    );
    if (info && info.valid) {
      return info;
    }
    for (let dist = 1; dist < maxDist; ++dist) {
      // Vertical sides of box.
      for (
        let y = dispPos[1] > dist ? dispPos[1] - dist : 0;
        y <= dispPos[1] + dist;
        ++y
      ) {
        curPos[1] = y;
        if (dispPos[0] >= dist) {
          curPos[0] = dispPos[0] - dist;
          info = publicAPI.getPixelInformation(curPos, 0, outSelectedPosition);
          if (info && info.valid) {
            return info;
          }
        }
        curPos[0] = dispPos[0] + dist;
        info = publicAPI.getPixelInformation(curPos, 0, outSelectedPosition);
        if (info && info.valid) {
          return info;
        }
      }
      // Horizontal sides of box.
      for (
        let x = dispPos[0] >= dist ? dispPos[0] - (dist - 1) : 0;
        x <= dispPos[0] + (dist - 1);
        ++x
      ) {
        curPos[0] = x;
        if (dispPos[1] >= dist) {
          curPos[1] = dispPos[1] - dist;
          info = publicAPI.getPixelInformation(curPos, 0, outSelectedPosition);
          if (info && info.valid) {
            return info;
          }
        }
        curPos[1] = dispPos[1] + dist;
        info = publicAPI.getPixelInformation(curPos, 0, outSelectedPosition);
        if (info && info.valid) {
          return info;
        }
      }
    }
 
    // nothing hit.
    outSelectedPosition[0] = inDisplayPosition[0];
    outSelectedPosition[1] = inDisplayPosition[1];
    return null;
  };
 
  //----------------------------------------------------------------------------
  publicAPI.generateSelection = (fx1, fy1, fx2, fy2) => {
    const x1 = Math.floor(fx1);
    const y1 = Math.floor(fy1);
    const x2 = Math.floor(fx2);
    const y2 = Math.floor(fy2);
 
    const dataMap = new Map();
 
    const outSelectedPosition = [0, 0];
 
    for (let yy = y1; yy <= y2; yy++) {
      for (let xx = x1; xx <= x2; xx++) {
        const pos = [xx, yy];
        const info = publicAPI.getPixelInformation(pos, 0, outSelectedPosition);
        if (info && info.valid) {
          const hash = getInfoHash(info);
          if (!dataMap.has(hash)) {
            dataMap.set(hash, {
              info,
              pixelCount: 1,
              attributeIDs: [info.attributeID],
            });
          } else {
            const dmv = dataMap.get(hash);
            dmv.pixelCount++;
            if (model.captureZValues) {
              if (info.zValue < dmv.info.zValue) {
                dmv.info = info;
              }
            }
            if (dmv.attributeIDs.indexOf(info.attributeID) === -1) {
              dmv.attributeIDs.push(info.attributeID);
            }
          }
        }
      }
    }
    return convertSelection(
      model.fieldAssociation,
      dataMap,
      model.captureZValues,
      model._renderer,
      model._openGLRenderWindow
    );
  };
 
  publicAPI.getRawPixelBuffer = (passNo) => model.rawPixBuffer[passNo];
  publicAPI.getPixelBuffer = (passNo) => model.pixBuffer[passNo];
 
  //----------------------------------------------------------------------------
 
  publicAPI.attach = (openGLRenderWindow, renderer) => {
    model._openGLRenderWindow = openGLRenderWindow;
    model._renderer = renderer;
  };
 
  // override
  const superSetArea = publicAPI.setArea;
  publicAPI.setArea = (...args) => {
    if (superSetArea(...args)) {
      model.area[0] = Math.floor(model.area[0]);
      model.area[1] = Math.floor(model.area[1]);
      model.area[2] = Math.floor(model.area[2]);
      model.area[3] = Math.floor(model.area[3]);
      return true;
    }
    return false;
  };
}
 
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
 
const DEFAULT_VALUES = {
  area: undefined,
  // _renderer: null,
  // _openGLRenderWindow: null,
  // _openGLRenderer: null,
  currentPass: -1,
  propColorValue: null,
  props: null,
  maximumPointId: 0,
  maximumCellId: 0,
  idOffset: 1,
};
 
// ----------------------------------------------------------------------------
 
export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);
 
  // Build VTK API
  vtkHardwareSelector.extend(publicAPI, model, initialValues);
 
  model.propColorValue = [0, 0, 0];
  model.props = [];
 
  if (!model.area) {
    model.area = [0, 0, 0, 0];
  }
 
  macro.setGetArray(publicAPI, model, ['area'], 4);
  macro.setGet(publicAPI, model, [
    '_renderer',
    'currentPass',
    '_openGLRenderWindow',
    'maximumPointId',
    'maximumCellId',
  ]);
 
  macro.setGetArray(publicAPI, model, ['propColorValue'], 3);
  macro.moveToProtected(publicAPI, model, ['renderer', 'openGLRenderWindow']);
  macro.event(publicAPI, model, 'event');
 
  // Object methods
  vtkOpenGLHardwareSelector(publicAPI, model);
}
 
// ----------------------------------------------------------------------------
 
export const newInstance = macro.newInstance(
  extend,
  'vtkOpenGLHardwareSelector'
);
 
// ----------------------------------------------------------------------------
 
export default { newInstance, extend, ...Constants };