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
|
// SPDX-FileCopyrightText: Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
// SPDX-License-Identifier: BSD-3-Clause
#include "vtkTesting.h"
#include "vtkAlgorithmOutput.h"
#include "vtkDataArray.h"
#include "vtkDataArrayRange.h"
#include "vtkDataSet.h"
#include "vtkDoubleArray.h"
#include "vtkDummyController.h"
#include "vtkFloatArray.h"
#include "vtkImageClip.h"
#include "vtkImageData.h"
#include "vtkImageDifference.h"
#include "vtkImageExtractComponents.h"
#include "vtkImageRGBToXYZ.h"
#include "vtkImageSSIM.h"
#include "vtkImageShiftScale.h"
#include "vtkImageXYZToLAB.h"
#include "vtkInformation.h"
#include "vtkInteractorEventRecorder.h"
#include "vtkLogger.h"
#include "vtkMultiProcessController.h"
#include "vtkNew.h"
#include "vtkObjectFactory.h"
#include "vtkPNGReader.h"
#include "vtkPNGWriter.h"
#include "vtkPointData.h"
#include "vtkPointSet.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkSmartPointer.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkTimerLog.h"
#include "vtkWindowToImageFilter.h"
#include "vtkImageRGBToHSI.h"
#include <sstream>
#include <vtksys/SystemTools.hxx>
#include <array>
#include <numeric>
#ifdef __EMSCRIPTEN__
#include "vtkTestUtilities.h"
#endif
#include "vtkXMLImageDataWriter.h"
VTK_ABI_NAMESPACE_BEGIN
vtkStandardNewMacro(vtkTesting);
vtkCxxSetObjectMacro(vtkTesting, RenderWindow, vtkRenderWindow);
using std::string;
using std::vector;
//------------------------------------------------------------------------------
// Find in command tail, failing that find in environment,
// failing that return a default.
// Up to caller to delete the string returned.
static string vtkTestingGetArgOrEnvOrDefault(
const string& argName, // argument idnetifier flag. eg "-D"
vector<string>& argv, // command tail
const string& env, // environment variable name to find
const string& def) // default to use if "env" is not found.
{
string argValue;
// Search command tail.
int argc = static_cast<int>(argv.size());
for (int i = 0; i < argc; i++)
{
if ((i < (argc - 1)) && (argName == argv[i]))
{
argValue = argv[i + 1];
}
}
// If not found search environment.
if (argValue.empty() && !(env.empty() || def.empty()))
{
char* foundenv = getenv(env.c_str());
if (foundenv)
{
argValue = foundenv;
}
else
{
// Not found, fall back to default.
argValue = def;
}
}
return argValue;
}
//------------------------------------------------------------------------------
// Description:
// Sum the L2 Norm point wise over all tuples. Each term
// is scaled by the magnitude of one of the inputs.
// Return sum and the number of terms.
template <class T>
vtkIdType AccumulateScaledL2Norm(T* pA, // pointer to first data array
T* pB, // pointer to second data array
vtkIdType nTups, // number of tuples
int nComps, // number of comps
double& SumModR) // result
{
//
SumModR = 0.0;
for (vtkIdType i = 0; i < nTups; ++i)
{
double modR = 0.0;
double modA = 0.0;
for (int q = 0; q < nComps; ++q)
{
double a = pA[q];
double b = pB[q];
modA += a * a;
double r = b - a;
modR += r * r;
}
modA = sqrt(modA);
modA = modA < 1.0 ? 1.0 : modA;
SumModR += sqrt(modR) / modA;
pA += nComps;
pB += nComps;
}
return nTups;
}
//=============================================================================
vtkTesting::vtkTesting()
{
this->FrontBuffer = 0;
this->RenderWindow = nullptr;
this->ValidImageFileName = nullptr;
this->ImageDifference = 0;
this->DataRoot = nullptr;
this->TempDirectory = nullptr;
this->BorderOffset = 0;
this->Verbose = 0;
this->Controller = vtkSmartPointer<vtkDummyController>::New();
// on construction we start the timer
this->StartCPUTime = vtkTimerLog::GetCPUTime();
this->StartWallTime = vtkTimerLog::GetUniversalTime();
}
//------------------------------------------------------------------------------
vtkTesting::~vtkTesting()
{
this->SetRenderWindow(nullptr);
this->SetValidImageFileName(nullptr);
this->SetDataRoot(nullptr);
this->SetTempDirectory(nullptr);
}
//------------------------------------------------------------------------------
vtkMultiProcessController* vtkTesting::GetController() const
{
return this->Controller;
}
//------------------------------------------------------------------------------
void vtkTesting::SetController(vtkMultiProcessController* controller)
{
vtkSetSmartPointerBodyMacro(Controller, vtkMultiProcessController, controller);
if (!this->Controller)
{
this->Controller = vtkSmartPointer<vtkDummyController>::New();
}
}
//------------------------------------------------------------------------------
void vtkTesting::AddArgument(const char* arg)
{
this->Args.emplace_back(arg);
}
//------------------------------------------------------------------------------
void vtkTesting::AddArguments(int argc, const char** argv)
{
for (int i = 0; i < argc; ++i)
{
this->Args.emplace_back(argv[i]);
}
}
//------------------------------------------------------------------------------
void vtkTesting::AddArguments(int argc, char** argv)
{
for (int i = 0; i < argc; ++i)
{
this->Args.emplace_back(argv[i]);
}
}
//------------------------------------------------------------------------------
char* vtkTesting::GetArgument(const char* argName)
{
string argValue = vtkTestingGetArgOrEnvOrDefault(argName, this->Args, "", "");
char* cArgValue = new char[argValue.size() + 1];
strcpy(cArgValue, argValue.c_str());
return cArgValue;
}
//------------------------------------------------------------------------------
void vtkTesting::CleanArguments()
{
this->Args.erase(this->Args.begin(), this->Args.end());
}
//------------------------------------------------------------------------------
const char* vtkTesting::GetDataRoot()
{
#ifdef VTK_DATA_ROOT
string dr = vtkTestingGetArgOrEnvOrDefault("-D", this->Args, "VTK_DATA_ROOT", VTK_DATA_ROOT);
#else
string dr =
vtkTestingGetArgOrEnvOrDefault("-D", this->Args, "VTK_DATA_ROOT", "../../../../VTKData");
#endif
this->SetDataRoot(vtksys::SystemTools::CollapseFullPath(dr).c_str());
return this->DataRoot;
}
//------------------------------------------------------------------------------
const char* vtkTesting::GetTempDirectory()
{
string td =
vtkTestingGetArgOrEnvOrDefault("-T", this->Args, "VTK_TEMP_DIR", "../../../Testing/Temporary");
this->SetTempDirectory(vtksys::SystemTools::CollapseFullPath(td).c_str());
return this->TempDirectory;
}
//------------------------------------------------------------------------------
const char* vtkTesting::GetValidImageFileName()
{
this->SetValidImageFileName(nullptr);
if (!this->IsValidImageSpecified())
{
return this->ValidImageFileName;
}
string baseline =
vtkTestingGetArgOrEnvOrDefault("-B", this->Args, "VTK_BASELINE_ROOT", this->GetDataRoot());
for (size_t i = 0; i < (this->Args.size() - 1); ++i)
{
if (this->Args[i] == "-V")
{
const char* ch = this->Args[i + 1].c_str();
if (ch[0] == '/'
#if defined(_WIN32) || \
defined(__EMSCRIPTEN__) // Emscripten too, because the file could be on a windows server.
|| (ch[0] >= 'a' && ch[0] <= 'z' && ch[1] == ':') ||
(ch[0] >= 'A' && ch[0] <= 'Z' && ch[1] == ':')
#endif
)
{
baseline = this->Args[i + 1];
}
else
{
baseline += "/";
baseline += this->Args[i + 1];
}
break;
}
}
this->SetValidImageFileName(baseline.c_str());
return this->ValidImageFileName;
}
//------------------------------------------------------------------------------
bool vtkTesting::GetMesaVersion(vtkRenderWindow* renderWindow, int version[3])
{
const std::string glCaps = renderWindow->ReportCapabilities();
bool mesaInUse = glCaps.find("OpenGL vendor string: Mesa/X.org") != std::string::npos;
if (!mesaInUse)
{
return false;
}
const char* versionPtr =
vtksys::SystemTools::FindLastString(glCaps.c_str(), "OpenGL version string");
const auto lines = vtksys::SystemTools::SplitString(std::string(versionPtr), '\n');
const auto words = vtksys::SystemTools::SplitString(lines[0], ' ');
auto versionIter = std::find(words.begin(), words.end(), "Mesa");
if (versionIter != words.end())
{
const auto versionString = (++versionIter)->c_str();
const auto versionNumbers = vtksys::SystemTools::SplitString(versionString, '.');
for (int i = 0; i < 3; ++i)
{
version[i] = std::stoi(versionNumbers[i]);
}
}
return true;
}
//------------------------------------------------------------------------------
int vtkTesting::IsInteractiveModeSpecified()
{
for (size_t i = 0; i < this->Args.size(); ++i)
{
if (this->Args[i] == "-I")
{
return 1;
}
}
return 0;
}
//------------------------------------------------------------------------------
int vtkTesting::IsFlagSpecified(const char* flag)
{
for (size_t i = 0; i < this->Args.size(); ++i)
{
if (this->Args[i] == flag)
{
return 1;
}
}
return 0;
}
//------------------------------------------------------------------------------
int vtkTesting::IsValidImageSpecified()
{
for (size_t i = 1; i < this->Args.size(); ++i)
{
if (this->Args[i - 1] == "-V")
{
return 1;
}
}
return 0;
}
//------------------------------------------------------------------------------
char* vtkTesting::IncrementFileName(const char* fname, int count)
{
char counts[256];
snprintf(counts, sizeof(counts), "%d", count);
int orgLen = static_cast<int>(strlen(fname));
if (orgLen < 5)
{
return nullptr;
}
int extLen = static_cast<int>(strlen(counts));
char* newFileName = new char[orgLen + extLen + 2];
strcpy(newFileName, fname);
newFileName[orgLen - 4] = '_';
int i, marker;
for (marker = orgLen - 3, i = 0; marker < orgLen - 3 + extLen; marker++, i++)
{
newFileName[marker] = counts[i];
}
strcpy(newFileName + marker, ".png");
return newFileName;
}
//------------------------------------------------------------------------------
int vtkTesting::LookForFile(const char* newFileName)
{
if (!newFileName)
{
return 0;
}
vtksys::SystemTools::Stat_t fs;
if (vtksys::SystemTools::Stat(newFileName, &fs) != 0)
{
return 0;
}
else
{
return 1;
}
}
//------------------------------------------------------------------------------
void vtkTesting::SetFrontBuffer(vtkTypeBool frontBuffer)
{
vtkWarningMacro("SetFrontBuffer method is deprecated and has no effect anymore.");
this->FrontBuffer = frontBuffer;
}
//------------------------------------------------------------------------------
int vtkTesting::RegressionTest(vtkAlgorithm* imageSource, double thresh)
{
int result = this->RegressionTest(imageSource, thresh, cout);
cout << "<DartMeasurement name=\"WallTime\" type=\"numeric/double\">";
cout << vtkTimerLog::GetUniversalTime() - this->StartWallTime;
cout << "</DartMeasurement>\n";
cout << "<DartMeasurement name=\"CPUTime\" type=\"numeric/double\">";
cout << vtkTimerLog::GetCPUTime() - this->StartCPUTime;
cout << "</DartMeasurement>\n";
return result;
}
//------------------------------------------------------------------------------
int vtkTesting::RegressionTestAndCaptureOutput(double thresh, ostream& os)
{
int result = this->RegressionTest(thresh, os);
os << "<DartMeasurement name=\"WallTime\" type=\"numeric/double\">";
os << vtkTimerLog::GetUniversalTime() - this->StartWallTime;
os << "</DartMeasurement>\n";
os << "<DartMeasurement name=\"CPUTime\" type=\"numeric/double\">";
os << vtkTimerLog::GetCPUTime() - this->StartCPUTime;
os << "</DartMeasurement>\n";
return result;
}
//------------------------------------------------------------------------------
int vtkTesting::RegressionTest(double thresh)
{
int result = this->RegressionTest(thresh, cout);
return result;
}
//------------------------------------------------------------------------------
int vtkTesting::RegressionTest(double thresh, ostream& os)
{
vtkNew<vtkWindowToImageFilter> rtW2if;
rtW2if->SetInput(this->RenderWindow);
for (unsigned int i = 0; i < this->Args.size(); ++i)
{
if ("-FrontBuffer" == this->Args[i])
{
vtkWarningMacro("-FrontBuffer option is deprecated and has no effet anymore.");
this->FrontBufferOn();
}
else if ("-NoRerender" == this->Args[i])
{
rtW2if->ShouldRerenderOff();
}
}
std::ostringstream out1;
// perform and extra render to make sure it is displayed
int swapBuffers = this->RenderWindow->GetSwapBuffers();
// since we're reading from back-buffer, it's essential that we turn off swapping
// otherwise what remains in the back-buffer after the swap is undefined by OpenGL specs.
this->RenderWindow->SwapBuffersOff();
this->RenderWindow->Render();
rtW2if->ReadFrontBufferOff();
rtW2if->Update();
this->RenderWindow->SetSwapBuffers(swapBuffers); // restore swap state.
int res = this->RegressionTest(rtW2if, thresh, out1);
int recvRes;
this->Controller->AllReduce(&res, &recvRes, 1, vtkCommunicator::MIN_OP);
if (recvRes == FAILED)
{
std::ostringstream out2;
// tell it to read front buffer
rtW2if->ReadFrontBufferOn();
rtW2if->Update();
res = this->RegressionTest(rtW2if, thresh, out2);
this->Controller->AllReduce(&res, &recvRes, 1, vtkCommunicator::MAX_OP);
// If both tests fail, rerun the backbuffer tests to recreate the test
// image. Otherwise an incorrect image will be uploaded to CDash.
if (recvRes == PASSED)
{
os << out2.str();
}
else
{
// we failed both back and front buffers so
// to help us debug, write out renderwindow capabilities
if (this->RenderWindow)
{
os << this->RenderWindow->ReportCapabilities();
}
rtW2if->ReadFrontBufferOff();
rtW2if->Update();
return this->RegressionTest(rtW2if, thresh, os);
}
}
else
{
os << out1.str();
}
return this->Controller->GetLocalProcessId() == 0 ? res : NOT_RUN;
}
//------------------------------------------------------------------------------
int vtkTesting::RegressionTest(const string& pngFileName, double thresh)
{
return this->RegressionTest(pngFileName, thresh, cout);
}
//------------------------------------------------------------------------------
int vtkTesting::RegressionTest(const string& pngFileName, double thresh, ostream& os)
{
vtkNew<vtkPNGReader> inputReader;
#ifdef __EMSCRIPTEN__
std::string sandboxName = vtkEmscriptenTestUtilities::PreloadDataFile(pngFileName.c_str());
inputReader->SetFileName(sandboxName.c_str());
#else
inputReader->SetFileName(pngFileName.c_str());
#endif
inputReader->Update();
vtkAlgorithm* src = inputReader;
vtkSmartPointer<vtkImageExtractComponents> extract;
// Convert rgba to rgb if needed
if (inputReader->GetOutput() && inputReader->GetOutput()->GetNumberOfScalarComponents() == 4)
{
extract = vtkSmartPointer<vtkImageExtractComponents>::New();
extract->SetInputConnection(src->GetOutputPort());
extract->SetComponents(0, 1, 2);
extract->Update();
src = extract;
}
return this->RegressionTest(src, thresh, os);
}
namespace
{
//------------------------------------------------------------------------------
std::array<double, 3> ComputeMinkowski(vtkDoubleArray* array, double (*f)(double))
{
std::array<double, 3> measure = {};
auto data = vtk::DataArrayTupleRange<3>(array);
for (auto lab : data)
{
for (int dim = 0; dim < 3; ++dim)
{
// The range of ssim values is [-1, 1]. By doing 1 - ssim value, we
// change the range to [0, 2]
measure[dim] += f(1.0 - lab[dim]);
}
}
// Normalize the measure
const vtkIdType div = array->GetNumberOfTuples();
for (int dim = 0; dim < 3; ++dim)
{
measure[dim] /= div;
}
return measure;
}
//------------------------------------------------------------------------------
std::array<double, 3> ComputeMinkowski1(vtkDoubleArray* array)
{
auto same = [](double v) -> double { return v; };
return ComputeMinkowski(array, same);
}
//------------------------------------------------------------------------------
std::array<double, 3> ComputeMinkowski2(vtkDoubleArray* array)
{
auto power2 = [](double v) { return v * v; };
auto measure = ComputeMinkowski(array, power2);
for (int dim = 0; dim < 3; ++dim)
{
measure[dim] = std::sqrt(measure[dim]);
}
return measure;
}
//------------------------------------------------------------------------------
std::array<double, 3> ComputeWasserstein(vtkDoubleArray* array, std::uint64_t (*f)(std::uint64_t))
{
std::array<double, 3> measure = {};
auto data = vtk::DataArrayTupleRange<3>(array);
constexpr std::uint64_t N = 200;
std::array<std::uint64_t, N> hist[3] = {};
for (auto lab : data)
{
for (int dim = 0; dim < 3; ++dim)
{
// The range of ssim values is [-1, 1], so we rescale it to [0, 1]
double value = (lab[dim] + 1.0) / 2.0;
// Find the bucket to place the value in, by rescaling it to [0, N - 1]
// [0, (N - 1) / 2] is for negative ssim values,
// N / 2 is for ssim = 0,
// ((N + 1) / 2, N - 1] is for positive ssim values
auto bucket = static_cast<std::uint64_t>(std::round(value * (N - 1)));
++hist[dim][bucket];
}
}
for (int dim = 0; dim < 3; ++dim)
{
// Compute the cumulative frequency distribution
std::array<std::uint64_t, N> cfd;
std::partial_sum(hist[dim].begin(), hist[dim].end(), cfd.begin());
for (std::size_t i = 0; i < N - 1; ++i)
{
measure[dim] += f(cfd[i]);
}
}
// Normalize the measure
const vtkIdType div = f(static_cast<std::uint64_t>(array->GetNumberOfTuples())) * (N - 1);
for (int dim = 0; dim < 3; ++dim)
{
measure[dim] /= div;
}
return measure;
}
//------------------------------------------------------------------------------
std::array<double, 3> ComputeWasserstein1(vtkDoubleArray* array)
{
auto same = [](std::uint64_t v) -> std::uint64_t { return v; };
return ComputeWasserstein(array, same);
}
//------------------------------------------------------------------------------
std::array<double, 3> ComputeWasserstein2(vtkDoubleArray* array)
{
auto power2 = [](std::uint64_t v) { return v * v; };
auto measure = ComputeWasserstein(array, power2);
for (int dim = 0; dim < 3; ++dim)
{
measure[dim] = std::sqrt(measure[dim]);
}
return measure;
}
} // anonymous namespace
//------------------------------------------------------------------------------
int vtkTesting::RegressionTest(vtkAlgorithm* imageSource, double thresh, ostream& os)
{
// do a get to compute the real value
this->GetValidImageFileName();
string tmpDir = this->GetTempDirectory();
// construct the names for the error images
string validName = this->ValidImageFileName;
string::size_type slashPos = validName.rfind('/');
if (slashPos != string::npos)
{
validName = validName.substr(slashPos + 1);
}
// We want to print the filename of the best matching image for better
// comparisons in CDash:
string bestImageFileName = this->ValidImageFileName;
// check the valid image
#ifdef __EMSCRIPTEN__
vtkEmscriptenTestUtilities::PreloadDataFile(this->ValidImageFileName, validName);
FILE* rtFin = vtksys::SystemTools::Fopen(validName, "r");
#else
FILE* rtFin = vtksys::SystemTools::Fopen(this->ValidImageFileName, "r");
#endif
if (rtFin)
{
fclose(rtFin);
}
else // there was no valid image, so write one to the temp dir
{
string vImage = tmpDir + "/" + validName;
#ifdef __EMSCRIPTEN__
vtkNew<vtkPNGWriter> rtPngw;
rtPngw->SetWriteToMemory(true);
rtPngw->SetInputConnection(imageSource->GetOutputPort());
rtPngw->Write();
auto* result = rtPngw->GetResult();
vtkEmscriptenTestUtilities::DumpFile(
vImage, result->GetPointer(0), result->GetDataTypeSize() * result->GetDataSize());
os << "<DartMeasurement name=\"ImageNotFound\" type=\"text/string\">"
<< this->ValidImageFileName << "</DartMeasurement>" << endl;
// Write out the image upload tag for the test image.
os << "<DartMeasurementFile name=\"TestImage\" type=\"image/png\">";
os << vImage;
os << "</DartMeasurementFile>";
#else
rtFin = vtksys::SystemTools::Fopen(vImage, "wb");
if (rtFin)
{
fclose(rtFin);
vtkNew<vtkPNGWriter> rtPngw;
rtPngw->SetFileName(vImage.c_str());
rtPngw->SetInputConnection(imageSource->GetOutputPort());
rtPngw->Write();
os << "<DartMeasurement name=\"ImageNotFound\" type=\"text/string\">"
<< this->ValidImageFileName << "</DartMeasurement>" << endl;
// Write out the image upload tag for the test image.
os << "<DartMeasurementFile name=\"TestImage\" type=\"image/png\">";
os << vImage;
os << "</DartMeasurementFile>";
}
else
{
vtkErrorMacro("Could not open file '" << vImage << "' for writing.");
}
#endif
return FAILED;
}
imageSource->Update();
vtkNew<vtkPNGReader> rtPng;
#ifdef __EMSCRIPTEN__
rtPng->SetFileName(validName.c_str());
#else
rtPng->SetFileName(this->ValidImageFileName);
#endif
rtPng->Update();
vtkNew<vtkImageExtractComponents> rtExtract;
rtExtract->SetInputConnection(rtPng->GetOutputPort());
rtExtract->SetComponents(0, 1, 2);
rtExtract->Update();
auto createLegacyDiffFilter = [](vtkAlgorithm* source, vtkAlgorithm* extract) {
auto alg = vtkSmartPointer<vtkAlgorithm>::Take(vtkImageDifference::New());
alg->SetInputConnection(source->GetOutputPort());
alg->SetInputConnection(1, extract->GetOutputPort());
return alg;
};
auto createSSIMFilter = [](vtkAlgorithm* source, vtkAlgorithm* extract) {
auto createPipeline = [](vtkAlgorithm* alg) {
vtkNew<vtkImageShiftScale> normalizer;
vtkNew<vtkImageRGBToXYZ> rgb2xyz;
vtkNew<vtkImageXYZToLAB> xyz2lab;
normalizer->SetScale(1.0 / 255);
normalizer->SetOutputScalarTypeToDouble();
normalizer->SetInputConnection(alg->GetOutputPort());
rgb2xyz->SetInputConnection(normalizer->GetOutputPort());
xyz2lab->SetInputConnection(rgb2xyz->GetOutputPort());
return xyz2lab;
};
auto pipeline1 = createPipeline(source);
auto pipeline2 = createPipeline(extract);
auto ssim = vtkImageSSIM::New();
ssim->SetInputToLab();
ssim->ClampNegativeValuesOn();
auto alg = vtkSmartPointer<vtkAlgorithm>::Take(ssim);
alg->SetInputConnection(pipeline1->GetOutputPort());
alg->SetInputConnection(1, pipeline2->GetOutputPort());
return alg;
};
vtkNew<vtkImageClip> ic1;
ic1->SetClipData(1);
ic1->SetInputConnection(imageSource->GetOutputPort());
vtkNew<vtkImageClip> ic2;
ic2->SetClipData(1);
ic2->SetInputConnection(rtExtract->GetOutputPort());
int* wExt1 = ic1->GetInputInformation()->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT());
int* wExt2 = ic2->GetInputInformation()->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT());
ic1->SetOutputWholeExtent(wExt1[0] + this->BorderOffset, wExt1[1] - this->BorderOffset,
wExt1[2] + this->BorderOffset, wExt1[3] - this->BorderOffset, wExt1[4], wExt1[5]);
ic2->SetOutputWholeExtent(wExt2[0] + this->BorderOffset, wExt2[1] - this->BorderOffset,
wExt2[2] + this->BorderOffset, wExt2[3] - this->BorderOffset, wExt2[4], wExt2[5]);
int ext1[6], ext2[6];
ic1->Update();
ic1->GetOutput()->GetExtent(ext1);
ic2->Update();
ic2->GetOutput()->GetExtent(ext2);
double minError = VTK_DOUBLE_MAX;
enum
{
LEGACY,
LOOSE,
TIGHT,
NONE
};
int imageCompareMethod = [] {
auto imageCompareString = [] {
if (!vtksys::SystemTools::HasEnv("VTK_TESTING_IMAGE_COMPARE_METHOD"))
{
vtkLog(WARNING, "Environment variable VTK_TESTING_IMAGE_COMPARE_METHOD is not set.");
return std::string("LEGACY_VALID");
}
return std::string(vtksys::SystemTools::GetEnv("VTK_TESTING_IMAGE_COMPARE_METHOD"));
}();
vtkLog(INFO, "Using " << imageCompareString << " image comparison method.");
if (imageCompareString == "LEGACY_VALID")
{
return LEGACY;
}
else if (imageCompareString == "TIGHT_VALID")
{
return TIGHT;
}
else if (imageCompareString == "LOOSE_VALID")
{
return LOOSE;
}
return NONE;
}();
auto rtId =
imageCompareMethod == LEGACY ? createLegacyDiffFilter(ic1, ic2) : createSSIMFilter(ic1, ic2);
auto executeComparison = [&](double& err) {
rtId->Update();
vtkDoubleArray* scalars = vtkArrayDownCast<vtkDoubleArray>(
vtkDataSet::SafeDownCast(rtId->GetOutputDataObject(0))->GetPointData()->GetScalars());
auto arrayMax = [](const std::array<double, 3>& v) {
return std::max(std::max(v[0], v[1]), v[2]);
};
if (imageCompareMethod == LEGACY)
{
err = vtkImageDifference::SafeDownCast(rtId)->GetThresholdedError();
}
else
{
auto mink1 = ComputeMinkowski1(scalars);
auto mink2 = ComputeMinkowski2(scalars);
auto wass1 = ComputeWasserstein1(scalars);
auto wass2 = ComputeWasserstein2(scalars);
vtkLog(INFO,
"When comparing images, error is defined as the maximum of all individual"
<< " values within the used method (TIGHT or LOOSE) using the threshold " << thresh);
vtkLog(
INFO, "Error computations on Lab channels using Minkownski and Wasserstein distances:");
vtkLog(INFO, "TIGHT_VALID metric (euclidian) :");
vtkLog(INFO, "mink2 = [" << mink2[0] << ", " << mink2[1] << ", " << mink2[2] << "]");
vtkLog(INFO, "wass2 = [" << wass2[0] << ", " << wass2[1] << ", " << wass2[2] << "]");
vtkLog(INFO, "LOOSE_VALID metric (manhattan / earth's mover) :");
vtkLog(INFO, "mink1 = [" << mink1[0] << ", " << mink1[1] << ", " << mink1[2] << "]");
vtkLog(INFO, "wass1 = [" << wass1[0] << ", " << wass1[1] << ", " << wass1[2] << "]");
vtkLog(INFO,
"Note: if the test fails but is visually acceptable, one can make the test pass"
<< " by changing the method (TIGHT_VALID vs LOOSE_VALID) and the threshold in CMake.");
switch (imageCompareMethod)
{
case TIGHT:
{
err = std::max(arrayMax(mink2), arrayMax(wass2));
break;
}
case LOOSE:
err = std::max(arrayMax(mink1), arrayMax(wass1));
break;
default:
vtkLog(ERROR,
"Image comparison method not set correctly."
<< " If not using the \"LEGACY_VALID\" method, it should be \"TIGHT_VALID\" or "
"\"LOOSE_VALID\");");
}
}
};
if ((ext2[1] - ext2[0]) == (ext1[1] - ext1[0]) && (ext2[3] - ext2[2]) == (ext1[3] - ext1[2]) &&
(ext2[5] - ext2[4]) == (ext1[5] - ext1[4]))
{
vtkLog(INFO, "Comparing baselines using the default image baseline.");
executeComparison(minError);
}
this->ImageDifference = minError;
int passed = 0;
if (minError <= thresh)
{
// Make sure there was actually a difference image before
// accepting the error measure.
vtkImageData* output = vtkImageData::SafeDownCast(rtId->GetOutputDataObject(0));
if (output)
{
int dims[3];
output->GetDimensions(dims);
if (dims[0] * dims[1] * dims[2] > 0)
{
passed = 1;
}
else
{
vtkErrorMacro("ImageDifference produced output with no data.");
}
}
else
{
vtkErrorMacro("ImageDifference did not produce output.");
}
}
// If the test failed with the first image (foo.png) check if there are
// images of the form foo_N.png (where N=1,2,3...) and compare against
// them.
double error;
int count = 1, errIndex = -1;
char* newFileName;
while (!passed)
{
newFileName = IncrementFileName(this->ValidImageFileName, count);
#ifdef __EMSCRIPTEN__
std::string hostFileName = std::string(newFileName);
// sandboxes the host file using the stem
std::string sandboxedFileName = vtksys::SystemTools::GetFilenameName(hostFileName);
vtkEmscriptenTestUtilities::PreloadDataFile(hostFileName.c_str(), sandboxedFileName);
// so that subsequent code uses the sandboxed file name instead of host file name.
delete[] newFileName;
newFileName = new char[sandboxedFileName.size() + 1];
strcpy(newFileName, sandboxedFileName.c_str());
#endif
if (!LookForFile(newFileName))
{
delete[] newFileName;
break;
}
rtPng->SetFileName(newFileName);
// Need to reset the output whole extent cause we may have baselines
// of differing sizes. (Yes, we have such cases !)
ic2->ResetOutputWholeExtent();
ic2->SetOutputWholeExtent(wExt2[0] + this->BorderOffset, wExt2[1] - this->BorderOffset,
wExt2[2] + this->BorderOffset, wExt2[3] - this->BorderOffset, wExt2[4], wExt2[5]);
ic2->UpdateWholeExtent();
vtkImageData::SafeDownCast(ic2->GetOutputDataObject(0))->GetExtent(ext2);
if ((ext2[1] - ext2[0]) == (ext1[1] - ext1[0]) && (ext2[3] - ext2[2]) == (ext1[3] - ext1[2]) &&
(ext2[5] - ext2[4]) == (ext1[5] - ext1[4]))
{
vtkLog(INFO, "Trying another baseline.");
// Cannot compute difference unless image sizes are the same
executeComparison(error);
}
else
{
error = VTK_DOUBLE_MAX;
}
if (error <= thresh)
{
// Make sure there was actually a difference image before
// accepting the error measure.
vtkImageData* output = vtkImageData::SafeDownCast(rtId->GetOutputDataObject(0));
if (output)
{
int dims[3];
output->GetDimensions(dims);
if (dims[0] * dims[1] * dims[2] > 0)
{
minError = error;
passed = 1;
}
}
}
else
{
if (error < minError)
{
errIndex = count;
minError = error;
bestImageFileName = newFileName;
}
}
++count;
delete[] newFileName;
}
this->ImageDifference = minError;
// output some information
os << "<DartMeasurement name=\"ImageError\" type=\"numeric/double\">";
os << minError;
os << "</DartMeasurement>";
if (errIndex <= 0)
{
os << "<DartMeasurement name=\"BaselineImage\" type=\"text/string\">Standard</DartMeasurement>";
}
else
{
os << "<DartMeasurement name=\"BaselineImage\" type=\"numeric/integer\">";
os << errIndex;
os << "</DartMeasurement>";
}
if (passed)
{
return PASSED;
}
// write out the image that was generated
string testImageFileName = tmpDir + "/" + validName;
#ifdef __EMSCRIPTEN__
{
vtkNew<vtkPNGWriter> rtPngw;
rtPngw->SetWriteToMemory(true);
rtPngw->SetInputConnection(imageSource->GetOutputPort());
rtPngw->Write();
auto* result = rtPngw->GetResult();
vtkEmscriptenTestUtilities::DumpFile(
testImageFileName, result->GetPointer(0), result->GetDataTypeSize() * result->GetDataSize());
// Write out the image upload tag for the test image.
os << "<DartMeasurementFile name=\"TestImage\" type=\"image/png\">";
os << testImageFileName;
os << "</DartMeasurementFile>\n";
}
#else
FILE* testImageFile = vtksys::SystemTools::Fopen(testImageFileName, "wb");
if (testImageFile)
{
fclose(testImageFile);
vtkNew<vtkPNGWriter> rtPngw;
rtPngw->SetFileName(testImageFileName.c_str());
rtPngw->SetInputConnection(imageSource->GetOutputPort());
rtPngw->Write();
// Write out the image upload tag for the test image.
os << "<DartMeasurementFile name=\"TestImage\" type=\"image/png\">";
os << testImageFileName;
os << "</DartMeasurementFile>\n";
}
else
{
vtkErrorMacro("Could not open file '" << testImageFileName
<< "' for "
"writing.");
}
#endif
os << "Failed Image Test ( " << validName << " ) : " << minError << endl;
if (errIndex >= 0)
{
newFileName = IncrementFileName(this->ValidImageFileName, errIndex);
#ifdef __EMSCRIPTEN__
std::string sandboxedFileName = vtkEmscriptenTestUtilities::PreloadDataFile(newFileName);
delete[] newFileName;
newFileName = new char[sandboxedFileName.size() + 1];
strcpy(newFileName, sandboxedFileName.c_str());
#endif
rtPng->SetFileName(newFileName);
delete[] newFileName;
}
else
{
#ifdef __EMSCRIPTEN__
rtPng->SetFileName(validName.c_str());
#else
rtPng->SetFileName(this->ValidImageFileName);
#endif
}
rtPng->Update();
vtkImageData::SafeDownCast(ic2->GetOutputDataObject(0))->GetExtent(ext2);
// If no image differences produced an image, do not write a
// difference image.
bool hasDiff = minError > 0;
if (!hasDiff)
{
os << "Image differencing failed to produce an image." << endl;
}
if (!((ext2[1] - ext2[0]) == (ext1[1] - ext1[0]) && (ext2[3] - ext2[2]) == (ext1[3] - ext1[2]) &&
(ext2[5] - ext2[4]) == (ext1[5] - ext1[4])))
{
os << "Image differencing failed to produce an image because images are "
"different size:"
<< endl;
os << "Valid image: " << (ext2[1] - ext2[0] + 1) << ", " << (ext2[3] - ext2[2] + 1) << ", "
<< (ext2[5] - ext2[4] + 1) << endl;
os << "Test image: " << (ext1[1] - ext1[0] + 1) << ", " << (ext1[3] - ext1[2] + 1) << ", "
<< (ext1[5] - ext1[4] + 1) << endl;
return FAILED;
}
rtId->Update();
// test the directory for writing
if (hasDiff)
{
string diffFilename = tmpDir + "/" + validName;
string::size_type dotPos = diffFilename.rfind('.');
if (dotPos != string::npos)
{
diffFilename = diffFilename.substr(0, dotPos);
}
if (imageCompareMethod != LEGACY)
{
auto ssim = vtkImageData::SafeDownCast(rtId->GetOutputDataObject(0));
vtkDataSet* current = vtkDataSet::SafeDownCast(rtId->GetExecutive()->GetInputData(0, 0));
vtkDataSet* baseline = vtkDataSet::SafeDownCast(rtId->GetExecutive()->GetInputData(1, 0));
auto addOriginalArray = [&ssim](vtkDataSet* ds, std::string&& name) {
vtkDataArray* scalars = ds->GetPointData()->GetScalars();
auto array = vtkSmartPointer<vtkDataArray>::Take(scalars->NewInstance());
array->ShallowCopy(scalars);
array->SetName(name.c_str());
ssim->GetPointData()->AddArray(array);
};
addOriginalArray(baseline, "Baseline");
addOriginalArray(current, "Current");
std::string vtiName = diffFilename + ".vti";
#ifdef __EMSCRIPTEN__
{
vtkNew<vtkXMLImageDataWriter> vtiWriter;
vtiWriter->WriteToOutputStringOn();
vtiWriter->SetInputData(ssim);
vtiWriter->Write();
const auto result = vtiWriter->GetOutputString();
vtkEmscriptenTestUtilities::DumpFile(vtiName, result.data(), result.size());
}
#else
vtkNew<vtkXMLImageDataWriter> vtiWriter;
vtiWriter->SetFileName(vtiName.c_str());
vtiWriter->SetInputData(ssim);
vtiWriter->Write();
#endif
}
diffFilename += ".diff.png";
// write out the difference image gamma adjusted for the dashboard
vtkNew<vtkImageShiftScale> rtGamma;
rtGamma->SetInputConnection(rtId->GetOutputPort());
rtGamma->SetShift(0);
rtGamma->SetScale(imageCompareMethod == LEGACY ? 10 : 255);
rtGamma->SetOutputScalarTypeToUnsignedChar();
rtGamma->ClampOverflowOn();
#ifdef __EMSCRIPTEN__
{
vtkNew<vtkPNGWriter> rtPngw;
rtPngw->SetWriteToMemory(true);
rtPngw->SetInputConnection(rtGamma->GetOutputPort());
rtPngw->Write();
const auto result = rtPngw->GetResult();
vtkEmscriptenTestUtilities::DumpFile(
diffFilename, result->GetPointer(0), result->GetDataTypeSize() * result->GetDataSize());
os << "<DartMeasurementFile name=\"DifferenceImage\" type=\"image/png\">";
os << diffFilename;
os << "</DartMeasurementFile>";
}
#else
FILE* rtDout = vtksys::SystemTools::Fopen(diffFilename, "wb");
if (rtDout)
{
fclose(rtDout);
vtkNew<vtkPNGWriter> rtPngw;
rtPngw->SetFileName(diffFilename.c_str());
rtPngw->SetInputConnection(rtGamma->GetOutputPort());
rtPngw->Write();
os << "<DartMeasurementFile name=\"DifferenceImage\" type=\"image/png\">";
os << diffFilename;
os << "</DartMeasurementFile>";
}
else
{
vtkErrorMacro("Could not open file '" << diffFilename << "' for writing.");
}
#endif
}
os << "<DartMeasurementFile name=\"ValidImage\" type=\"image/png\">";
os << bestImageFileName;
os << "</DartMeasurementFile>";
return FAILED;
}
//------------------------------------------------------------------------------
int vtkTesting::Test(int argc, char* argv[], vtkRenderWindow* rw, double thresh)
{
vtkNew<vtkTesting> testing;
for (int i = 0; i < argc; ++i)
{
testing->AddArgument(argv[i]);
}
if (testing->IsInteractiveModeSpecified())
{
return DO_INTERACTOR;
}
if (testing->IsValidImageSpecified())
{
testing->SetRenderWindow(rw);
return testing->RegressionTest(thresh, cout);
}
return NOT_RUN;
}
//------------------------------------------------------------------------------
int vtkTesting::CompareAverageOfL2Norm(vtkDataArray* daA, vtkDataArray* daB, double tol)
{
int typeA = daA->GetDataType();
int typeB = daB->GetDataType();
if (typeA != typeB)
{
vtkWarningMacro("Incompatible data types: " << typeA << "," << typeB << ".");
return 0;
}
//
vtkIdType nTupsA = daA->GetNumberOfTuples();
vtkIdType nTupsB = daB->GetNumberOfTuples();
int nCompsA = daA->GetNumberOfComponents();
int nCompsB = daB->GetNumberOfComponents();
//
if ((nTupsA != nTupsB) || (nCompsA != nCompsB))
{
vtkWarningMacro("Arrays: " << daA->GetName() << " (nC=" << nCompsA << " nT= " << nTupsA << ")"
<< " and " << daB->GetName() << " (nC=" << nCompsB
<< " nT= " << nTupsB << ")"
<< " do not have the same structure.");
return 0;
}
double L2 = 0.0;
vtkIdType N = 0;
switch (typeA)
{
case VTK_DOUBLE:
{
vtkDoubleArray* A = vtkArrayDownCast<vtkDoubleArray>(daA);
double* pA = A->GetPointer(0);
vtkDoubleArray* B = vtkArrayDownCast<vtkDoubleArray>(daB);
double* pB = B->GetPointer(0);
N = AccumulateScaledL2Norm(pA, pB, nTupsA, nCompsA, L2);
}
break;
case VTK_FLOAT:
{
vtkFloatArray* A = vtkArrayDownCast<vtkFloatArray>(daA);
float* pA = A->GetPointer(0);
vtkFloatArray* B = vtkArrayDownCast<vtkFloatArray>(daB);
float* pB = B->GetPointer(0);
N = AccumulateScaledL2Norm(pA, pB, nTupsA, nCompsA, L2);
}
break;
default:
if (this->Verbose)
{
cout << "Skipping:" << daA->GetName() << endl;
}
return true;
}
//
if (N <= 0)
{
return 0;
}
//
if (this->Verbose)
{
cout << "Sum(L2)/N of " << daA->GetName() << " < " << tol << "? = " << L2 << "/" << N << "."
<< endl;
}
//
double avgL2 = L2 / static_cast<double>(N);
if (avgL2 > tol)
{
return 0;
}
// Test passed
return 1;
}
//------------------------------------------------------------------------------
int vtkTesting::CompareAverageOfL2Norm(vtkDataSet* dsA, vtkDataSet* dsB, double tol)
{
vtkDataArray* daA = nullptr;
vtkDataArray* daB = nullptr;
int status = 0;
// Compare points if the dataset derives from
// vtkPointSet.
vtkPointSet* ptSetA = vtkPointSet::SafeDownCast(dsA);
vtkPointSet* ptSetB = vtkPointSet::SafeDownCast(dsB);
if (ptSetA != nullptr && ptSetB != nullptr)
{
if (this->Verbose)
{
cout << "Comparing points:" << endl;
}
daA = ptSetA->GetPoints()->GetData();
daB = ptSetB->GetPoints()->GetData();
//
status = CompareAverageOfL2Norm(daA, daB, tol);
if (status == 0)
{
return 0;
}
}
// Compare point data arrays.
if (this->Verbose)
{
cout << "Comparing data arrays:" << endl;
}
int nDaA = dsA->GetPointData()->GetNumberOfArrays();
int nDaB = dsB->GetPointData()->GetNumberOfArrays();
if (nDaA != nDaB)
{
vtkWarningMacro("Point data, " << dsA << " and " << dsB << " differ in number of arrays"
<< " and cannot be compared.");
return 0;
}
//
for (int arrayId = 0; arrayId < nDaA; ++arrayId)
{
daA = dsA->GetPointData()->GetArray(arrayId);
daB = dsB->GetPointData()->GetArray(arrayId);
//
status = CompareAverageOfL2Norm(daA, daB, tol);
if (status == 0)
{
return 0;
}
}
// All tests passed.
return 1;
}
//------------------------------------------------------------------------------
int vtkTesting::InteractorEventLoop(
int argc, char* argv[], vtkRenderWindowInteractor* iren, const char* playbackStream)
{
bool disableReplay = false, record = false, playbackFile = false;
std::string playbackFileName;
for (int i = 0; i < argc; i++)
{
disableReplay |= (strcmp("--DisableReplay", argv[i]) == 0);
record |= (strcmp("--Record", argv[i]) == 0);
playbackFile |= (strcmp("--PlaybackFile", argv[i]) == 0);
if (playbackFile && playbackFileName.empty())
{
if (i + 1 < argc)
{
playbackFileName = std::string(argv[i + 1]);
++i;
}
}
}
vtkNew<vtkInteractorEventRecorder> recorder;
recorder->SetInteractor(iren);
if (!disableReplay)
{
if (record)
{
recorder->SetFileName("vtkInteractorEventRecorder.log");
recorder->On();
recorder->Record();
}
else
{
if (playbackStream)
{
recorder->ReadFromInputStringOn();
recorder->SetInputString(playbackStream);
recorder->Play();
// Without this, the "-I" option if specified will fail
recorder->Off();
}
else if (playbackFile)
{
recorder->SetFileName(playbackFileName.c_str());
recorder->Play();
// Without this, the "-I" option if specified will fail
recorder->Off();
}
}
}
// iren will be either the object factory instantiation (vtkTestingInteractor)
// or vtkRenderWindowInteractor depending on whether or not "-I" is specified.
iren->Start();
recorder->Off();
return EXIT_SUCCESS;
}
//------------------------------------------------------------------------------
void vtkTesting::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "RenderWindow: " << this->RenderWindow << endl;
os << indent
<< "ValidImageFileName: " << (this->ValidImageFileName ? this->ValidImageFileName : "(none)")
<< endl;
os << indent << "FrontBuffer: " << (this->FrontBuffer ? "On" : "Off") << endl;
os << indent << "ImageDifference: " << this->ImageDifference << endl;
os << indent << "DataRoot: " << this->GetDataRoot() << endl;
os << indent << "Temp Directory: " << this->GetTempDirectory() << endl;
os << indent << "BorderOffset: " << this->GetBorderOffset() << endl;
os << indent << "Verbose: " << this->GetVerbose() << endl;
}
VTK_ABI_NAMESPACE_END
|