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 | 1x 1x 1x 1x 1x | import macro from 'vtk.js/Sources/macros'; import { mat4, vec3 } from 'gl-matrix'; import { Filter } from 'vtk.js/Sources/Rendering/OpenGL/Texture/Constants'; import { InterpolationType } from 'vtk.js/Sources/Rendering/Core/ImageProperty/Constants'; import { ProjectionMode } from 'vtk.js/Sources/Rendering/Core/ImageCPRMapper/Constants'; import { Representation } from 'vtk.js/Sources/Rendering/Core/Property/Constants'; import { VtkDataTypes } from 'vtk.js/Sources/Common/Core/DataArray/Constants'; import vtkDataArray from 'vtk.js/Sources/Common/Core/DataArray'; import vtkHelper from 'vtk.js/Sources/Rendering/OpenGL/Helper'; import vtkOpenGLTexture from 'vtk.js/Sources/Rendering/OpenGL/Texture'; 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 { getTransferFunctionHash, getImageDataHash, } from 'vtk.js/Sources/Rendering/OpenGL/RenderWindow/resourceSharingHelper'; import vtkPolyDataVS from 'vtk.js/Sources/Rendering/OpenGL/glsl/vtkPolyDataVS.glsl'; import vtkPolyDataFS from 'vtk.js/Sources/Rendering/OpenGL/glsl/vtkPolyDataFS.glsl'; import { registerOverride } from 'vtk.js/Sources/Rendering/OpenGL/ViewNodeFactory'; import { Resolve } from 'vtk.js/Sources/Rendering/Core/Mapper/CoincidentTopologyHelper'; const { vtkErrorMacro } = macro; // ---------------------------------------------------------------------------- // vtkOpenGLImageCPRMapper methods // ---------------------------------------------------------------------------- function vtkOpenGLImageCPRMapper(publicAPI, model) { // Set our className model.classHierarchy.push('vtkOpenGLImageCPRMapper'); function unregisterGraphicsResources(renderWindow) { [model._scalars, model._colorTransferFunc, model._pwFunc].forEach( (coreObject) => renderWindow.unregisterGraphicsResourceUser(coreObject, publicAPI) ); } publicAPI.buildPass = (prepass) => { if (prepass) { model.currentRenderPass = null; model.openGLImageSlice = publicAPI.getFirstAncestorOfType( 'vtkOpenGLImageSlice' ); model._openGLRenderer = publicAPI.getFirstAncestorOfType('vtkOpenGLRenderer'); const oldOglRenderWindow = model._openGLRenderWindow; model._openGLRenderWindow = model._openGLRenderer.getLastAncestorOfType( 'vtkOpenGLRenderWindow' ); if ( oldOglRenderWindow && !oldOglRenderWindow.isDeleted() && oldOglRenderWindow !== model._openGLRenderWindow ) { unregisterGraphicsResources(oldOglRenderWindow); } model.context = model._openGLRenderWindow.getContext(); model.openGLCamera = model._openGLRenderer.getViewNodeFor( model._openGLRenderer.getRenderable().getActiveCamera() ); model.tris.setOpenGLRenderWindow(model._openGLRenderWindow); } }; publicAPI.opaquePass = (prepass, renderPass) => { if (prepass) { model.currentRenderPass = renderPass; publicAPI.render(); } }; publicAPI.opaqueZBufferPass = (prepass) => { if (prepass) { model.haveSeenDepthRequest = true; model.renderDepth = true; publicAPI.render(); model.renderDepth = false; } }; publicAPI.getCoincidentParameters = (ren, actor) => { if ( model.renderable.getResolveCoincidentTopology() === Resolve.PolygonOffset ) { return model.renderable.getCoincidentTopologyPolygonOffsetParameters(); } return null; }; publicAPI.render = () => { const prop = model.openGLImageSlice.getRenderable(); const ren = model._openGLRenderer.getRenderable(); publicAPI.renderPiece(ren, prop); }; publicAPI.renderPiece = (ren, prop) => { publicAPI.invokeEvent({ type: 'StartEvent' }); model.renderable.update(); publicAPI.invokeEvent({ type: 'EndEvent' }); // Check if the ImageCPRMapper has everything it needs to render if (!model.renderable.preRenderCheck()) { return; } model.currentImageDataInput = model.renderable.getInputData(0); model.currentCenterlineInput = model.renderable.getOrientedCenterline(); publicAPI.renderPieceStart(ren, prop); publicAPI.renderPieceDraw(ren, prop); publicAPI.renderPieceFinish(ren, prop); }; publicAPI.renderPieceStart = (ren, actor) => { // make sure the BOs are up to date publicAPI.updateBufferObjects(ren, actor); }; publicAPI.renderPieceDraw = (ren, actor) => { const gl = model.context; // activate the texture model.volumeTexture.activate(); model.colorTexture.activate(); model.pwfTexture.activate(); // draw polygons if (model.tris.getCABO().getElementCount()) { // First we do the triangles, update the shader, set uniforms, etc. publicAPI.updateShaders(model.tris, ren, actor); gl.drawArrays(gl.TRIANGLES, 0, model.tris.getCABO().getElementCount()); model.tris.getVAO().release(); } model.volumeTexture.deactivate(); model.colorTexture.deactivate(); model.pwfTexture.deactivate(); }; publicAPI.renderPieceFinish = (ren, actor) => {}; publicAPI.updateBufferObjects = (ren, actor) => { // Rebuild buffers if needed if (publicAPI.getNeedToRebuildBufferObjects(ren, actor)) { publicAPI.buildBufferObjects(ren, actor); } // Set interpolation on the texture based on property setting const actorProperty = actor.getProperty(); if (actorProperty.getInterpolationType() === InterpolationType.NEAREST) { model.volumeTexture.setMinificationFilter(Filter.NEAREST); model.volumeTexture.setMagnificationFilter(Filter.NEAREST); model.colorTexture.setMinificationFilter(Filter.NEAREST); model.colorTexture.setMagnificationFilter(Filter.NEAREST); model.pwfTexture.setMinificationFilter(Filter.NEAREST); model.pwfTexture.setMagnificationFilter(Filter.NEAREST); } else { model.volumeTexture.setMinificationFilter(Filter.LINEAR); model.volumeTexture.setMagnificationFilter(Filter.LINEAR); model.colorTexture.setMinificationFilter(Filter.LINEAR); model.colorTexture.setMagnificationFilter(Filter.LINEAR); model.pwfTexture.setMinificationFilter(Filter.LINEAR); model.pwfTexture.setMagnificationFilter(Filter.LINEAR); } }; 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(); return ( vmtime < publicAPI.getMTime() || vmtime < model.renderable.getMTime() || vmtime < actor.getMTime() || vmtime < model.currentImageDataInput.getMTime() || vmtime < model.currentCenterlineInput.getMTime() || !model.volumeTexture?.getHandle() ); }; publicAPI.buildBufferObjects = (ren, actor) => { const image = model.currentImageDataInput; const centerline = model.currentCenterlineInput; // Rebuild the volumeTexture if the data has changed const scalars = image?.getPointData()?.getScalars(); if (!scalars) { return; } const cachedScalarsEntry = model._openGLRenderWindow.getGraphicsResourceForObject(scalars); const volumeTextureHash = getImageDataHash(image, scalars); const reBuildTex = !cachedScalarsEntry?.oglObject?.getHandle() || cachedScalarsEntry?.hash !== volumeTextureHash; if (reBuildTex) { model.volumeTexture = vtkOpenGLTexture.newInstance(); model.volumeTexture.setOpenGLRenderWindow(model._openGLRenderWindow); // Build the textures const dims = image.getDimensions(); // Use norm16 for scalar texture if the extension is available model.volumeTexture.setOglNorm16Ext( model.context.getExtension('EXT_texture_norm16') ); model.volumeTexture.resetFormatAndType(); model.volumeTexture.create3DFilterableFromDataArray( dims[0], dims[1], dims[2], scalars, model.renderable.getPreferSizeOverAccuracy() ); model._openGLRenderWindow.setGraphicsResourceForObject( scalars, model.volumeTexture, volumeTextureHash ); if (scalars !== model._scalars) { model._openGLRenderWindow.registerGraphicsResourceUser( scalars, publicAPI ); model._openGLRenderWindow.unregisterGraphicsResourceUser( model._scalars, publicAPI ); } model._scalars = scalars; } else { model.volumeTexture = cachedScalarsEntry.oglObject; } // Rebuild the color texture if needed const numComp = scalars.getNumberOfComponents(); const ppty = actor.getProperty(); const iComps = ppty.getIndependentComponents(); const numIComps = iComps ? numComp : 1; const textureHeight = iComps ? 2 * numIComps : 1; const colorTransferFunc = ppty.getRGBTransferFunction(); const colorTextureHash = getTransferFunctionHash( colorTransferFunc, iComps, numIComps ); const cachedColorEntry = model._openGLRenderWindow.getGraphicsResourceForObject(colorTransferFunc); const reBuildColorTexture = !cachedColorEntry?.oglObject?.getHandle() || cachedColorEntry?.hash !== colorTextureHash; if (reBuildColorTexture) { const cWidth = 1024; const cSize = cWidth * textureHeight * 3; const cTable = new Uint8ClampedArray(cSize); model.colorTexture = vtkOpenGLTexture.newInstance(); model.colorTexture.setOpenGLRenderWindow(model._openGLRenderWindow); if (colorTransferFunc) { const tmpTable = new Float32Array(cWidth * 3); for (let c = 0; c < numIComps; c++) { const cfun = ppty.getRGBTransferFunction(c); const cRange = cfun.getRange(); cfun.getTable(cRange[0], cRange[1], cWidth, tmpTable, 1); if (iComps) { for (let i = 0; i < cWidth * 3; i++) { cTable[c * cWidth * 6 + i] = 255.0 * tmpTable[i]; cTable[c * cWidth * 6 + i + cWidth * 3] = 255.0 * tmpTable[i]; } } else { for (let i = 0; i < cWidth * 3; i++) { cTable[c * cWidth * 6 + i] = 255.0 * tmpTable[i]; } } } model.colorTexture.resetFormatAndType(); model.colorTexture.create2DFromRaw( cWidth, textureHeight, 3, VtkDataTypes.UNSIGNED_CHAR, cTable ); } else { for (let i = 0; i < cWidth * 3; ++i) { cTable[i] = (255.0 * i) / ((cWidth - 1) * 3); cTable[i + 1] = (255.0 * i) / ((cWidth - 1) * 3); cTable[i + 2] = (255.0 * i) / ((cWidth - 1) * 3); } model.colorTexture.resetFormatAndType(); model.colorTexture.create2DFromRaw( cWidth, 1, 3, VtkDataTypes.UNSIGNED_CHAR, cTable ); } if (colorTransferFunc) { model._openGLRenderWindow.setGraphicsResourceForObject( colorTransferFunc, model.colorTexture, colorTextureHash ); if (colorTransferFunc !== model._colorTransferFunc) { model._openGLRenderWindow.registerGraphicsResourceUser( colorTransferFunc, publicAPI ); model._openGLRenderWindow.unregisterGraphicsResourceUser( model._colorTransferFunc, publicAPI ); } model._colorTransferFunc = colorTransferFunc; } } else { model.colorTexture = cachedColorEntry.oglObject; } // Build piecewise function buffer. This buffer is used either // for component weighting or opacity, depending on whether we're // rendering components independently or not. const pwFunc = ppty.getPiecewiseFunction(); const pwfTextureHash = getTransferFunctionHash(pwFunc, iComps, numIComps); const cachedPwfEntry = model._openGLRenderWindow.getGraphicsResourceForObject(pwFunc); const reBuildPwf = !cachedPwfEntry?.oglObject?.getHandle() || cachedPwfEntry?.hash !== pwfTextureHash; if (reBuildPwf) { const pwfWidth = 1024; const pwfSize = pwfWidth * textureHeight; const pwfTable = new Uint8ClampedArray(pwfSize); model.pwfTexture = vtkOpenGLTexture.newInstance(); model.pwfTexture.setOpenGLRenderWindow(model._openGLRenderWindow); if (pwFunc) { const pwfFloatTable = new Float32Array(pwfSize); const tmpTable = new Float32Array(pwfWidth); for (let c = 0; c < numIComps; ++c) { const pwfun = ppty.getPiecewiseFunction(c); if (pwfun === null) { // Piecewise constant max if no function supplied for this component pwfFloatTable.fill(1.0); } else { const pwfRange = pwfun.getRange(); pwfun.getTable(pwfRange[0], pwfRange[1], pwfWidth, tmpTable, 1); // adjust for sample distance etc if (iComps) { for (let i = 0; i < pwfWidth; i++) { pwfFloatTable[c * pwfWidth * 2 + i] = tmpTable[i]; pwfFloatTable[c * pwfWidth * 2 + i + pwfWidth] = tmpTable[i]; } } else { for (let i = 0; i < pwfWidth; i++) { pwfFloatTable[c * pwfWidth * 2 + i] = tmpTable[i]; } } } } model.pwfTexture.resetFormatAndType(); model.pwfTexture.create2DFromRaw( pwfWidth, textureHeight, 1, VtkDataTypes.FLOAT, pwfFloatTable ); } else { // default is opaque pwfTable.fill(255.0); model.pwfTexture.resetFormatAndType(); model.pwfTexture.create2DFromRaw( pwfWidth, 1, 1, VtkDataTypes.UNSIGNED_CHAR, pwfTable ); } if (pwFunc) { model._openGLRenderWindow.setGraphicsResourceForObject( pwFunc, model.pwfTexture, pwfTextureHash ); if (pwFunc !== model._pwFunc) { model._openGLRenderWindow.registerGraphicsResourceUser( pwFunc, publicAPI ); model._openGLRenderWindow.unregisterGraphicsResourceUser( model._pwFunc, publicAPI ); } model._pwFunc = pwFunc; } } else { model.pwfTexture = cachedPwfEntry.oglObject; } // Rebuild the image vertices if needed if ( model.VBOBuildTime.getMTime() < model.renderable.getMTime() || model.VBOBuildTime.getMTime() < centerline.getMTime() ) { const nPoints = centerline.getNumberOfPoints(); const nLines = nPoints <= 1 ? 0 : nPoints - 1; const distances = centerline.getDistancesToFirstPoint(); const totalHeight = model.renderable.getHeight(); const nPts = 4 * nLines; // Create the array of point: 4 points per segment const ptsArray = new Float32Array(3 * nPts); const widthMC = model.renderable.getWidth(); for (let lineIdx = 0, offset = 0; lineIdx < nLines; ++lineIdx) { // Use model coordinates // See "setCameraShaderParameters" to see how MCPCMatrix is built // Top left ptsArray.set([0, totalHeight - distances[lineIdx], 0], offset); offset += 3; // Top right ptsArray.set([widthMC, totalHeight - distances[lineIdx], 0], offset); offset += 3; // Bottom right ptsArray.set( [widthMC, totalHeight - distances[lineIdx + 1], 0], offset ); offset += 3; // Bottom left ptsArray.set([0, totalHeight - distances[lineIdx + 1], 0], offset); offset += 3; } const points = vtkDataArray.newInstance({ numberOfComponents: 3, values: ptsArray, }); points.setName('points'); // Create the array of cells: a quad per segment const cellArray = new Uint16Array(5 * nLines); for ( let lineIdx = 0, offset = 0, ptIdx = 0; lineIdx < nLines; ++lineIdx ) { cellArray.set([4, ptIdx + 3, ptIdx + 2, ptIdx + 1, ptIdx], offset); offset += 5; ptIdx += 4; } const cells = vtkDataArray.newInstance({ numberOfComponents: 1, values: cellArray, }); // Create the array of centerline positions (VBO custom attribute) const pointsDataArray = centerline.getPoints(); const centerlinePositionArray = new Float32Array(3 * nPts); const pa = new Array(3); const pb = new Array(3); for (let lineIdx = 0, offset = 0; lineIdx < nLines; ++lineIdx) { pointsDataArray.getPoint(lineIdx, pa); pointsDataArray.getPoint(lineIdx + 1, pb); // Top left centerlinePositionArray.set(pa, offset); offset += 3; // Top right centerlinePositionArray.set(pa, offset); offset += 3; // Bottom right centerlinePositionArray.set(pb, offset); offset += 3; // Bottom left centerlinePositionArray.set(pb, offset); offset += 3; } const centerlinePosition = vtkDataArray.newInstance({ numberOfComponents: 3, values: centerlinePositionArray, name: 'centerlinePosition', }); // Create the array of quad index: // 0 ____ 1 // | | // |____| // 2 3 const quadIndexArray = new Float32Array(nPts); for (let lineIdx = 0, offset = 0; lineIdx < nLines; ++lineIdx) { quadIndexArray.set( [ 0, // Top left 1, // Top right 3, // Bottom right 2, // Bottom left ], offset ); offset += 4; } const quadIndex = vtkDataArray.newInstance({ numberOfComponents: 1, values: quadIndexArray, name: 'quadIndex', }); const customAttributes = [centerlinePosition, quadIndex]; if (!model.renderable.getUseUniformOrientation()) { // For each quad (i.e. centerline segment), a top and bottom quaternion give the orientation // Send both quaternions to each vertex and use flat interpolation to get them "as is" in the fragment shader // The interpolation of the quaternions will occur in the fragment shader (slerp) const orientationQuats = model.renderable.getOrientedCenterline().getOrientations() ?? []; const centerlineTopOrientationArray = new Float32Array(4 * nPts); const centerlineBotOrientationArray = new Float32Array(4 * nPts); for (let quadIdx = 0; quadIdx < nLines; ++quadIdx) { // All vertices of a given quad have the same topDir and botDir // Polyline goes from top to bottom const topQuat = orientationQuats[quadIdx]; const botQuat = orientationQuats[quadIdx + 1]; for (let pointInQuadIdx = 0; pointInQuadIdx < 4; ++pointInQuadIdx) { const pointIdx = pointInQuadIdx + 4 * quadIdx; const quaternionArrayOffset = 4 * pointIdx; centerlineTopOrientationArray.set(topQuat, quaternionArrayOffset); centerlineBotOrientationArray.set(botQuat, quaternionArrayOffset); } } const centerlineTopOrientation = vtkDataArray.newInstance({ numberOfComponents: 4, values: centerlineTopOrientationArray, name: 'centerlineTopOrientation', }); const centerlineBotOrientation = vtkDataArray.newInstance({ numberOfComponents: 4, values: centerlineBotOrientationArray, name: 'centerlineBotOrientation', }); customAttributes.push( centerlineTopOrientation, centerlineBotOrientation ); } model.tris.getCABO().createVBO(cells, 'polys', Representation.SURFACE, { points, customAttributes, }); model.VBOBuildTime.modified(); } }; publicAPI.getNeedToRebuildShaders = (cellBO, ren, actor) => { // has something changed that would require us to recreate the shader? // candidates are // presence of centerPoint // value of useUniformOrientation // property modified (representation interpolation and lighting) // input modified // light complexity changed // render pass shader replacement changed const tNumComp = model.volumeTexture.getComponents(); const iComp = actor.getProperty().getIndependentComponents(); const useCenterPoint = !!model.renderable.getCenterPoint(); const useUniformOrientation = model.renderable.getUseUniformOrientation(); const projectionMode = model.renderable.isProjectionEnabled() && model.renderable.getProjectionMode(); if ( cellBO.getProgram() === 0 || model.lastUseCenterPoint !== useCenterPoint || model.lastUseUniformOrientation !== useUniformOrientation || model.lastProjectionMode !== projectionMode || model.lastHaveSeenDepthRequest !== model.haveSeenDepthRequest || model.lastTextureComponents !== tNumComp || model.lastIndependentComponents !== iComp ) { model.lastUseCenterPoint = useCenterPoint; model.lastUseUniformOrientation = useUniformOrientation; model.lastProjectionMode = projectionMode; model.lastHaveSeenDepthRequest = model.haveSeenDepthRequest; model.lastTextureComponents = tNumComp; model.lastIndependentComponents = iComp; return true; } return false; }; publicAPI.buildShaders = (shaders, ren, actor) => { publicAPI.getShaderTemplate(shaders, ren, actor); publicAPI.replaceShaderValues(shaders, ren, actor); }; publicAPI.replaceShaderValues = (shaders, ren, actor) => { let VSSource = shaders.Vertex; let FSSource = shaders.Fragment; // https://glmatrix.net/docs/vec3.js.html#line522 const applyQuaternionToVecShaderFunction = [ 'vec3 applyQuaternionToVec(vec4 q, vec3 v) {', ' float uvx = q.y * v.z - q.z * v.y;', ' float uvy = q.z * v.x - q.x * v.z;', ' float uvz = q.x * v.y - q.y * v.x;', ' float uuvx = q.y * uvz - q.z * uvy;', ' float uuvy = q.z * uvx - q.x * uvz;', ' float uuvz = q.x * uvy - q.y * uvx;', ' float w2 = q.w * 2.0;', ' uvx *= w2;', ' uvy *= w2;', ' uvz *= w2;', ' uuvx *= 2.0;', ' uuvy *= 2.0;', ' uuvz *= 2.0;', ' return vec3(v.x + uvx + uuvx, v.y + uvy + uuvy, v.z + uvz + uuvz);', '}', ]; // Vertex shader main replacements VSSource = vtkShaderProgram.substitute(VSSource, '//VTK::Camera::Dec', [ 'uniform mat4 MCPCMatrix;', ]).result; VSSource = vtkShaderProgram.substitute( VSSource, '//VTK::PositionVC::Impl', [' gl_Position = MCPCMatrix * vertexMC;'] ).result; const vsColorDec = [ 'attribute vec3 centerlinePosition;', 'attribute float quadIndex;', 'uniform float width;', 'out vec2 quadOffsetVSOutput;', 'out vec3 centerlinePosVSOutput;', ]; const useProjection = model.renderable.isProjectionEnabled(); const isDirectionUniform = model.renderable.getUseUniformOrientation(); if (isDirectionUniform) { vsColorDec.push( 'out vec3 samplingDirVSOutput;', 'uniform vec4 centerlineOrientation;', 'uniform vec3 tangentDirection;', ...applyQuaternionToVecShaderFunction ); if (useProjection) { vsColorDec.push( 'out vec3 projectionDirVSOutput;', 'uniform vec3 bitangentDirection;' ); } } else { vsColorDec.push( 'out vec4 centerlineTopOrientationVSOutput;', 'out vec4 centerlineBotOrientationVSOutput;', 'attribute vec4 centerlineTopOrientation;', 'attribute vec4 centerlineBotOrientation;' ); } VSSource = vtkShaderProgram.substitute( VSSource, '//VTK::Color::Dec', vsColorDec ).result; const vsColorImpl = [ // quadOffsetVSOutput.x: left = -0.5* width; right = 0.5 * width // quadOffsetVSOutput.y: bottom = 0.0; top = 1.0; 'quadOffsetVSOutput = vec2(width * (mod(quadIndex, 2.0) == 0.0 ? -0.5 : 0.5), quadIndex > 1.0 ? 0.0 : 1.0);', 'centerlinePosVSOutput = centerlinePosition;', ]; if (isDirectionUniform) { vsColorImpl.push( 'samplingDirVSOutput = applyQuaternionToVec(centerlineOrientation, tangentDirection);' ); if (useProjection) { vsColorImpl.push( 'projectionDirVSOutput = applyQuaternionToVec(centerlineOrientation, bitangentDirection);' ); } } else { vsColorImpl.push( 'centerlineTopOrientationVSOutput = centerlineTopOrientation;', 'centerlineBotOrientationVSOutput = centerlineBotOrientation;' ); } VSSource = vtkShaderProgram.substitute( VSSource, '//VTK::Color::Impl', vsColorImpl ).result; // Fragment shader main replacements const tNumComp = model.volumeTexture.getComponents(); const iComps = actor.getProperty().getIndependentComponents(); let tcoordFSDec = [ // used to compute texture coordinates of the sample 'uniform mat4 MCTCMatrix; // Model coordinates to texture coordinates', 'in vec2 quadOffsetVSOutput;', 'in vec3 centerlinePosVSOutput;', // volume texture 'uniform highp sampler3D volumeTexture;', // color and pwf textures 'uniform sampler2D colorTexture1;', 'uniform sampler2D pwfTexture1;', // opacity 'uniform float opacity;', // background color (out of volume samples) 'uniform vec4 backgroundColor;', // color shift and scale `uniform float cshift0;`, `uniform float cscale0;`, // weighting shift and scale `uniform float pwfshift0;`, `uniform float pwfscale0;`, ]; if (useProjection) { tcoordFSDec.push( 'uniform vec3 volumeSizeMC;', 'uniform int projectionSlabNumberOfSamples;', 'uniform float projectionConstantOffset;', 'uniform float projectionStepLength;' ); } if (isDirectionUniform) { tcoordFSDec.push('in vec3 samplingDirVSOutput;'); if (useProjection) { tcoordFSDec.push('in vec3 projectionDirVSOutput;'); } } else { tcoordFSDec.push( 'uniform vec3 tangentDirection;', 'in vec4 centerlineTopOrientationVSOutput;', 'in vec4 centerlineBotOrientationVSOutput;', ...applyQuaternionToVecShaderFunction ); if (useProjection) { tcoordFSDec.push('uniform vec3 bitangentDirection;'); } } const centerPoint = model.renderable.getCenterPoint(); if (centerPoint) { tcoordFSDec.push('uniform vec3 globalCenterPoint;'); } if (iComps) { for (let comp = 1; comp < tNumComp; comp++) { tcoordFSDec = tcoordFSDec.concat([ // color shift and scale `uniform float cshift${comp};`, `uniform float cscale${comp};`, // weighting shift and scale `uniform float pwfshift${comp};`, `uniform float pwfscale${comp};`, ]); } // the heights defined below are the locations // for the up to four components of the tfuns // the tfuns have a height of 2XnumComps pixels so the // values are computed to hit the middle of the two rows // for that component switch (tNumComp) { case 1: tcoordFSDec = tcoordFSDec.concat([ 'uniform float mix0;', '#define height0 0.5', ]); break; case 2: tcoordFSDec = tcoordFSDec.concat([ 'uniform float mix0;', 'uniform float mix1;', '#define height0 0.25', '#define height1 0.75', ]); break; case 3: tcoordFSDec = tcoordFSDec.concat([ 'uniform float mix0;', 'uniform float mix1;', 'uniform float mix2;', '#define height0 0.17', '#define height1 0.5', '#define height2 0.83', ]); break; case 4: tcoordFSDec = tcoordFSDec.concat([ 'uniform float mix0;', 'uniform float mix1;', 'uniform float mix2;', 'uniform float mix3;', '#define height0 0.125', '#define height1 0.375', '#define height2 0.625', '#define height3 0.875', ]); break; default: vtkErrorMacro('Unsupported number of independent coordinates.'); } } FSSource = vtkShaderProgram.substitute( FSSource, '//VTK::TCoord::Dec', tcoordFSDec ).result; let tcoordFSImpl = []; if (isDirectionUniform) { tcoordFSImpl.push('vec3 samplingDirection = samplingDirVSOutput;'); if (useProjection) { tcoordFSImpl.push('vec3 projectionDirection = projectionDirVSOutput;'); } } else { // Slerp or lerp between centerlineTopDirVSOutput and centerlineBotDirVSOutput // We use quadOffsetVSOutput.y: bottom = 0.0; top = 1.0; tcoordFSImpl.push( // Slerp / Lerp 'vec4 q0 = centerlineBotOrientationVSOutput;', 'vec4 q1 = centerlineTopOrientationVSOutput;', 'float qCosAngle = dot(q0, q1);', 'vec4 interpolatedOrientation;', 'if (qCosAngle > 0.999 || qCosAngle < -0.999) {', ' // Use LERP instead of SLERP when the two quaternions are close or opposite', ' interpolatedOrientation = normalize(mix(q0, q1, quadOffsetVSOutput.y));', '} else {', ' float omega = acos(qCosAngle);', ' interpolatedOrientation = normalize(sin((1.0 - quadOffsetVSOutput.y) * omega) * q0 + sin(quadOffsetVSOutput.y * omega) * q1);', '}', 'vec3 samplingDirection = applyQuaternionToVec(interpolatedOrientation, tangentDirection);' ); if (useProjection) { tcoordFSImpl.push( 'vec3 projectionDirection = applyQuaternionToVec(interpolatedOrientation, bitangentDirection);' ); } } if (centerPoint) { tcoordFSImpl.push( 'float baseOffset = dot(samplingDirection, globalCenterPoint - centerlinePosVSOutput);', 'float horizontalOffset = quadOffsetVSOutput.x + baseOffset;' ); } else { tcoordFSImpl.push('float horizontalOffset = quadOffsetVSOutput.x;'); } tcoordFSImpl.push( 'vec3 volumePosMC = centerlinePosVSOutput + horizontalOffset * samplingDirection;', 'vec3 volumePosTC = (MCTCMatrix * vec4(volumePosMC, 1.0)).xyz;', 'if (any(lessThan(volumePosTC, vec3(0.0))) || any(greaterThan(volumePosTC, vec3(1.0))))', '{', ' // set the background color and exit', ' gl_FragData[0] = backgroundColor;', ' return;', '}' ); if (useProjection) { const projectionMode = model.renderable.getProjectionMode(); switch (projectionMode) { case ProjectionMode.MIN: tcoordFSImpl.push( 'const vec4 initialProjectionTextureValue = vec4(1.0);' ); break; case ProjectionMode.MAX: case ProjectionMode.AVERAGE: default: tcoordFSImpl.push( 'const vec4 initialProjectionTextureValue = vec4(0.0);' ); break; } // Loop on all the samples of the projection tcoordFSImpl.push( 'vec3 projectionScaledDirection = projectionDirection / volumeSizeMC;', 'vec3 projectionStep = projectionStepLength * projectionScaledDirection;', 'vec3 projectionStartPosition = volumePosTC + projectionConstantOffset * projectionScaledDirection;', 'vec4 tvalue = initialProjectionTextureValue;', 'for (int projectionSampleIdx = 0; projectionSampleIdx < projectionSlabNumberOfSamples; ++projectionSampleIdx) {', ' vec3 projectionSamplePosition = projectionStartPosition + float(projectionSampleIdx) * projectionStep;', ' vec4 sampledTextureValue = texture(volumeTexture, projectionSamplePosition);' ); switch (projectionMode) { case ProjectionMode.MAX: tcoordFSImpl.push(' tvalue = max(tvalue, sampledTextureValue);'); break; case ProjectionMode.MIN: tcoordFSImpl.push(' tvalue = min(tvalue, sampledTextureValue);'); break; case ProjectionMode.AVERAGE: default: tcoordFSImpl.push(' tvalue = tvalue + sampledTextureValue;'); break; } tcoordFSImpl.push('}'); // Process the total if needed if (projectionMode === ProjectionMode.AVERAGE) { tcoordFSImpl.push( 'tvalue = tvalue / float(projectionSlabNumberOfSamples);' ); } } else { tcoordFSImpl.push('vec4 tvalue = texture(volumeTexture, volumePosTC);'); } if (iComps) { const rgba = ['r', 'g', 'b', 'a']; for (let comp = 0; comp < tNumComp; ++comp) { tcoordFSImpl = tcoordFSImpl.concat([ `vec3 tcolor${comp} = mix${comp} * texture2D(colorTexture1, vec2(tvalue.${rgba[comp]} * cscale${comp} + cshift${comp}, height${comp})).rgb;`, `float compWeight${comp} = mix${comp} * texture2D(pwfTexture1, vec2(tvalue.${rgba[comp]} * pwfscale${comp} + pwfshift${comp}, height${comp})).r;`, ]); } switch (tNumComp) { case 1: tcoordFSImpl = tcoordFSImpl.concat([ 'gl_FragData[0] = vec4(tcolor0.rgb, compWeight0 * opacity);', ]); break; case 2: tcoordFSImpl = tcoordFSImpl.concat([ 'float weightSum = compWeight0 + compWeight1;', 'gl_FragData[0] = vec4(vec3((tcolor0.rgb * (compWeight0 / weightSum)) + (tcolor1.rgb * (compWeight1 / weightSum))), opacity);', ]); break; case 3: tcoordFSImpl = tcoordFSImpl.concat([ 'float weightSum = compWeight0 + compWeight1 + compWeight2;', 'gl_FragData[0] = vec4(vec3((tcolor0.rgb * (compWeight0 / weightSum)) + (tcolor1.rgb * (compWeight1 / weightSum)) + (tcolor2.rgb * (compWeight2 / weightSum))), opacity);', ]); break; case 4: tcoordFSImpl = tcoordFSImpl.concat([ 'float weightSum = compWeight0 + compWeight1 + compWeight2 + compWeight3;', 'gl_FragData[0] = vec4(vec3((tcolor0.rgb * (compWeight0 / weightSum)) + (tcolor1.rgb * (compWeight1 / weightSum)) + (tcolor2.rgb * (compWeight2 / weightSum)) + (tcolor3.rgb * (compWeight3 / weightSum))), opacity);', ]); break; default: vtkErrorMacro('Unsupported number of independent coordinates.'); } } else { // dependent components switch (tNumComp) { case 1: tcoordFSImpl = tcoordFSImpl.concat([ '// Dependent components', 'float intensity = tvalue.r;', 'vec3 tcolor = texture2D(colorTexture1, vec2(intensity * cscale0 + cshift0, 0.5)).rgb;', 'float scalarOpacity = texture2D(pwfTexture1, vec2(intensity * pwfscale0 + pwfshift0, 0.5)).r;', 'gl_FragData[0] = vec4(tcolor, scalarOpacity * opacity);', ]); break; case 2: tcoordFSImpl = tcoordFSImpl.concat([ 'float intensity = tvalue.r*cscale0 + cshift0;', 'gl_FragData[0] = vec4(texture2D(colorTexture1, vec2(intensity, 0.5)).rgb, pwfscale0*tvalue.g + pwfshift0);', ]); break; case 3: tcoordFSImpl = tcoordFSImpl.concat([ 'vec4 tcolor = cscale0*tvalue + cshift0;', 'gl_FragData[0] = vec4(texture2D(colorTexture1, vec2(tcolor.r,0.5)).r,', ' texture2D(colorTexture1, vec2(tcolor.g,0.5)).r,', ' texture2D(colorTexture1, vec2(tcolor.b,0.5)).r, opacity);', ]); break; default: tcoordFSImpl = tcoordFSImpl.concat([ 'vec4 tcolor = cscale0*tvalue + cshift0;', 'gl_FragData[0] = vec4(texture2D(colorTexture1, vec2(tcolor.r,0.5)).r,', ' texture2D(colorTexture1, vec2(tcolor.g,0.5)).r,', ' texture2D(colorTexture1, vec2(tcolor.b,0.5)).r, tcolor.a);', ]); } } FSSource = vtkShaderProgram.substitute( FSSource, '//VTK::TCoord::Impl', tcoordFSImpl ).result; // Picking shader replacements if (model.haveSeenDepthRequest) { FSSource = vtkShaderProgram.substitute( FSSource, '//VTK::ZBuffer::Dec', 'uniform int depthRequest;' ).result; FSSource = vtkShaderProgram.substitute(FSSource, '//VTK::ZBuffer::Impl', [ 'if (depthRequest == 1) {', 'float iz = floor(gl_FragCoord.z*65535.0 + 0.1);', 'float rf = floor(iz/256.0)/255.0;', 'float gf = mod(iz,256.0)/255.0;', 'gl_FragData[0] = vec4(rf, gf, 0.0, 1.0); }', ]).result; } shaders.Vertex = VSSource; shaders.Fragment = FSSource; publicAPI.replaceShaderClip(shaders, ren, actor); publicAPI.replaceShaderCoincidentOffset(shaders, ren, actor); }; publicAPI.replaceShaderClip = (shaders, ren, actor) => { let VSSource = shaders.Vertex; let FSSource = shaders.Fragment; if (model.renderable.getNumberOfClippingPlanes()) { let numClipPlanes = model.renderable.getNumberOfClippingPlanes(); if (numClipPlanes > 6) { macro.vtkErrorMacro('OpenGL has a limit of 6 clipping planes'); numClipPlanes = 6; } VSSource = vtkShaderProgram.substitute(VSSource, '//VTK::Clip::Dec', [ 'uniform int numClipPlanes;', 'uniform vec4 clipPlanes[6];', 'varying float clipDistancesVSOutput[6];', ]).result; VSSource = vtkShaderProgram.substitute(VSSource, '//VTK::Clip::Impl', [ 'for (int planeNum = 0; planeNum < 6; planeNum++)', ' {', ' if (planeNum >= numClipPlanes)', ' {', ' break;', ' }', ' clipDistancesVSOutput[planeNum] = dot(clipPlanes[planeNum], vertexMC);', ' }', ]).result; FSSource = vtkShaderProgram.substitute(FSSource, '//VTK::Clip::Dec', [ 'uniform int numClipPlanes;', 'varying float clipDistancesVSOutput[6];', ]).result; FSSource = vtkShaderProgram.substitute(FSSource, '//VTK::Clip::Impl', [ 'for (int planeNum = 0; planeNum < 6; planeNum++)', ' {', ' if (planeNum >= numClipPlanes)', ' {', ' break;', ' }', ' if (clipDistancesVSOutput[planeNum] < 0.0) discard;', ' }', ]).result; } shaders.Vertex = VSSource; shaders.Fragment = FSSource; }; publicAPI.getShaderTemplate = (shaders, ren, actor) => { shaders.Vertex = vtkPolyDataVS; shaders.Fragment = vtkPolyDataFS; shaders.Geometry = ''; }; publicAPI.setMapperShaderParameters = (cellBO, ren, actor) => { const program = cellBO.getProgram(); const cellArrayBufferObject = cellBO.getCABO(); if ( cellArrayBufferObject.getElementCount() && (model.VBOBuildTime.getMTime() > cellBO.getAttributeUpdateTime().getMTime() || cellBO.getShaderSourceTime().getMTime() > cellBO.getAttributeUpdateTime().getMTime()) ) { if (program.isAttributeUsed('vertexMC')) { if ( !cellBO .getVAO() .addAttributeArray( program, cellArrayBufferObject, 'vertexMC', cellArrayBufferObject.getVertexOffset(), cellArrayBufferObject.getStride(), model.context.FLOAT, 3, model.context.FALSE ) ) { vtkErrorMacro('Error setting vertexMC in shader VAO.'); } } // Custom data of the CABO (centerlinePosition, centerlineTopDirection, // centerlineBotDirection, quadIndex and user defined custom data) cellBO .getCABO() .getCustomData() .forEach((data) => { if ( data && program.isAttributeUsed(data.name) && !cellBO .getVAO() .addAttributeArray( program, cellArrayBufferObject, data.name, data.offset, cellArrayBufferObject.getStride(), model.context.FLOAT, data.components, model.context.FALSE ) ) { vtkErrorMacro(`Error setting ${data.name} in shader VAO.`); } }); cellBO.getAttributeUpdateTime().modified(); } const texUnit = model.volumeTexture.getTextureUnit(); program.setUniformi('volumeTexture', texUnit); program.setUniformf('width', model.renderable.getWidth()); cellBO .getProgram() .setUniform4fv('backgroundColor', model.renderable.getBackgroundColor()); if (program.isUniformUsed('tangentDirection')) { const tangentDirection = model.renderable.getTangentDirection(); cellBO .getProgram() .setUniform3fArray('tangentDirection', tangentDirection); } if (program.isUniformUsed('bitangentDirection')) { const bitangentDirection = model.renderable.getBitangentDirection(); cellBO .getProgram() .setUniform3fArray('bitangentDirection', bitangentDirection); } if (program.isUniformUsed('centerlineOrientation')) { const uniformOrientation = model.renderable.getUniformOrientation(); cellBO .getProgram() .setUniform4fv('centerlineOrientation', uniformOrientation); } if (program.isUniformUsed('globalCenterPoint')) { const centerPoint = model.renderable.getCenterPoint(); program.setUniform3fArray('globalCenterPoint', centerPoint); } // Projection uniforms if (model.renderable.isProjectionEnabled()) { const image = model.currentImageDataInput; const spacing = image.getSpacing(); const dimensions = image.getDimensions(); const projectionSlabThickness = model.renderable.getProjectionSlabThickness(); const projectionSlabNumberOfSamples = model.renderable.getProjectionSlabNumberOfSamples(); const volumeSize = vec3.mul([], spacing, dimensions); program.setUniform3fArray('volumeSizeMC', volumeSize); program.setUniformi( 'projectionSlabNumberOfSamples', projectionSlabNumberOfSamples ); const constantOffset = -0.5 * projectionSlabThickness; program.setUniformf('projectionConstantOffset', constantOffset); const stepLength = projectionSlabThickness / (projectionSlabNumberOfSamples - 1); program.setUniformf('projectionStepLength', stepLength); } // Model coordinates to image space // getWorldToIndex is badly named and is in fact modelToIndex // MCIC -> Model coordinates to index coordinates // MCTC -> Model coordinates to texture coordinates const image = model.currentImageDataInput; const MCICMatrix = image.getWorldToIndex(); const ICTCMatrix = mat4.fromScaling( new Float32Array(16), vec3.inverse([], image.getDimensions()) ); const MCTCMatrix = mat4.mul(ICTCMatrix, ICTCMatrix, MCICMatrix); program.setUniformMatrix('MCTCMatrix', MCTCMatrix); if (model.haveSeenDepthRequest) { cellBO .getProgram() .setUniformi('depthRequest', model.renderDepth ? 1 : 0); } if (model.renderable.getNumberOfClippingPlanes()) { // add all the clipping planes let numClipPlanes = model.renderable.getNumberOfClippingPlanes(); if (numClipPlanes > 6) { macro.vtkErrorMacro('OpenGL has a limit of 6 clipping planes'); numClipPlanes = 6; } const shiftScaleEnabled = cellArrayBufferObject.getCoordShiftAndScaleEnabled(); const inverseShiftScaleMatrix = shiftScaleEnabled ? cellArrayBufferObject.getInverseShiftAndScaleMatrix() : null; const mat = inverseShiftScaleMatrix ? mat4.copy(model.imagematinv, actor.getMatrix()) : actor.getMatrix(); if (inverseShiftScaleMatrix) { mat4.transpose(mat, mat); mat4.multiply(mat, mat, inverseShiftScaleMatrix); mat4.transpose(mat, mat); } // transform crop plane normal with transpose(inverse(worldToIndex)) mat4.transpose( model.imagemat, model.currentImageDataInput.getIndexToWorld() ); mat4.multiply(model.imagematinv, mat, model.imagemat); const planeEquations = []; for (let i = 0; i < numClipPlanes; i++) { const planeEquation = []; model.renderable.getClippingPlaneInDataCoords( model.imagematinv, i, planeEquation ); for (let j = 0; j < 4; j++) { planeEquations.push(planeEquation[j]); } } program.setUniformi('numClipPlanes', numClipPlanes); program.setUniform4fv('clipPlanes', planeEquations); } // handle coincident if (program.isUniformUsed('coffset')) { const cp = publicAPI.getCoincidentParameters(ren, actor); program.setUniformf('coffset', cp.offset); // cfactor isn't always used when coffset is. if (program.isUniformUsed('cfactor')) { program.setUniformf('cfactor', cp.factor); } } }; publicAPI.setCameraShaderParameters = (cellBO, ren, actor) => { const MCWCMatrix = model.openGLImageSlice.getKeyMatrices().mcwc; const WCPCMatrix = model.openGLCamera.getKeyMatrices(ren).wcpc; mat4.multiply(model.imagemat, WCPCMatrix, MCWCMatrix); if (cellBO.getCABO().getCoordShiftAndScaleEnabled()) { const inverseShiftScaleMat = cellBO .getCABO() .getInverseShiftAndScaleMatrix(); mat4.multiply(model.imagemat, model.imagemat, inverseShiftScaleMat); } cellBO.getProgram().setUniformMatrix('MCPCMatrix', model.imagemat); }; publicAPI.setPropertyShaderParameters = (cellBO, ren, actor) => { const program = cellBO.getProgram(); const ppty = actor.getProperty(); const opacity = ppty.getOpacity(); program.setUniformf('opacity', opacity); // Component mix // Independent components: Mixed according to component weights // Dependent components: Mixed using the following logic: // - 2 comps => LA // - 3 comps => RGB + opacity from pwf // - 4 comps => RGBA const numComp = model.volumeTexture.getComponents(); const iComps = ppty.getIndependentComponents(); if (iComps) { for (let i = 0; i < numComp; ++i) { program.setUniformf(`mix${i}`, ppty.getComponentWeight(i)); } } // Color opacity map const volInfo = model.volumeTexture.getVolumeInfo(); // three levels of shift scale combined into one // for performance in the fragment shader for (let i = 0; i < numComp; i++) { let cw = ppty.getColorWindow(); let cl = ppty.getColorLevel(); const target = iComps ? i : 0; const cfun = ppty.getRGBTransferFunction(target); if (cfun && ppty.getUseLookupTableScalarRange()) { const cRange = cfun.getRange(); cw = cRange[1] - cRange[0]; cl = 0.5 * (cRange[1] + cRange[0]); } const scale = volInfo.scale[i] / cw; const shift = (volInfo.offset[i] - cl) / cw + 0.5; program.setUniformf(`cshift${i}`, shift); program.setUniformf(`cscale${i}`, scale); } const texColorUnit = model.colorTexture.getTextureUnit(); // TODO program.setUniformi('colorTexture1', texColorUnit); // pwf shift/scale for (let i = 0; i < numComp; i++) { let pwfScale = 1.0; let pwfShift = 0.0; const target = iComps ? i : 0; const pwfun = ppty.getPiecewiseFunction(target); if (pwfun) { const pwfRange = pwfun.getRange(); const length = pwfRange[1] - pwfRange[0]; const mid = 0.5 * (pwfRange[0] + pwfRange[1]); pwfScale = volInfo.scale[i] / length; pwfShift = (volInfo.offset[i] - mid) / length + 0.5; } program.setUniformf(`pwfshift${i}`, pwfShift); program.setUniformf(`pwfscale${i}`, pwfScale); } const texOpacityUnit = model.pwfTexture.getTextureUnit(); // TODO program.setUniformi('pwfTexture1', texOpacityUnit); }; publicAPI.updateShaders = (cellBO, ren, actor) => { // has something changed that would require us to recreate the shader? if (publicAPI.getNeedToRebuildShaders(cellBO, ren, actor)) { const shaders = { Vertex: null, Fragment: null, Geometry: null }; publicAPI.buildShaders(shaders, ren, actor); // compile and bind the program if needed const newShader = model._openGLRenderWindow .getShaderCache() .readyShaderProgramArray( shaders.Vertex, shaders.Fragment, shaders.Geometry ); // if the shader changed reinitialize the VAO if (newShader !== cellBO.getProgram()) { cellBO.setProgram(newShader); // reset the VAO as the shader has changed cellBO.getVAO().releaseGraphicsResources(); } cellBO.getShaderSourceTime().modified(); } else { model._openGLRenderWindow .getShaderCache() .readyShaderProgram(cellBO.getProgram()); } cellBO.getVAO().bind(); publicAPI.setMapperShaderParameters(cellBO, ren, actor); publicAPI.setCameraShaderParameters(cellBO, ren, actor); publicAPI.setPropertyShaderParameters(cellBO, ren, actor); }; publicAPI.delete = macro.chain(() => { if (model._openGLRenderWindow) { unregisterGraphicsResources(model._openGLRenderWindow); } }, publicAPI.delete); } // ---------------------------------------------------------------------------- // Object factory // ---------------------------------------------------------------------------- const DEFAULT_VALUES = { currentRenderPass: null, volumeTexture: null, colorTexture: null, pwfTexture: null, tris: null, lastHaveSeenDepthRequest: false, haveSeenDepthRequest: false, lastTextureComponents: 0, lastIndependentComponents: 0, imagemat: null, imagematinv: null, // _scalars: null, // _colorTransferFunc: null, // _pwFunc: null, }; // ---------------------------------------------------------------------------- export function extend(publicAPI, model, initialValues = {}) { Object.assign(model, DEFAULT_VALUES, initialValues); // Inheritance vtkViewNode.extend(publicAPI, model, initialValues); vtkReplacementShaderMapper.implementReplaceShaderCoincidentOffset( publicAPI, model, initialValues ); // Two inputs: one for the ImageData/Texture and one for the PolyData (centerline) macro.algo(publicAPI, model, 2, 0); model.tris = vtkHelper.newInstance(); model.volumeTexture = null; model.colorTexture = null; model.pwfTexture = null; model.imagemat = mat4.identity(new Float64Array(16)); model.imagematinv = mat4.identity(new Float64Array(16)); model.VBOBuildTime = {}; macro.obj(model.VBOBuildTime, { mtime: 0 }); // Object methods vtkOpenGLImageCPRMapper(publicAPI, model); } // ---------------------------------------------------------------------------- export const newInstance = macro.newInstance(extend, 'vtkOpenGLImageCPRMapper'); export const STATIC = {}; // ---------------------------------------------------------------------------- export default { newInstance, extend, ...STATIC }; // Register ourself to OpenGL backend if imported registerOverride('vtkImageCPRMapper', newInstance); |