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

76.65% Statements 220/287
44.92% Branches 62/138
83.87% Functions 26/31
76.59% Lines 216/282

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                                      1x 1x 1x 1x 1x               9x   9x 16x 8x   8x   8x 8x           9x 16x 8x       9x 8x 8x 8x     9x 8x 8x 8x 8x 48x     8x 8x 8x     9x 8x 8x 8x   8x 8x   8x           8x           8x 8x 8x     9x 8x   8x             8x     8x     9x           8x       8x           9x   8x 8x       9x     8x 8x               8x         9x 8x   8x       8x 8x   8x 8x 8x                           8x   8x 8x 8x     8x   8x 8x   8x         8x   8x 8x 8x 8x 8x 8x 8x 3222x 3222x 3222x 3222x   8x   8x                   8x     8x     8x     8x       8x 8x       9x 8x 8x 8x     8x   48x 48x 8x 8x                   9x 8x 8x       9x 8x 8x 8x 8x     9x 8x 8x 8x 8x               8x                                           8x     8x         8x 8x 8x     9x 8x                                                                                                                                                               9x 8x 8x       8x         8x     9x   8x     9x   8x 8x             9x   8x           8x 8x                                 8x             8x                                         8x                                         8x   8x               8x 8x                       8x           8x 8x           8x           9x 8x 8x 8x 8x 8x 8x 8x 8x       9x         8x 8x 16x 8x   8x       9x 8x   8x 8x         8x 8x 8x 8x           8x 8x 8x 8x 8x 8x 8x     8x     8x 8x   8x   8x 8x     8x 8x 8x 8x       8x     8x         8x 8x 8x 8x 8x 8x 8x       8x 8x 8x                   9x                           1x                       9x     9x 9x         9x           9x 9x   9x   9x 54x 54x 54x             9x   9x 9x     9x         1x                   1x  
// import { mat3, mat4, vec3 } from 'gl-matrix';
import { mat4 } from 'gl-matrix';
 
import * as macro from 'vtk.js/Sources/macros';
import vtkHelper from 'vtk.js/Sources/Rendering/OpenGL/Helper';
import vtkMapper2D from 'vtk.js/Sources/Rendering/Core/Mapper2D';
import vtkPoints from 'vtk.js/Sources/Common/Core/Points';
import vtkPolyData2DFS from 'vtk.js/Sources/Rendering/OpenGL/glsl/vtkPolyData2DFS.glsl';
import vtkPolyData2DVS from 'vtk.js/Sources/Rendering/OpenGL/glsl/vtkPolyData2DVS.glsl';
import vtkReplacementShaderMapper from 'vtk.js/Sources/Rendering/OpenGL/ReplacementShaderMapper';
import vtkShaderProgram from 'vtk.js/Sources/Rendering/OpenGL/ShaderProgram';
import vtkViewNode from 'vtk.js/Sources/Rendering/SceneGraph/ViewNode';
 
import { round } from 'vtk.js/Sources/Common/Core/Math';
 
import { DisplayLocation } from 'vtk.js/Sources/Rendering/Core/Property2D/Constants';
 
import { registerOverride } from 'vtk.js/Sources/Rendering/OpenGL/ViewNodeFactory';
 
const { primTypes } = vtkHelper;
const { ScalarMode } = vtkMapper2D;
const { vtkErrorMacro } = macro;
const StartEvent = { type: 'StartEvent' };
const EndEvent = { type: 'EndEvent' };
 
// ----------------------------------------------------------------------------
// vtkOpenGLPolyDataMapper2D methods
// ----------------------------------------------------------------------------
 
function vtkOpenGLPolyDataMapper2D(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkOpenGLPolyDataMapper2D');
 
  publicAPI.buildPass = (prepass) => {
    if (prepass) {
      model.openGLActor2D =
        publicAPI.getFirstAncestorOfType('vtkOpenGLActor2D');
      model._openGLRenderer =
        model.openGLActor2D.getFirstAncestorOfType('vtkOpenGLRenderer');
      model._openGLRenderWindow = model._openGLRenderer.getParent();
      model.openGLCamera = model._openGLRenderer.getViewNodeFor(
        model._openGLRenderer.getRenderable().getActiveCamera()
      );
    }
  };
 
  publicAPI.overlayPass = (prepass) => {
    if (prepass) {
      publicAPI.render();
    }
  };
 
  publicAPI.getShaderTemplate = (shaders, ren, actor) => {
    shaders.Vertex = vtkPolyData2DVS;
    shaders.Fragment = vtkPolyData2DFS;
    shaders.Geometry = '';
  };
 
  publicAPI.render = () => {
    const ctx = model._openGLRenderWindow.getContext();
    if (model.context !== ctx) {
      model.context = ctx;
      for (let i = primTypes.Start; i < primTypes.End; i++) {
        model.primitives[i].setOpenGLRenderWindow(model._openGLRenderWindow);
      }
    }
    const actor = model.openGLActor2D.getRenderable();
    const ren = model._openGLRenderer.getRenderable();
    publicAPI.renderPiece(ren, actor);
  };
 
  publicAPI.renderPiece = (ren, actor) => {
    publicAPI.invokeEvent(StartEvent);
    if (!model.renderable.getStatic()) {
      model.renderable.update();
    }
    model.currentInput = model.renderable.getInputData();
    publicAPI.invokeEvent(EndEvent);
 
    Iif (!model.currentInput) {
      vtkErrorMacro('No input!');
      return;
    }
 
    // if there are no points then we are done
    Iif (
      !model.currentInput.getPoints ||
      !model.currentInput.getPoints().getNumberOfValues()
    ) {
      return;
    }
    publicAPI.renderPieceStart(ren, actor);
    publicAPI.renderPieceDraw(ren, actor);
    publicAPI.renderPieceFinish(ren, actor);
  };
 
  publicAPI.renderPieceStart = (ren, actor) => {
    model.primitiveIDOffset = 0;
 
    Iif (model._openGLRenderer.getSelector()) {
      switch (model._openGLRenderer.getSelector().getCurrentPass()) {
        default:
          model._openGLRenderer.getSelector().renderProp(actor);
      }
    }
    // make sure the BOs are up to date
    publicAPI.updateBufferObjects(ren, actor);
 
    // Bind the OpenGL, this is shared between the different primitive/cell types.
    model.lastBoundBO = null;
  };
 
  publicAPI.getNeedToRebuildShaders = (cellBO, ren, actor) => {
    // has something changed that would require us to recreate the shader?
    // candidates are
    // property modified (representation interpolation and lighting)
    // input modified
    // light complexity changed
    if (
      cellBO.getShaderSourceTime().getMTime() < model.renderable.getMTime() ||
      cellBO.getShaderSourceTime().getMTime() < model.currentInput.getMTime()
    ) {
      return true;
    }
 
    return false;
  };
 
  publicAPI.updateBufferObjects = (ren, actor) => {
    // Rebuild buffers if needed
    if (publicAPI.getNeedToRebuildBufferObjects(ren, actor)) {
      publicAPI.buildBufferObjects(ren, actor);
    }
  };
 
  publicAPI.getNeedToRebuildBufferObjects = (ren, actor) => {
    // first do a coarse check
    // Note that the actor's mtime includes it's properties mtime
    const vmtime = model.VBOBuildTime.getMTime();
    if (
      vmtime < publicAPI.getMTime() ||
      vmtime < model._openGLRenderWindow.getMTime() ||
      vmtime < model.renderable.getMTime() ||
      vmtime < actor.getMTime() ||
      vmtime < model.currentInput.getMTime() ||
      (model.renderable.getTransformCoordinate() && vmtime < ren.getMTime())
    ) {
      return true;
    }
    return false;
  };
 
  publicAPI.buildBufferObjects = (ren, actor) => {
    const poly = model.currentInput;
 
    Iif (poly === null) {
      return;
    }
 
    model.renderable.mapScalars(poly, actor.getProperty().getOpacity());
    const c = model.renderable.getColorMapColors();
 
    model.haveCellScalars = false;
    const scalarMode = model.renderable.getScalarMode();
    Iif (model.renderable.getScalarVisibility()) {
      // We must figure out how the scalars should be mapped to the polydata.
      if (
        (scalarMode === ScalarMode.USE_CELL_DATA ||
          scalarMode === ScalarMode.USE_CELL_FIELD_DATA ||
          scalarMode === ScalarMode.USE_FIELD_DATA ||
          !poly.getPointData().getScalars()) &&
        scalarMode !== ScalarMode.USE_POINT_FIELD_DATA &&
        c
      ) {
        model.haveCellScalars = true;
      }
    }
 
    const representation = actor.getProperty().getRepresentation();
 
    let tcoords = poly.getPointData().getTCoords();
    if (!model.openGLActor2D.getActiveTextures()) {
      tcoords = null;
    }
 
    const transformCoordinate = model.renderable.getTransformCoordinate();
 
    const view = ren.getRenderWindow().getViews()[0];
    const vsize = view.getViewportSize(ren);
    const toString =
      `${poly.getMTime()}A${representation}B${poly.getMTime()}` +
      `C${c ? c.getMTime() : 1}` +
      `D${tcoords ? tcoords.getMTime() : 1}` +
      `E${transformCoordinate ? ren.getMTime() : 1}` +
      `F${vsize}`;
    if (model.VBOBuildString !== toString) {
      // Build the VBOs
      let points = poly.getPoints();
      if (transformCoordinate) {
        const p = vtkPoints.newInstance();
        const numPts = points.getNumberOfPoints();
        p.setNumberOfPoints(numPts);
        const point = [];
        for (let i = 0; i < numPts; ++i) {
          points.getPoint(i, point);
          transformCoordinate.setValue(point);
          const v = transformCoordinate.getComputedDoubleViewportValue(ren);
          p.setPoint(i, v[0], v[1], 0.0);
        }
        points = p;
      }
      const options = {
        points,
        tcoords,
        colors: c,
        cellOffset: 0,
        haveCellScalars: model.haveCellSCalars,
        customAttributes: model.renderable
          .getCustomShaderAttributes()
          .map((arrayName) => poly.getPointData().getArrayByName(arrayName)),
      };
      options.cellOffset += model.primitives[primTypes.Points]
        .getCABO()
        .createVBO(poly.getVerts(), 'verts', representation, options);
      options.cellOffset += model.primitives[primTypes.Lines]
        .getCABO()
        .createVBO(poly.getLines(), 'lines', representation, options);
      options.cellOffset += model.primitives[primTypes.Tris]
        .getCABO()
        .createVBO(poly.getPolys(), 'polys', representation, options);
      options.cellOffset += model.primitives[primTypes.TriStrips]
        .getCABO()
        .createVBO(poly.getStrips(), 'strips', representation, options);
 
      model.VBOBuildTime.modified();
      model.VBOBuildString = toString;
    }
  };
 
  publicAPI.renderPieceDraw = (ren, actor) => {
    const representation = actor.getProperty().getRepresentation();
    const gl = model.context;
    gl.depthMask(true);
 
    // for every primitive type
    for (let i = primTypes.Start; i < primTypes.End; i++) {
      // if there are entries
      const cabo = model.primitives[i].getCABO();
      if (cabo.getElementCount()) {
        model.lastBoundBO = model.primitives[i];
        model.primitiveIDOffset += model.primitives[i].drawArrays(
          ren,
          actor,
          representation,
          publicAPI
        );
      }
    }
  };
 
  publicAPI.renderPieceFinish = (ren, actor) => {
    if (model.lastBoundBO) {
      model.lastBoundBO.getVAO().release();
    }
  };
 
  publicAPI.replaceShaderValues = (shaders, ren, actor) => {
    publicAPI.replaceShaderColor(shaders, ren, actor);
    publicAPI.replaceShaderTCoord(shaders, ren, actor);
    publicAPI.replaceShaderPicking(shaders, ren, actor);
    publicAPI.replaceShaderPositionVC(shaders, ren, actor);
  };
 
  publicAPI.replaceShaderColor = (shaders, ren, actor) => {
    let VSSource = shaders.Vertex;
    let GSSource = shaders.Geometry;
    let FSSource = shaders.Fragment;
    Iif (model.haveCellScalars) {
      FSSource = vtkShaderProgram.substitute(FSSource, '//VTK::Color::Dec', [
        'uniform samplerBuffer texture1;',
      ]).result;
      FSSource = vtkShaderProgram.substitute(FSSource, '//VTK::Color::Impl', [
        'gl_FragData[0] = texelFetchBuffer(texture1, gl_PrimitiveID + PrimitiveIDOffset);',
      ]).result;
    }
    Iif (model.lastBoundBO.getCABO().getColorComponents() !== 0) {
      VSSource = vtkShaderProgram.substitute(VSSource, '//VTK::Color::Dec', [
        'in vec4 diffuseColor;',
        'out vec4 fcolorVSOutput;',
      ]).result;
      VSSource = vtkShaderProgram.substitute(VSSource, '//VTK::Color::Impl', [
        'fcolorVSOutput = diffuseColor;',
      ]).result;
      GSSource = vtkShaderProgram.substitute(GSSource, '//VTK::Color::Dec', [
        'in vec4 fcolorVSOutput[];\n',
        'out vec4 fcolorGSOutput;',
      ]).result;
      GSSource = vtkShaderProgram.substitute(GSSource, '//VTK::Color::Impl', [
        'fcolorGSOutput = fcolorVSOutput[i];',
      ]).result;
      FSSource = vtkShaderProgram.substitute(FSSource, '//VTK::Color::Dec', [
        'in vec4 fcolorVSOutput;',
      ]).result;
      FSSource = vtkShaderProgram.substitute(FSSource, '//VTK::Color::Impl', [
        'gl_FragData[0] = fcolorVSOutput;',
      ]).result;
    } else {
      FSSource = vtkShaderProgram.substitute(FSSource, '//VTK::Color::Dec', [
        'uniform vec4 diffuseColor;',
      ]).result;
      FSSource = vtkShaderProgram.substitute(FSSource, '//VTK::Color::Impl', [
        'gl_FragData[0] = diffuseColor;',
      ]).result;
    }
 
    shaders.Vertex = VSSource;
    shaders.Geometry = GSSource;
    shaders.Fragment = FSSource;
  };
 
  publicAPI.replaceShaderTCoord = (shaders, ren, actor) => {
    Iif (model.lastBoundBO.getCABO().getTCoordOffset()) {
      let VSSource = shaders.Vertex;
      let GSSource = shaders.Geometry;
      let FSSource = shaders.Fragment;
 
      const tcdim = model.lastBoundBO.getCABO().getTCoordComponents();
      if (tcdim === 1) {
        VSSource = vtkShaderProgram.substitute(VSSource, '//VTK::TCoord::Dec', [
          'in float tcoordMC;',
          'out float tcoordVCVSOutput;',
        ]).result;
        VSSource = vtkShaderProgram.substitute(
          VSSource,
          '//VTK::TCoord::Impl',
          ['tcoordVCVSOutput = tcoordMC;']
        ).result;
        GSSource = vtkShaderProgram.substitute(GSSource, '//VTK::TCoord::Dec', [
          'in float tcoordVCVSOutput[];\n',
          'out float tcoordVCGSOutput;',
        ]).result;
        GSSource = vtkShaderProgram.substitute(GSSource, [
          '//VTK::TCoord::Impl',
          'tcoordVCGSOutput = tcoordVCVSOutput[i];',
        ]).result;
        FSSource = vtkShaderProgram.substitute(FSSource, '//VTK::TCoord::Dec', [
          'in float tcoordVCVSOutput;',
          'uniform sampler2D texture1;',
        ]).result;
        FSSource = vtkShaderProgram.substitute(
          FSSource,
          '//VTK::TCoord::Impl',
          [
            'gl_FragData[0] = gl_FragData[0]*texture2D(texture1, vec2(tcoordVCVSOutput,0));',
          ]
        ).result;
      } else if (tcdim === 2) {
        VSSource = vtkShaderProgram.substitute(VSSource, '//VTK::TCoord::Dec', [
          'in vec2 tcoordMC;',
          'out vec2 tcoordVCVSOutput;',
        ]).result;
        VSSource = vtkShaderProgram.substitute(
          VSSource,
          '//VTK::TCoord::Impl',
          ['tcoordVCVSOutput = tcoordMC;']
        ).result;
        GSSource = vtkShaderProgram.substitute(GSSource, '//VTK::TCoord::Dec', [
          'in vec2 tcoordVCVSOutput[];\n',
          'out vec2 tcoordVCGSOutput;',
        ]).result;
        GSSource = vtkShaderProgram.substitute(
          GSSource,
          '//VTK::TCoord::Impl',
          ['tcoordVCGSOutput = tcoordVCVSOutput[i];']
        ).result;
        FSSource = vtkShaderProgram.substitute(FSSource, '//VTK::TCoord::Dec', [
          'in vec2 tcoordVCVSOutput;',
          'uniform sampler2D texture1;',
        ]).result;
        FSSource = vtkShaderProgram.substitute(
          FSSource,
          '//VTK::TCoord::Impl',
          [
            'gl_FragData[0] = gl_FragData[0]*texture2D(texture1, tcoordVCVSOutput.st);',
          ]
        ).result;
      }
 
      if (model.haveCellScalars) {
        GSSource = vtkShaderProgram.substitute(
          GSSource,
          '//VTK::PrimID::Impl',
          ['gl_PrimitiveID = gl_PrimitiveIDIn;']
        ).result;
      }
      shaders.Vertex = VSSource;
      shaders.Geometry = GSSource;
      shaders.Fragment = FSSource;
    }
  };
 
  publicAPI.replaceShaderPicking = (shaders, ren, actor) => {
    let FSSource = shaders.Fragment;
    FSSource = vtkShaderProgram.substitute(FSSource, '//VTK::Picking::Dec', [
      'uniform vec3 mapperIndex;',
      'uniform int picking;',
    ]).result;
    FSSource = vtkShaderProgram.substitute(
      FSSource,
      '//VTK::Picking::Impl',
      '  gl_FragData[0] = picking != 0 ? vec4(mapperIndex,1.0) : gl_FragData[0];'
    ).result;
    shaders.Fragment = FSSource;
  };
 
  publicAPI.replaceShaderPositionVC = (shaders, ren, actor) => {
    // replace common shader code
    model.lastBoundBO.replaceShaderPositionVC(shaders, ren, actor);
  };
 
  publicAPI.invokeShaderCallbacks = (cellBO, ren, actor) => {
    const listCallbacks =
      model.renderable.getViewSpecificProperties().ShadersCallbacks;
    Iif (listCallbacks) {
      listCallbacks.forEach((object) => {
        object.callback(object.userData, cellBO, ren, actor);
      });
    }
  };
 
  publicAPI.setMapperShaderParameters = (cellBO, ren, actor) => {
    // Now to update the VAO too, if necessary.
    Iif (cellBO.getProgram().isUniformUsed('PrimitiveIDOffset')) {
      cellBO
        .getProgram()
        .setUniformi('PrimitiveIDOffset', model.primitiveIDOffset);
    }
 
    if (cellBO.getProgram().isAttributeUsed('vertexWC')) {
      Iif (
        !cellBO
          .getVAO()
          .addAttributeArray(
            cellBO.getProgram(),
            cellBO.getCABO(),
            'vertexWC',
            cellBO.getCABO().getVertexOffset(),
            cellBO.getCABO().getStride(),
            model.context.FLOAT,
            3,
            false
          )
      ) {
        vtkErrorMacro('Error setting vertexWC in shader VAO.');
      }
    }
    if (
      cellBO.getCABO().getElementCount() &&
      (model.VBOBuildTime.getMTime() >
        cellBO.getAttributeUpdateTime().getMTime() ||
        cellBO.getShaderSourceTime().getMTime() >
          cellBO.getAttributeUpdateTime().getMTime())
    ) {
      model.renderable.getCustomShaderAttributes().forEach((attrName, idx) => {
        if (cellBO.getProgram().isAttributeUsed(`${attrName}MC`)) {
          if (
            !cellBO
              .getVAO()
              .addAttributeArray(
                cellBO.getProgram(),
                cellBO.getCABO(),
                `${attrName}MC`,
                cellBO.getCABO().getCustomData()[idx].offset,
                cellBO.getCABO().getStride(),
                model.context.FLOAT,
                cellBO.getCABO().getCustomData()[idx].components,
                false
              )
          ) {
            vtkErrorMacro(`Error setting ${attrName}MC in shader VAO.`);
          }
        }
      });
 
      Iif (
        cellBO.getProgram().isAttributeUsed('tcoordMC') &&
        cellBO.getCABO().getTCoordOffset()
      ) {
        if (
          !cellBO
            .getVAO()
            .addAttributeArray(
              cellBO.getProgram(),
              cellBO.getCABO(),
              'tcoordMC',
              cellBO.getCABO().getTCoordOffset(),
              cellBO.getCABO().getStride(),
              model.context.FLOAT,
              cellBO.getCABO().getTCoordComponents(),
              false
            )
        ) {
          vtkErrorMacro('Error setting tcoordMC in shader VAO.');
        }
      } else {
        cellBO.getVAO().removeAttributeArray('tcoordMC');
      }
      Iif (
        model.internalColorTexture &&
        cellBO.getProgram().isUniformUsed('texture1')
      ) {
        cellBO
          .getProgram()
          .setUniformi('texture1', model.internalColorTexture.getTextureUnit());
      }
      const tus = model.openGLActor2D.getActiveTextures();
      Iif (tus) {
        for (let index = 0; index < tus.length; ++index) {
          const tex = tus[index];
          const texUnit = tex.getTextureUnit();
          const tname = `texture${texUnit + 1}`;
          if (cellBO.getProgram().isUniformUsed(tname)) {
            cellBO.getProgram().setUniformi(tname, texUnit);
          }
        }
      }
 
      // handle wide lines
      cellBO.setMapperShaderParameters(
        ren,
        actor,
        model._openGLRenderer.getTiledSizeAndOrigin()
      );
 
      const selector = model._openGLRenderer.getSelector();
      cellBO
        .getProgram()
        .setUniform3fArray(
          'mapperIndex',
          selector ? selector.getPropColorValue() : [0.0, 0.0, 0.0]
        );
      cellBO
        .getProgram()
        .setUniformi('picking', selector ? selector.getCurrentPass() + 1 : 0);
    }
  };
 
  publicAPI.setPropertyShaderParameters = (cellBO, ren, actor) => {
    const c = model.renderable.getColorMapColors();
    if (!c || c.getNumberOfComponents() === 0) {
      const program = cellBO.getProgram();
      const ppty = actor.getProperty();
      const opacity = ppty.getOpacity();
      const dColor = ppty.getColor();
      const diffuseColor = [dColor[0], dColor[1], dColor[2], opacity];
      program.setUniform4f('diffuseColor', diffuseColor);
    }
  };
 
  publicAPI.setLightingShaderParameters = (cellBO, ren, actor) => {
    // no-op
  };
 
  function safeMatrixMultiply(matrixArray, matrixType, tmpMat) {
    matrixType.identity(tmpMat);
    return matrixArray.reduce((res, matrix, index) => {
      if (index === 0) {
        return matrix ? matrixType.copy(res, matrix) : matrixType.identity(res);
      }
      return matrix ? matrixType.multiply(res, res, matrix) : res;
    }, tmpMat);
  }
 
  publicAPI.setCameraShaderParameters = (cellBO, ren, actor) => {
    const program = cellBO.getProgram();
 
    const shiftScaleEnabled = cellBO.getCABO().getCoordShiftAndScaleEnabled();
    const inverseShiftScaleMatrix = shiftScaleEnabled
      ? cellBO.getCABO().getInverseShiftAndScaleMatrix()
      : null;
 
    // Get the position of the actor
    const view = ren.getRenderWindow().getViews()[0];
    const size = view.getViewportSize(ren);
    const vport = ren.getViewport();
    const actorPos = actor
      .getActualPositionCoordinate()
      .getComputedDoubleViewportValue(ren);
 
    // Get the window info
    // Assume tile viewport is 0 1 based on vtkOpenGLRenderer
    const tileViewport = [0.0, 0.0, 1.0, 1.0];
    const visVP = [0.0, 0.0, 1.0, 1.0];
    visVP[0] = vport[0] >= tileViewport[0] ? vport[0] : tileViewport[0];
    visVP[1] = vport[1] >= tileViewport[1] ? vport[1] : tileViewport[1];
    visVP[2] = vport[2] <= tileViewport[2] ? vport[2] : tileViewport[2];
    visVP[3] = vport[3] <= tileViewport[3] ? vport[3] : tileViewport[3];
    Iif (visVP[0] >= visVP[2]) {
      return;
    }
    Iif (visVP[1] >= visVP[3]) {
      return;
    }
    size[0] = round((size[0] * (visVP[2] - visVP[0])) / (vport[2] - vport[0]));
    size[1] = round((size[1] * (visVP[3] - visVP[1])) / (vport[3] - vport[1]));
 
    const winSize = model._openGLRenderer.getParent().getSize();
 
    const xoff = round(actorPos[0] - (visVP[0] - vport[0]) * winSize[0]);
    const yoff = round(actorPos[1] - (visVP[1] - vport[1]) * winSize[1]);
 
    // set ortho projection
    const left = -xoff;
    let right = -xoff + size[0];
    const bottom = -yoff;
    let top = -yoff + size[1];
 
    // it's an error to call glOrtho with
    // either left==right or top==bottom
    Iif (left === right) {
      right = left + 1.0;
    }
    Iif (bottom === top) {
      top = bottom + 1.0;
    }
 
    // compute the combined ModelView matrix and send it down to save time in the shader
    const tmpMat4 = mat4.identity(new Float64Array(16));
    tmpMat4[0] = 2.0 / (right - left);
    tmpMat4[1 * 4 + 1] = 2.0 / (top - bottom);
    tmpMat4[0 * 4 + 3] = (-1.0 * (right + left)) / (right - left);
    tmpMat4[1 * 4 + 3] = (-1.0 * (top + bottom)) / (top - bottom);
    tmpMat4[2 * 4 + 2] = 0.0;
    tmpMat4[2 * 4 + 3] =
      actor.getProperty().getDisplayLocation() === DisplayLocation.FOREGROUND
        ? -1.0
        : 1.0;
    tmpMat4[3 * 4 + 3] = 1.0;
    mat4.transpose(tmpMat4, tmpMat4);
    program.setUniformMatrix(
      'WCVCMatrix',
      safeMatrixMultiply(
        [tmpMat4, inverseShiftScaleMatrix],
        mat4,
        model.tmpMat4
      )
    );
  };
 
  publicAPI.getAllocatedGPUMemoryInBytes = () => {
    let memUsed = 0;
    model.primitives.forEach((prim) => {
      memUsed += prim.getAllocatedGPUMemoryInBytes();
    });
    // Return in MB
    return memUsed;
  };
}
 
// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------
 
const DEFAULT_VALUES = {
  context: null,
  VBOBuildTime: 0,
  VBOBuildString: null,
  primitives: null,
  primTypes: null,
  shaderRebuildString: null,
};
 
// ----------------------------------------------------------------------------
 
export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);
 
  // Inheritance
  vtkViewNode.extend(publicAPI, model, initialValues);
  vtkReplacementShaderMapper.implementReplaceShaderCoincidentOffset(
    publicAPI,
    model,
    initialValues
  );
  vtkReplacementShaderMapper.implementBuildShadersWithReplacements(
    publicAPI,
    model,
    initialValues
  );
 
  model.primitives = [];
  model.primTypes = primTypes;
 
  model.tmpMat4 = mat4.identity(new Float64Array(16));
 
  for (let i = primTypes.Start; i < primTypes.End; i++) {
    model.primitives[i] = vtkHelper.newInstance();
    model.primitives[i].setPrimitiveType(i);
    model.primitives[i].set(
      { lastLightComplexity: 0, lastLightCount: 0, lastSelectionPass: false },
      true
    );
  }
 
  // Build VTK API
  macro.setGet(publicAPI, model, ['context']);
 
  model.VBOBuildTime = {};
  macro.obj(model.VBOBuildTime, { mtime: 0 });
 
  // Object methods
  vtkOpenGLPolyDataMapper2D(publicAPI, model);
}
 
// ----------------------------------------------------------------------------
 
export const newInstance = macro.newInstance(
  extend,
  'vtkOpenGLPolyDataMapper2D'
);
 
// ----------------------------------------------------------------------------
 
export default { newInstance, extend };
 
// Register ourself to OpenGL backend if imported
registerOverride('vtkMapper2D', newInstance);